diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..fb06d5d --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "demo", + "runtimeExecutable": "cargo", + "runtimeArgs": ["run", "-p", "jm-server", "--example", "demo"], + "port": 8097 + } + ] +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cf6b087..2e4314e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,10 @@ name: CI -# Branch pushes only: a version tag points at a commit CI has already checked -# on its branch, and release.yml runs the tests again for tags. +# Gitflow: pushes to master and develop run here. Feature, release and hotfix +# branches are checked through their pull request, so they don't run twice. +# Tags aren't matched: release.yml runs the tests again for them. on: push: - branches: ["**"] + branches: [master, develop] pull_request: jobs: test: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7e6b867..e565b46 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -51,6 +51,19 @@ jobs: node .github/scripts/changelog.mjs "$GITHUB_REF_NAME" > dist/release-notes.md cat dist/release-notes.md + # Gitea doesn't let the workflow's own token push packages, so the image + # needs a personal access token. Checked here so a missing secret fails + # before the long build, not after the release is published. + - name: Check the registry secrets are set + env: + REGISTRY_USER: ${{ secrets.REGISTRY_USER }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + run: | + if [ -z "$REGISTRY_USER" ] || [ -z "$REGISTRY_TOKEN" ]; then + echo "::error::Set the REGISTRY_USER (your Gitea username) and REGISTRY_TOKEN (a token with package read and write) secrets under the repo's Settings → Actions → Secrets, then re-run." + exit 1 + fi + - name: Build the UI run: | npm --prefix ui ci @@ -103,12 +116,11 @@ jobs: echo "$HOME/.local/bin" >> "$GITHUB_PATH" # Pushes //jellymove:, plus :latest unless the - # tag is a pre-release. The workflow's own token is tried first; if Gitea - # refuses it, add REGISTRY_USER and REGISTRY_TOKEN (write:package) secrets. + # tag is a pre-release. - name: Publish the Docker image env: - REGISTRY_USER: ${{ secrets.REGISTRY_USER || github.actor }} - REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN || secrets.GITHUB_TOKEN }} + REGISTRY_USER: ${{ secrets.REGISTRY_USER }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} run: | registry="${GITHUB_SERVER_URL#*://}" registry="${registry%%/*}" diff --git a/CHANGELOG.md b/CHANGELOG.md index d777d76..9d524a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,55 @@ # Changelog +## v0.2.0 + +### Added + +- **Trash view.** A new Trash tab lists what's waiting in `.jellymove-trash/` + on either server: the item, its size and file count, when it was moved and + where to. Empty one item, a whole library or everything, with a confirmation. + Entries are deleted by ID only, never by path. (#3) +- **Folder sizes in the library.** Every movie and show now shows how much + space it takes, counting everything a move copies, with a per-season + breakdown for shows and a "Largest first" sort. Sizes are measured in the + background and cached, so big libraries open straight away. (#5) +- **Move a single season.** Shows list their seasons with sizes and a move + button each. A season joins the same show on the other server (matched by + TVDB/TMDB/IMDb ID, then name), bringing the show's NFO and artwork only if + that server doesn't have the show. Moving the last season also trashes the + leftover show folder on the source. (#4) +- **Warning before watch history is left behind.** Moving something asks + first if anyone with watch history for it has no account on the other + server. Dry runs and the move itself say so too. (#2) +- **Re-apply watch history.** A finished move remembers whose history it + couldn't apply. Once their account exists, one button in Moves applies it, + without touching anyone else's. (#2) + +### Updated + +- **Update both agents together.** The agents use new routes to talk to each + other (seasons, trash, watch-history checks), so a v0.1.x agent can't drive + these features. Each agent's database upgrades itself on first start. +- **Starting a move keeps you in the Library.** The item shows "Moving to …" + while it moves, rather than the app switching to the Moves tab. +- **The Docker Compose example uses environment variables only.** No + `jellymove.toml` is needed: every setting can be a `JELLYMOVE_*` variable. +- **Releases need registry secrets.** The release workflow pushes the Docker + image with `REGISTRY_USER` and `REGISTRY_TOKEN`, and stops straight away if + either is missing. + +### Fixed + +- **Moving an item away a second time failed** if its first trip was still in + the trash. Each move now gets its own trash entry. +- **Library lists didn't update after a move.** They now reload when a move + finishes: the item appears on the destination straight away, and is marked + "Moved to …" on the source until that server's Jellyfin drops it after its + next scan. Sizes of folders a move touched are measured again at once. (#1) +- **Switching servers in the Library could show an empty list** when both + libraries had the same ID. +- **Errors passed on from the other server** now show its message rather than + raw JSON and an HTTP status. + ## v0.1.1 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 73985a1..1b20a80 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ enough while developing. | `jm-core` | Pure domain: `Job`/`Stage`/`JobStatus`, `ExportInfo`/`Manifest`, `PathMap`, folder safety rules, user-data types. No I/O. | | `jm-transfer` | Manifest building + BLAKE3, `range_response` (serve), `Puller` (resume/retry/throttle/verify), `promote` (atomic rename). | | `jm-jellyfin` | Thin typed client for the ~10 Jellyfin endpoints used. | -| `jm-store` | SQLite (rusqlite, WAL). Jobs and exports as JSON blobs. Migrations are the `MIGRATIONS` array; append only. | +| `jm-store` | SQLite (rusqlite, WAL). Jobs, exports and cached folder sizes as JSON blobs. Migrations are the `MIGRATIONS` array; append only. | | `jm-server` | axum app: `/api/*` (UI), `/peer/v1/*` (agent↔agent), `export.rs` (source side), `runner.rs` (destination side), embedded UI. | | `jellymove` | Binary: clap + figment config loading, tracing setup. | | `ui/` | Svelte 5 (runes) + Vite + TS SPA. No SvelteKit. | @@ -45,7 +45,10 @@ enough while developing. - **Nothing is deleted from the source until the destination has indexed every file** (`Stage::TargetScanned`) and user data is applied. Source "deletion" is - a rename into `/.jellymove-trash/`, never `remove_dir_all`. + a rename into `/.jellymove-trash//`, never `remove_dir_all`. + The only code that deletes is `trash::empty`, which resolves opaque entry + IDs by scanning the trash folders and only removes real folders directly + inside them. - **Every runner step is idempotent.** `Job.stage` is the last *completed* milestone; the runner re-executes from there after a crash. If you add a stage, make re-running it safe. @@ -53,7 +56,9 @@ enough while developing. never by path. Relative paths from a peer always go through `jm_core::paths::join_relative`, which rejects `..`, absolute paths and `\`. - **Never overwrite** at the destination: `plan` refuses if the target folder - exists; `promote` refuses on any clash before renaming anything. + exists (for a season, the season's folder inside the show); `promote` + refuses on any clash before renaming anything. A season going into a show + the destination already has skips the show's own files (`Job.skip_files`). - Partial/trash folders start with `.jellymove-` (Jellyfin skips dot-folders) and get a `.ignore` file. - Two path namespaces: what Jellyfin reports vs. what the agent sees. diff --git a/Cargo.lock b/Cargo.lock index 41d23a2..478b382 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1010,7 +1010,7 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jellymove" -version = "0.1.1" +version = "0.2.0" dependencies = [ "anyhow", "clap", @@ -1026,7 +1026,7 @@ dependencies = [ [[package]] name = "jm-core" -version = "0.1.1" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -1037,7 +1037,7 @@ dependencies = [ [[package]] name = "jm-jellyfin" -version = "0.1.1" +version = "0.2.0" dependencies = [ "axum", "jm-core", @@ -1051,7 +1051,7 @@ dependencies = [ [[package]] name = "jm-server" -version = "0.1.1" +version = "0.2.0" dependencies = [ "anyhow", "axum", @@ -1080,7 +1080,7 @@ dependencies = [ [[package]] name = "jm-store" -version = "0.1.1" +version = "0.2.0" dependencies = [ "jm-core", "rusqlite", @@ -1093,7 +1093,7 @@ dependencies = [ [[package]] name = "jm-transfer" -version = "0.1.1" +version = "0.2.0" dependencies = [ "axum", "blake3", diff --git a/Cargo.toml b/Cargo.toml index f9182e5..e65d418 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.1.1" +version = "0.2.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.85" diff --git a/README.md b/README.md index 2c08410..75ce43c 100644 --- a/README.md +++ b/README.md @@ -31,12 +31,33 @@ One agent runs next to each Jellyfin and sees the same media folders. The 4. **Index.** The destination asks Jellyfin to scan that folder, then waits until the item and every episode appear. 5. **Restore watch history.** Jellyfin gives moved files new item IDs, so - jellymove re-applies each user's data to the new items, matching users by name. + jellymove re-applies each user's data to the new items, matching users by + name. Before a move starts, jellymove warns if someone with watch history + has no account on the other server. If you move anyway, their history is + kept with the move: create the user there, then use **Re-apply watch + history** on the move in Moves. Only their history is applied, so anything + others have watched since is left alone. 6. **Clean up.** The source moves its folder to `.jellymove-trash/` in the same - library and rescans. It is not deleted. + library and rescans. It is not deleted: the **Trash** tab shows what's + waiting on each server, how much space it uses, and empties it when you're + ready. A crash or restart at any point resumes from the last completed step. +### Moving a single season + +In TV Shows, **Show seasons** lists a show's seasons with their sizes, each +with its own move button. A season moves into the same show on the other +server, found by its TVDB/TMDB/IMDb ID or its name, and its episodes keep +their watch history. If the other server doesn't have the show yet, the show's +own files (`tvshow.nfo`, posters) are copied with the season; if it does, they +are left alone. When the last season leaves a server, what's left of the show +folder goes to the trash with it. + +A season can only move on its own if it has its own folder (`Show/Season 02/`) +holding just that season's episodes. Specials (`Season 00` or `Specials`) work +the same way. + ## Quick look (no Jellyfin needed) ```sh @@ -50,11 +71,22 @@ cargo run -p jm-server --example demo Install one agent per server. **Mount media at the same paths as the Jellyfin container**, so the paths Jellyfin reports are the paths jellymove sees. +With Docker, copy [deploy/docker-compose.yml](deploy/docker-compose.yml), +fill in the `environment:` section, fix the volumes and `user:`, then: + ```sh -cp config.example.toml jellymove.toml # edit: node_name, jellyfin.api_key, peer.url, peer.token -docker compose -f deploy/docker-compose.yml up -d +mkdir jellymove-data && sudo chown 1000:1000 jellymove-data # same IDs as user: +docker compose run --rm jellymove check-config # prints the settings, secrets hidden +docker compose up -d ``` +Every setting in [config.example.toml](config.example.toml) can be set as +`JELLYMOVE_`, with `__` between a section and its key +(`[peer] token` → `JELLYMOVE_PEER__TOKEN`). There's no config file in this +setup, so the "config file not found; using environment only" warning at +start-up is expected. If you'd rather use a file, mount it at +`/config/jellymove.toml`. Environment variables still override it. + Each release publishes an image (x86_64) to the Gitea container registry: `git.malgra.com/ixianpixel/jellymove:`, and `:latest` for anything that isn't a pre-release. It's the same static binary as the systemd tarball, @@ -77,7 +109,8 @@ To upgrade, run `docker compose pull && docker compose up -d`. the roadmap. - Run the container as the same user as Jellyfin (`user: "1000:1000"`) so moved files keep the right ownership. -- Set a UI password (`[ui]`) unless the port is only reachable privately. +- Set a UI password (`[ui]`, or `JELLYMOVE_UI__USERNAME`/`__PASSWORD`) + unless the port is only reachable privately. - The **Status** tab checks that every library folder is visible and writable. ### Without Docker (systemd) @@ -117,8 +150,10 @@ git tag v0.1.1 && git push origin v0.1.1 The workflow runs the tests, builds the UI and binary, attaches the tarball and its `.sha256` to a Gitea release for that tag, then pushes the Docker image. It builds the image with `crane`, so the runner needs no Docker -socket. It pushes with the workflow's own token; if Gitea refuses that, add -`REGISTRY_USER` and `REGISTRY_TOKEN` (`write:package`) secrets. The release notes +socket. Gitea won't let the workflow's own token push packages, so the repo +needs two Actions secrets: `REGISTRY_USER` (your Gitea username) and +`REGISTRY_TOKEN` (a personal access token with only package read and write). +The workflow stops straight away if either is missing. The release notes are that version's section of `CHANGELOG.md`; the workflow stops straight away if there isn't one. Re-running it replaces the files and refreshes the notes. Tags with a `-` (`v0.2.0-rc1`) are marked pre-release. @@ -154,9 +189,10 @@ host. Prefer a socket proxy that only allows restarts, or restart by hand. ## Safety rules - Nothing leaves the source until the destination has indexed every file. -- The source copy goes to `.jellymove-trash/`. Empty it yourself once you're +- The source copy goes to `.jellymove-trash/`. Empty it from the **Trash** tab once you're happy (automatic retention is on the roadmap). -- Nothing at the destination is ever overwritten. +- Nothing at the destination is ever overwritten. A season move refuses if + that season's folder already exists there. - A movie must be in **its own folder**. jellymove refuses flat folders like `Movies/Heat.mkv` + `Movies/Ronin.mkv`, because moving "the folder" would take both. - Peers can only fetch files the source has explicitly exported, by index. @@ -173,8 +209,8 @@ host. Prefer a socket proxy that only allows restarts, or restart by hand. ## Roadmap -- Season-level moves; "promote" (pre-warm) shortcuts -- Trash retention and a trash view in the UI +- "Promote" (pre-warm) shortcuts +- Automatic trash retention (e.g. empty after N days) - Pairing codes and pinned TLS instead of a shared token - Outbound-only control channel so a NATed home agent needs no inbound port - Automatic tiering rules ("demote anything unwatched for 90 days when the cloud disk is over 80%") diff --git a/crates/jellymove/Cargo.toml b/crates/jellymove/Cargo.toml index 9a0aea1..064ddb1 100644 --- a/crates/jellymove/Cargo.toml +++ b/crates/jellymove/Cargo.toml @@ -9,8 +9,8 @@ rust-version.workspace = true 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" } +jm-core = { path = "../jm-core" } +jm-server = { path = "../jm-server" } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" tokio = { version = "1.54.1", features = ["full"] } diff --git a/crates/jm-core/src/job.rs b/crates/jm-core/src/job.rs index 9208824..e414e5f 100644 --- a/crates/jm-core/src/job.rs +++ b/crates/jm-core/src/job.rs @@ -38,6 +38,16 @@ impl std::str::FromStr for JobId { pub enum ItemKind { Movie, Series, + /// One season of a series, moved on its own into the show's folder. + Season, +} + +impl ItemKind { + /// Whether the item has episodes whose watch state is mapped by + /// (season, episode). + pub fn has_episodes(self) -> bool { + matches!(self, ItemKind::Series | ItemKind::Season) + } } /// The last milestone a job has *completed*. The runner looks at the stage, @@ -129,10 +139,31 @@ pub struct ExportInfo { pub rel_folder: String, pub manifest: Manifest, pub user_data: Vec, - /// Every episode the source knows about (series only). The destination - /// waits until its scan has found all of them before anything is deleted. + /// Every episode the source knows about (series and seasons). The + /// destination waits until its scan has found all of them before anything + /// is deleted. #[serde(default)] pub episode_keys: Vec, + /// Set for a season move. `rel_folder` and the manifest are then the + /// show's folder, holding only this season's folder and the show's own + /// loose files. + #[serde(default)] + pub season: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SeasonInfo { + pub number: i32, + /// The season's folder inside the show folder, e.g. `Season 02`. + pub folder: String, + pub show_name: String, + /// The show's provider IDs (Tvdb, Tmdb, Imdb...), for finding the same + /// show on the destination. + #[serde(default)] + pub show_provider_ids: std::collections::HashMap, + /// Manifest indexes of the show's own files (tvshow.nfo, artwork). Only + /// copied when the destination doesn't have the show yet. + pub show_files: Vec, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -167,6 +198,19 @@ pub struct Job { pub target_folder_jellyfin: Option, /// Item ID Jellyfin assigned on the destination after the scan. pub target_item_id: Option, + /// Destination library location (Jellyfin namespace) holding the target + /// folder. Missing on jobs from before v0.2.0. + #[serde(default)] + pub target_location: Option, + /// Manifest indexes not to copy, e.g. a show's files when a season goes + /// into a show the destination already has. + #[serde(default)] + pub skip_files: Vec, + /// Users with watch state on the source who have no account here, so + /// their watch state wasn't (or won't be) applied. Their records stay in + /// `export.user_data` and can be re-applied once the account exists. + #[serde(default)] + pub missing_users: Vec, pub progress: Progress, /// Human-readable log of what happened, newest last. pub log: Vec, @@ -197,6 +241,9 @@ impl Job { target_library: None, target_folder_jellyfin: None, target_item_id: None, + target_location: None, + skip_files: Vec::new(), + missing_users: Vec::new(), progress: Progress::default(), log: Vec::new(), } diff --git a/crates/jm-core/src/userdata.rs b/crates/jm-core/src/userdata.rs index c37fb1e..6f0b4f4 100644 --- a/crates/jm-core/src/userdata.rs +++ b/crates/jm-core/src/userdata.rs @@ -51,10 +51,39 @@ pub fn same_user(a: &str, b: &str) -> bool { a.trim().eq_ignore_ascii_case(b.trim()) } +/// Users with watch state in `records` who have no account among `users`, +/// each named once, in the order they first appear. +pub fn missing_users<'a>( + records: &'a [UserDataRecord], + users: impl IntoIterator + Clone, +) -> Vec { + let mut out: Vec = Vec::new(); + for r in records { + let known = users.clone().into_iter().any(|u| same_user(u, &r.user_name)); + if !known && !out.iter().any(|m| same_user(m, &r.user_name)) { + out.push(r.user_name.clone()); + } + } + out +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn finds_users_with_no_account() { + let rec = |name: &str| UserDataRecord { + user_name: name.into(), + key: ItemKey::Root, + data: UserData::default(), + }; + let records = [rec("Alice"), rec("Bob"), rec("bob "), rec("Carol")]; + let here = ["alice", "Carol"]; + assert_eq!(missing_users(&records, here.iter().copied()), ["Bob"]); + assert!(missing_users(&records[..1], here.iter().copied()).is_empty()); + } + #[test] fn empty_detection() { assert!(UserData::default().is_empty()); diff --git a/crates/jm-jellyfin/Cargo.toml b/crates/jm-jellyfin/Cargo.toml index 0e7d2c4..2cc551c 100644 --- a/crates/jm-jellyfin/Cargo.toml +++ b/crates/jm-jellyfin/Cargo.toml @@ -6,7 +6,7 @@ license.workspace = true rust-version.workspace = true [dependencies] -jm-core = { version = "0.1.0", path = "../jm-core" } +jm-core = { 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" diff --git a/crates/jm-jellyfin/src/lib.rs b/crates/jm-jellyfin/src/lib.rs index 146d315..d26b4e7 100644 --- a/crates/jm-jellyfin/src/lib.rs +++ b/crates/jm-jellyfin/src/lib.rs @@ -103,9 +103,12 @@ pub struct Item { /// Season number for episodes. #[serde(default)] pub parent_index_number: Option, - /// Episode number for episodes. + /// Episode number for episodes; season number for seasons. #[serde(default)] pub index_number: Option, + /// The series a season or episode belongs to. + #[serde(default)] + pub series_id: Option, #[serde(default)] pub user_data: Option, } diff --git a/crates/jm-server/Cargo.toml b/crates/jm-server/Cargo.toml index 8049027..0a5c7a4 100644 --- a/crates/jm-server/Cargo.toml +++ b/crates/jm-server/Cargo.toml @@ -9,11 +9,12 @@ rust-version.workspace = true anyhow = "1.0.104" axum = { version = "0.8.9", features = ["macros"] } base64 = "0.23.1" +blake3 = "1.8.7" 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" } +jm-core = { path = "../jm-core" } +jm-jellyfin = { path = "../jm-jellyfin" } +jm-store = { path = "../jm-store" } +jm-transfer = { 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" @@ -29,7 +30,6 @@ 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" diff --git a/crates/jm-server/examples/demo.rs b/crates/jm-server/examples/demo.rs index aac9efe..f6fcf13 100644 --- a/crates/jm-server/examples/demo.rs +++ b/crates/jm-server/examples/demo.rs @@ -44,9 +44,14 @@ fn libs(root: &Path) -> Vec { #[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"); + // One fixed folder, emptied on each start: a temp folder per run would + // be left behind (hundreds of MB) whenever the demo is killed. + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/demo"); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root)?; + let root = root.canonicalize()?; + let cloud = root.join("cloud"); + let home = root.join("home"); for r in [&cloud, &home] { std::fs::create_dir_all(r.join("movies"))?; std::fs::create_dir_all(r.join("tv"))?; @@ -63,12 +68,18 @@ async fn main() -> anyhow::Result<()> { 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, - ); + for (season, eps) in [(1, 6), (2, 4)] { + for ep in 1..=eps { + write( + &cloud.join(format!( + "tv/Severance/Season {season:02}/Severance S{season:02}E{ep:02}.mkv" + )), + 20 * MB, + ); + } } + write(&cloud.join("tv/Severance/tvshow.nfo"), 2_000); + write(&cloud.join("tv/Severance/poster.jpg"), 300_000); write( &home.join("movies/The Thing (1982)/The Thing (1982).mkv"), 40 * MB, @@ -76,7 +87,11 @@ async fn main() -> anyhow::Result<()> { let fake_cloud = Fake::new(libs(&cloud)); let fake_home = Fake::new(libs(&home)); + // Bob only has an account on cloud, so his watch history can't follow a + // move to home until one is created there. + fake_cloud.add_user("u2", "Bob"); if let Some(id) = fake_cloud.find("Movie", "Arrival") { + fake_cloud.set_user_data_for("u2", &id, serde_json::json!({"PlaybackPositionTicks": 36_000_000_000i64})); fake_cloud.set_user_data(&id, serde_json::json!({"Played": true, "PlayCount": 1})); } let jf_cloud = fake_cloud.serve().await; @@ -118,7 +133,7 @@ async fn main() -> anyhow::Result<()> { axum::serve(listener, jm_server::api::router(state)).await })); } - println!("demo media in {}", tmp.path().display()); + println!("demo media in {}", root.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(()) diff --git a/crates/jm-server/src/api.rs b/crates/jm-server/src/api.rs index acc6984..ab408c7 100644 --- a/crates/jm-server/src/api.rs +++ b/crates/jm-server/src/api.rs @@ -19,11 +19,12 @@ 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::export::{self, CompleteRequest, Export, ExportStatus}; +use crate::library::{self, Library, LibraryItem, LocationCheck, SeasonItem}; use crate::peer::{CreateJob, NodeInfo}; use crate::runner; use crate::state::Shared; +use crate::trash::{self, EmptyResult, TrashEntry}; pub struct ApiError(StatusCode, String); @@ -58,20 +59,31 @@ pub fn router(state: Shared) -> Router { .route("/status", get(status)) .route("/libraries", get(ui_libraries)) .route("/items", get(ui_items)) + .route("/seasons", get(ui_seasons)) .route("/moves", post(ui_move)) + .route("/moves/check", get(ui_check_move)) .route("/jobs", get(ui_jobs)) .route("/jobs/{id}/retry", post(ui_retry)) + .route("/jobs/{id}/reapply", post(ui_reapply)) + .route("/trash", get(ui_trash)) + .route("/trash/empty", post(ui_empty_trash)) .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("/seasons", get(peer_seasons)) .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)) + .route("/jobs/{id}/reapply", post(peer_reapply)) + .route("/users", get(peer_users)) + .route("/watchers", get(peer_watchers)) + .route("/trash", get(peer_trash)) + .route("/trash/empty", post(peer_empty_trash)) .layer(middleware::from_fn_with_state( state.clone(), require_peer_token, @@ -248,6 +260,23 @@ async fn ui_items( })) } +#[derive(Deserialize)] +struct SeasonsQuery { + #[serde(default)] + node: Side, + series: String, +} + +async fn ui_seasons( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(match q.node { + Side::Local => library::seasons(&state, &q.series).await?, + Side::Peer => state.peer()?.seasons(&q.series).await?, + })) +} + #[derive(Deserialize)] struct MoveRequest { /// Where the item is now. @@ -313,6 +342,72 @@ async fn ui_jobs(State(state): State) -> ApiResult { })) } +#[derive(Deserialize)] +struct CheckMoveQuery { + /// Where the item is now. + from: Side, + item_id: String, +} + +#[derive(Serialize)] +struct MoveCheck { + /// Users with watch state for the item on the source. + watchers: Vec, + /// Those of them with no account on the destination, whose watch state + /// won't carry over. + missing_users: Vec, +} + +/// Before a move: whose watch history wouldn't carry over, because the +/// destination has no user with that name. +async fn ui_check_move( + State(state): State, + Query(q): Query, +) -> ApiResult { + let peer = state.peer()?; + let (watchers, dest_users) = match q.from { + Side::Local => ( + export::watchers(&state, &q.item_id).await?, + peer.users().await?, + ), + Side::Peer => ( + peer.watchers(&q.item_id).await?, + state + .jellyfin + .users() + .await? + .into_iter() + .map(|u| u.name) + .collect(), + ), + }; + let missing_users = watchers + .iter() + .filter(|w| !dest_users.iter().any(|u| jm_core::userdata::same_user(u, w))) + .cloned() + .collect(); + Ok(Json(MoveCheck { + watchers, + missing_users, + })) +} + +/// Re-apply skipped watch history on a finished move. The job lives on the +/// destination, which may be the peer. +async fn ui_reapply(State(state): State, Path(id): Path) -> ApiResult { + let job_id: JobId = id + .parse() + .map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?; + match state.store.get_job(job_id).await? { + Some(job) => { + let mut job = runner::reapply_user_data(&state, job).await?; + job.export = None; + Ok(Json(job)) + } + None => Ok(Json(state.peer()?.reapply(&id).await?)), + } +} + async fn ui_retry(State(state): State, Path(id): Path) -> ApiResult { let id: JobId = id .parse() @@ -333,6 +428,35 @@ async fn ui_retry(State(state): State, Path(id): Path) -> ApiRes Ok(Json(job)) } +async fn ui_trash( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(match q.node { + Side::Local => trash::list(&state).await?, + Side::Peer => state.peer()?.trash().await?, + })) +} + +#[derive(Deserialize)] +struct EmptyTrashRequest { + #[serde(default)] + node: Side, + ids: Vec, +} + +/// Delete trash entries for good, by ID. Each node only ever deletes its own +/// files; for the peer's trash the request is passed on. +async fn ui_empty_trash( + State(state): State, + Json(req): Json, +) -> ApiResult { + Ok(Json(match req.node { + Side::Local => trash::empty(&state, &req.ids).await?, + Side::Peer => state.peer()?.empty_trash(&req.ids).await?, + })) +} + async fn events(State(state): State) -> Sse>> { let stream = BroadcastStream::new(state.events.subscribe()).filter_map(|msg| { msg.ok().and_then(|mut job| { @@ -368,6 +492,18 @@ async fn peer_items( )) } +#[derive(Deserialize)] +struct PeerSeasonsQuery { + series: String, +} + +async fn peer_seasons( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(library::seasons(&state, &q.series).await?)) +} + #[derive(Deserialize)] struct CreateExport { item_id: String, @@ -409,8 +545,26 @@ async fn peer_file( async fn peer_complete_export( State(state): State, Path(id): Path, + body: Option>, ) -> ApiResult { - Ok(Json(export::complete(&state, &id).await?)) + let req = body.map(|Json(r)| r).unwrap_or_default(); + Ok(Json(export::complete(&state, &id, req).await?)) +} + +async fn peer_trash(State(state): State) -> ApiResult> { + Ok(Json(trash::list(&state).await?)) +} + +#[derive(Deserialize)] +struct PeerEmptyTrash { + ids: Vec, +} + +async fn peer_empty_trash( + State(state): State, + Json(req): Json, +) -> ApiResult { + Ok(Json(trash::empty(&state, &req.ids).await?)) } async fn peer_create_job( @@ -435,6 +589,44 @@ async fn peer_create_job( Ok(Json(job)) } +async fn peer_reapply(State(state): State, Path(id): Path) -> ApiResult { + let job_id: JobId = id + .parse() + .map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?; + let job = state + .store + .get_job(job_id) + .await? + .ok_or(ApiError(StatusCode::NOT_FOUND, "no such job".into()))?; + let mut job = runner::reapply_user_data(&state, job).await?; + job.export = None; + Ok(Json(job)) +} + +async fn peer_users(State(state): State) -> ApiResult> { + Ok(Json( + state + .jellyfin + .users() + .await? + .into_iter() + .map(|u| u.name) + .collect(), + )) +} + +#[derive(Deserialize)] +struct WatchersQuery { + item: String, +} + +async fn peer_watchers( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(export::watchers(&state, &q.item).await?)) +} + async fn peer_jobs(State(state): State) -> ApiResult> { let mut jobs = state.store.list_jobs(100).await?; for j in &mut jobs { diff --git a/crates/jm-server/src/export.rs b/crates/jm-server/src/export.rs index ce21bf0..280ae8c 100644 --- a/crates/jm-server/src/export.rs +++ b/crates/jm-server/src/export.rs @@ -7,14 +7,15 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, bail}; use jm_core::ItemKind; -use jm_core::job::ExportInfo; +use jm_core::job::{ExportInfo, SeasonInfo}; use jm_core::paths::{join_relative, relative_inside}; -use jm_core::safety::{check_inside_library, check_movie_folder}; +use jm_core::safety::{FolderProblem, check_inside_library, check_movie_folder, is_video}; use jm_core::userdata::{ItemKey, UserDataRecord}; use jm_jellyfin::ItemQuery; use serde::{Deserialize, Serialize}; use crate::state::{AppState, Shared}; +use crate::trash; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", content = "detail")] @@ -39,6 +40,10 @@ pub struct Export { /// Library location (Jellyfin namespace) containing the folder. #[serde(default)] pub jellyfin_location: String, + /// Trash entry folder chosen when completing, kept so a re-run after a + /// crash finishes in the same entry. + #[serde(default)] + pub trash_entry: Option, } impl Export { @@ -79,6 +84,7 @@ pub async fn create(state: &Shared, item_id: &str) -> anyhow::Result { info: None, jellyfin_folder: String::new(), jellyfin_location: String::new(), + trash_entry: None, }; state.store.put_export(&id, &export).await?; spawn_prepare(state.clone(), export.clone()); @@ -136,19 +142,57 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, let kind = match item.kind.as_str() { "Movie" => ItemKind::Movie, "Series" => ItemKind::Series, - other => bail!("can only move movies and series, not {other}"), + "Season" => ItemKind::Season, + other => bail!("can only move movies, shows and seasons, not {other}"), }; - let item_path = PathBuf::from( - item.path - .clone() - .context("Jellyfin did not report a path for this item")?, - ); + let item_path = match (&item.path, kind) { + (Some(p), _) => PathBuf::from(p), + (None, ItemKind::Season) => bail!( + "{} has no folder of its own (its episodes sit in the show folder); move the whole show instead", + item.name + ), + (None, _) => bail!("Jellyfin did not report a path for this item"), + }; + + // The folder handed over. For a season it's the show's folder, and the + // manifest is narrowed to the season's folder and the show's own files. + let mut season: Option<(jm_jellyfin::Item, String)> = None; let folder = match kind { ItemKind::Movie => item_path .parent() .context("movie path has no parent folder")? .to_path_buf(), ItemKind::Series => item_path.clone(), + ItemKind::Season => { + let series_id = item + .series_id + .clone() + .context("Jellyfin did not say which show this season belongs to")?; + let series = jf + .item(&series_id) + .await + .context("looking up the season's show on Jellyfin")?; + let show = PathBuf::from( + series + .path + .clone() + .context("Jellyfin did not report a path for the show")?, + ); + if item_path.parent() != Some(show.as_path()) { + bail!( + "{} has no folder of its own directly inside {}; move the whole show instead", + item.name, + show.display() + ); + } + let name = item_path + .file_name() + .and_then(|n| n.to_str()) + .context("season folder has no name")? + .to_string(); + season = Some((series, name)); + show + } }; let libraries = jf.virtual_folders().await?; @@ -197,28 +241,118 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, check_movie_folder(&files, &own)?; } - let manifest = jm_transfer::build_manifest(&local_folder) - .await - .context("hashing files")?; + let manifest = match &season { + None => jm_transfer::build_manifest(&local_folder).await, + Some((_, season_folder)) => { + // Other seasons' episodes must not ride along with this one. + let episodes = jf + .items(&ItemQuery { + parent_id: Some(item_id), + include_types: &["Episode"], + recursive: true, + ..Default::default() + }) + .await?; + let sl = local_folder.join(season_folder); + let files = tokio::task::spawn_blocking(move || jm_transfer::list_relative(&sl)).await??; + let own: Vec = episodes + .iter() + .flat_map(|e| { + e.media_sources + .iter() + .flatten() + .filter_map(|m| m.path.clone()) + .chain(e.path.clone()) + }) + .filter_map(|p| relative_inside(&item_path, Path::new(&p))) + .collect(); + if let Err(FolderProblem::SharedFolder(list)) = check_movie_folder(&files, &own) { + bail!( + "the {} folder also holds videos that aren't its episodes ({list}); \ + sort them into their own season folders first", + item.name + ); + } + // The season's folder, plus the show's own loose files (NFO, + // artwork). Loose videos belong to other seasons, so they stay. + let prefix = format!("{season_folder}/"); + jm_transfer::build_manifest_filtered(&local_folder, move |rel| { + rel.starts_with(&prefix) || (!rel.contains('/') && !is_video(rel)) + }) + .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 (user_data, episode_keys) = capture_user_data(state, item_id, kind).await?; + + let (name, season) = match season { + None => (item.name, None), + Some((series, season_folder)) => { + let show_files = manifest + .files + .iter() + .enumerate() + .filter(|(_, f)| !f.rel_path.contains('/')) + .map(|(i, _)| i) + .collect(); + ( + format!("{} – {}", series.name, item.name), + Some(SeasonInfo { + number: item + .index_number + .with_context(|| format!("Jellyfin gave {} no season number", item.name))?, + folder: season_folder, + show_name: series.name, + show_provider_ids: series.provider_ids, + show_files, + }), + ) + } + }; + let info = ExportInfo { + item_id: item_id.to_string(), + name, + kind, + library_name: library.name.clone(), + rel_folder, + manifest, + user_data, + episode_keys, + season, + }; + Ok((info, folder.display().to_string(), location)) +} + +/// Every user's watch state for an item: the item itself (not for a season, +/// whose own state would land on the whole show at the destination) and, for +/// shows and seasons, each episode. Also returns every episode's key. +pub async fn capture_user_data( + state: &AppState, + item_id: &str, + kind: ItemKind, +) -> anyhow::Result<(Vec, Vec)> { + let jf = &state.jellyfin; 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::Season { + 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 { + if kind.has_episodes() { let episodes = jf .items(&ItemQuery { parent_id: Some(item_id), @@ -243,18 +377,27 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, } } } + Ok((user_data, episode_keys)) +} - 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, +/// Names of the users who have watch state for an item, for the check before +/// a move. +pub async fn watchers(state: &AppState, item_id: &str) -> anyhow::Result> { + let item = state.jellyfin.item(item_id).await?; + let kind = match item.kind.as_str() { + "Movie" => ItemKind::Movie, + "Series" => ItemKind::Series, + "Season" => ItemKind::Season, + other => bail!("can only move movies, shows and seasons, not {other}"), }; - Ok((info, folder.display().to_string(), location)) + let (records, _) = capture_user_data(state, item_id, kind).await?; + let mut names: Vec = Vec::new(); + for r in records { + if !names.contains(&r.user_name) { + names.push(r.user_name); + } + } + Ok(names) } fn push_record( @@ -272,9 +415,17 @@ fn push_record( } } +/// Who finished the move; recorded with the trash entry. Older peers send +/// nothing. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct CompleteRequest { + pub job_id: Option, + pub moved_to: Option, +} + /// 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 { +pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow::Result { let mut export: Export = state .store .get_export(id) @@ -285,30 +436,87 @@ pub async fn complete(state: &Shared, id: &str) -> anyhow::Result { ExportStatus::Ready => {} other => bail!("export is not ready to complete ({other:?})"), } - let info = export.info.as_ref().context("export has no info")?; + let info = export.info.clone().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")?; + let trash_root = location_local.join(trash::TRASH_DIR); - if tokio::fs::metadata(&local_folder).await.is_ok() { - if let Some(parent) = trash.parent() { - tokio::fs::create_dir_all(parent).await?; - } + // What leaves: the item's folder, or for a season just the season's folder. + let (moving, rel_moving) = match &info.season { + None => (local_folder.clone(), info.rel_folder.clone()), + Some(s) => ( + join_relative(&local_folder, &s.folder).context("unsafe season folder name")?, + format!("{}/{}", info.rel_folder, s.folder), + ), + }; + + // Re-running after a crash: if the folder is already gone it was moved + // last time, so only the steps after it remain. + if tokio::fs::metadata(&moving).await.is_ok() { + tokio::fs::create_dir_all(&trash_root).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"); + // The same item can be trashed more than once (moved away, back, + // and away again), so each move gets its own entry folder. + let entry_dir = match &export.trash_entry { + Some(d) => d.clone(), + None => { + let d = trash::new_entry_dir(&trash_root, &export.id); + export.trash_entry = Some(d.clone()); + state.store.put_export(&export.id, &export).await?; + d + } + }; + let trash = join_relative(&entry_dir, &rel_moving).context("unsafe folder name")?; + if let Some(parent) = trash.parent() { + tokio::fs::create_dir_all(parent).await?; + } + trash::write_meta( + &entry_dir, + &trash::EntryMeta { + name: info.name.clone(), + kind: info.kind, + library: info.library_name.clone(), + rel_folder: rel_moving.clone(), + moved_at: time::OffsetDateTime::now_utc(), + moved_to: req.moved_to, + job_id: req.job_id, + }, + )?; + if let Err(e) = tokio::fs::rename(&moving, &trash).await { + // Don't leave an empty entry behind in the trash view. Only the + // metadata file and empty folders are removed, never contents. + let _ = tokio::fs::remove_file(entry_dir.join(trash::META_FILE)).await; + let mut dir = trash.parent(); + while let Some(d) = dir { + if !d.starts_with(&entry_dir) || tokio::fs::remove_dir(d).await.is_err() { + break; + } + dir = d.parent(); + } + return Err(e).with_context(|| format!("moving {} to the trash", moving.display())); + } + tracing::info!(from = %moving.display(), to = %trash.display(), "source moved to trash"); } + // If that was the show's last season, what's left of the show folder + // (its NFO and artwork) joins the season in the same trash entry. + if let (Some(_), Some(entry_dir)) = (&info.season, &export.trash_entry) { + let show = local_folder.clone(); + let dest = join_relative(entry_dir, &info.rel_folder).context("unsafe folder name")?; + let emptied = tokio::task::spawn_blocking(move || trash_leftover_show(&show, &dest)).await??; + if emptied { + tracing::info!(folder = %local_folder.display(), "last season moved; show folder moved to trash"); + } + } + + // After a season move the show is still listed here, but smaller. + crate::sizes::forget(state, &local_folder).await; if let Err(e) = state .jellyfin .media_updated(std::slice::from_ref(&export.jellyfin_folder)) @@ -320,3 +528,63 @@ pub async fn complete(state: &Shared, id: &str) -> anyhow::Result { state.store.put_export(&export.id, &export).await?; Ok(export) } + +/// Move everything left in `show` into `dest` and remove `show`, but only if +/// no videos are left in it (so no seasons, episodes or extras remain). +/// Returns whether it did. +fn trash_leftover_show(show: &Path, dest: &Path) -> anyhow::Result { + if !std::fs::symlink_metadata(show).is_ok_and(|m| m.is_dir()) || has_videos(show) { + return Ok(false); + } + std::fs::create_dir_all(dest)?; + for e in std::fs::read_dir(show)?.flatten() { + let to = dest.join(e.file_name()); + if std::fs::symlink_metadata(&to).is_ok() { + bail!("{} is already in the trash", to.display()); + } + std::fs::rename(e.path(), &to) + .with_context(|| format!("moving {} to the trash", e.path().display()))?; + } + std::fs::remove_dir(show).with_context(|| format!("removing {}", show.display()))?; + Ok(true) +} + +fn has_videos(dir: &Path) -> bool { + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).into_iter().flatten().flatten() { + let Ok(t) = e.file_type() else { continue }; + if t.is_dir() { + stack.push(e.path()); + } else if is_video(&e.file_name().to_string_lossy()) { + return true; + } + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn leftover_show_is_trashed_only_without_videos() { + let tmp = tempfile::tempdir().unwrap(); + let show = tmp.path().join("Show"); + let dest = tmp.path().join("trash/Show"); + std::fs::create_dir_all(show.join("Season 02")).unwrap(); + std::fs::write(show.join("tvshow.nfo"), b"n").unwrap(); + std::fs::write(show.join("Season 02/S02E01.mkv"), b"v").unwrap(); + assert!(!trash_leftover_show(&show, &dest).unwrap()); + assert!(show.join("tvshow.nfo").exists()); + + std::fs::remove_dir_all(show.join("Season 02")).unwrap(); + std::fs::create_dir_all(show.join("extrafanart")).unwrap(); + std::fs::write(show.join("extrafanart/1.jpg"), b"j").unwrap(); + assert!(trash_leftover_show(&show, &dest).unwrap()); + assert!(!show.exists()); + assert!(dest.join("tvshow.nfo").exists()); + assert!(dest.join("extrafanart/1.jpg").exists()); + } +} diff --git a/crates/jm-server/src/lib.rs b/crates/jm-server/src/lib.rs index 41054d2..ec9c324 100644 --- a/crates/jm-server/src/lib.rs +++ b/crates/jm-server/src/lib.rs @@ -6,7 +6,9 @@ pub mod export; pub mod library; pub mod peer; pub mod runner; +pub mod sizes; pub mod state; +pub mod trash; pub mod ui; use std::sync::Arc; diff --git a/crates/jm-server/src/library.rs b/crates/jm-server/src/library.rs index cdecf8a..27b85fd 100644 --- a/crates/jm-server/src/library.rs +++ b/crates/jm-server/src/library.rs @@ -1,11 +1,12 @@ //! Browsing the local Jellyfin libraries. -use std::path::Path; +use std::path::{Path, PathBuf}; use jm_jellyfin::ItemQuery; use serde::{Deserialize, Serialize}; -use crate::state::AppState; +use crate::sizes::{self, FolderSize}; +use crate::state::{AppState, Shared}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Library { @@ -23,6 +24,23 @@ pub struct LibraryItem { pub kind: String, pub year: Option, pub path: Option, + /// Size of the item's folder on disk; `None` until it has been measured. + #[serde(default)] + pub size: Option, +} + +/// A season of a show, as Jellyfin lists it. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SeasonItem { + pub id: String, + pub name: String, + pub number: Option, + /// The season's own folder. `None` when its episodes sit directly in the + /// show folder, in which case it can't be moved on its own. + pub path: Option, + /// Name of that folder inside the show folder, to match it with the + /// show's per-folder sizes. + pub folder: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -55,8 +73,10 @@ pub async fn libraries(state: &AppState) -> anyhow::Result> { .collect()) } +/// The movies and series in a library, with the size of each one's folder if +/// it's known yet. Sizes still missing are being measured in the background. pub async fn items( - state: &AppState, + state: &Shared, library_id: &str, search: Option<&str>, ) -> anyhow::Result> { @@ -71,7 +91,7 @@ pub async fn items( ..Default::default() }) .await?; - Ok(items + let mut out: Vec = items .into_iter() .map(|i| LibraryItem { id: i.id, @@ -79,8 +99,69 @@ pub async fn items( kind: i.kind, year: i.production_year, path: i.path, + size: None, }) - .collect()) + .collect(); + + // Only items whose folder we can place are measured. + let folders: Vec<(usize, PathBuf)> = out + .iter() + .enumerate() + .filter_map(|(n, i)| Some((n, item_folder(state, i)?))) + .collect(); + let paths: Vec = folders.iter().map(|(_, p)| p.clone()).collect(); + let sizes = sizes::lookup(state, &paths).await?; + for ((n, _), size) in folders.into_iter().zip(sizes) { + out[n].size = size; + } + Ok(out) +} + +/// The seasons of a show, in order. Seasons without a folder of their own +/// inside the show folder are listed with no path. +pub async fn seasons(state: &AppState, series_id: &str) -> anyhow::Result> { + let series = state.jellyfin.item(series_id).await?; + let show = series.path.map(PathBuf::from); + let mut out: Vec = state + .jellyfin + .items(&ItemQuery { + parent_id: Some(series_id), + include_types: &["Season"], + ..Default::default() + }) + .await? + .into_iter() + .map(|s| { + let path = s + .path + .filter(|p| show.as_deref().is_some_and(|show| Path::new(p).parent() == Some(show))); + let folder = path + .as_deref() + .and_then(|p| Path::new(p).file_name()) + .map(|n| n.to_string_lossy().into_owned()); + SeasonItem { + id: s.id, + name: s.name, + number: s.index_number, + path, + folder, + } + }) + .collect(); + out.sort_by_key(|s| s.number.unwrap_or(i32::MAX)); + Ok(out) +} + +/// The folder a move would take, as this agent sees it: a movie's parent +/// folder, or the series folder itself. +fn item_folder(state: &AppState, item: &LibraryItem) -> Option { + let path = Path::new(item.path.as_deref()?); + let folder = match item.kind.as_str() { + "Movie" => path.parent()?, + "Series" => path, + _ => return None, + }; + Some(state.cfg.path_map.to_local(folder)) } /// Confirm every library location exists and is writable from this agent. diff --git a/crates/jm-server/src/peer.rs b/crates/jm-server/src/peer.rs index 43ec8b7..972f25b 100644 --- a/crates/jm-server/src/peer.rs +++ b/crates/jm-server/src/peer.rs @@ -4,8 +4,9 @@ use jm_core::Job; use reqwest::header::AUTHORIZATION; use serde::{Deserialize, Serialize, de::DeserializeOwned}; -use crate::export::Export; -use crate::library::{Library, LibraryItem}; +use crate::export::{CompleteRequest, Export}; +use crate::library::{Library, LibraryItem, SeasonItem}; +use crate::trash::{EmptyResult, TrashEntry}; #[derive(Clone)] pub struct PeerClient { @@ -57,7 +58,14 @@ impl PeerClient { let status = resp.status(); if !status.is_success() { let body = resp.text().await.unwrap_or_default(); - anyhow::bail!("peer refused {what}: HTTP {status}: {body}"); + // Our own API answers {"error": "..."}; pass on just the message. + let message = serde_json::from_str::(&body) + .ok() + .and_then(|v| v.get("error")?.as_str().map(str::to_string)); + match message { + Some(m) => anyhow::bail!("peer refused {what}: {m}"), + None => anyhow::bail!("peer refused {what}: HTTP {status}: {body}"), + } } Ok(resp.json().await?) } @@ -84,6 +92,14 @@ impl PeerClient { .await } + pub async fn seasons(&self, series: &str) -> anyhow::Result> { + self.send( + self.http.get(self.url("/seasons")).query(&[("series", series)]), + "list seasons", + ) + .await + } + pub async fn create_export(&self, item_id: &str) -> anyhow::Result { self.send( self.http @@ -106,19 +122,59 @@ impl PeerClient { self.url(&format!("/exports/{export_id}/files/{idx}")) } - pub async fn complete_export(&self, id: &str) -> anyhow::Result { + pub async fn complete_export(&self, id: &str, req: &CompleteRequest) -> anyhow::Result { self.send( - self.http.post(self.url(&format!("/exports/{id}/complete"))), + self.http + .post(self.url(&format!("/exports/{id}/complete"))) + .json(req), "clean up source", ) .await } + pub async fn trash(&self) -> anyhow::Result> { + self.send(self.http.get(self.url("/trash")), "list trash") + .await + } + + pub async fn empty_trash(&self, ids: &[String]) -> anyhow::Result { + self.send( + self.http + .post(self.url("/trash/empty")) + .json(&serde_json::json!({ "ids": ids })), + "empty trash", + ) + .await + } + pub async fn create_job(&self, req: &CreateJob) -> anyhow::Result { self.send(self.http.post(self.url("/jobs")).json(req), "start job") .await } + /// Names of the users on the peer's Jellyfin. + pub async fn users(&self) -> anyhow::Result> { + self.send(self.http.get(self.url("/users")), "list users") + .await + } + + /// Users on the peer with watch state for one of its items. + pub async fn watchers(&self, item_id: &str) -> anyhow::Result> { + self.send( + self.http.get(self.url("/watchers")).query(&[("item", item_id)]), + "check watch history", + ) + .await + } + + pub async fn reapply(&self, job_id: &str) -> anyhow::Result { + self.send( + self.http.post(self.url(&format!("/jobs/{job_id}/reapply"))), + "re-apply watch history", + ) + .await + } + pub async fn jobs(&self) -> anyhow::Result> { self.send(self.http.get(self.url("/jobs")), "list jobs") .await diff --git a/crates/jm-server/src/runner.rs b/crates/jm-server/src/runner.rs index 42c66cc..312fbdc 100644 --- a/crates/jm-server/src/runner.rs +++ b/crates/jm-server/src/runner.rs @@ -5,9 +5,10 @@ use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use anyhow::{Context, bail}; -use jm_core::job::ExportInfo; +use jm_core::job::{ExportInfo, SeasonInfo}; use jm_core::paths::join_relative; -use jm_core::userdata::{ItemKey, same_user}; +use jm_core::safety::check_inside_library; +use jm_core::userdata::{ItemKey, UserDataRecord, missing_users, same_user}; use jm_core::{ItemKind, Job, JobStatus, Stage}; use jm_jellyfin::ItemQuery; @@ -100,6 +101,10 @@ fn target_jellyfin(job: &Job) -> anyhow::Result { /// Destination library location (local path) that holds the target folder. fn target_library_root(state: &Shared, job: &Job) -> anyhow::Result { + if let Some(loc) = &job.target_location { + return Ok(state.cfg.path_map.to_local(Path::new(loc))); + } + // Jobs planned before v0.2.0: work it out from the folder's depth. let info = info(job)?; let target = target_jellyfin(job)?; let depth = info.rel_folder.split('/').count(); @@ -154,7 +159,7 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result { })?; let expected = match info.kind { ItemKind::Movie => "movies", - ItemKind::Series => "tvshows", + ItemKind::Series | ItemKind::Season => "tvshows", }; if let Some(ct) = &lib.collection_type { if ct != expected { @@ -166,31 +171,76 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result { ); } } - let location = lib + let first_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() - ); - } + let (target, location, skip, place) = match &info.season { + None => { + let target = join_relative(Path::new(first_location), &info.rel_folder) + .context("unsafe folder name from source")?; + refuse_if_exists(state, &target)?; + let place = target.display().to_string(); + (target, first_location.clone(), Vec::new(), place) + } + Some(season) => { + // A season joins the show if this server already has it. + let existing = find_show(state, &lib.item_id, season).await?; + let show = match &existing { + Some(path) => PathBuf::from(path), + None => join_relative(Path::new(first_location), &info.rel_folder) + .context("unsafe folder name from source")?, + }; + let location = check_inside_library(&show, &lib.locations) + .map(str::to_string) + .unwrap_or_else(|_| first_location.clone()); + let season_target = + join_relative(&show, &season.folder).context("unsafe season folder name from source")?; + refuse_if_exists(state, &season_target)?; + let show_here = tokio::fs::metadata(state.cfg.path_map.to_local(&show)) + .await + .is_ok(); + // Never overwrite the show's own files here; only bring them for a new show. + let (skip, how) = if show_here { + (season.show_files.clone(), "adding to the show already here") + } else { + (Vec::new(), "a new show, with its NFO and artwork") + }; + let place = format!("{} ({how})", season_target.display()); + (show, location, skip, place) + } + }; job.name = info.name.clone(); - job.progress.bytes_total = info.manifest.total_bytes(); + job.progress.bytes_total = info + .manifest + .files + .iter() + .enumerate() + .filter(|(i, _)| !skip.contains(i)) + .map(|(_, f)| f.size) + .sum(); job.target_library = Some(lib.name.clone()); job.target_folder_jellyfin = Some(target.display().to_string()); + job.target_location = Some(location); job.note(format!( - "plan: {} files, {} into \"{}\" at {}", - info.manifest.files.len(), + "plan: {} files, {} into \"{}\" at {place}", + info.manifest.files.len() - skip.len(), human_bytes(job.progress.bytes_total), lib.name, - target.display() )); + job.skip_files = skip; + + // Watch state is matched to users by name; say now whose won't carry over. + let users = state.jellyfin.users().await?; + job.missing_users = missing_users(&info.user_data, users.iter().map(|u| u.name.as_str())); + if !job.missing_users.is_empty() { + job.note(format!( + "watch history won't carry over for {}: no user with that name on this server. \ + Create them in Jellyfin here first, or re-apply it from Moves afterwards", + job.missing_users.join(", ") + )); + } job.export = Some(info); if job.dry_run { @@ -202,6 +252,50 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result { Ok(Flow::Continue) } +/// Refuse to plan a move into a folder that already exists here. +fn refuse_if_exists(state: &Shared, target: &Path) -> anyhow::Result<()> { + let local = state.cfg.path_map.to_local(target); + if std::fs::symlink_metadata(&local).is_ok() { + bail!( + "{} already exists on this server; refusing to merge into it", + local.display() + ); + } + Ok(()) +} + +/// The folder of the show a season belongs to, if this library has it: +/// matched by provider ID (TVDB, TMDB, IMDb...) first, then by name. +async fn find_show( + state: &Shared, + library_id: &str, + season: &SeasonInfo, +) -> anyhow::Result> { + let shows = state + .jellyfin + .items(&ItemQuery { + parent_id: Some(library_id), + include_types: &["Series"], + recursive: true, + ..Default::default() + }) + .await?; + let same_id = |s: &&jm_jellyfin::Item| { + season.show_provider_ids.iter().any(|(k, v)| { + !v.trim().is_empty() + && s.provider_ids + .iter() + .any(|(k2, v2)| k2.eq_ignore_ascii_case(k) && v2.trim().eq_ignore_ascii_case(v.trim())) + }) + }; + let same_name = |s: &&jm_jellyfin::Item| s.name.trim().eq_ignore_ascii_case(season.show_name.trim()); + Ok(shows + .iter() + .find(same_id) + .or_else(|| shows.iter().find(same_name)) + .and_then(|s| s.path.clone())) +} + async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let peer = state.peer()?; let export_id = job.export_id.clone().context("no export")?; @@ -209,10 +303,14 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string()); jm_transfer::prepare_partial(&partial).await?; + let skip = job.skip_files.clone(); 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() { + if skip.contains(&idx) { + continue; + } 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); @@ -247,7 +345,7 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { } } job.progress.current_file = None; - job.note(format!("copied and verified {} files", files.len())); + job.note(format!("copied and verified {} files", files.len() - skip.len())); job.advance(Stage::Copied); Ok(()) } @@ -255,8 +353,14 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { 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())); + jm_transfer::promote(&partial, &target_local, &info(job)?.manifest, &job.skip_files).await?; + let placed = match &info(job)?.season { + Some(season) => target_local.join(&season.folder), + None => target_local.clone(), + }; + // A season changes the size of a show that may already be listed here. + crate::sizes::forget(state, &target_local).await; + job.note(format!("moved into {}", placed.display())); job.advance(Stage::Promoted); Ok(()) } @@ -322,16 +426,22 @@ async fn find_new_item( .iter() .find(|l| l.name == lib_name) .context("target library disappeared")?; + // A season's target is its show's folder: wait for the show, then for + // the season's episodes inside it. let kind = match info.kind { ItemKind::Movie => "Movie", - ItemKind::Series => "Series", + ItemKind::Series | ItemKind::Season => "Series", }; let matches = |p: &str| match info.kind { ItemKind::Movie => Path::new(p).parent() == Some(target), - ItemKind::Series => Path::new(p) == target, + ItemKind::Series | ItemKind::Season => 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 name = info + .season + .as_ref() + .map_or(info.name.as_str(), |s| s.show_name.as_str()); + for search in [Some(name), None] { let items = state .jellyfin .items(&ItemQuery { @@ -381,7 +491,7 @@ async fn missing_episodes( series_id: &str, info: &ExportInfo, ) -> anyhow::Result { - if info.kind != ItemKind::Series || info.episode_keys.is_empty() { + if !info.kind.has_episodes() || info.episode_keys.is_empty() { return Ok(0); } let found = episode_ids(state, series_id).await?; @@ -394,22 +504,46 @@ async fn missing_episodes( async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let info = info(job)?.clone(); + let (applied, no_item, missing) = apply_records(state, job, &info.user_data).await?; + job.note(format!("restored {applied} watch-state records")); + if !missing.is_empty() { + job.note(format!( + "skipped watch history for users missing on this server: {}. \ + Create them in Jellyfin, then use Re-apply watch history in Moves", + missing.join(", ") + )); + } + if no_item > 0 { + job.note(format!( + "skipped {no_item} records whose episode wasn't found" + )); + } + job.missing_users = missing; + job.advance(Stage::UserDataApplied); + Ok(()) +} + +/// Write `records` to the moved item and its episodes for every user who has +/// an account here. Returns (records applied, records whose episode wasn't +/// found, users with no account). +async fn apply_records( + state: &Shared, + job: &Job, + records: &[UserDataRecord], +) -> anyhow::Result<(usize, usize, Vec)> { + let info = info(job)?; let root_id = job.target_item_id.clone().context("no target item")?; - let episodes = if info.kind == ItemKind::Series { + let episodes = if info.kind.has_episodes() { episode_ids(state, &root_id).await? } else { HashMap::new() }; let users = state.jellyfin.users().await?; + let missing = missing_users(records, users.iter().map(|u| u.name.as_str())); - let (mut applied, mut no_user, mut no_item) = (0, 0, 0); - let mut unknown_users: Vec = Vec::new(); - for rec in &info.user_data { + let (mut applied, mut no_item) = (0, 0); + for rec in records { 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 { @@ -426,25 +560,68 @@ async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> { .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(", ") - )); + Ok((applied, no_item, missing)) +} + +/// After a move, apply the watch state of users who had no account here at +/// the time, once their accounts exist. Only their records are applied, so +/// anything other users have watched since is left alone. +pub async fn reapply_user_data(state: &Shared, mut job: Job) -> anyhow::Result { + if job.dry_run || job.status != JobStatus::Done { + bail!("watch history can only be re-applied to a finished move"); } - if no_item > 0 { - job.note(format!( - "skipped {no_item} records whose episode wasn't found" - )); + if job.missing_users.is_empty() { + bail!("this move has no skipped watch history to re-apply"); } - job.advance(Stage::UserDataApplied); - Ok(()) + let info = info(&job)?.clone(); + let root_id = job.target_item_id.clone().context("no target item")?; + if state.jellyfin.item(&root_id).await.is_err() { + bail!( + "{} is no longer where it was moved to on {} (moved again?), \ + so its watch history can't be re-applied", + job.name, + state.cfg.node_name + ); + } + let users = state.jellyfin.users().await?; + let records: Vec = info + .user_data + .iter() + .filter(|r| job.missing_users.iter().any(|m| same_user(m, &r.user_name))) + .cloned() + .collect(); + let still_missing = missing_users(&records, users.iter().map(|u| u.name.as_str())); + let here = &state.cfg.node_name; + if still_missing.len() == job.missing_users.len() { + bail!( + "there's no user called {} on {here} yet; create them in Jellyfin on {here} first", + still_missing.join(" or ") + ); + } + let (applied, no_item, missing) = apply_records(state, &job, &records).await?; + job.note(format!( + "re-applied {applied} watch-state records{}", + if no_item > 0 { + format!(" ({no_item} episodes not found)") + } else { + String::new() + } + )); + if !missing.is_empty() { + job.note(format!("still no user here called: {}", missing.join(", "))); + } + job.missing_users = missing; + state.save(&job).await?; + Ok(job) } 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?; + let req = crate::export::CompleteRequest { + job_id: Some(job.id.to_string()), + moved_to: Some(state.cfg.node_name.clone()), + }; + state.peer()?.complete_export(&export_id, &req).await?; job.note("source folder moved to its trash and source library rescanned"); job.advance(Stage::SourceCleaned); Ok(()) diff --git a/crates/jm-server/src/sizes.rs b/crates/jm-server/src/sizes.rs new file mode 100644 index 0000000..3a5d968 --- /dev/null +++ b/crates/jm-server/src/sizes.rs @@ -0,0 +1,321 @@ +//! Sizes of item folders on disk, for the library lists. +//! +//! Adding up a big library is slow on a NAS, so sizes are cached in the store +//! and worked out by a single background worker, one folder at a time. Listing +//! a library returns whatever is cached straight away and queues every folder +//! for checking; the UI asks again until every size has arrived. +//! +//! A cached size is trusted until the folder's *signature* changes (the +//! modified times of the folder and its direct subfolders, which change when +//! files are added, removed or renamed in them), and is measured again anyway +//! after [`MAX_AGE`] to catch changes deeper down. The signature itself is +//! only re-read every [`RECHECK`], so opening a library doesn't touch every +//! folder on disk each time. + +use std::collections::{HashSet, VecDeque}; +use std::hash::{Hash, Hasher}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use serde::{Deserialize, Serialize}; +use time::OffsetDateTime; + +use crate::state::{AppState, Shared}; + +/// How often a cached size's signature is checked against the disk. +pub const RECHECK: time::Duration = time::Duration::hours(1); +/// How long a size is trusted even if the signature hasn't changed. +pub const MAX_AGE: time::Duration = time::Duration::days(7); + +/// Size of an item folder: what a move would copy. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FolderSize { + pub bytes: u64, + pub files: u64, + /// Direct subfolders, e.g. a show's seasons or a movie's extras. Bytes in + /// files directly inside the folder are `bytes` minus these. + pub parts: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PartSize { + pub name: String, + pub bytes: u64, + pub files: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Record { + size: FolderSize, + signature: u64, + #[serde(with = "time::serde::rfc3339")] + measured_at: OffsetDateTime, + #[serde(with = "time::serde::rfc3339")] + checked_at: OffsetDateTime, +} + +#[derive(Default)] +pub struct SizeQueue { + inner: Mutex, +} + +#[derive(Default)] +struct QueueState { + queue: VecDeque, + queued: HashSet, + running: bool, +} + +/// Cached sizes for these local folders, in the same order (`None` where +/// nothing is cached yet). Every folder is queued for checking. +pub async fn lookup(state: &Shared, folders: &[PathBuf]) -> anyhow::Result>> { + let keys: Vec = folders.iter().map(|p| key(p)).collect(); + let mut cached: std::collections::HashMap = + state.store.get_folder_sizes(keys.clone()).await?; + enqueue(state, folders.iter().cloned()); + Ok(keys + .iter() + .map(|k| cached.remove(k).map(|r| r.size)) + .collect()) +} + +fn enqueue(state: &Shared, folders: impl IntoIterator) { + let mut q = state.sizes.inner.lock().expect("size queue"); + for f in folders { + if q.queued.insert(f.clone()) { + q.queue.push_back(f); + } + } + if !q.running && !q.queue.is_empty() { + q.running = true; + tokio::spawn(worker(state.clone())); + } +} + +/// One folder at a time, so a NAS isn't asked to walk several at once. +async fn worker(state: Shared) { + loop { + let next = { + let mut q = state.sizes.inner.lock().expect("size queue"); + match q.queue.pop_front() { + Some(p) => { + q.queued.remove(&p); + p + } + None => { + q.running = false; + return; + } + } + }; + if let Err(e) = refresh(&state, &next).await { + tracing::warn!(folder = %next.display(), error = %format!("{e:#}"), "could not measure folder"); + } + } +} + +async fn refresh(state: &Shared, folder: &Path) -> anyhow::Result<()> { + let k = key(folder); + let cached: Option = state + .store + .get_folder_sizes(vec![k.clone()]) + .await? + .remove(&k); + let now = OffsetDateTime::now_utc(); + if cached.as_ref().is_some_and(|r| now - r.checked_at < RECHECK) { + return Ok(()); + } + let f = folder.to_path_buf(); + let Some(sig) = tokio::task::spawn_blocking(move || signature(&f)).await? else { + // Gone, e.g. moved away. Forget it. + state.store.delete_folder_size(&k).await?; + return Ok(()); + }; + let record = match cached { + Some(mut r) if r.signature == sig && now - r.measured_at < MAX_AGE => { + r.checked_at = now; + r + } + _ => { + let f = folder.to_path_buf(); + let size = tokio::task::spawn_blocking(move || measure(&f)).await?; + Record { + size, + signature: sig, + measured_at: now, + checked_at: now, + } + } + }; + state.store.put_folder_size(&k, &record).await?; + Ok(()) +} + +/// Drop the cached size of a folder a move has just changed, so the next +/// listing measures it again instead of waiting for the hourly check. +pub async fn forget(state: &AppState, folder: &Path) { + if let Err(e) = state.store.delete_folder_size(&key(folder)).await { + tracing::warn!(folder = %folder.display(), error = %e, "could not forget folder size"); + } +} + +fn key(p: &Path) -> String { + p.to_string_lossy().into_owned() +} + +fn skipped(name: &std::ffi::OsStr) -> bool { + name.to_string_lossy().starts_with(jm_transfer::HIDDEN_PREFIX) +} + +/// Modified times of the folder and its direct subfolders, hashed. `None` if +/// the folder doesn't exist. +pub fn signature(folder: &Path) -> Option { + let meta = std::fs::symlink_metadata(folder).ok()?; + if !meta.is_dir() { + return None; + } + let mut h = std::collections::hash_map::DefaultHasher::new(); + meta.modified().ok().hash(&mut h); + let mut subdirs: Vec<(std::ffi::OsString, Option)> = + std::fs::read_dir(folder) + .ok()? + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !skipped(&e.file_name())) + .map(|e| (e.file_name(), e.metadata().and_then(|m| m.modified()).ok())) + .collect(); + subdirs.sort(); + subdirs.hash(&mut h); + Some(h.finish()) +} + +/// Add up every regular file below `folder`, counting the same files a move +/// copies: links and jellymove's own `.jellymove-*` entries are skipped. +pub fn measure(folder: &Path) -> FolderSize { + let mut total = PartSize { + name: String::new(), + bytes: 0, + files: 0, + }; + let mut parts = Vec::new(); + for e in std::fs::read_dir(folder).into_iter().flatten().flatten() { + if skipped(&e.file_name()) { + continue; + } + let Ok(t) = e.file_type() else { continue }; + if t.is_dir() { + let (bytes, files) = tree(&e.path()); + parts.push(PartSize { + name: e.file_name().to_string_lossy().into_owned(), + bytes, + files, + }); + total.bytes += bytes; + total.files += files; + } else if t.is_file() { + total.bytes += e.metadata().map(|m| m.len()).unwrap_or(0); + total.files += 1; + } + } + parts.sort_by_key(|p| natural_key(&p.name)); + FolderSize { + bytes: total.bytes, + files: total.files, + parts, + } +} + +fn tree(dir: &Path) -> (u64, u64) { + let mut bytes = 0; + let mut files = 0; + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).into_iter().flatten().flatten() { + if skipped(&e.file_name()) { + continue; + } + let Ok(t) = e.file_type() else { continue }; + if t.is_dir() { + stack.push(e.path()); + } else if t.is_file() { + bytes += e.metadata().map(|m| m.len()).unwrap_or(0); + files += 1; + } + } + } + (bytes, files) +} + +/// Sort "Season 2" before "Season 10". +fn natural_key(s: &str) -> Vec<(String, u64)> { + let mut out = Vec::new(); + let mut text = String::new(); + let mut num = String::new(); + for c in s.chars() { + if c.is_ascii_digit() { + num.push(c); + } else { + if !num.is_empty() { + out.push((std::mem::take(&mut text), num.parse().unwrap_or(u64::MAX))); + num.clear(); + } + text.extend(c.to_lowercase()); + } + } + out.push((text, num.parse().unwrap_or(0))); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(p: &Path, len: usize) { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, vec![0u8; len]).unwrap(); + } + + #[test] + fn measures_files_and_direct_subfolders() { + let tmp = tempfile::tempdir().unwrap(); + let show = tmp.path().join("Severance"); + write(&show.join("tvshow.nfo"), 10); + write(&show.join("Season 10/e.mkv"), 300); + write(&show.join("Season 2/e1.mkv"), 100); + write(&show.join("Season 2/e2.mkv"), 200); + write(&show.join("Season 2/subs/e1.srt"), 5); + write(&show.join(".jellymove-partial/x.part"), 999); + #[cfg(unix)] + std::os::unix::fs::symlink(show.join("Season 2/e1.mkv"), show.join("link.mkv")).unwrap(); + + let s = measure(&show); + assert_eq!((s.bytes, s.files), (615, 5)); + let parts: Vec<_> = s.parts.iter().map(|p| (p.name.as_str(), p.bytes, p.files)).collect(); + assert_eq!(parts, [("Season 2", 305, 3), ("Season 10", 300, 1)]); + } + + #[test] + fn signature_changes_when_a_season_changes() { + let tmp = tempfile::tempdir().unwrap(); + let show = tmp.path().join("Show"); + write(&show.join("Season 1/e1.mkv"), 1); + let before = signature(&show).unwrap(); + assert_eq!(signature(&show), Some(before)); + + // Adding an episode changes the season folder's modified time. + let s1 = show.join("Season 1"); + let old = std::fs::metadata(&s1).unwrap().modified().unwrap(); + write(&s1.join("e2.mkv"), 1); + let file = std::fs::File::open(&s1).unwrap(); + file.set_modified(old + std::time::Duration::from_secs(5)).unwrap(); + assert_ne!(signature(&show), Some(before)); + + assert_eq!(signature(&tmp.path().join("missing")), None); + } + + #[test] + fn natural_order() { + let mut v = vec!["Season 10", "Specials", "Season 2", "Season 1"]; + v.sort_by_key(|s| natural_key(s)); + assert_eq!(v, ["Season 1", "Season 2", "Season 10", "Specials"]); + } +} diff --git a/crates/jm-server/src/state.rs b/crates/jm-server/src/state.rs index 650eaa6..9822753 100644 --- a/crates/jm-server/src/state.rs +++ b/crates/jm-server/src/state.rs @@ -21,6 +21,8 @@ pub struct AppState { pub running: Mutex>, /// Exports currently being hashed, so a duplicate request doesn't start a second pass. pub preparing: Mutex>, + /// Folders waiting to have their size measured. + pub sizes: crate::sizes::SizeQueue, } pub type Shared = Arc; @@ -58,6 +60,7 @@ impl AppState { job_slots: Arc::new(Semaphore::new(slots)), running: Mutex::new(HashSet::new()), preparing: Mutex::new(HashSet::new()), + sizes: Default::default(), }) } diff --git a/crates/jm-server/src/trash.rs b/crates/jm-server/src/trash.rs new file mode 100644 index 0000000..55cb217 --- /dev/null +++ b/crates/jm-server/src/trash.rs @@ -0,0 +1,314 @@ +//! The source's trash. When a move finishes, the source renames the item's +//! folder to `/.jellymove-trash//` rather than +//! deleting it. Entries stay there until someone empties them from the UI. +//! +//! Each entry folder also holds a small metadata file describing the move. +//! Entries are only ever referred to by an opaque ID derived from their path, +//! and are resolved by scanning the trash folders, so neither the UI nor the +//! peer can name a path to delete. + +use std::path::{Path, PathBuf}; + +use anyhow::Context; +use jm_core::ItemKind; +use serde::{Deserialize, Serialize}; +use time::OffsetDateTime; + +use crate::library; +use crate::state::AppState; + +/// Folder inside each library location that holds the trash. +pub const TRASH_DIR: &str = ".jellymove-trash"; +/// Metadata file written into each entry folder. +pub const META_FILE: &str = ".jellymove-entry.json"; + +/// What the source records about a move when it trashes the folder. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EntryMeta { + pub name: String, + pub kind: ItemKind, + pub library: String, + /// The folder's path inside its library, e.g. `Alien (1979)`. + pub rel_folder: String, + #[serde(with = "time::serde::rfc3339")] + pub moved_at: OffsetDateTime, + /// Node the item was moved to. + pub moved_to: Option, + /// The job on that node that moved it. + pub job_id: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TrashEntry { + /// Opaque, stable while the entry exists. The only way to refer to it. + pub id: String, + pub name: String, + /// Missing for entries trashed before v0.2.0, which have no metadata. + pub kind: Option, + pub library: String, + pub folder: String, + #[serde(with = "time::serde::rfc3339::option")] + pub moved_at: Option, + pub moved_to: Option, + pub job_id: Option, + pub size: u64, + pub files: u64, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct EmptyResult { + pub removed: usize, + pub freed: u64, + /// IDs that weren't in the trash (already emptied, or never existed). + pub missing: Vec, +} + +struct Found { + entry: TrashEntry, + path: PathBuf, +} + +/// Pick a folder for a new entry under `trash_root`, starting with `base` and +/// adding `-2`, `-3`, ... if an item with the same ID was trashed before. +pub fn new_entry_dir(trash_root: &Path, base: &str) -> PathBuf { + let first = trash_root.join(base); + if std::fs::symlink_metadata(&first).is_err() { + return first; + } + (2u32..) + .map(|n| trash_root.join(format!("{base}-{n}"))) + .find(|p| std::fs::symlink_metadata(p).is_err()) + .expect("a free name exists") +} + +pub fn write_meta(entry_dir: &Path, meta: &EntryMeta) -> anyhow::Result<()> { + let json = serde_json::to_vec_pretty(meta)?; + std::fs::write(entry_dir.join(META_FILE), json) + .with_context(|| format!("writing trash metadata in {}", entry_dir.display())) +} + +/// Every entry in this node's trash, newest first. +pub async fn list(state: &AppState) -> anyhow::Result> { + Ok(scan(state).await?.into_iter().map(|f| f.entry).collect()) +} + +/// Delete the given entries for good. Unknown IDs are reported, not errors, +/// so emptying twice (e.g. from both UIs) is harmless. +pub async fn empty(state: &AppState, ids: &[String]) -> anyhow::Result { + let found = scan(state).await?; + let mut result = EmptyResult::default(); + let mut doomed = Vec::new(); + for id in ids { + match found.iter().find(|f| &f.entry.id == id) { + Some(f) => doomed.push((f.path.clone(), f.entry.size, f.entry.name.clone())), + None => result.missing.push(id.clone()), + } + } + for (path, size, name) in doomed { + // Belt and braces: scan only returns real folders directly inside a + // trash folder, but never delete anything else. + let in_trash = path + .parent() + .and_then(Path::file_name) + .is_some_and(|n| n == TRASH_DIR); + anyhow::ensure!(in_trash, "refusing to delete {}", path.display()); + let p = path.clone(); + tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&p)) + .await? + .with_context(|| format!("emptying {} from the trash", path.display()))?; + tracing::info!(item = %name, path = %path.display(), "emptied from trash"); + result.removed += 1; + result.freed += size; + } + Ok(result) +} + +async fn scan(state: &AppState) -> anyhow::Result> { + let mut roots: Vec<(String, PathBuf)> = Vec::new(); + for lib in library::libraries(state).await? { + for loc in &lib.locations { + let root = state.cfg.path_map.to_local(Path::new(loc)).join(TRASH_DIR); + if !roots.iter().any(|(_, r)| r == &root) { + roots.push((lib.name.clone(), root)); + } + } + } + let mut found = tokio::task::spawn_blocking(move || { + roots + .iter() + .flat_map(|(library, root)| scan_root(library, root)) + .collect::>() + }) + .await?; + found.sort_by_key(|f| std::cmp::Reverse(f.entry.moved_at)); + Ok(found) +} + +fn scan_root(library: &str, root: &Path) -> Vec { + // The trash folder itself must be a real folder, not a link elsewhere. + if !std::fs::symlink_metadata(root).is_ok_and(|m| m.is_dir()) { + return vec![]; + } + let Ok(rd) = std::fs::read_dir(root) else { + return vec![]; + }; + let mut out = Vec::new(); + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + // `.ignore` and anything else hidden is ours, not an entry. Links + // are skipped so emptying can't reach outside the trash. + if name.starts_with('.') || !e.file_type().is_ok_and(|t| t.is_dir()) { + continue; + } + let path = e.path(); + let meta: Option = std::fs::read(path.join(META_FILE)) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()); + let (size, files) = dir_size(&path); + let entry = match meta { + Some(m) => TrashEntry { + id: entry_id(&path), + name: m.name, + kind: Some(m.kind), + library: library.to_string(), + folder: m.rel_folder, + moved_at: Some(m.moved_at), + moved_to: m.moved_to, + job_id: m.job_id, + size, + files, + }, + None => { + // Trashed before metadata existed: the entry holds the + // folder at its path inside the library. + let folder = first_visible_child(&path).unwrap_or_else(|| name.clone()); + TrashEntry { + id: entry_id(&path), + name: folder.clone(), + kind: None, + library: library.to_string(), + folder, + moved_at: std::fs::metadata(&path) + .and_then(|m| m.modified()) + .ok() + .map(OffsetDateTime::from), + moved_to: None, + job_id: None, + size, + files, + } + } + }; + out.push(Found { entry, path }); + } + out +} + +fn first_visible_child(dir: &Path) -> Option { + std::fs::read_dir(dir) + .ok()? + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .find(|n| !n.starts_with('.')) +} + +/// Total bytes and file count below `dir`, not following links and not +/// counting the entry's metadata file. +fn dir_size(dir: &Path) -> (u64, u64) { + let mut bytes = 0; + let mut files = 0; + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { + continue; + }; + for e in rd.flatten() { + let Ok(t) = e.file_type() else { continue }; + if t.is_dir() { + stack.push(e.path()); + } else if t.is_file() && !(d == dir && e.file_name() == META_FILE) { + bytes += e.metadata().map(|m| m.len()).unwrap_or(0); + files += 1; + } + } + } + (bytes, files) +} + +fn entry_id(path: &Path) -> String { + let hash = blake3::hash(path.as_os_str().as_encoded_bytes()); + hash.to_hex()[..16].to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn new_entry_dir_avoids_existing_names() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1")); + std::fs::create_dir(root.join("item-1")).unwrap(); + assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1-2")); + std::fs::create_dir(root.join("item-1-2")).unwrap(); + assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1-3")); + } + + #[test] + fn scan_lists_entries_and_skips_links_and_hidden_files() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(TRASH_DIR); + let entry = root.join("item-1"); + std::fs::create_dir_all(entry.join("Alien (1979)/extras")).unwrap(); + std::fs::write(entry.join("Alien (1979)/Alien.mkv"), b"12345").unwrap(); + std::fs::write(entry.join("Alien (1979)/extras/x.mkv"), b"123").unwrap(); + write_meta( + &entry, + &EntryMeta { + name: "Alien".into(), + kind: ItemKind::Movie, + library: "Movies".into(), + rel_folder: "Alien (1979)".into(), + moved_at: OffsetDateTime::now_utc(), + moved_to: Some("home".into()), + job_id: Some("j1".into()), + }, + ) + .unwrap(); + // An old entry without metadata. + std::fs::create_dir_all(root.join("item-2/Heat (1995)")).unwrap(); + std::fs::write(root.join("item-2/Heat (1995)/Heat.mkv"), b"1").unwrap(); + std::fs::write(root.join(".ignore"), b"").unwrap(); + #[cfg(unix)] + { + let outside = tmp.path().join("outside"); + std::fs::create_dir(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("sneaky")).unwrap(); + } + + let mut found = scan_root("Movies", &root); + found.sort_by(|a, b| a.entry.name.cmp(&b.entry.name)); + let names: Vec<_> = found.iter().map(|f| f.entry.name.as_str()).collect(); + assert_eq!(names, ["Alien", "Heat (1995)"]); + let alien = &found[0].entry; + assert_eq!((alien.size, alien.files), (8, 2)); + assert_eq!(alien.moved_to.as_deref(), Some("home")); + assert_eq!(alien.kind, Some(ItemKind::Movie)); + assert_eq!(found[1].entry.kind, None); + assert!(found[1].entry.moved_at.is_some()); + assert_ne!(alien.id, found[1].entry.id); + } + + #[test] + fn scan_ignores_a_trash_folder_that_is_a_link() { + let tmp = tempfile::tempdir().unwrap(); + let real = tmp.path().join("elsewhere"); + std::fs::create_dir_all(real.join("item-1/Movie")).unwrap(); + #[cfg(unix)] + { + std::os::unix::fs::symlink(&real, tmp.path().join(TRASH_DIR)).unwrap(); + assert!(scan_root("Movies", &tmp.path().join(TRASH_DIR)).is_empty()); + } + } +} diff --git a/crates/jm-server/tests/e2e.rs b/crates/jm-server/tests/e2e.rs index 7b8b85f..aa195fe 100644 --- a/crates/jm-server/tests/e2e.rs +++ b/crates/jm-server/tests/e2e.rs @@ -375,6 +375,446 @@ async fn refuses_when_destination_exists() { 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 { + 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 moves_seasons_one_at_a_time_and_trashes_the_empty_show() { + let (cloud, home) = pair(seed_series).await; + 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})); + cloud + .fake + .set_user_data(&e3, json!({"PlaybackPositionTicks": 42})); + let series = cloud.fake.find("Series", "Severance").unwrap(); + cloud.fake.set_user_data(&series, json!({"IsFavorite": true})); + + // The UI lists the show's seasons with their folders. + let seasons = get( + &home.url, + &format!("/api/seasons?node=peer&series={series}"), + ) + .await; + assert_eq!(seasons[0]["name"], "Season 1"); + assert_eq!(seasons[0]["folder"], "Season 01"); + assert_eq!(seasons[1]["number"], 2); + + // List cloud's shows first so their sizes are cached. + items_with_sizes(&cloud.url, "node=local&library=lib-tv-shows").await; + + // Season 2 into a show home doesn't have yet: the show's NFO comes too. + let s2 = cloud.fake.season_id("Severance", 2).unwrap(); + assert_eq!(seasons[1]["id"], s2); + let job = move_item(&cloud.url, "local", &s2, "Season 2").await; + assert_eq!(job["name"], "Severance – Season 2"); + let show_home = home.tv().join("Severance"); + assert!(show_home.join("Season 02/Severance S02E01.mkv").exists()); + assert!(show_home.join("tvshow.nfo").exists()); + assert!(!show_home.join("Season 01").exists()); + // The source keeps the rest of the show. + let show_cloud = cloud.tv().join("Severance"); + assert!(!show_cloud.join("Season 02").exists()); + assert!(show_cloud.join("Season 01/Severance S01E01.mkv").exists()); + assert!(show_cloud.join("tvshow.nfo").exists()); + // Episode watch state followed; the season's show-level state didn't. + let new_e3 = home.fake.episode_id("Severance", 2, 1).unwrap(); + assert_eq!( + home.fake.get_user_data(&new_e3).unwrap()["PlaybackPositionTicks"], + 42 + ); + let home_series = home.fake.find("Series", "Severance").unwrap(); + assert!(home.fake.get_user_data(&home_series).is_none()); + + // The cached size of cloud's show was dropped, so it's measured again + // without waiting for the hourly check. + let shows = items_with_sizes(&cloud.url, "node=local&library=lib-tv-shows").await; + assert_eq!(shows[0]["size"]["bytes"], tree_size(&show_cloud)); + assert_eq!(shows[0]["size"]["parts"].as_array().unwrap().len(), 1); + + // Mark home's copy of the NFO so we can tell it isn't overwritten. + std::fs::write(show_home.join("tvshow.nfo"), b"home's own").unwrap(); + items_with_sizes(&home.url, "node=local&library=lib-tv-shows").await; + + // Season 1 joins the existing show, and was the last one on cloud. + let s1 = cloud.fake.season_id("Severance", 1).unwrap(); + let job = move_item(&home.url, "peer", &s1, "Season 1").await; + assert!( + job["log"] + .as_array() + .unwrap() + .iter() + .any(|l| l.as_str().unwrap().contains("adding to the show already here")), + "{job:#}" + ); + assert!(show_home.join("Season 01/Severance S01E02.mkv").exists()); + assert_eq!(std::fs::read(show_home.join("tvshow.nfo")).unwrap(), b"home's own"); + // Home's show grew, and its size says so straight away. + let shows = items_with_sizes(&home.url, "node=local&library=lib-tv-shows").await; + assert_eq!(shows[0]["size"]["bytes"], tree_size(&show_home)); + assert_eq!(shows[0]["size"]["parts"].as_array().unwrap().len(), 2); + let new_e1 = home.fake.episode_id("Severance", 1, 1).unwrap(); + assert_eq!(home.fake.get_user_data(&new_e1).unwrap()["Played"], true); + + // Nothing is left of the show on cloud: its NFO went to the trash with + // the last season. + assert!(!show_cloud.exists()); + let trash = get(&cloud.url, "/api/trash?node=local").await; + let entries = trash.as_array().unwrap(); + assert_eq!(entries.len(), 2, "{trash:#}"); + let last = entries + .iter() + .find(|e| e["name"] == "Severance – Season 1") + .unwrap(); + assert_eq!(last["kind"], "Season"); + assert_eq!(last["folder"], "Severance/Season 01"); + assert_eq!(last["files"], 3); +} + +#[tokio::test] +async fn refuses_a_season_the_destination_already_has() { + let (cloud, home) = pair(seed_series).await; + write( + &home.tv().join("Severance/Season 02/Severance S02E01.mkv"), + b"home's copy", + ); + home.fake.scan(); + let s2 = cloud.fake.season_id("Severance", 2).unwrap(); + let job: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": s2, "name": "Season 2"}), + ) + .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"), + "{done:#}" + ); + assert_eq!( + std::fs::read(home.tv().join("Severance/Season 02/Severance S02E01.mkv")).unwrap(), + b"home's copy" + ); + assert!(cloud.tv().join("Severance/Season 02").exists()); +} + +#[tokio::test] +async fn refuses_a_season_folder_holding_other_seasons() { + let (cloud, _home) = pair(|root| { + seed_series(root); + // A season 3 episode filed in the Season 02 folder. + write( + &root.join("tv/Severance/Season 02/Severance S03E01.mkv"), + b"misfiled", + ); + }) + .await; + let s2 = cloud.fake.season_id("Severance", 2).unwrap(); + let job: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": s2, "name": "Season 2"}), + ) + .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("aren't its episodes"), + "{done:#}" + ); +} + +#[tokio::test] +async fn warns_about_missing_users_and_reapplies_their_watch_state_later() { + let (cloud, home) = pair(seed_movie).await; + // Cloud has a second user, Bob, whom home doesn't know yet. + cloud.fake.add_user("u2", "Bob"); + let movie = cloud.fake.find("Movie", "Alien").unwrap(); + cloud.fake.set_user_data(&movie, json!({"Played": true})); + cloud + .fake + .set_user_data_for("u2", &movie, json!({"PlaybackPositionTicks": 777})); + + // Before moving, the UI can see whose watch history won't carry over, + // whichever side it asks from. + let check = get( + &cloud.url, + &format!("/api/moves/check?from=local&item_id={movie}"), + ) + .await; + assert_eq!(check["watchers"], json!(["Alice", "Bob"])); + assert_eq!(check["missing_users"], json!(["Bob"])); + let check = get( + &home.url, + &format!("/api/moves/check?from=peer&item_id={movie}"), + ) + .await; + assert_eq!(check["missing_users"], json!(["Bob"])); + + // A dry run says so too. + let dry: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": movie, "name": "Alien", "dry_run": true}), + ) + .await + .json() + .await + .unwrap(); + let dry = wait_job(&cloud.url, dry["id"].as_str().unwrap()).await; + assert_eq!(dry["status"]["kind"], "Planned"); + assert_eq!(dry["missing_users"], json!(["Bob"])); + assert!( + dry["log"] + .as_array() + .unwrap() + .iter() + .any(|l| l.as_str().unwrap().contains("won't carry over for Bob")), + "{dry:#}" + ); + + // The move goes ahead; Alice's watch state follows, Bob's is kept. + let job = move_item(&cloud.url, "local", &movie, "Alien").await; + assert_eq!(job["missing_users"], json!(["Bob"])); + let new_id = home.fake.find("Movie", "Alien").unwrap(); + assert_eq!(home.fake.get_user_data(&new_id).unwrap()["Played"], true); + let id = job["id"].as_str().unwrap(); + + // Re-applying before Bob has an account explains what to do. + let r = post(&cloud.url, &format!("/api/jobs/{id}/reapply"), json!({})).await; + assert!(!r.status().is_success()); + let text = r.text().await.unwrap(); + assert!( + text.contains("no user called Bob on home yet; create them in Jellyfin on home first"), + "{text}" + ); + assert!(!text.contains("HTTP 502"), "{text}"); + + // Alice carries on watching on home in the meantime. + home.fake + .set_user_data(&new_id, json!({"Played": true, "PlayCount": 5})); + + // Once home has a "bob" (names match ignoring case), re-apply from the + // cloud UI: the job runs on home, so the request is passed on. + home.fake.add_user("u9", "bob"); + let r = post(&cloud.url, &format!("/api/jobs/{id}/reapply"), json!({})).await; + assert!(r.status().is_success(), "{}", r.text().await.unwrap()); + let job: Value = r.json().await.unwrap(); + assert_eq!(job["missing_users"], json!([])); + assert_eq!( + home.fake.get_user_data_for("u9", &new_id).unwrap()["PlaybackPositionTicks"], + 777 + ); + // Alice's newer watch state wasn't overwritten by the old snapshot. + assert_eq!(home.fake.get_user_data(&new_id).unwrap()["PlayCount"], 5); + + // Nothing left to re-apply. + let r = post(&home.url, &format!("/api/jobs/{id}/reapply"), json!({})).await; + assert!(r.text().await.unwrap().contains("no skipped watch history")); +} + #[tokio::test] async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() { let (cloud, _home) = pair(|_| {}).await; diff --git a/crates/jm-server/tests/fake_jellyfin/mod.rs b/crates/jm-server/tests/fake_jellyfin/mod.rs index c9f12c4..200adb1 100644 --- a/crates/jm-server/tests/fake_jellyfin/mod.rs +++ b/crates/jm-server/tests/fake_jellyfin/mod.rs @@ -34,7 +34,10 @@ struct FakeItem { kind: &'static str, path: String, parent: String, + /// The series a season or episode belongs to. + series: Option, season: Option, + /// Episode number, or a season's own number. episode: Option, } @@ -44,6 +47,8 @@ pub struct Fake { items: Arc>>, /// (user id, item id) → UserData JSON pub user_data: Arc>>, + /// (user id, name) + users: Arc>>, } pub fn id_for(path: &Path) -> String { @@ -100,6 +105,7 @@ impl Fake { libs: Arc::new(libs), items: Default::default(), user_data: Default::default(), + users: Arc::new(Mutex::new(vec![("u1".into(), "Alice".into())])), }; f.scan(); f @@ -133,6 +139,7 @@ impl Fake { kind: "Movie", path: f.display().to_string(), parent: lib.id(), + series: None, season: None, episode: None, }); @@ -145,25 +152,74 @@ impl Fake { kind: "Series", path: folder.display().to_string(), parent: lib.id(), + series: None, season: None, episode: None, }); + // Like Jellyfin: a season per season folder, holding its + // episodes; episodes loose in the show folder hang off + // the series. + let mut seasons: Vec<(PathBuf, i32, String)> = Vec::new(); 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), - }); - } + let Some((s, e)) = parse_sxxexx(&fname) else { + continue; + }; + let in_folder = f + .strip_prefix(&folder) + .ok() + .and_then(|r| r.components().next()) + .map(|c| folder.join(c)) + .filter(|p| p.is_dir()); + // The folder name gives the season's number ("Season 02", + // "Specials"); an episode filed under the wrong season + // doesn't belong to it. + let folder_number = |p: &Path| { + let n = p.file_name()?.to_string_lossy().to_lowercase(); + if n == "specials" { + return Some(0); + } + n.chars() + .filter(|c| c.is_ascii_digit()) + .collect::() + .parse::() + .ok() + }; + let parent = match in_folder { + Some(season_folder) if folder_number(&season_folder) == Some(s) => { + let id = id_for(&season_folder); + if !seasons.iter().any(|(p, _, _)| p == &season_folder) { + seasons.push((season_folder, s, id.clone())); + } + id + } + _ => series_id.clone(), + }; + items.push(FakeItem { + id: id_for(f), + name: fname.to_string(), + kind: "Episode", + path: f.display().to_string(), + parent, + series: Some(series_id.clone()), + season: Some(s), + episode: Some(e), + }); + } + for (path, n, id) in seasons { + items.push(FakeItem { + id, + name: if n == 0 { "Specials".into() } else { format!("Season {n}") }, + kind: "Season", + path: path.display().to_string(), + parent: series_id.clone(), + series: Some(series_id.clone()), + season: None, + episode: Some(n), + }); } } } @@ -186,10 +242,44 @@ impl Fake { .lock() .unwrap() .iter() - .find(|i| i.parent == series_id && i.season == Some(season) && i.episode == Some(ep)) + .find(|i| { + i.kind == "Episode" + && i.series.as_deref() == Some(&series_id) + && i.season == Some(season) + && i.episode == Some(ep) + }) .map(|i| i.id.clone()) } + pub fn season_id(&self, series: &str, season: i32) -> Option { + let series_id = self.find("Series", series)?; + self.items + .lock() + .unwrap() + .iter() + .find(|i| i.kind == "Season" && i.parent == series_id && i.episode == Some(season)) + .map(|i| i.id.clone()) + } + + pub fn add_user(&self, id: &str, name: &str) { + self.users.lock().unwrap().push((id.into(), name.into())); + } + + pub fn set_user_data_for(&self, user: &str, item: &str, data: Value) { + self.user_data + .lock() + .unwrap() + .insert((user.into(), item.into()), data); + } + + pub fn get_user_data_for(&self, user: &str, item: &str) -> Option { + self.user_data + .lock() + .unwrap() + .get(&(user.to_string(), item.to_string())) + .cloned() + } + pub fn set_user_data(&self, item: &str, data: Value) { self.user_data .lock() @@ -213,10 +303,7 @@ impl Fake { Json(json!({"ServerName": "fake", "Version": "10.11.0", "Id": "x"})) }), ) - .route( - "/Users", - get(|| async { Json(json!([{"Id": "u1", "Name": "Alice"}])) }), - ) + .route("/Users", get(users)) .route("/Library/VirtualFolders", get(virtual_folders)) .route("/Items", get(items)) .route("/Library/Media/Updated", post(media_updated)) @@ -229,6 +316,17 @@ impl Fake { } } +async fn users(State(f): State) -> Json { + Json(Value::Array( + f.users + .lock() + .unwrap() + .iter() + .map(|(id, name)| json!({"Id": id, "Name": name})) + .collect(), + )) +} + async fn virtual_folders(State(f): State) -> Json { Json(Value::Array( f.libs @@ -250,7 +348,14 @@ async fn items(State(f): State, Query(q): Query>) let out: Vec = 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| { + // Recursive queries under a series also reach its episodes, + // which hang off their seasons. + let recursive = q.get("recursive").is_some_and(|r| r == "true"); + q.get("parentId").is_none_or(|p| { + &i.parent == p || (recursive && i.series.as_deref() == Some(p.as_str())) + }) + }) .filter(|i| types.as_ref().is_none_or(|t| t.contains(&i.kind))) .filter(|i| { q.get("searchTerm") @@ -258,7 +363,7 @@ async fn items(State(f): State, Query(q): Query>) }) .map(|i| { let mut v = json!({"Id": i.id, "Name": i.name, "Type": i.kind, "Path": i.path, - "ParentIndexNumber": i.season, "IndexNumber": i.episode, + "ParentIndexNumber": i.season, "IndexNumber": i.episode, "SeriesId": i.series, "MediaSources": [{"Path": i.path}]}); if let Some(u) = user { v["UserData"] = ud diff --git a/crates/jm-store/Cargo.toml b/crates/jm-store/Cargo.toml index 998676c..d24dd2e 100644 --- a/crates/jm-store/Cargo.toml +++ b/crates/jm-store/Cargo.toml @@ -6,7 +6,7 @@ license.workspace = true rust-version.workspace = true [dependencies] -jm-core = { version = "0.1.0", path = "../jm-core" } +jm-core = { path = "../jm-core" } rusqlite = { version = "0.40.2", features = ["bundled"] } serde = "1.0.229" serde_json = "1.0.154" diff --git a/crates/jm-store/src/lib.rs b/crates/jm-store/src/lib.rs index 440cc3c..ea6aeb0 100644 --- a/crates/jm-store/src/lib.rs +++ b/crates/jm-store/src/lib.rs @@ -3,6 +3,7 @@ //! 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::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex}; @@ -33,6 +34,11 @@ const MIGRATIONS: &[&str] = &[ id TEXT PRIMARY KEY, body TEXT NOT NULL );", + // v2: cached sizes of item folders, keyed by local path. + "CREATE TABLE folder_sizes ( + path TEXT PRIMARY KEY, + body TEXT NOT NULL + );", ]; #[derive(Clone)] @@ -161,6 +167,54 @@ impl Store { body.map(|b| serde_json::from_str(&b).map_err(Into::into)) .transpose() } + + /// Cached folder sizes for `paths`. Paths with no record are left out. + pub async fn get_folder_sizes( + &self, + paths: Vec, + ) -> Result> { + let rows: Vec<(String, String)> = self + .with(move |c| { + let mut out = Vec::new(); + let mut stmt = c.prepare_cached("SELECT path, body FROM folder_sizes WHERE path = ?1")?; + for p in &paths { + if let Some(row) = stmt + .query_row([p], |r| Ok((r.get(0)?, r.get(1)?))) + .optional()? + { + out.push(row); + } + } + Ok(out) + }) + .await?; + rows.into_iter() + .map(|(p, b)| Ok((p, serde_json::from_str(&b)?))) + .collect() + } + + pub async fn put_folder_size(&self, path: &str, size: &T) -> Result<()> { + let path = path.to_string(); + let body = serde_json::to_string(size)?; + self.with(move |c| { + c.execute( + "INSERT INTO folder_sizes (path, body) VALUES (?1, ?2) + ON CONFLICT(path) DO UPDATE SET body = excluded.body", + params![path, body], + )?; + Ok(()) + }) + .await + } + + pub async fn delete_folder_size(&self, path: &str) -> Result<()> { + let path = path.to_string(); + self.with(move |c| { + c.execute("DELETE FROM folder_sizes WHERE path = ?1", [path])?; + Ok(()) + }) + .await + } } #[cfg(test)] @@ -205,4 +259,50 @@ mod tests { let e: serde_json::Value = s.get_export("e1").await.unwrap().unwrap(); assert_eq!(e["x"], 1); } + + #[tokio::test] + async fn folder_sizes_roundtrip() { + let store = Store::in_memory().unwrap(); + store + .put_folder_size("/m/A", &serde_json::json!({"bytes": 1})) + .await + .unwrap(); + store + .put_folder_size("/m/A", &serde_json::json!({"bytes": 2})) + .await + .unwrap(); + store + .put_folder_size("/m/B", &serde_json::json!({"bytes": 3})) + .await + .unwrap(); + let got: HashMap = store + .get_folder_sizes(vec!["/m/A".into(), "/m/B".into(), "/m/C".into()]) + .await + .unwrap(); + assert_eq!(got.len(), 2); + assert_eq!(got["/m/A"]["bytes"], 2); + store.delete_folder_size("/m/A").await.unwrap(); + let got: HashMap = + store.get_folder_sizes(vec!["/m/A".into()]).await.unwrap(); + assert!(got.is_empty()); + } + + #[test] + fn upgrades_a_v1_database() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("state.db"); + { + let c = Connection::open(&path).unwrap(); + c.execute_batch(MIGRATIONS[0]).unwrap(); + c.pragma_update(None, "user_version", 1).unwrap(); + } + Store::open(&path).unwrap(); + let c = Connection::open(&path).unwrap(); + let v: i64 = c + .pragma_query_value(None, "user_version", |r| r.get(0)) + .unwrap(); + assert_eq!(v as usize, MIGRATIONS.len()); + c.execute("INSERT INTO folder_sizes (path, body) VALUES ('p', '{}')", []) + .unwrap(); + } } diff --git a/crates/jm-transfer/Cargo.toml b/crates/jm-transfer/Cargo.toml index 3029129..b83a00a 100644 --- a/crates/jm-transfer/Cargo.toml +++ b/crates/jm-transfer/Cargo.toml @@ -11,7 +11,7 @@ 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" } +jm-core = { 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" diff --git a/crates/jm-transfer/src/lib.rs b/crates/jm-transfer/src/lib.rs index 9046b62..17c8e36 100644 --- a/crates/jm-transfer/src/lib.rs +++ b/crates/jm-transfer/src/lib.rs @@ -12,7 +12,7 @@ pub mod promote; pub mod pull; pub mod serve; -pub use manifest::{build_manifest, hash_file, list_relative}; +pub use manifest::{build_manifest, build_manifest_filtered, hash_file, list_relative}; pub use promote::{part_path, partial_dir, prepare_partial, promote}; pub use pull::{Puller, PullerOptions}; pub use serve::range_response; diff --git a/crates/jm-transfer/src/manifest.rs b/crates/jm-transfer/src/manifest.rs index 4341df1..9f0005d 100644 --- a/crates/jm-transfer/src/manifest.rs +++ b/crates/jm-transfer/src/manifest.rs @@ -20,10 +20,21 @@ pub async fn hash_file(path: &Path) -> Result { /// them sorted by relative path. Symlinks and jellymove's own hidden folders /// are skipped. pub async fn build_manifest(root: &Path) -> Result { + build_manifest_filtered(root, |_| true).await +} + +/// Like [`build_manifest`], but only for files whose relative path passes +/// `keep`, e.g. one season's folder plus the show's loose files. +pub async fn build_manifest_filtered( + root: &Path, + keep: impl Fn(&str) -> bool + Send + 'static, +) -> Result { let root_owned = root.to_path_buf(); - let listed = tokio::task::spawn_blocking(move || list_files(&root_owned)) - .await - .expect("list task panicked")?; + let listed = tokio::task::spawn_blocking(move || { + list_files(&root_owned).map(|l| l.into_iter().filter(|(rel, _, _)| keep(rel)).collect::>()) + }) + .await + .expect("list task panicked")?; let mut files = Vec::with_capacity(listed.len()); for (rel, abs, size) in listed { @@ -101,4 +112,21 @@ mod tests { blake3::hash(b"video").to_hex().to_string() ); } + + #[tokio::test] + async fn filtered_manifest_keeps_only_matching_files() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + for f in ["tvshow.nfo", "Season 01/a.mkv", "Season 02/b.mkv"] { + std::fs::create_dir_all(root.join(f).parent().unwrap()).unwrap(); + std::fs::write(root.join(f), b"x").unwrap(); + } + let m = build_manifest_filtered(root, |rel| { + !rel.contains('/') || rel.starts_with("Season 02/") + }) + .await + .unwrap(); + let names: Vec<_> = m.files.iter().map(|f| f.rel_path.as_str()).collect(); + assert_eq!(names, ["Season 02/b.mkv", "tvshow.nfo"]); + } } diff --git a/crates/jm-transfer/src/promote.rs b/crates/jm-transfer/src/promote.rs index cdf7e02..6aff92d 100644 --- a/crates/jm-transfer/src/promote.rs +++ b/crates/jm-transfer/src/promote.rs @@ -29,16 +29,25 @@ pub async fn prepare_partial(partial: &Path) -> Result<(), TransferError> { Ok(()) } -/// Rename every verified `.part` into `target_folder`. Safe to run again after +/// Rename every verified `.part` into `target_folder`, except the manifest +/// entries listed in `skip` (which were never copied). 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, + skip: &[usize], ) -> Result<(), TransferError> { + let wanted = || { + manifest + .files + .iter() + .enumerate() + .filter(|(idx, _)| !skip.contains(idx)) + }; // Check every destination first so we never half-promote into a clash. - for (idx, entry) in manifest.files.iter().enumerate() { + for (idx, entry) in wanted() { 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(); @@ -47,7 +56,7 @@ pub async fn promote( } } - for (idx, entry) in manifest.files.iter().enumerate() { + for (idx, entry) in wanted() { let part = part_path(partial, idx); let dest = join_relative(target_folder, &entry.rel_path).expect("checked above"); match tokio::fs::metadata(&part).await { diff --git a/crates/jm-transfer/tests/transfer.rs b/crates/jm-transfer/tests/transfer.rs index 19ba3ba..c4b356b 100644 --- a/crates/jm-transfer/tests/transfer.rs +++ b/crates/jm-transfer/tests/transfer.rs @@ -119,7 +119,7 @@ async fn pull_all(fx: &Fixture, p: &Puller) -> PathBuf { .unwrap(); } let target = lib_root.join("Alien (1979)"); - promote(&partial, &target, &manifest).await.unwrap(); + promote(&partial, &target, &manifest, &[]).await.unwrap(); target } @@ -200,7 +200,7 @@ async fn refuses_to_overwrite_existing_files() { .await .unwrap(); } - let err = promote(&partial, &target, &manifest).await.unwrap_err(); + 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!( @@ -216,11 +216,43 @@ async fn promote_is_idempotent() { 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) + promote(&partial_dir(fx.dst_dir.path(), "job1"), &target, &manifest, &[]) .await .unwrap(); } +#[tokio::test] +async fn promote_leaves_skipped_files_alone() { + let fx = fixture().await; + let manifest = build_manifest(&fx.src.root).await.unwrap(); + let nfo = manifest + .files + .iter() + .position(|f| f.rel_path == "Alien (1979).nfo") + .unwrap(); + // The target already has its own NFO; that entry is skipped and never copied. + 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"mine").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() { + if idx == nfo { + continue; + } + let url = format!("{}/files/{idx}", fx.base); + p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {}) + .await + .unwrap(); + } + promote(&partial, &target, &manifest, &[nfo]).await.unwrap(); + assert_eq!(std::fs::read(target.join("Alien (1979).nfo")).unwrap(), b"mine"); + assert!(target.join("Alien (1979).mkv").exists()); + // And it's still idempotent. + promote(&partial, &target, &manifest, &[nfo]).await.unwrap(); +} + #[tokio::test] async fn bandwidth_limit_is_applied() { let fx = fixture().await; diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index e23542d..21ff552 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -14,12 +14,29 @@ services: ports: - "8097:8097" volumes: - - ./jellymove.toml:/config/jellymove.toml:ro - ./jellymove-data:/data # must be writable by `user:` above - /srv/media/movies:/media/movies # ← match your jellyfin service - /srv/media/tv:/media/tv + # Every setting in config.example.toml works here as JELLYMOVE_, with + # "__" between a section and its key. A value made only of digits needs + # inner quotes ('"123456"'), or it's read as a number. To keep secrets out + # of this file, put them in a .env file next to it and write ${NAME} here. environment: - # Secrets can come from the environment instead of the file: - # JELLYMOVE_JELLYFIN__API_KEY: ... - # JELLYMOVE_PEER__TOKEN: ... + JELLYMOVE_NODE_NAME: home + JELLYMOVE_DATA_DIR: /data # the jellymove-data volume above + JELLYMOVE_JELLYFIN__URL: http://jellyfin:8096 + # Jellyfin → Dashboard → API Keys. Needs an admin key. + JELLYMOVE_JELLYFIN__API_KEY: replace-me + # The other agent. Both sides use the same token (openssl rand -hex 32). + JELLYMOVE_PEER__URL: https://cloud.example.com + JELLYMOVE_PEER__TOKEN: replace-me + # Protect the web UI unless the port is only reachable privately. + JELLYMOVE_UI__USERNAME: admin + JELLYMOVE_UI__PASSWORD: replace-me JELLYMOVE_LOG: info + # Optional. Incoming cap in megabits per second (0 = unlimited): + # JELLYMOVE_TRANSFER__BANDWIDTH_LIMIT_MBPS: 200 + # Optional. File items from the peer's "TV Shows" library into "Series": + # JELLYMOVE_INCOMING_LIBRARIES: '{"TV Shows"="Series"}' + # Optional. Only if jellymove sees media at different paths from Jellyfin: + # JELLYMOVE_PATH_MAP: '[{jellyfin="/media",local="/mnt/user/media"}]' diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0289615..35f73ce 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -35,11 +35,15 @@ forwarding. |---|---| | `GET /info` | Node name, version, Jellyfin version | | `GET /libraries`, `GET /items?library=&search=` | Browse the peer's Jellyfin | +| `GET /seasons?series=` | A show's seasons, with each one's folder if it has its own | +| `GET /users`, `GET /watchers?item=` | User names; users with watch state for an item. Used to warn before a move whose watch history wouldn't carry over | | `POST /exports {item_id}` | Source: start checking, hashing and capturing user data. Idempotent per item. | | `GET /exports/{id}` | Poll: `Preparing` → `Ready` (with `ExportInfo`) or `Failed` | | `GET /exports/{id}/files/{idx}` | Range-capable download of manifest entry `idx` | -| `POST /exports/{id}/complete` | Source: move folder to trash and rescan. Idempotent. | +| `POST /exports/{id}/complete {job_id?, moved_to?}` | Source: move folder to a new trash entry and rescan. Idempotent. | +| `GET /trash`, `POST /trash/empty {ids}` | List the source's trash entries; delete entries by ID (never by path) | | `POST /jobs`, `GET /jobs` | Create or list jobs on the peer (destination) | +| `POST /jobs/{id}/reapply` | Apply the watch state of users who had no account when the move ran (`Job.missing_users`), once they do | ## Job stages @@ -67,11 +71,29 @@ Retrying a failed job re-runs from its stage. Interrupted jobs resume on start. - Alternatives kept open behind the pull/serve split: iroh (QUIC, NAT traversal) once iroh-blobs reaches 1.0; rclone as a pluggable transport. +## Folder sizes + +Library items carry the size of their folder on disk, counting the same files a +move copies. Each agent measures its own folders (`sizes.rs`): listing a library +returns cached sizes at once and queues every folder for a single background +worker, so a NAS is never asked to walk several folders at once. A cached size +is kept while the folder's signature (modified times of the folder and its +direct subfolders) is unchanged, re-checked at most hourly, and measured again +after seven days regardless. The UI polls the list until every size is in. + ## Jellyfin integration - Browse: `GET /Items?parentId=&includeItemTypes=Movie,Series&recursive=true&fields=Path,…` - Folder: a movie's parent folder, or a series' own folder. It must sit strictly inside a library location. A movie folder must contain no other main videos. +- Seasons: `includeItemTypes=Season` under the series. A season export's folder + is the show's; its manifest holds only `/…` plus the show's + loose non-video files (`SeasonInfo.show_files`). The destination finds the + show by provider ID, then name, and skips those show files if it already has + the show. A season's own user data isn't carried (it would land on the + whole show); its episodes' is. After the last season leaves, the source + moves what remains of the show folder into the same trash entry, but only if + no videos are left in it. - Rescan: `POST /Library/Media/Updated` for the exact folder, then poll. The first update can be lost, so it is re-sent halfway through the timeout. - Finding the new item: by **path**, since we know exactly where we put it. diff --git a/ui/src/App.svelte b/ui/src/App.svelte index c60f623..111025a 100644 --- a/ui/src/App.svelte +++ b/ui/src/App.svelte @@ -4,8 +4,10 @@ import Library from './lib/Library.svelte'; import Jobs from './lib/Jobs.svelte'; import StatusView from './lib/StatusView.svelte'; + import Trash from './lib/Trash.svelte'; + import { watchMoves } from './lib/moves.svelte'; - type Tab = 'library' | 'jobs' | 'status'; + type Tab = 'library' | 'jobs' | 'trash' | 'status'; let tab = $state('library'); let status = $state(null); let statusError = $state(null); @@ -22,7 +24,11 @@ onMount(() => { loadStatus(); const t = setInterval(loadStatus, 30_000); - return () => clearInterval(t); + const stopWatching = watchMoves(); + return () => { + clearInterval(t); + stopWatching(); + }; }); const localName = $derived(status?.node.node_name ?? 'this server'); @@ -48,6 +54,7 @@