diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..bf14d03 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +target +ui/node_modules +ui/dist +data +.git +.claude +**/.DS_Store +jellymove.toml +cloud.toml +home.toml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8879deb --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,15 @@ +name: CI +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: 22, cache: npm, cache-dependency-path: ui/package-lock.json } + - run: npm --prefix ui ci && npm --prefix ui run check && npm --prefix ui run build + - uses: dtolnay/rust-toolchain@stable + with: { components: clippy } + - uses: Swatinem/rust-cache@v2 + - run: cargo clippy --workspace --all-targets -- -D warnings + - run: cargo test --workspace diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..3ab8532 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,77 @@ +name: Release + +# Push a tag such as v0.1.0 to build a static Linux binary (web UI included) +# and publish it as a Gitea release. The tag must match the version in +# Cargo.toml's [workspace.package]. +# +# Written for Gitea Actions (act_runner). It lives in .github/workflows so the +# CI workflow next to it keeps running too: Gitea ignores .github/workflows +# once a .gitea/workflows folder exists. +on: + push: + tags: ["v*"] + +permissions: + contents: write + +env: + TARGET: x86_64-unknown-linux-musl + ZIG_VERSION: 0.17.0 + CARGO_TERM_COLOR: always + CARGO_PROFILE_RELEASE_STRIP: symbols + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Check the tag matches Cargo.toml + run: | + version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n1) + if [ "$GITHUB_REF_NAME" != "v$version" ]; then + echo "::error::Tag $GITHUB_REF_NAME doesn't match Cargo.toml version $version. Bump the version or fix the tag." + exit 1 + fi + + - uses: actions/setup-node@v4 + with: { node-version: 22, cache: npm, cache-dependency-path: ui/package-lock.json } + - name: Build the UI + run: | + npm --prefix ui ci + npm --prefix ui run check + npm --prefix ui run build + test -f ui/dist/index.html + + - uses: dtolnay/rust-toolchain@stable + with: { targets: "${{ env.TARGET }}" } + - uses: mlugg/setup-zig@v2 + with: { version: "${{ env.ZIG_VERSION }}" } + - uses: taiki-e/install-action@v2 + with: { tool: cargo-zigbuild } + - uses: Swatinem/rust-cache@v2 + with: { key: "${{ env.TARGET }}" } + + - name: Test + run: cargo test --workspace --locked + + # musl + zig gives one static binary with no glibc version to match on + # the server. + - name: Build + run: cargo zigbuild --release --locked --target "$TARGET" -p jellymove + + - name: Package + run: | + name="jellymove-$GITHUB_REF_NAME-$TARGET" + mkdir -p "dist/$name" + cp "target/$TARGET/release/jellymove" deploy/jellymove.service \ + config.example.toml README.md "dist/$name/" + "dist/$name/jellymove" --version + tar -C dist -czf "dist/$name.tar.gz" "$name" + (cd dist && sha256sum "$name.tar.gz" > "$name.tar.gz.sha256") + echo "ASSET=dist/$name.tar.gz" >> "$GITHUB_ENV" + + - name: Publish the release + env: + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: node .github/scripts/gitea-release.mjs "$GITHUB_REF_NAME" "$ASSET" "$ASSET.sha256" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..03161f5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/target +/data +jellymove.toml +cloud.toml +home.toml +ui/node_modules +ui/dist +.DS_Store +.claude/settings.local.json diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..73985a1 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,87 @@ +# CLAUDE.md + +Guidance for Claude Code (and humans) working in this repo. + +## What this is + +jellymove moves movies and TV series between two separate Jellyfin servers +(e.g. a fast-but-small cloud box and a slow-but-big home NAS, federated by +Jellyswarrm). One agent runs next to each Jellyfin. The **destination pulls** +from the source over HTTP range requests, verifies with BLAKE3, renames into +its library, waits for Jellyfin to index it, re-applies every user's watch +state, then tells the source to move its copy to a hidden trash folder. + +Design background and prior-art research: `docs/ARCHITECTURE.md`. + +## Commands + +```sh +cargo test --workspace # all tests (~15 s; e2e spins up 2 agents + 2 fake Jellyfins) +cargo clippy --workspace --all-targets # must be warning-free +npm --prefix ui ci && npm --prefix ui run build # UI → ui/dist (embedded by rust-embed) +npm --prefix ui run check # svelte-check +cargo run -p jm-server --example demo # two agents on :8097 (cloud) and :8098 (home) with fake media +npm --prefix ui run dev # Vite dev server proxying /api to 127.0.0.1:8097 +cargo run -p jellymove -- --config jellymove.toml # real daemon +``` + +Build the UI before `cargo build --release`, or the binary serves a "UI not +built" page. Debug builds read `ui/dist` from disk, so rebuilding the UI is +enough while developing. + +## Layout + +| Crate | Role | +|---|---| +| `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-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. | + +## Invariants — don't break these + +- **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`. +- **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. +- **Peers can only read exported files by index** (`/exports/{id}/files/{idx}`), + 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. +- 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. + Convert with `cfg.path_map.to_local()` / `to_jellyfin()`; Jellyfin API calls + always take Jellyfin-namespace paths. + +## Jellyfin facts that shape the design + +- Item IDs derive from file paths, so a moved item is a *new* item with no + watch history; hence user-data capture on the source and re-apply on the + destination. We find the new item by **path** (we know exactly where we put + it), then episodes by (season, episode). +- `POST /Library/Media/Updated` returns 204 even for paths outside every + library and only scans after `LibraryMonitorDelay` (60 s default). Always poll. +- User-data routes are the 10.9+ ones (`/UserItems/{id}/UserData`). Verify + against a real server's `/api-docs/openapi.json` before trusting. + +## Testing approach + +`crates/jm-server/tests/fake_jellyfin/` is a filesystem-backed fake Jellyfin +(path-derived IDs, delayed scans, user data). E2E tests in +`crates/jm-server/tests/e2e.rs` run two real agents against two fakes. Add an +e2e test for any behaviour change in the move flow. The fake is *not* proof +of real-Jellyfin compatibility; see "Not yet verified" in README. + +## Style + +- Errors: `thiserror` in library crates, `anyhow` with `.context()` in + `jm-server`. Job failure messages are shown to users; make them actionable. +- UI copy: plain, short, UK English. Svelte 5 runes only; run the Svelte + autofixer / `npm run check` after editing components. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..48a6d5f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2977 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "axum-macros", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures", + "memmap2", + "rayon-core", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "powerfmt", + "serde_core", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "figment" +version = "0.10.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" +dependencies = [ + "atomic", + "pear", + "serde", + "toml", + "uncased", + "version_check", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-timer" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "governor" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9efcab3c1958580ff1f25a2a41be1668f7603d849bb63af523b208a3cc1223b8" +dependencies = [ + "cfg-if", + "dashmap", + "futures-sink", + "futures-timer", + "futures-util", + "getrandom 0.3.4", + "hashbrown 0.16.1", + "nonzero_ext", + "parking_lot", + "portable-atomic", + "quanta", + "rand 0.9.5", + "smallvec", + "spinning_top", + "web-time", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.1", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inlinable_string" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jellymove" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "figment", + "jm-core", + "jm-server", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "jm-core" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror", + "time", + "uuid", +] + +[[package]] +name = "jm-jellyfin" +version = "0.1.0" +dependencies = [ + "axum", + "jm-core", + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "jm-server" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "base64", + "blake3", + "futures", + "jm-core", + "jm-jellyfin", + "jm-store", + "jm-transfer", + "mime_guess", + "reqwest", + "rust-embed", + "serde", + "serde_json", + "tempfile", + "thiserror", + "time", + "tokio", + "tokio-stream", + "tower", + "tower-http 0.7.1", + "tracing", + "uuid", +] + +[[package]] +name = "jm-store" +version = "0.1.0" +dependencies = [ + "jm-core", + "rusqlite", + "serde", + "serde_json", + "tempfile", + "thiserror", + "tokio", +] + +[[package]] +name = "jm-transfer" +version = "0.1.0" +dependencies = [ + "axum", + "blake3", + "bytes", + "futures", + "governor", + "jm-core", + "reqwest", + "serde", + "serde_json", + "tempfile", + "thiserror", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nonzero_ext" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pear" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" +dependencies = [ + "inlinable_string", + "pear_codegen", + "yansi", +] + +[[package]] +name = "pear_codegen" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" +dependencies = [ + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", + "yansi", +] + +[[package]] +name = "quanta" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3ab5a9d756f0d97bdc89019bd2e4ea098cf9cde50ee7564dde6b81ccc8f06c7" +dependencies = [ + "crossbeam-utils", + "libc", + "once_cell", + "raw-cpuid", + "wasi", + "web-sys", + "winapi", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http 0.6.11", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.40.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rust-embed" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053" +dependencies = [ + "mime_guess", + "proc-macro2", + "quote", + "rust-embed-utils", + "syn 2.0.119", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a" +dependencies = [ + "sha2", + "walkdir", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spinning_top" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf02766a1eb909bc7653557c66b384e44edc3ad979e6257c6173c65ea51bc7d" +dependencies = [ + "lock_api", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca" + +[[package]] +name = "time-macros" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-http" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" +dependencies = [ + "bitflags", + "bytes", + "http", + "http-body", + "percent-encoding", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..37a0a38 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] +resolver = "3" +members = ["crates/*"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MIT OR Apache-2.0" +rust-version = "1.85" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7bf52b3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +# syntax=docker/dockerfile:1 +FROM node:22-bookworm-slim AS ui +WORKDIR /src/ui +COPY ui/package.json ui/package-lock.json ./ +RUN npm ci +COPY ui/ ./ +RUN npm run build + +FROM rust:1-bookworm AS build +WORKDIR /src +COPY . . +COPY --from=ui /src/ui/dist ui/dist +RUN cargo build --release -p jellymove && cp target/release/jellymove /jellymove + +FROM gcr.io/distroless/cc-debian12 +COPY --from=build /jellymove /usr/local/bin/jellymove +ENV JELLYMOVE_CONFIG=/config/jellymove.toml +EXPOSE 8097 +VOLUME ["/config", "/data"] +ENTRYPOINT ["/usr/local/bin/jellymove"] +CMD ["run"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..eb1f2e8 --- /dev/null +++ b/README.md @@ -0,0 +1,160 @@ +# jellymove + +Move movies and TV series between two Jellyfin servers, with their subtitles, +artwork, NFOs, extras and everyone's watch history. + +Built for a two-tier setup: a cloud server with fast but limited storage and +a home server with slow but large storage, presented as one library by +[Jellyswarrm](https://github.com/LLukas22/Jellyswarrm). Pick a film or series +in the web UI and send it to the other side. jellymove copies it, checks it, +gets the other Jellyfin to index it, carries the watch state across, and only +then removes it from the source. + +> **Status: early (v0.1).** The whole move flow works end to end against a +> test double of Jellyfin. It has **not yet been run against a real Jellyfin +> server**. Try a dry run first, keep backups, and read "Not yet verified" below. + +## How a move works + +One agent runs next to each Jellyfin and sees the same media folders. The +**destination pulls**: + +1. **Plan.** The source checks that the item has its own folder, hashes every + file (BLAKE3) and records each user's played state, resume points and + favourites. The destination picks a library and refuses if the folder + already exists. *Dry runs stop here.* +2. **Copy.** Files stream into a hidden `.jellymove-partial/` folder inside the + destination library. Dropped connections resume from where they stopped, + and each file is hash-checked. +3. **Promote.** Verified files are renamed into place, an atomic operation on + the same filesystem. +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. +6. **Clean up.** The source moves its folder to `.jellymove-trash/` in the same + library and rescans. It is not deleted. + +A crash or restart at any point resumes from the last completed step. + +## Quick look (no Jellyfin needed) + +```sh +npm --prefix ui ci && npm --prefix ui run build +cargo run -p jm-server --example demo +# open http://127.0.0.1:8097 (cloud) and http://127.0.0.1:8098 (home) +``` + +## Running it for real + +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. + +```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 +``` + +- Create an admin API key in Jellyfin (Dashboard → API Keys). jellymove reads + every user's watch state. +- Use the same `peer.token` on both agents (`openssl rand -hex 32`). +- The agents talk over HTTP, and **each must be able to reach the other**: the + destination pulls, so a move *to* the cloud needs the cloud agent to reach + home. Put them on Tailscale/WireGuard (simplest), or behind your reverse + proxy with TLS. An outbound-only mode for a home server behind NAT is on + 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. +- The **Status** tab checks that every library folder is visible and writable. + +### Without Docker (systemd) + +Each release has a static Linux binary (x86_64, musl, web UI built in), so it +runs on any distro with no other dependencies: + +```sh +tar -xzf jellymove-v0.1.0-x86_64-unknown-linux-musl.tar.gz +cd jellymove-v0.1.0-x86_64-unknown-linux-musl +sudo install -m 755 jellymove /usr/local/bin/jellymove +sudo install -D -m 640 -g jellyfin config.example.toml /etc/jellymove/jellymove.toml +sudo cp jellymove.service /etc/systemd/system/ +sudo systemctl daemon-reload && sudo systemctl enable --now jellymove +``` + +Before starting it, edit `/etc/jellymove/jellymove.toml` and set +`data_dir = "/var/lib/jellymove"` (the unit's `StateDirectory`). If Jellyfin +runs as a different user, change `User=`/`Group=` in the unit and `-g` above. + +To upgrade, replace `/usr/local/bin/jellymove` and run `sudo systemctl restart jellymove`. +Interrupted transfers resume after a restart. + +### Making a release + +`.github/workflows/release.yml` runs on Gitea Actions. To cut a release, bump +`version` in the root `Cargo.toml`, commit, then push a matching tag: + +```sh +git tag v0.1.1 && git push origin v0.1.1 +``` + +The workflow runs the tests, builds the UI and binary, and attaches the +tarball and its `.sha256` to a Gitea release for that tag. Re-running it +replaces the files. Tags with a `-` (`v0.2.0-rc1`) are marked pre-release. + +### Library mapping + +By default an item goes into the library with the same name on the other +server. To file things elsewhere, configure this on the **receiving** agent: + +```toml +[incoming_libraries] +"Movies" = "Movies (archive)" +``` + +### Jellyswarrm + +While a move is running the item exists on both servers, and Jellyswarrm +v0.3.1+ shows it once with two versions. Jellyswarrm's merge cache can go stale +when files move ([#216](https://github.com/LLukas22/Jellyswarrm/issues/216)). +Until that is fixed upstream, a post-move hook can restart it: + +```toml +[hooks] +post_move = "docker restart jellyswarrm" +``` + +## 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 + happy (automatic retention is on the roadmap). +- Nothing at the destination is ever overwritten. +- 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. + +## Not yet verified + +- Against real Jellyfin, in particular user-data writes + (`POST /UserItems/{id}/UserData`), `/Library/Media/Updated` timing on large + libraries, and multi-version movies. +- Against real Jellyswarrm. +- The Docker image build (the Dockerfile is written but untested here). +- Windows and macOS. The code is cross-platform, but only Linux has been run. + +## Roadmap + +- Season-level moves; "promote" (pre-warm) shortcuts +- Trash retention and a trash view in the UI +- 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%") +- Sonarr/Radarr root-folder updates so the *arrs follow the move +- iroh transport (built-in NAT traversal); scheduled bandwidth windows +- `jellymove service install` (systemd/launchd/Windows service) + +## Development + +See [CLAUDE.md](CLAUDE.md) for layout, commands and invariants, and +[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the design. diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..f487726 --- /dev/null +++ b/config.example.toml @@ -0,0 +1,57 @@ +# jellymove configuration. Install one agent next to each Jellyfin server. +# Every key can also be set with an environment variable: JELLYMOVE_, +# with nested keys joined by "__" (e.g. JELLYMOVE_PEER__TOKEN). + +# Shown in the UI and in job history. +node_name = "cloud" + +# Where the agent listens. Put it behind your reverse proxy (TLS) or a +# Tailscale/WireGuard tunnel; peers talk to each other over this port. +listen = "0.0.0.0:8097" + +# SQLite state (jobs, exports). +data_dir = "/data" + +[jellyfin] +url = "http://jellyfin:8096" +# Dashboard → API Keys. Needs an admin key (reads every user's watch state). +api_key = "replace-me" + +# The other agent. Both sides must use the same token: generate one with +# openssl rand -hex 32 +[peer] +url = "https://home.example.com:8097" +token = "replace-me-with-a-long-random-secret" + +# Only needed if this agent sees media at different paths from Jellyfin. +# In Docker, mount media at the same paths in both containers and leave this out. +# [[path_map]] +# jellyfin = "/media" +# local = "/mnt/pool/media" + +# Items arriving from the peer's library on the left go into the local library +# on the right. Libraries not listed go to a local library with the same name. +[incoming_libraries] +# "Movies" = "Movies (archive)" +# "TV Shows" = "TV (archive)" + +[transfer] +# Incoming bandwidth cap in megabits per second (0 = unlimited). +bandwidth_limit_mbps = 0 +# Attempts per file; each attempt resumes from where the last one stopped. +retries = 20 +# How long to wait for Jellyfin to index a moved item before failing the job +# (nothing is deleted from the source until it has). +scan_timeout_secs = 1200 +max_concurrent_jobs = 1 + +# Protect the web UI. Strongly recommended unless the port is only reachable +# from localhost or your tailnet. +[ui] +# username = "admin" +# password = "change-me" + +[hooks] +# Run on the destination after each move. Jellyswarrm (v0.3.1) can keep a +# stale merge cache after files move; restarting it clears that. +# post_move = "docker restart jellyswarrm" diff --git a/crates/jellymove/Cargo.toml b/crates/jellymove/Cargo.toml new file mode 100644 index 0000000..9a0aea1 --- /dev/null +++ b/crates/jellymove/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "jellymove" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +anyhow = "1.0.104" +clap = { version = "4.6.7", features = ["derive", "env"] } +figment = { version = "0.10.19", features = ["toml", "env"] } +jm-core = { version = "0.1.0", path = "../jm-core" } +jm-server = { version = "0.1.0", path = "../jm-server" } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +tokio = { version = "1.54.1", features = ["full"] } +tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } diff --git a/crates/jellymove/src/main.rs b/crates/jellymove/src/main.rs new file mode 100644 index 0000000..c237584 --- /dev/null +++ b/crates/jellymove/src/main.rs @@ -0,0 +1,77 @@ +use std::path::PathBuf; + +use anyhow::Context; +use clap::{Parser, Subcommand}; +use figment::Figment; +use figment::providers::{Env, Format, Toml}; +use tracing_subscriber::EnvFilter; + +const EXAMPLE_CONFIG: &str = include_str!("../../../config.example.toml"); + +#[derive(Parser)] +#[command(version, about = "Move media between two Jellyfin servers")] +struct Cli { + /// Config file (TOML). Values can be overridden with JELLYMOVE_* env vars. + #[arg( + short, + long, + env = "JELLYMOVE_CONFIG", + default_value = "jellymove.toml", + global = true + )] + config: PathBuf, + /// Log as JSON lines (for log shippers). + #[arg(long, env = "JELLYMOVE_LOG_JSON", global = true)] + log_json: bool, + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Command { + /// Run the daemon (default). + Run, + /// Load and validate the config, print it with secrets redacted, then exit. + CheckConfig, + /// Print an example config file. + ExampleConfig, +} + +fn load(path: &PathBuf) -> anyhow::Result { + let mut fig = Figment::new(); + if path.exists() { + fig = fig.merge(Toml::file(path)); + } else { + tracing::warn!(path = %path.display(), "config file not found; using environment only"); + } + fig.merge( + Env::prefixed("JELLYMOVE_") + .split("__") + .ignore(&["config", "log_json"]), + ) + .extract() + .with_context(|| format!("invalid configuration (file: {})", path.display())) +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let cli = Cli::parse(); + let filter = EnvFilter::try_from_env("JELLYMOVE_LOG") + .unwrap_or_else(|_| EnvFilter::new("info,tower_http=warn")); + let fmt = tracing_subscriber::fmt().with_env_filter(filter); + if cli.log_json { + fmt.json().init() + } else { + fmt.init() + } + + match cli.command.unwrap_or(Command::Run) { + Command::ExampleConfig => print!("{EXAMPLE_CONFIG}"), + Command::CheckConfig => { + let cfg = load(&cli.config)?; + println!("{}", serde_json::to_string_pretty(&cfg.redacted())?); + } + Command::Run => jm_server::run(load(&cli.config)?).await?, + } + Ok(()) +} diff --git a/crates/jm-core/Cargo.toml b/crates/jm-core/Cargo.toml new file mode 100644 index 0000000..99ad0de --- /dev/null +++ b/crates/jm-core/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "jm-core" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +thiserror = "2.0.21" +time = { version = "0.3.45", features = ["serde", "formatting", "parsing", "macros"] } +uuid = { version = "1.26.1", features = ["v4", "serde"] } diff --git a/crates/jm-core/src/job.rs b/crates/jm-core/src/job.rs new file mode 100644 index 0000000..9208824 --- /dev/null +++ b/crates/jm-core/src/job.rs @@ -0,0 +1,263 @@ +use serde::{Deserialize, Serialize}; +use std::fmt; +use time::OffsetDateTime; +use uuid::Uuid; + +use crate::userdata::{ItemKey, UserDataRecord}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct JobId(pub Uuid); + +impl JobId { + pub fn new() -> Self { + Self(Uuid::new_v4()) + } +} + +impl Default for JobId { + fn default() -> Self { + Self::new() + } +} + +impl fmt::Display for JobId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl std::str::FromStr for JobId { + type Err = uuid::Error; + fn from_str(s: &str) -> Result { + Ok(Self(s.parse()?)) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ItemKind { + Movie, + Series, +} + +/// The last milestone a job has *completed*. The runner looks at the stage, +/// performs the next step, then advances. Every step is idempotent, so a job +/// interrupted at any point can resume by simply running again. +/// +/// Created → ExportReady → Copied → Promoted → TargetScanned +/// → UserDataApplied → SourceCleaned → Done +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Stage { + /// Job recorded; nothing done yet. + Created, + /// Source has hashed the item folder and returned a manifest. + ExportReady, + /// Every file is in the partial area and its BLAKE3 hash matches. + Copied, + /// Files renamed from the partial area into the destination library. + Promoted, + /// Destination Jellyfin has indexed the new item. + TargetScanned, + /// Played state, resume points and favourites re-applied on destination. + UserDataApplied, + /// Source folder moved to the source trash and source library rescanned. + SourceCleaned, + Done, +} + +impl Stage { + pub fn label(self) -> &'static str { + match self { + Stage::Created => "Waiting for source", + Stage::ExportReady => "Copying", + Stage::Copied => "Moving into library", + Stage::Promoted => "Waiting for Jellyfin scan", + Stage::TargetScanned => "Restoring watch history", + Stage::UserDataApplied => "Cleaning up source", + Stage::SourceCleaned => "Finishing", + Stage::Done => "Done", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "detail")] +pub enum JobStatus { + Queued, + Running, + /// A dry run stops after planning. Nothing was copied or deleted. + Planned, + Failed(String), + Done, +} + +impl JobStatus { + pub fn is_active(&self) -> bool { + matches!(self, JobStatus::Queued | JobStatus::Running) + } +} + +/// One file inside the item folder, relative to that folder. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ManifestEntry { + pub rel_path: String, + pub size: u64, + /// Lowercase hex BLAKE3. + pub blake3: String, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Manifest { + pub files: Vec, +} + +impl Manifest { + pub fn total_bytes(&self) -> u64 { + self.files.iter().map(|f| f.size).sum() + } +} + +/// What the source node tells the destination about the item being moved. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ExportInfo { + pub item_id: String, + pub name: String, + pub kind: ItemKind, + /// Library the item lives in on the source. + pub library_name: String, + /// Item folder relative to its library root, using `/` separators. + pub rel_folder: String, + pub manifest: Manifest, + pub user_data: Vec, + /// Every episode the source knows about (series only). The destination + /// waits until its scan has found all of them before anything is deleted. + #[serde(default)] + pub episode_keys: Vec, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Progress { + pub bytes_done: u64, + pub bytes_total: u64, + pub current_file: Option, +} + +/// A move job. It lives on the *destination* node, which pulls the data. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Job { + pub id: JobId, + #[serde(with = "time::serde::rfc3339")] + pub created: OffsetDateTime, + #[serde(with = "time::serde::rfc3339")] + pub updated: OffsetDateTime, + /// Item ID on the source Jellyfin. + pub source_item_id: String, + /// Display name; replaced by the source's name once the export is ready. + pub name: String, + pub source_node: String, + pub target_node: String, + pub dry_run: bool, + pub stage: Stage, + pub status: JobStatus, + pub export_id: Option, + pub export: Option, + /// Destination library chosen for the item. + pub target_library: Option, + /// Final item folder in the destination's *Jellyfin* path namespace. + pub target_folder_jellyfin: Option, + /// Item ID Jellyfin assigned on the destination after the scan. + pub target_item_id: Option, + pub progress: Progress, + /// Human-readable log of what happened, newest last. + pub log: Vec, +} + +impl Job { + pub fn new( + source_item_id: impl Into, + name: impl Into, + source_node: impl Into, + target_node: impl Into, + dry_run: bool, + ) -> Self { + let now = OffsetDateTime::now_utc(); + Self { + id: JobId::new(), + created: now, + updated: now, + source_item_id: source_item_id.into(), + name: name.into(), + source_node: source_node.into(), + target_node: target_node.into(), + dry_run, + stage: Stage::Created, + status: JobStatus::Queued, + export_id: None, + export: None, + target_library: None, + target_folder_jellyfin: None, + target_item_id: None, + progress: Progress::default(), + log: Vec::new(), + } + } + + pub fn note(&mut self, msg: impl Into) { + let ts = OffsetDateTime::now_utc() + .format(time::macros::format_description!( + "[year]-[month]-[day] [hour]:[minute]:[second]Z" + )) + .unwrap_or_default(); + self.log.push(format!("{ts} {}", msg.into())); + // Keep the log bounded; old lines are rarely useful. + if self.log.len() > 200 { + let excess = self.log.len() - 200; + self.log.drain(..excess); + } + self.touch(); + } + + pub fn advance(&mut self, stage: Stage) { + debug_assert!(stage > self.stage, "stages only move forward"); + self.stage = stage; + self.touch(); + } + + pub fn touch(&mut self) { + self.updated = OffsetDateTime::now_utc(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stages_are_ordered() { + assert!(Stage::Created < Stage::ExportReady); + assert!(Stage::Promoted < Stage::TargetScanned); + assert!(Stage::SourceCleaned < Stage::Done); + } + + #[test] + fn job_roundtrips_through_json() { + let mut job = Job::new("abc", "Alien (1979)", "cloud", "home", false); + job.note("created"); + let json = serde_json::to_string(&job).unwrap(); + let back: Job = serde_json::from_str(&json).unwrap(); + assert_eq!(back.id, job.id); + assert_eq!(back.stage, Stage::Created); + assert_eq!(back.status, JobStatus::Queued); + assert_eq!(back.log.len(), 1); + } + + #[test] + fn log_is_bounded() { + let mut job = Job::new("abc", "x", "a", "b", false); + for i in 0..250 { + job.note(format!("line {i}")); + } + assert_eq!(job.log.len(), 200); + assert!(job.log.last().unwrap().ends_with("line 249")); + } +} diff --git a/crates/jm-core/src/lib.rs b/crates/jm-core/src/lib.rs new file mode 100644 index 0000000..4beab34 --- /dev/null +++ b/crates/jm-core/src/lib.rs @@ -0,0 +1,11 @@ +//! Domain types shared by every jellymove crate: jobs and their stages, +//! path mapping between Jellyfin's view of the filesystem and the agent's, +//! and the safety rules that decide whether a folder can be moved. + +pub mod job; +pub mod paths; +pub mod safety; +pub mod userdata; + +pub use job::{ItemKind, Job, JobId, JobStatus, Stage}; +pub use paths::PathMap; diff --git a/crates/jm-core/src/paths.rs b/crates/jm-core/src/paths.rs new file mode 100644 index 0000000..45a6a37 --- /dev/null +++ b/crates/jm-core/src/paths.rs @@ -0,0 +1,168 @@ +//! Jellyfin reports paths as *it* sees them (inside its container). The agent +//! may see the same files at a different path. A `PathMap` translates between +//! the two. In the recommended Docker setup both containers mount media at the +//! same paths and the map is empty (identity). + +use serde::{Deserialize, Serialize}; +use std::path::{Component, Path, PathBuf}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PathMapping { + /// Prefix as Jellyfin reports it, e.g. `/media/tv`. + pub jellyfin: PathBuf, + /// The same location as this agent sees it, e.g. `/mnt/pool/tv`. + pub local: PathBuf, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct PathMap(pub Vec); + +impl PathMap { + /// Translate a Jellyfin path to a local one. The longest matching prefix + /// wins. With no matching mapping the path is returned unchanged. + pub fn to_local(&self, p: &Path) -> PathBuf { + translate(p, self.0.iter().map(|m| (&m.jellyfin, &m.local))) + } + + pub fn to_jellyfin(&self, p: &Path) -> PathBuf { + translate(p, self.0.iter().map(|m| (&m.local, &m.jellyfin))) + } +} + +fn translate<'a>(p: &Path, pairs: impl Iterator) -> PathBuf { + let best = pairs + .filter(|(from, _)| p.starts_with(from)) // component-wise, so /tv ≠ /tvshows + .max_by_key(|(from, _)| from.components().count()); + match best { + Some((from, to)) => to.join(p.strip_prefix(from).expect("checked by starts_with")), + None => p.to_path_buf(), + } +} + +/// A relative path that is safe to join onto a root: no `..`, no absolute +/// components, not empty. +pub fn is_safe_relative(rel: &Path) -> bool { + !rel.as_os_str().is_empty() + && rel + .components() + .all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) +} + +/// Path of `item` relative to `root`, as a `/`-separated string, if `item` is +/// strictly inside `root`. +pub fn relative_inside(root: &Path, item: &Path) -> Option { + let rel = item.strip_prefix(root).ok()?; + if !is_safe_relative(rel) { + return None; + } + let parts: Vec<_> = rel + .components() + .filter_map(|c| match c { + Component::Normal(s) => Some(s.to_string_lossy().into_owned()), + _ => None, + }) + .collect(); + if parts.is_empty() { + None + } else { + Some(parts.join("/")) + } +} + +/// Join a `/`-separated relative path received from a peer onto a root, +/// refusing anything that could escape it. +pub fn join_relative(root: &Path, rel: &str) -> Option { + // Empty segments mean a leading `/` (absolute) or `//`; refuse both. + if rel.contains('\\') || rel.split('/').any(|seg| seg.is_empty() || seg == "..") { + return None; + } + let rel_path: PathBuf = rel.split('/').collect(); + if !is_safe_relative(&rel_path) { + return None; + } + Some(root.join(rel_path)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn map() -> PathMap { + PathMap(vec![ + PathMapping { + jellyfin: "/media".into(), + local: "/mnt/pool".into(), + }, + PathMapping { + jellyfin: "/media/tv".into(), + local: "/mnt/fast/tv".into(), + }, + ]) + } + + #[test] + fn longest_prefix_wins() { + let m = map(); + assert_eq!( + m.to_local(Path::new("/media/tv/Show/S01")), + PathBuf::from("/mnt/fast/tv/Show/S01") + ); + assert_eq!( + m.to_local(Path::new("/media/movies/A")), + PathBuf::from("/mnt/pool/movies/A") + ); + } + + #[test] + fn prefix_match_is_by_component() { + let m = PathMap(vec![PathMapping { + jellyfin: "/media/tv".into(), + local: "/x".into(), + }]); + assert_eq!( + m.to_local(Path::new("/media/tvshows/A")), + PathBuf::from("/media/tvshows/A") + ); + } + + #[test] + fn roundtrip() { + let m = map(); + let p = Path::new("/media/movies/Alien (1979)/Alien.mkv"); + assert_eq!(m.to_jellyfin(&m.to_local(p)), p); + } + + #[test] + fn empty_map_is_identity() { + assert_eq!( + PathMap::default().to_local(Path::new("/a/b")), + PathBuf::from("/a/b") + ); + } + + #[test] + fn relative_inside_requires_strict_child() { + let root = Path::new("/media/movies"); + assert_eq!( + relative_inside(root, Path::new("/media/movies/Alien (1979)")).as_deref(), + Some("Alien (1979)") + ); + assert_eq!(relative_inside(root, Path::new("/media/movies")), None); + assert_eq!(relative_inside(root, Path::new("/media/tv/X")), None); + } + + #[test] + fn join_relative_rejects_escapes() { + let root = Path::new("/data"); + assert_eq!( + join_relative(root, "Show/Season 1/e.mkv"), + Some(PathBuf::from("/data/Show/Season 1/e.mkv")) + ); + assert_eq!(join_relative(root, "../etc/passwd"), None); + assert_eq!(join_relative(root, "a/../../b"), None); + assert_eq!(join_relative(root, "/etc/passwd"), None); + assert_eq!(join_relative(root, ""), None); + assert_eq!(join_relative(root, "a\\..\\b"), None); + } +} diff --git a/crates/jm-core/src/safety.rs b/crates/jm-core/src/safety.rs new file mode 100644 index 0000000..57296ae --- /dev/null +++ b/crates/jm-core/src/safety.rs @@ -0,0 +1,187 @@ +//! Rules that decide whether an item's folder can be moved as a unit. +//! +//! jellymove moves whole folders so sidecars (NFO, artwork, subtitles, +//! trickplay, extras) travel with the media. That is only safe when the folder +//! belongs to exactly one item. A flat movie library (`/movies/A.mkv`, +//! `/movies/B.mkv`) would otherwise drag every other movie along. + +use std::path::Path; + +pub const VIDEO_EXTENSIONS: &[&str] = &[ + "mkv", "mp4", "m4v", "avi", "mov", "wmv", "ts", "m2ts", "mpg", "mpeg", "webm", "flv", "iso", + "vob", +]; + +/// Folder names Jellyfin treats as extras. Videos inside them belong to the item. +pub const EXTRAS_FOLDERS: &[&str] = &[ + "extras", + "specials", + "shorts", + "scenes", + "featurettes", + "behind the scenes", + "deleted scenes", + "interviews", + "clips", + "trailers", + "other", + "theme-music", + "backdrops", +]; + +/// Filename suffixes Jellyfin treats as extras (`Movie-trailer.mkv`). +pub const EXTRAS_SUFFIXES: &[&str] = &[ + "-trailer", + ".trailer", + "_trailer", + "-sample", + ".sample", + "_sample", + "-scene", + "-clip", + "-interview", + "-behindthescenes", + "-deleted", + "-deletedscene", + "-featurette", + "-short", + "-other", + "-extra", +]; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum FolderProblem { + #[error("the item folder is a library root; moving it would move the whole library")] + IsLibraryRoot, + #[error("the item folder is not inside any library location")] + OutsideLibraries, + #[error( + "the folder also holds other videos ({0}); give each movie its own folder before moving it" + )] + SharedFolder(String), +} + +pub fn is_video(name: &str) -> bool { + Path::new(name) + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| VIDEO_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str())) +} + +fn is_extra(rel_path: &str) -> bool { + let lower = rel_path.to_ascii_lowercase(); + let mut parts: Vec<&str> = lower.split('/').collect(); + let file = parts.pop().unwrap_or_default(); + if parts.iter().any(|p| EXTRAS_FOLDERS.contains(p)) { + return true; + } + let stem = Path::new(file) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or_default(); + EXTRAS_SUFFIXES.iter().any(|s| stem.ends_with(s)) +} + +/// Check that a movie folder belongs to this movie alone. +/// +/// `files` are every file in the folder relative to it (`/` separated). +/// `own_media` are the item's media source paths relative to the same folder, +/// so multi-version movies (`Movie - 1080p.mkv`, `Movie - 4K.mkv`) pass. +pub fn check_movie_folder(files: &[String], own_media: &[String]) -> Result<(), FolderProblem> { + let strangers: Vec<&String> = files + .iter() + .filter(|f| is_video(f) && !is_extra(f) && !own_media.iter().any(|m| m == *f)) + .collect(); + if strangers.is_empty() { + Ok(()) + } else { + let mut names: Vec = strangers.iter().take(3).map(|s| s.to_string()).collect(); + if strangers.len() > 3 { + names.push(format!("and {} more", strangers.len() - 3)); + } + Err(FolderProblem::SharedFolder(names.join(", "))) + } +} + +/// Check that `folder` sits strictly inside one of the library `locations`. +/// Returns the matching location. +pub fn check_inside_library<'a>( + folder: &Path, + locations: &'a [String], +) -> Result<&'a str, FolderProblem> { + for loc in locations { + let loc_path = Path::new(loc); + if folder == loc_path { + return Err(FolderProblem::IsLibraryRoot); + } + if folder.starts_with(loc_path) { + return Ok(loc); + } + } + Err(FolderProblem::OutsideLibraries) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() + } + + #[test] + fn single_movie_folder_with_sidecars_passes() { + let files = s(&[ + "Alien (1979).mkv", + "Alien (1979).nfo", + "poster.jpg", + "fanart.jpg", + "Alien (1979).en.srt", + "Alien (1979)-trailer.mp4", + "extras/Making of.mkv", + "Behind The Scenes/Ridley.mkv", + "trickplay/320 - 10x10/0.jpg", + ]); + assert_eq!( + check_movie_folder(&files, &s(&["Alien (1979).mkv"])), + Ok(()) + ); + } + + #[test] + fn multi_version_movie_passes() { + let files = s(&["Dune - 1080p.mkv", "Dune - 2160p.mkv", "movie.nfo"]); + assert_eq!( + check_movie_folder(&files, &s(&["Dune - 1080p.mkv", "Dune - 2160p.mkv"])), + Ok(()) + ); + } + + #[test] + fn flat_folder_is_refused() { + let files = s(&["Alien (1979).mkv", "Aliens (1986).mkv", "Heat (1995).mp4"]); + let err = check_movie_folder(&files, &s(&["Alien (1979).mkv"])).unwrap_err(); + assert!(matches!(err, FolderProblem::SharedFolder(ref m) if m.contains("Aliens"))); + } + + #[test] + fn library_root_is_refused() { + let locs = s(&["/media/movies"]); + assert_eq!( + check_inside_library(Path::new("/media/movies"), &locs), + Err(FolderProblem::IsLibraryRoot) + ); + assert_eq!( + check_inside_library(Path::new("/media/movies/Alien"), &locs), + Ok("/media/movies") + ); + assert_eq!( + check_inside_library(Path::new("/other/Alien"), &locs), + Err(FolderProblem::OutsideLibraries) + ); + assert_eq!( + check_inside_library(Path::new("/media/moviesx/Alien"), &locs), + Err(FolderProblem::OutsideLibraries) + ); + } +} diff --git a/crates/jm-core/src/userdata.rs b/crates/jm-core/src/userdata.rs new file mode 100644 index 0000000..c37fb1e --- /dev/null +++ b/crates/jm-core/src/userdata.rs @@ -0,0 +1,82 @@ +//! Watch state that has to be carried across a move. +//! +//! Jellyfin derives item IDs from file paths, so a moved item is a brand-new +//! item on the destination with no history. The source captures each user's +//! data before the move; the destination re-applies it once the scan has +//! produced the new items. Users are matched by name (case-insensitive). +//! Items are matched by position inside the moved folder: the root item +//! itself, or an episode's season and episode number. + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum ItemKey { + /// The movie or series being moved. + Root, + Episode { + season: i32, + episode: i32, + }, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct UserData { + pub played: bool, + pub play_count: i32, + pub is_favorite: bool, + pub playback_position_ticks: i64, + /// RFC 3339, as Jellyfin returns it. + pub last_played_date: Option, +} + +impl UserData { + /// Nothing worth copying: unwatched, not started, not a favourite. + pub fn is_empty(&self) -> bool { + !self.played + && self.play_count == 0 + && !self.is_favorite + && self.playback_position_ticks == 0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct UserDataRecord { + pub user_name: String, + pub key: ItemKey, + pub data: UserData, +} + +pub fn same_user(a: &str, b: &str) -> bool { + a.trim().eq_ignore_ascii_case(b.trim()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_detection() { + assert!(UserData::default().is_empty()); + assert!( + !UserData { + is_favorite: true, + ..Default::default() + } + .is_empty() + ); + assert!( + !UserData { + playback_position_ticks: 10, + ..Default::default() + } + .is_empty() + ); + } + + #[test] + fn users_match_case_insensitively() { + assert!(same_user("Alice", " alice ")); + assert!(!same_user("Alice", "Ali")); + } +} diff --git a/crates/jm-jellyfin/Cargo.toml b/crates/jm-jellyfin/Cargo.toml new file mode 100644 index 0000000..0e7d2c4 --- /dev/null +++ b/crates/jm-jellyfin/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "jm-jellyfin" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +jm-core = { version = "0.1.0", path = "../jm-core" } +reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "query", "http2"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +thiserror = "2.0.21" +tracing = "0.1.44" + +[dev-dependencies] +axum = "0.8.9" +tokio = { version = "1.54.1", features = ["full"] } diff --git a/crates/jm-jellyfin/src/lib.rs b/crates/jm-jellyfin/src/lib.rs new file mode 100644 index 0000000..146d315 --- /dev/null +++ b/crates/jm-jellyfin/src/lib.rs @@ -0,0 +1,425 @@ +//! A thin, typed client for the handful of Jellyfin endpoints jellymove needs. +//! +//! Written against Jellyfin 10.9+ (including the v12 line). Routes for user +//! data moved in 10.9 (`/UserItems/...`); check against your server's +//! `/api-docs/openapi.json` if something returns 404. + +use std::collections::HashMap; +use std::time::Duration; + +use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue}; +use serde::{Deserialize, Serialize}; + +pub use jm_core::userdata::UserData; + +#[derive(Debug, thiserror::Error)] +pub enum JellyfinError { + #[error("could not reach Jellyfin: {0}")] + Http(#[from] reqwest::Error), + #[error("Jellyfin returned HTTP {status} for {path}")] + Status { status: u16, path: String }, + #[error("invalid Jellyfin URL: {0}")] + BadUrl(String), +} + +type Result = std::result::Result; + +#[derive(Clone)] +pub struct Client { + base: String, + http: reqwest::Client, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct SystemInfo { + pub server_name: String, + pub version: String, + #[serde(default)] + pub id: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct VirtualFolder { + pub name: String, + #[serde(default)] + pub locations: Vec, + #[serde(default)] + pub collection_type: Option, + #[serde(default)] + pub item_id: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct MediaSource { + #[serde(default)] + pub path: Option, +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct ItemUserData { + #[serde(default)] + pub played: bool, + #[serde(default)] + pub play_count: i32, + #[serde(default)] + pub is_favorite: bool, + #[serde(default)] + pub playback_position_ticks: i64, + #[serde(default)] + pub last_played_date: Option, +} + +impl From for UserData { + fn from(u: ItemUserData) -> Self { + UserData { + played: u.played, + play_count: u.play_count, + is_favorite: u.is_favorite, + playback_position_ticks: u.playback_position_ticks, + last_played_date: u.last_played_date, + } + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct Item { + pub id: String, + pub name: String, + #[serde(rename = "Type")] + pub kind: String, + #[serde(default)] + pub path: Option, + #[serde(default)] + pub production_year: Option, + #[serde(default)] + pub provider_ids: HashMap, + #[serde(default)] + pub media_sources: Option>, + /// Season number for episodes. + #[serde(default)] + pub parent_index_number: Option, + /// Episode number for episodes. + #[serde(default)] + pub index_number: Option, + #[serde(default)] + pub user_data: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +struct ItemsPage { + #[serde(default)] + items: Vec, + #[serde(default)] + total_record_count: usize, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct User { + pub id: String, + pub name: String, +} + +/// Query for `GET /Items`. +#[derive(Debug, Clone, Default)] +pub struct ItemQuery<'a> { + pub ids: Option<&'a str>, + pub parent_id: Option<&'a str>, + pub include_types: &'a [&'a str], + pub recursive: bool, + pub search: Option<&'a str>, + /// Ask for this user's watch state alongside each item. + pub user_id: Option<&'a str>, +} + +const FIELDS: &str = "Path,ProviderIds,MediaSources,ProductionYear"; +const PAGE: usize = 500; + +impl Client { + pub fn new(base_url: &str, api_key: &str) -> Result { + let base = base_url.trim_end_matches('/').to_string(); + if !(base.starts_with("http://") || base.starts_with("https://")) { + return Err(JellyfinError::BadUrl(base_url.to_string())); + } + let mut headers = HeaderMap::new(); + let auth = format!( + r#"MediaBrowser Client="jellymove", Device="jellymove", DeviceId="jellymove", Version="{}", Token="{}""#, + env!("CARGO_PKG_VERSION"), + api_key + ); + headers.insert( + AUTHORIZATION, + HeaderValue::from_str(&auth).map_err(|_| JellyfinError::BadUrl("api key".into()))?, + ); + let http = reqwest::Client::builder() + .default_headers(headers) + .timeout(Duration::from_secs(60)) + .build()?; + Ok(Self { base, http }) + } + + async fn get Deserialize<'de>>( + &self, + path: &str, + query: &[(&str, String)], + ) -> Result { + let resp = self + .http + .get(format!("{}{path}", self.base)) + .query(query) + .send() + .await?; + check(resp, path).await?.json().await.map_err(Into::into) + } + + async fn post_json( + &self, + path: &str, + query: &[(&str, String)], + body: &B, + ) -> Result<()> { + let resp = self + .http + .post(format!("{}{path}", self.base)) + .query(query) + .json(body) + .send() + .await?; + check(resp, path).await.map(|_| ()) + } + + pub async fn system_info(&self) -> Result { + self.get("/System/Info", &[]).await + } + + pub async fn virtual_folders(&self) -> Result> { + self.get("/Library/VirtualFolders", &[]).await + } + + pub async fn users(&self) -> Result> { + self.get("/Users", &[]).await + } + + pub async fn item(&self, id: &str) -> Result { + let mut items = self + .get::( + "/Items", + &[("ids", id.to_string()), ("fields", FIELDS.to_string())], + ) + .await? + .items; + items.pop().ok_or(JellyfinError::Status { + status: 404, + path: format!("/Items?ids={id}"), + }) + } + + /// Fetch every item matching `q`, following pagination. + pub async fn items(&self, q: &ItemQuery<'_>) -> Result> { + let mut out = Vec::new(); + loop { + let mut query: Vec<(&str, String)> = vec![ + ("fields", FIELDS.to_string()), + ("recursive", q.recursive.to_string()), + ("startIndex", out.len().to_string()), + ("limit", PAGE.to_string()), + ("sortBy", "SortName".to_string()), + ]; + if let Some(ids) = q.ids { + query.push(("ids", ids.to_string())); + } + if let Some(p) = q.parent_id { + query.push(("parentId", p.to_string())); + } + if !q.include_types.is_empty() { + query.push(("includeItemTypes", q.include_types.join(","))); + } + if let Some(s) = q.search { + query.push(("searchTerm", s.to_string())); + } + if let Some(u) = q.user_id { + query.push(("userId", u.to_string())); + query.push(("enableUserData", "true".to_string())); + } + let page: ItemsPage = self.get("/Items", &query).await?; + let got = page.items.len(); + out.extend(page.items); + if got < PAGE || out.len() >= page.total_record_count { + return Ok(out); + } + } + } + + /// Ask Jellyfin to rescan just these folders. Jellyfin answers 204 even for + /// paths outside every library and waits `LibraryMonitorDelay` (60 s by + /// default) before scanning, so callers must poll for the result. + pub async fn media_updated(&self, paths: &[String]) -> Result<()> { + #[derive(Serialize)] + #[serde(rename_all = "PascalCase")] + struct Update<'a> { + path: &'a str, + update_type: &'a str, + } + #[derive(Serialize)] + #[serde(rename_all = "PascalCase")] + struct Body<'a> { + updates: Vec>, + } + let body = Body { + updates: paths + .iter() + .map(|p| Update { + path: p, + update_type: "Modified", + }) + .collect(), + }; + self.post_json("/Library/Media/Updated", &[], &body).await + } + + /// Full library scan. A fallback when targeted updates don't take. + pub async fn refresh_library(&self) -> Result<()> { + let resp = self + .http + .post(format!("{}/Library/Refresh", self.base)) + .send() + .await?; + check(resp, "/Library/Refresh").await.map(|_| ()) + } + + /// Write a user's watch state for an item (Jellyfin 10.9+). + pub async fn set_user_data(&self, user_id: &str, item_id: &str, data: &UserData) -> Result<()> { + #[derive(Serialize)] + #[serde(rename_all = "PascalCase")] + struct Dto<'a> { + played: bool, + play_count: i32, + is_favorite: bool, + playback_position_ticks: i64, + #[serde(skip_serializing_if = "Option::is_none")] + last_played_date: Option<&'a str>, + } + let dto = Dto { + played: data.played, + play_count: data.play_count, + is_favorite: data.is_favorite, + playback_position_ticks: data.playback_position_ticks, + last_played_date: data.last_played_date.as_deref(), + }; + self.post_json( + &format!("/UserItems/{item_id}/UserData"), + &[("userId", user_id.to_string())], + &dto, + ) + .await + } +} + +async fn check(resp: reqwest::Response, path: &str) -> Result { + if resp.status().is_success() { + Ok(resp) + } else { + Err(JellyfinError::Status { + status: resp.status().as_u16(), + path: path.to_string(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::extract::Query; + use axum::http::{HeaderMap as AxHeaders, StatusCode}; + use axum::routing::{get, post}; + use axum::{Json, Router}; + use serde_json::{Value, json}; + + async fn mock() -> String { + async fn items( + headers: AxHeaders, + Query(q): Query>, + ) -> std::result::Result, StatusCode> { + let auth = headers + .get("authorization") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default(); + if !auth.contains(r#"Token="secret""#) { + return Err(StatusCode::UNAUTHORIZED); + } + // 1 200 fake movies served in pages. + let start: usize = q + .get("startIndex") + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let limit: usize = q.get("limit").and_then(|s| s.parse().ok()).unwrap_or(100); + let total = 1200; + let items: Vec = (start..(start + limit).min(total)) + .map(|i| json!({"Id": format!("id{i}"), "Name": format!("Movie {i}"), "Type": "Movie", + "Path": format!("/media/movies/Movie {i}/Movie {i}.mkv"), + "ProviderIds": {"Tmdb": i.to_string()}, + "UserData": {"Played": i % 2 == 0, "PlaybackPositionTicks": 0, "PlayCount": 1, "IsFavorite": false}})) + .collect(); + Ok(Json(json!({"Items": items, "TotalRecordCount": total}))) + } + async fn updated(Json(body): Json) -> StatusCode { + assert_eq!(body["Updates"][0]["Path"], "/media/movies/X"); + StatusCode::NO_CONTENT + } + let app = Router::new() + .route("/Items", get(items)) + .route("/Library/Media/Updated", post(updated)) + .route("/Library/VirtualFolders", get(|| async { + Json(json!([{"Name": "Movies", "Locations": ["/media/movies"], "CollectionType": "movies", "ItemId": "lib1"}])) + })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}/") + } + + #[tokio::test] + async fn paginates_and_parses_items() { + let c = Client::new(&mock().await, "secret").unwrap(); + let items = c + .items(&ItemQuery { + include_types: &["Movie"], + recursive: true, + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(items.len(), 1200); + assert_eq!(items[1199].name, "Movie 1199"); + assert_eq!(items[3].provider_ids["Tmdb"], "3"); + assert!(items[2].user_data.as_ref().unwrap().played); + } + + #[tokio::test] + async fn bad_token_is_an_error() { + let c = Client::new(&mock().await, "wrong").unwrap(); + let err = c.items(&ItemQuery::default()).await.unwrap_err(); + assert!(matches!(err, JellyfinError::Status { status: 401, .. })); + } + + #[tokio::test] + async fn virtual_folders_and_media_updated() { + let c = Client::new(&mock().await, "secret").unwrap(); + let vf = c.virtual_folders().await.unwrap(); + assert_eq!(vf[0].locations, ["/media/movies"]); + c.media_updated(&["/media/movies/X".to_string()]) + .await + .unwrap(); + } + + #[test] + fn rejects_bad_url() { + assert!(Client::new("jellyfin:8096", "k").is_err()); + } +} diff --git a/crates/jm-server/Cargo.toml b/crates/jm-server/Cargo.toml new file mode 100644 index 0000000..8049027 --- /dev/null +++ b/crates/jm-server/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "jm-server" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +anyhow = "1.0.104" +axum = { version = "0.8.9", features = ["macros"] } +base64 = "0.23.1" +futures = "0.3.34" +jm-core = { version = "0.1.0", path = "../jm-core" } +jm-jellyfin = { version = "0.1.0", path = "../jm-jellyfin" } +jm-store = { version = "0.1.0", path = "../jm-store" } +jm-transfer = { version = "0.1.0", path = "../jm-transfer" } +mime_guess = "2.0.5" +reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "stream", "http2"] } +rust-embed = "8.13.0" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +thiserror = "2.0.21" +time = "0.3.45" +tokio = { version = "1.54.1", features = ["full"] } +tokio-stream = { version = "0.1.19", features = ["sync"] } +tower-http = { version = "0.7.1", features = ["trace"] } +tracing = "0.1.44" +uuid = { version = "1.26.1", features = ["v4"] } + +[dev-dependencies] +anyhow = "1.0.104" +blake3 = "1.8.7" +reqwest = { version = "0.13.5", default-features = false, features = ["json"] } +serde_json = "1.0.154" +tempfile = "3.27.0" +tokio = { version = "1.54.1", features = ["full"] } +tower = "0.5.3" diff --git a/crates/jm-server/examples/demo.rs b/crates/jm-server/examples/demo.rs new file mode 100644 index 0000000..aac9efe --- /dev/null +++ b/crates/jm-server/examples/demo.rs @@ -0,0 +1,132 @@ +//! Local demo: two jellymove agents ("cloud" on :8097, "home" on :8098), each +//! with a fake Jellyfin and some throwaway media in a temp folder. +//! +//! npm --prefix ui ci && npm --prefix ui run build +//! cargo run -p jm-server --example demo +//! +//! Then open http://127.0.0.1:8097 and move something to "home". + +#[path = "../tests/fake_jellyfin/mod.rs"] +#[allow(dead_code)] +mod fake_jellyfin; + +use std::path::Path; +use std::sync::Arc; + +use fake_jellyfin::{Fake, Lib}; +use jm_server::config::{ + Config, HooksConfig, JellyfinConfig, PeerConfig, TransferConfig, UiConfig, +}; + +fn write(path: &Path, len: usize) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let data: Vec = (0..len as u32) + .map(|i| (i.wrapping_mul(2654435761) >> 11) as u8) + .collect(); + std::fs::write(path, data).unwrap(); +} + +fn libs(root: &Path) -> Vec { + vec![ + Lib { + name: "Movies".into(), + collection_type: "movies", + location: root.join("movies"), + }, + Lib { + name: "TV Shows".into(), + collection_type: "tvshows", + location: root.join("tv"), + }, + ] +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber_init(); + let tmp = tempfile::tempdir()?; + let cloud = tmp.path().join("cloud"); + let home = tmp.path().join("home"); + for r in [&cloud, &home] { + std::fs::create_dir_all(r.join("movies"))?; + std::fs::create_dir_all(r.join("tv"))?; + } + const MB: usize = 1024 * 1024; + for (folder, size) in [ + ("Arrival (2016)", 180 * MB), + ("Blade Runner (1982)", 120 * MB), + ("Heat (1995)", 60 * MB), + ] { + let base = cloud.join("movies").join(folder); + write(&base.join(format!("{folder}.mkv")), size); + write(&base.join(format!("{folder}.nfo")), 300); + write(&base.join(format!("{folder}.en.srt")), 40_000); + write(&base.join("poster.jpg"), 200_000); + } + for ep in 1..=6 { + write( + &cloud.join(format!("tv/Severance/Season 01/Severance S01E{ep:02}.mkv")), + 20 * MB, + ); + } + write( + &home.join("movies/The Thing (1982)/The Thing (1982).mkv"), + 40 * MB, + ); + + let fake_cloud = Fake::new(libs(&cloud)); + let fake_home = Fake::new(libs(&home)); + if let Some(id) = fake_cloud.find("Movie", "Arrival") { + fake_cloud.set_user_data(&id, serde_json::json!({"Played": true, "PlayCount": 1})); + } + let jf_cloud = fake_cloud.serve().await; + let jf_home = fake_home.serve().await; + + let mut tasks = Vec::new(); + for (name, root, jf, port, peer_port) in [ + ("cloud", &cloud, jf_cloud, 8097, 8098), + ("home", &home, jf_home, 8098, 8097), + ] { + let cfg = Config { + node_name: name.into(), + listen: format!("127.0.0.1:{port}").parse()?, + data_dir: root.join(".state"), + jellyfin: JellyfinConfig { + url: jf, + api_key: "demo".into(), + }, + path_map: Default::default(), + peer: Some(PeerConfig { + url: format!("http://127.0.0.1:{peer_port}"), + token: "demo-token".into(), + }), + incoming_libraries: Default::default(), + // Throttled so you can watch the progress bar. + transfer: TransferConfig { + bandwidth_limit_mbps: 200.0, + ..Default::default() + }, + ui: UiConfig::default(), + hooks: HooksConfig::default(), + }; + std::fs::create_dir_all(&cfg.data_dir)?; + let store = jm_store::Store::open(&cfg.data_dir.join("db"))?; + let state = Arc::new(jm_server::state::AppState::new(cfg, store)?); + jm_server::runner::resume_all(&state).await?; + let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?; + tasks.push(tokio::spawn(async move { + axum::serve(listener, jm_server::api::router(state)).await + })); + } + println!("demo media in {}", tmp.path().display()); + println!("cloud: http://127.0.0.1:8097 home: http://127.0.0.1:8098 (Ctrl+C to stop)"); + tokio::signal::ctrl_c().await?; + Ok(()) +} + +fn tracing_subscriber_init() { + // Keep the demo quiet unless asked. + if std::env::var_os("RUST_LOG").is_some() { + eprintln!("(set up your own subscriber for logs)"); + } +} diff --git a/crates/jm-server/src/api.rs b/crates/jm-server/src/api.rs new file mode 100644 index 0000000..acc6984 --- /dev/null +++ b/crates/jm-server/src/api.rs @@ -0,0 +1,444 @@ +//! HTTP routes. `/api/*` serves the browser UI; `/peer/v1/*` is the +//! agent-to-agent protocol, authenticated with the shared peer token. + +use std::convert::Infallible; +use std::time::Duration; + +use axum::extract::{Path, Query, Request, State}; +use axum::http::{HeaderMap, Method, StatusCode, header}; +use axum::middleware::{self, Next}; +use axum::response::sse::{Event, KeepAlive, Sse}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use base64::Engine; +use futures::Stream; +use jm_core::{Job, JobId, JobStatus}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use tokio_stream::StreamExt; +use tokio_stream::wrappers::BroadcastStream; + +use crate::export::{self, Export, ExportStatus}; +use crate::library::{self, Library, LibraryItem, LocationCheck}; +use crate::peer::{CreateJob, NodeInfo}; +use crate::runner; +use crate::state::Shared; + +pub struct ApiError(StatusCode, String); + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + (self.0, Json(json!({ "error": self.1 }))).into_response() + } +} + +impl From for ApiError { + fn from(e: anyhow::Error) -> Self { + ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")) + } +} + +impl From for ApiError { + fn from(e: jm_store::StoreError) -> Self { + ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()) + } +} + +impl From for ApiError { + fn from(e: jm_jellyfin::JellyfinError) -> Self { + ApiError(StatusCode::BAD_GATEWAY, e.to_string()) + } +} + +type ApiResult = Result, ApiError>; + +pub fn router(state: Shared) -> Router { + let ui_api = Router::new() + .route("/status", get(status)) + .route("/libraries", get(ui_libraries)) + .route("/items", get(ui_items)) + .route("/moves", post(ui_move)) + .route("/jobs", get(ui_jobs)) + .route("/jobs/{id}/retry", post(ui_retry)) + .route("/events", get(events)); + + let peer_api = Router::new() + .route("/info", get(peer_info)) + .route("/libraries", get(peer_libraries)) + .route("/items", get(peer_items)) + .route("/exports", post(peer_create_export)) + .route("/exports/{id}", get(peer_get_export)) + .route("/exports/{id}/files/{idx}", get(peer_file)) + .route("/exports/{id}/complete", post(peer_complete_export)) + .route("/jobs", get(peer_jobs).post(peer_create_job)) + .layer(middleware::from_fn_with_state( + state.clone(), + require_peer_token, + )); + + Router::new() + .nest( + "/api", + ui_api.layer(middleware::from_fn(require_csrf_header)), + ) + .nest("/peer/v1", peer_api) + .fallback(crate::ui::serve) + .layer(middleware::from_fn_with_state( + state.clone(), + require_ui_auth, + )) + .with_state(state) +} + +// ---------------------------------------------------------------- auth + +fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +async fn require_peer_token(State(state): State, req: Request, next: Next) -> Response { + let Some(peer) = &state.cfg.peer else { + return ApiError(StatusCode::SERVICE_UNAVAILABLE, "no peer configured".into()) + .into_response(); + }; + let presented = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .unwrap_or_default(); + if constant_time_eq(presented.as_bytes(), peer.token.as_bytes()) { + next.run(req).await + } else { + ApiError(StatusCode::UNAUTHORIZED, "bad peer token".into()).into_response() + } +} + +/// HTTP Basic auth for everything except the peer API, if a password is set. +async fn require_ui_auth(State(state): State, req: Request, next: Next) -> Response { + let (Some(user), Some(pass)) = (&state.cfg.ui.username, &state.cfg.ui.password) else { + return next.run(req).await; + }; + if req.uri().path().starts_with("/peer/") { + return next.run(req).await; + } + let ok = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Basic ")) + .and_then(|b| base64::engine::general_purpose::STANDARD.decode(b).ok()) + .is_some_and(|decoded| constant_time_eq(&decoded, format!("{user}:{pass}").as_bytes())); + if ok { + next.run(req).await + } else { + ( + StatusCode::UNAUTHORIZED, + [(header::WWW_AUTHENTICATE, r#"Basic realm="jellymove""#)], + "login required", + ) + .into_response() + } +} + +/// Browsers send Basic credentials automatically, so state-changing requests +/// must carry a header a cross-site form can't set. +async fn require_csrf_header(req: Request, next: Next) -> Response { + if req.method() != Method::GET && !req.headers().contains_key("x-jellymove") { + return ApiError(StatusCode::FORBIDDEN, "missing X-Jellymove header".into()) + .into_response(); + } + next.run(req).await +} + +// ---------------------------------------------------------------- UI API + +#[derive(Serialize)] +struct Status { + node: NodeInfo, + jellyfin_error: Option, + locations: Vec, + peer_url: Option, + peer: Option, + peer_error: Option, + config: crate::config::Config, +} + +async fn node_info(state: &Shared) -> (NodeInfo, Option) { + let (server, err) = match state.jellyfin.system_info().await { + Ok(i) => (Some(i), None), + Err(e) => (None, Some(e.to_string())), + }; + ( + NodeInfo { + node_name: state.cfg.node_name.clone(), + version: env!("CARGO_PKG_VERSION").to_string(), + jellyfin_server: server.as_ref().map(|s| s.server_name.clone()), + jellyfin_version: server.map(|s| s.version), + }, + err, + ) +} + +async fn status(State(state): State) -> ApiResult { + let (node, jellyfin_error) = node_info(&state).await; + let locations = if jellyfin_error.is_none() { + library::check_locations(&state).await? + } else { + vec![] + }; + let (peer, peer_error) = match &state.peer { + None => (None, None), + Some(p) => match p.info().await { + Ok(i) => (Some(i), None), + Err(e) => (None, Some(format!("{e:#}"))), + }, + }; + Ok(Json(Status { + node, + jellyfin_error, + locations, + peer_url: state.cfg.peer.as_ref().map(|p| p.url.clone()), + peer, + peer_error, + config: state.cfg.redacted(), + })) +} + +#[derive(Deserialize)] +struct NodeQuery { + #[serde(default)] + node: Side, +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "lowercase")] +enum Side { + #[default] + Local, + Peer, +} + +async fn ui_libraries( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(match q.node { + Side::Local => library::libraries(&state).await?, + Side::Peer => state.peer()?.libraries().await?, + })) +} + +#[derive(Deserialize)] +struct ItemsQuery { + #[serde(default)] + node: Side, + library: String, + search: Option, +} + +async fn ui_items( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(match q.node { + Side::Local => library::items(&state, &q.library, q.search.as_deref()).await?, + Side::Peer => state.peer()?.items(&q.library, q.search.as_deref()).await?, + })) +} + +#[derive(Deserialize)] +struct MoveRequest { + /// Where the item is now. + from: Side, + item_id: String, + name: String, + #[serde(default)] + dry_run: bool, +} + +/// Start a move. Jobs always run on the destination, which pulls the data. +async fn ui_move(State(state): State, Json(req): Json) -> ApiResult { + let peer = state.peer()?; + match req.from { + Side::Peer => { + let peer_name = peer.info().await?.node_name; + let job = Job::new( + &req.item_id, + &req.name, + peer_name, + &state.cfg.node_name, + req.dry_run, + ); + state.save(&job).await?; + runner::start(state.clone(), job.clone()); + Ok(Json(job)) + } + Side::Local => { + let job = peer + .create_job(&CreateJob { + item_id: req.item_id, + name: req.name, + dry_run: req.dry_run, + }) + .await?; + Ok(Json(job)) + } + } +} + +#[derive(Serialize)] +struct JobsView { + /// Jobs this node is running (items moving *to* here). + local: Vec, + /// Jobs the peer is running (items moving *from* here). + peer: Vec, + peer_error: Option, +} + +async fn ui_jobs(State(state): State) -> ApiResult { + let local = state.store.list_jobs(100).await?; + let (peer, peer_error) = match &state.peer { + None => (vec![], None), + Some(p) => match p.jobs().await { + Ok(j) => (j, None), + Err(e) => (vec![], Some(format!("{e:#}"))), + }, + }; + Ok(Json(JobsView { + local, + peer, + peer_error, + })) +} + +async fn ui_retry(State(state): State, Path(id): Path) -> ApiResult { + let id: JobId = id + .parse() + .map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?; + let mut job = state + .store + .get_job(id) + .await? + .ok_or(ApiError(StatusCode::NOT_FOUND, "no such job".into()))?; + match &job.status { + JobStatus::Failed(_) => {} + JobStatus::Planned => job.dry_run = false, // "run it for real" + other => return Err(ApiError(StatusCode::CONFLICT, format!("job is {other:?}"))), + } + job.note("retry requested"); + state.save(&job).await?; + runner::start(state.clone(), job.clone()); + Ok(Json(job)) +} + +async fn events(State(state): State) -> Sse>> { + let stream = BroadcastStream::new(state.events.subscribe()).filter_map(|msg| { + msg.ok().and_then(|mut job| { + job.export = None; // manifests can be large; the UI doesn't need them live + Event::default().event("job").json_data(&job).ok().map(Ok) + }) + }); + Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))) +} + +// ---------------------------------------------------------------- peer API + +async fn peer_info(State(state): State) -> Json { + Json(node_info(&state).await.0) +} + +async fn peer_libraries(State(state): State) -> ApiResult> { + Ok(Json(library::libraries(&state).await?)) +} + +#[derive(Deserialize)] +struct PeerItemsQuery { + library: String, + search: Option, +} + +async fn peer_items( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json( + library::items(&state, &q.library, q.search.as_deref()).await?, + )) +} + +#[derive(Deserialize)] +struct CreateExport { + item_id: String, +} + +async fn peer_create_export( + State(state): State, + Json(req): Json, +) -> ApiResult { + Ok(Json(export::create(&state, &req.item_id).await?)) +} + +async fn peer_get_export(State(state): State, Path(id): Path) -> ApiResult { + export::get(&state, &id) + .await? + .map(Json) + .ok_or(ApiError(StatusCode::NOT_FOUND, "no such export".into())) +} + +async fn peer_file( + State(state): State, + Path((id, idx)): Path<(String, usize)>, + headers: HeaderMap, +) -> Response { + let export = match export::get(&state, &id).await { + Ok(Some(e)) if e.status == ExportStatus::Ready => e, + Ok(Some(_)) => { + return ApiError(StatusCode::CONFLICT, "export not ready".into()).into_response(); + } + Ok(None) => return StatusCode::NOT_FOUND.into_response(), + Err(e) => return ApiError::from(e).into_response(), + }; + match export.file_path(&state, idx) { + Some(path) => jm_transfer::range_response(&path, &headers).await, + None => StatusCode::NOT_FOUND.into_response(), + } +} + +async fn peer_complete_export( + State(state): State, + Path(id): Path, +) -> ApiResult { + Ok(Json(export::complete(&state, &id).await?)) +} + +async fn peer_create_job( + State(state): State, + Json(req): Json, +) -> ApiResult { + let peer_name = state + .peer()? + .info() + .await + .map(|i| i.node_name) + .unwrap_or_else(|_| "peer".into()); + let job = Job::new( + &req.item_id, + &req.name, + peer_name, + &state.cfg.node_name, + req.dry_run, + ); + state.save(&job).await?; + runner::start(state.clone(), job.clone()); + Ok(Json(job)) +} + +async fn peer_jobs(State(state): State) -> ApiResult> { + let mut jobs = state.store.list_jobs(100).await?; + for j in &mut jobs { + j.export = None; + } + Ok(Json(jobs)) +} diff --git a/crates/jm-server/src/config.rs b/crates/jm-server/src/config.rs new file mode 100644 index 0000000..4117baa --- /dev/null +++ b/crates/jm-server/src/config.rs @@ -0,0 +1,121 @@ +use std::collections::HashMap; +use std::net::SocketAddr; +use std::path::PathBuf; + +use jm_core::PathMap; +use serde::{Deserialize, Serialize}; + +/// Daemon configuration. Loaded from TOML plus `JELLYMOVE_*` environment +/// variables (nested keys use `__`, e.g. `JELLYMOVE_PEER__TOKEN`). +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct Config { + /// Name shown in the UI and in job history, e.g. "cloud" or "home". + pub node_name: String, + #[serde(default = "default_listen")] + pub listen: SocketAddr, + /// Where the SQLite database lives. + #[serde(default = "default_data_dir")] + pub data_dir: PathBuf, + pub jellyfin: JellyfinConfig, + /// Jellyfin path → local path translations. Leave empty when this agent + /// mounts media at the same paths as Jellyfin (recommended). + #[serde(default)] + pub path_map: PathMap, + pub peer: Option, + /// When an item arrives from the peer's library "X", put it in local + /// library `incoming_libraries["X"]`. Unlisted libraries map to a local + /// library with the same name. + #[serde(default)] + pub incoming_libraries: HashMap, + #[serde(default)] + pub transfer: TransferConfig, + #[serde(default)] + pub ui: UiConfig, + #[serde(default)] + pub hooks: HooksConfig, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct JellyfinConfig { + pub url: String, + pub api_key: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct PeerConfig { + /// Base URL of the other jellymove agent, e.g. `https://cloud.example.com:8097`. + pub url: String, + /// Shared secret. Both agents must use the same value. + pub token: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(default)] +pub struct TransferConfig { + /// Cap on incoming transfer speed in megabits per second. 0 = unlimited. + pub bandwidth_limit_mbps: f64, + /// Attempts per file before the job fails (each attempt resumes). + pub retries: u32, + /// How long to wait for Jellyfin to index a moved item. + pub scan_timeout_secs: u64, + pub max_concurrent_jobs: usize, +} + +impl Default for TransferConfig { + fn default() -> Self { + Self { + bandwidth_limit_mbps: 0.0, + retries: 20, + scan_timeout_secs: 1200, + max_concurrent_jobs: 1, + } + } +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +pub struct UiConfig { + /// Protect the web UI with HTTP Basic auth. Strongly recommended if the + /// port is reachable from anywhere but localhost. + pub username: Option, + pub password: Option, +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +pub struct HooksConfig { + /// Shell command run on the destination after a move finishes, e.g. + /// `docker restart jellyswarrm` to clear Jellyswarrm's merge cache. + /// Gets JELLYMOVE_ITEM_NAME and JELLYMOVE_TARGET_FOLDER in its environment. + pub post_move: Option, +} + +fn default_listen() -> SocketAddr { + "0.0.0.0:8097".parse().expect("valid") +} + +fn default_data_dir() -> PathBuf { + PathBuf::from("./data") +} + +impl Config { + pub fn bytes_per_sec(&self) -> Option { + let bps = self.transfer.bandwidth_limit_mbps * 1_000_000.0 / 8.0; + if bps >= 1.0 { + std::num::NonZeroU32::new(bps.min(u32::MAX as f64) as u32) + } else { + None + } + } + + /// Redacted copy safe to show in the UI. + pub fn redacted(&self) -> Config { + let mut c = self.clone(); + c.jellyfin.api_key = "••••".into(); + if let Some(p) = c.peer.as_mut() { + p.token = "••••".into(); + } + if c.ui.password.is_some() { + c.ui.password = Some("••••".into()); + } + c + } +} diff --git a/crates/jm-server/src/export.rs b/crates/jm-server/src/export.rs new file mode 100644 index 0000000..ce21bf0 --- /dev/null +++ b/crates/jm-server/src/export.rs @@ -0,0 +1,322 @@ +//! Source side of a move. An *export* is an item folder this node has agreed +//! to hand over: it has been safety-checked, hashed and its users' watch state +//! captured. Files are served from it by index, never by path, so a peer can +//! only read what was exported. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, bail}; +use jm_core::ItemKind; +use jm_core::job::ExportInfo; +use jm_core::paths::{join_relative, relative_inside}; +use jm_core::safety::{check_inside_library, check_movie_folder}; +use jm_core::userdata::{ItemKey, UserDataRecord}; +use jm_jellyfin::ItemQuery; +use serde::{Deserialize, Serialize}; + +use crate::state::{AppState, Shared}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "detail")] +pub enum ExportStatus { + /// Checking the folder and hashing files. + Preparing, + Ready, + Failed(String), + /// Folder moved to the source trash; nothing left to serve. + Completed, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Export { + pub id: String, + pub item_id: String, + pub status: ExportStatus, + pub info: Option, + /// Item folder as Jellyfin sees it. + #[serde(default)] + pub jellyfin_folder: String, + /// Library location (Jellyfin namespace) containing the folder. + #[serde(default)] + pub jellyfin_location: String, +} + +impl Export { + fn local_folder(&self, state: &AppState) -> PathBuf { + state + .cfg + .path_map + .to_local(Path::new(&self.jellyfin_folder)) + } + + /// Absolute local path of manifest entry `idx`, if it exists in the export. + pub fn file_path(&self, state: &AppState, idx: usize) -> Option { + let info = self.info.as_ref()?; + let entry = info.manifest.files.get(idx)?; + join_relative(&self.local_folder(state), &entry.rel_path) + } +} + +/// Start (or reuse) an export for `item_id`. Hashing runs in the background; +/// the caller polls [`get`] until the status is `Ready`. +pub async fn create(state: &Shared, item_id: &str) -> anyhow::Result { + // One export per item: re-requesting returns the existing one, so a + // destination that restarts mid-copy reattaches instead of re-hashing. + let id = format!("item-{item_id}"); + if let Some(existing) = state.store.get_export::(&id).await? { + let retry = matches!( + existing.status, + ExportStatus::Failed(_) | ExportStatus::Completed + ); + if !retry { + return Ok(existing); + } + } + let export = Export { + id: id.clone(), + item_id: item_id.to_string(), + status: ExportStatus::Preparing, + info: None, + jellyfin_folder: String::new(), + jellyfin_location: String::new(), + }; + state.store.put_export(&id, &export).await?; + spawn_prepare(state.clone(), export.clone()); + Ok(export) +} + +/// Load an export. If it was being prepared when the daemon stopped, the +/// preparation is restarted. +pub async fn get(state: &Shared, id: &str) -> anyhow::Result> { + let export: Option = state.store.get_export(id).await?; + if let Some(e) = &export { + if e.status == ExportStatus::Preparing { + spawn_prepare(state.clone(), e.clone()); + } + } + Ok(export) +} + +fn spawn_prepare(state: Shared, mut export: Export) { + if !state + .preparing + .lock() + .expect("lock") + .insert(export.id.clone()) + { + return; // already running + } + tokio::spawn(async move { + match prepare(&state, &export.item_id).await { + Ok((info, folder, location)) => { + tracing::info!(item = %info.name, files = info.manifest.files.len(), "export ready"); + export.info = Some(info); + export.jellyfin_folder = folder; + export.jellyfin_location = location; + export.status = ExportStatus::Ready; + } + Err(e) => { + tracing::warn!(item = %export.item_id, error = %format!("{e:#}"), "export failed"); + export.status = ExportStatus::Failed(format!("{e:#}")); + } + } + if let Err(e) = state.store.put_export(&export.id, &export).await { + tracing::error!(error = %e, "could not save export"); + } + state.preparing.lock().expect("lock").remove(&export.id); + }); +} + +async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, String, String)> { + let jf = &state.jellyfin; + let item = jf + .item(item_id) + .await + .context("looking up the item on Jellyfin")?; + let kind = match item.kind.as_str() { + "Movie" => ItemKind::Movie, + "Series" => ItemKind::Series, + other => bail!("can only move movies and series, not {other}"), + }; + let item_path = PathBuf::from( + item.path + .clone() + .context("Jellyfin did not report a path for this item")?, + ); + let folder = match kind { + ItemKind::Movie => item_path + .parent() + .context("movie path has no parent folder")? + .to_path_buf(), + ItemKind::Series => item_path.clone(), + }; + + let libraries = jf.virtual_folders().await?; + let (library, location) = libraries + .iter() + .find_map(|lib| { + check_inside_library(&folder, &lib.locations) + .ok() + .map(|loc| (lib, loc.to_string())) + }) + .with_context(|| { + // Re-run against all locations for a precise error. + let all: Vec = libraries.iter().flat_map(|l| l.locations.clone()).collect(); + match check_inside_library(&folder, &all) { + Err(e) => format!("{}: {e}", folder.display()), + Ok(_) => format!("{} is not in a library", folder.display()), + } + })?; + let rel_folder = relative_inside(Path::new(&location), &folder) + .context("item folder is not below its library")?; + + let local_folder = state.cfg.path_map.to_local(&folder); + if !tokio::fs::metadata(&local_folder) + .await + .map(|m| m.is_dir()) + .unwrap_or(false) + { + bail!( + "folder {} (Jellyfin path {}) is not visible to jellymove; check the volume mounts or path_map", + local_folder.display(), + folder.display() + ); + } + + if kind == ItemKind::Movie { + let lf = local_folder.clone(); + let files = tokio::task::spawn_blocking(move || jm_transfer::list_relative(&lf)).await??; + let own: Vec = item + .media_sources + .iter() + .flatten() + .filter_map(|m| m.path.as_deref()) + .chain(std::iter::once(item_path.to_str().unwrap_or_default())) + .filter_map(|p| relative_inside(&folder, Path::new(p))) + .collect(); + check_movie_folder(&files, &own)?; + } + + let manifest = jm_transfer::build_manifest(&local_folder) + .await + .context("hashing files")?; + if manifest.files.is_empty() { + bail!("the item folder is empty"); + } + + // Capture each user's watch state now, before anything moves. + let mut user_data = Vec::new(); + let mut episode_keys = Vec::new(); + for user in jf.users().await? { + let root = jf + .items(&ItemQuery { + ids: Some(item_id), + user_id: Some(&user.id), + ..Default::default() + }) + .await?; + if let Some(ud) = root.into_iter().next().and_then(|i| i.user_data) { + push_record(&mut user_data, &user.name, ItemKey::Root, ud.into()); + } + if kind == ItemKind::Series { + let episodes = jf + .items(&ItemQuery { + parent_id: Some(item_id), + include_types: &["Episode"], + recursive: true, + user_id: Some(&user.id), + ..Default::default() + }) + .await?; + for ep in episodes { + let (Some(season), Some(episode)) = (ep.parent_index_number, ep.index_number) + else { + continue; + }; + let key = ItemKey::Episode { season, episode }; + if !episode_keys.contains(&key) { + episode_keys.push(key); + } + if let Some(ud) = ep.user_data { + push_record(&mut user_data, &user.name, key, ud.into()); + } + } + } + } + + let info = ExportInfo { + item_id: item_id.to_string(), + name: item.name, + kind, + library_name: library.name.clone(), + rel_folder, + manifest, + user_data, + episode_keys, + }; + Ok((info, folder.display().to_string(), location)) +} + +fn push_record( + out: &mut Vec, + user: &str, + key: ItemKey, + data: jm_core::userdata::UserData, +) { + if !data.is_empty() { + out.push(UserDataRecord { + user_name: user.to_string(), + key, + data, + }); + } +} + +/// Final step on the source: move the folder into a hidden trash folder in +/// the same library (same filesystem, so it's a rename) and rescan. +pub async fn complete(state: &Shared, id: &str) -> anyhow::Result { + let mut export: Export = state + .store + .get_export(id) + .await? + .context("no such export")?; + match &export.status { + ExportStatus::Completed => return Ok(export), + ExportStatus::Ready => {} + other => bail!("export is not ready to complete ({other:?})"), + } + let info = export.info.as_ref().context("export has no info")?; + let local_folder = export.local_folder(state); + let location_local = state + .cfg + .path_map + .to_local(Path::new(&export.jellyfin_location)); + let trash_root = location_local.join(".jellymove-trash"); + let trash = join_relative(&trash_root.join(&export.id), &info.rel_folder) + .context("unsafe folder name")?; + + if tokio::fs::metadata(&local_folder).await.is_ok() { + if let Some(parent) = trash.parent() { + tokio::fs::create_dir_all(parent).await?; + } + let marker = trash_root.join(".ignore"); + if tokio::fs::metadata(&marker).await.is_err() { + tokio::fs::write(&marker, b"").await?; + } + tokio::fs::rename(&local_folder, &trash) + .await + .with_context(|| format!("moving {} to the trash", local_folder.display()))?; + tracing::info!(from = %local_folder.display(), to = %trash.display(), "source moved to trash"); + } + + if let Err(e) = state + .jellyfin + .media_updated(std::slice::from_ref(&export.jellyfin_folder)) + .await + { + tracing::warn!(error = %e, "could not ask Jellyfin to rescan the source folder"); + } + export.status = ExportStatus::Completed; + state.store.put_export(&export.id, &export).await?; + Ok(export) +} diff --git a/crates/jm-server/src/lib.rs b/crates/jm-server/src/lib.rs new file mode 100644 index 0000000..41054d2 --- /dev/null +++ b/crates/jm-server/src/lib.rs @@ -0,0 +1,58 @@ +//! The jellymove daemon: HTTP API, embedded UI, job runner and source exports. + +pub mod api; +pub mod config; +pub mod export; +pub mod library; +pub mod peer; +pub mod runner; +pub mod state; +pub mod ui; + +use std::sync::Arc; + +pub use config::Config; +use tower_http::trace::TraceLayer; + +/// Open state, resume interrupted jobs and serve until shutdown. +pub async fn run(cfg: Config) -> anyhow::Result<()> { + std::fs::create_dir_all(&cfg.data_dir)?; + let store = jm_store::Store::open(&cfg.data_dir.join("jellymove.db"))?; + let listen = cfg.listen; + let state = Arc::new(state::AppState::new(cfg, store)?); + + match state.jellyfin.system_info().await { + Ok(i) => { + tracing::info!(server = %i.server_name, version = %i.version, "connected to Jellyfin") + } + Err(e) => { + tracing::warn!(error = %e, "can't reach Jellyfin yet; will keep trying on demand") + } + } + runner::resume_all(&state).await?; + + let app = api::router(state.clone()).layer(TraceLayer::new_for_http()); + let listener = tokio::net::TcpListener::bind(listen).await?; + tracing::info!(%listen, node = %state.cfg.node_name, "jellymove listening"); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await?; + Ok(()) +} + +async fn shutdown_signal() { + let ctrl_c = async { + let _ = tokio::signal::ctrl_c().await; + }; + #[cfg(unix)] + let term = async { + if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + { + s.recv().await; + } + }; + #[cfg(not(unix))] + let term = std::future::pending::<()>(); + tokio::select! { _ = ctrl_c => {}, _ = term => {} } + tracing::info!("shutting down; in-flight transfers will resume on next start"); +} diff --git a/crates/jm-server/src/library.rs b/crates/jm-server/src/library.rs new file mode 100644 index 0000000..cdecf8a --- /dev/null +++ b/crates/jm-server/src/library.rs @@ -0,0 +1,114 @@ +//! Browsing the local Jellyfin libraries. + +use std::path::Path; + +use jm_jellyfin::ItemQuery; +use serde::{Deserialize, Serialize}; + +use crate::state::AppState; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Library { + pub id: String, + pub name: String, + pub collection_type: Option, + pub locations: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LibraryItem { + pub id: String, + pub name: String, + /// "Movie" or "Series". + pub kind: String, + pub year: Option, + pub path: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LocationCheck { + pub library: String, + pub jellyfin_path: String, + pub local_path: String, + pub exists: bool, + pub writable: bool, +} + +/// Only libraries jellymove knows how to move items out of. +fn supported(collection_type: Option<&str>) -> bool { + matches!(collection_type, Some("movies") | Some("tvshows") | None) +} + +pub async fn libraries(state: &AppState) -> anyhow::Result> { + Ok(state + .jellyfin + .virtual_folders() + .await? + .into_iter() + .filter(|v| supported(v.collection_type.as_deref())) + .map(|v| Library { + id: v.item_id, + name: v.name, + collection_type: v.collection_type, + locations: v.locations, + }) + .collect()) +} + +pub async fn items( + state: &AppState, + library_id: &str, + search: Option<&str>, +) -> anyhow::Result> { + let search = search.map(str::trim).filter(|s| !s.is_empty()); + let items = state + .jellyfin + .items(&ItemQuery { + parent_id: Some(library_id), + include_types: &["Movie", "Series"], + recursive: true, + search, + ..Default::default() + }) + .await?; + Ok(items + .into_iter() + .map(|i| LibraryItem { + id: i.id, + name: i.name, + kind: i.kind, + year: i.production_year, + path: i.path, + }) + .collect()) +} + +/// Confirm every library location exists and is writable from this agent. +/// The most common setup mistakes (wrong mount, wrong PUID/PGID, missing +/// path_map) all show up here. +pub async fn check_locations(state: &AppState) -> anyhow::Result> { + let mut out = Vec::new(); + for lib in libraries(state).await? { + for loc in &lib.locations { + let local = state.cfg.path_map.to_local(Path::new(loc)); + let exists = tokio::fs::metadata(&local) + .await + .map(|m| m.is_dir()) + .unwrap_or(false); + let writable = exists && { + let probe = local.join(format!(".jellymove-probe-{}", uuid::Uuid::new_v4())); + let ok = tokio::fs::write(&probe, b"").await.is_ok(); + let _ = tokio::fs::remove_file(&probe).await; + ok + }; + out.push(LocationCheck { + library: lib.name.clone(), + jellyfin_path: loc.clone(), + local_path: local.display().to_string(), + exists, + writable, + }); + } + } + Ok(out) +} diff --git a/crates/jm-server/src/peer.rs b/crates/jm-server/src/peer.rs new file mode 100644 index 0000000..43ec8b7 --- /dev/null +++ b/crates/jm-server/src/peer.rs @@ -0,0 +1,126 @@ +//! Client for the other agent's `/peer/v1` API. + +use jm_core::Job; +use reqwest::header::AUTHORIZATION; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; + +use crate::export::Export; +use crate::library::{Library, LibraryItem}; + +#[derive(Clone)] +pub struct PeerClient { + http: reqwest::Client, + base: String, + token: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct NodeInfo { + pub node_name: String, + pub version: String, + pub jellyfin_server: Option, + pub jellyfin_version: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CreateJob { + pub item_id: String, + pub name: String, + #[serde(default)] + pub dry_run: bool, +} + +impl PeerClient { + pub fn new(http: reqwest::Client, base: &str, token: &str) -> Self { + Self { + http, + base: base.trim_end_matches('/').to_string(), + token: token.to_string(), + } + } + + fn url(&self, path: &str) -> String { + format!("{}/peer/v1{path}", self.base) + } + + async fn send( + &self, + req: reqwest::RequestBuilder, + what: &str, + ) -> anyhow::Result { + let resp = req + .header(AUTHORIZATION, format!("Bearer {}", self.token)) + .timeout(std::time::Duration::from_secs(60)) + .send() + .await + .map_err(|e| anyhow::anyhow!("could not reach peer ({what}): {e}"))?; + let status = resp.status(); + if !status.is_success() { + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!("peer refused {what}: HTTP {status}: {body}"); + } + Ok(resp.json().await?) + } + + pub async fn info(&self) -> anyhow::Result { + self.send(self.http.get(self.url("/info")), "info").await + } + + pub async fn libraries(&self) -> anyhow::Result> { + self.send(self.http.get(self.url("/libraries")), "list libraries") + .await + } + + pub async fn items( + &self, + library: &str, + search: Option<&str>, + ) -> anyhow::Result> { + let mut q = vec![("library", library)]; + if let Some(s) = search { + q.push(("search", s)); + } + self.send(self.http.get(self.url("/items")).query(&q), "list items") + .await + } + + pub async fn create_export(&self, item_id: &str) -> anyhow::Result { + self.send( + self.http + .post(self.url("/exports")) + .json(&serde_json::json!({ "item_id": item_id })), + "create export", + ) + .await + } + + pub async fn export(&self, id: &str) -> anyhow::Result { + self.send( + self.http.get(self.url(&format!("/exports/{id}"))), + "get export", + ) + .await + } + + pub fn file_url(&self, export_id: &str, idx: usize) -> String { + self.url(&format!("/exports/{export_id}/files/{idx}")) + } + + pub async fn complete_export(&self, id: &str) -> anyhow::Result { + self.send( + self.http.post(self.url(&format!("/exports/{id}/complete"))), + "clean up source", + ) + .await + } + + pub async fn create_job(&self, req: &CreateJob) -> anyhow::Result { + self.send(self.http.post(self.url("/jobs")).json(req), "start job") + .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 new file mode 100644 index 0000000..42c66cc --- /dev/null +++ b/crates/jm-server/src/runner.rs @@ -0,0 +1,503 @@ +//! Destination side of a move: drives a job through its stages. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, bail}; +use jm_core::job::ExportInfo; +use jm_core::paths::join_relative; +use jm_core::userdata::{ItemKey, same_user}; +use jm_core::{ItemKind, Job, JobStatus, Stage}; +use jm_jellyfin::ItemQuery; + +use crate::export::ExportStatus; +use crate::state::Shared; + +enum Flow { + Continue, + Stop, +} + +/// Re-queue jobs that were active when the daemon last stopped. +pub async fn resume_all(state: &Shared) -> anyhow::Result<()> { + for job in state.store.active_jobs().await? { + tracing::info!(job = %job.id, name = %job.name, stage = ?job.stage, "resuming job"); + start(state.clone(), job); + } + Ok(()) +} + +/// Run a job in the background. A job that is already running is ignored. +pub fn start(state: Shared, mut job: Job) { + if !state.running.lock().expect("lock").insert(job.id) { + return; + } + tokio::spawn(async move { + job.status = JobStatus::Queued; + let _ = state.save(&job).await; + let _permit = state + .job_slots + .clone() + .acquire_owned() + .await + .expect("semaphore closed"); + job.status = JobStatus::Running; + job.note(format!("started at stage {:?}", job.stage)); + let _ = state.save(&job).await; + + loop { + if job.stage == Stage::Done { + job.status = JobStatus::Done; + job.note("move complete"); + break; + } + match step(&state, &mut job).await { + Ok(Flow::Continue) => { + let _ = state.save(&job).await; + } + Ok(Flow::Stop) => break, + Err(e) => { + let msg = format!("{e:#}"); + tracing::warn!(job = %job.id, stage = ?job.stage, error = %msg, "job failed"); + job.note(format!("failed: {msg}")); + job.status = JobStatus::Failed(msg); + break; + } + } + } + if let Err(e) = state.save(&job).await { + tracing::error!(job = %job.id, error = %e, "could not save job"); + } + state.running.lock().expect("lock").remove(&job.id); + }); +} + +async fn step(state: &Shared, job: &mut Job) -> anyhow::Result { + match job.stage { + Stage::Created => plan(state, job).await, + Stage::ExportReady => copy(state, job).await.map(|_| Flow::Continue), + Stage::Copied => promote(state, job).await.map(|_| Flow::Continue), + Stage::Promoted => wait_for_scan(state, job).await.map(|_| Flow::Continue), + Stage::TargetScanned => apply_user_data(state, job).await.map(|_| Flow::Continue), + Stage::UserDataApplied => clean_source(state, job).await.map(|_| Flow::Continue), + Stage::SourceCleaned => finish(state, job).await.map(|_| Flow::Continue), + Stage::Done => Ok(Flow::Stop), + } +} + +fn info(job: &Job) -> anyhow::Result<&ExportInfo> { + job.export.as_ref().context("job has no export info") +} + +fn target_jellyfin(job: &Job) -> anyhow::Result { + Ok(PathBuf::from( + job.target_folder_jellyfin + .as_deref() + .context("job has no target folder")?, + )) +} + +/// Destination library location (local path) that holds the target folder. +fn target_library_root(state: &Shared, job: &Job) -> anyhow::Result { + let info = info(job)?; + let target = target_jellyfin(job)?; + let depth = info.rel_folder.split('/').count(); + let mut root = target.as_path(); + for _ in 0..depth { + root = root + .parent() + .context("target folder is shallower than expected")?; + } + Ok(state.cfg.path_map.to_local(root)) +} + +async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result { + let peer = state.peer()?; + if job.export_id.is_none() { + let export = peer.create_export(&job.source_item_id).await?; + job.note("source is checking and hashing the item"); + job.export_id = Some(export.id); + state.save(job).await?; + } + let export_id = job.export_id.clone().expect("set above"); + + // Hashing a 50 GB remux takes a while on slow disks; just keep polling. + let export = loop { + let e = peer.export(&export_id).await?; + match &e.status { + ExportStatus::Ready => break e, + ExportStatus::Preparing => tokio::time::sleep(Duration::from_secs(2)).await, + ExportStatus::Failed(why) => bail!("source refused: {why}"), + ExportStatus::Completed => bail!("source already completed this export"), + } + }; + let info = export.info.context("source sent no item info")?; + + // Choose the destination library. + let wanted = state + .cfg + .incoming_libraries + .get(&info.library_name) + .unwrap_or(&info.library_name) + .clone(); + let libraries = state.jellyfin.virtual_folders().await?; + let lib = libraries + .iter() + .find(|l| l.name == wanted) + .with_context(|| { + format!( + "this server has no library called \"{wanted}\". Create it, or map it with \ + incoming_libraries.\"{}\" = \"\"", + info.library_name + ) + })?; + let expected = match info.kind { + ItemKind::Movie => "movies", + ItemKind::Series => "tvshows", + }; + if let Some(ct) = &lib.collection_type { + if ct != expected { + bail!( + "library \"{}\" holds {ct}, but {} is a {:?}", + lib.name, + info.name, + info.kind + ); + } + } + let location = lib + .locations + .first() + .context("destination library has no folders")?; + let target = join_relative(Path::new(location), &info.rel_folder) + .context("unsafe folder name from source")?; + let target_local = state.cfg.path_map.to_local(&target); + if tokio::fs::metadata(&target_local).await.is_ok() { + bail!( + "{} already exists on this server; refusing to merge into it", + target_local.display() + ); + } + + job.name = info.name.clone(); + job.progress.bytes_total = info.manifest.total_bytes(); + job.target_library = Some(lib.name.clone()); + job.target_folder_jellyfin = Some(target.display().to_string()); + job.note(format!( + "plan: {} files, {} into \"{}\" at {}", + info.manifest.files.len(), + human_bytes(job.progress.bytes_total), + lib.name, + target.display() + )); + job.export = Some(info); + + if job.dry_run { + job.status = JobStatus::Planned; + job.note("dry run: stopping before anything is copied"); + return Ok(Flow::Stop); + } + job.advance(Stage::ExportReady); + Ok(Flow::Continue) +} + +async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { + let peer = state.peer()?; + let export_id = job.export_id.clone().context("no export")?; + let files = info(job)?.manifest.files.clone(); + let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string()); + jm_transfer::prepare_partial(&partial).await?; + + let mut done_before: u64 = 0; + let mut last_emit = Instant::now(); + let mut last_save = Instant::now(); + for (idx, entry) in files.iter().enumerate() { + job.progress.current_file = Some(entry.rel_path.clone()); + let url = peer.file_url(&export_id, idx); + let part = jm_transfer::part_path(&partial, idx); + let base = done_before; + let snapshot_state = state.clone(); + let mut snapshot = job.clone(); + let mut on_progress = |have: u64| { + if last_emit.elapsed() >= Duration::from_millis(500) { + snapshot.progress.bytes_done = base + have; + let _ = snapshot_state.events.send(snapshot.clone()); + last_emit = Instant::now(); + } + if last_save.elapsed() >= Duration::from_secs(2) { + snapshot.progress.bytes_done = base + have; + let (st, snap) = (snapshot_state.clone(), snapshot.clone()); + tokio::spawn(async move { + let _ = st.store.put_job(&snap).await; + }); + last_save = Instant::now(); + } + }; + state + .puller + .pull_verified(&url, entry, &part, &mut on_progress) + .await + .with_context(|| format!("copying {}", entry.rel_path))?; + done_before += entry.size; + job.progress.bytes_done = done_before; + if last_save.elapsed() >= Duration::from_secs(2) { + state.save(job).await?; + last_save = Instant::now(); + } + } + job.progress.current_file = None; + job.note(format!("copied and verified {} files", files.len())); + job.advance(Stage::Copied); + Ok(()) +} + +async fn promote(state: &Shared, job: &mut Job) -> anyhow::Result<()> { + let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string()); + let target_local = state.cfg.path_map.to_local(&target_jellyfin(job)?); + jm_transfer::promote(&partial, &target_local, &info(job)?.manifest).await?; + job.note(format!("moved into {}", target_local.display())); + job.advance(Stage::Promoted); + Ok(()) +} + +async fn wait_for_scan(state: &Shared, job: &mut Job) -> anyhow::Result<()> { + let target = target_jellyfin(job)?; + let target_str = target.display().to_string(); + state + .jellyfin + .media_updated(std::slice::from_ref(&target_str)) + .await?; + job.note( + "asked Jellyfin to scan the new folder (it waits LibraryMonitorDelay, 60 s by default)", + ); + state.save(job).await?; + + let info = info(job)?.clone(); + let deadline = Instant::now() + Duration::from_secs(state.cfg.transfer.scan_timeout_secs); + let mut nudged = false; + loop { + if let Some(id) = find_new_item(state, job, &info, &target).await? { + let missing = missing_episodes(state, &id, &info).await?; + if missing == 0 { + job.target_item_id = Some(id); + job.note("Jellyfin has indexed the item"); + job.advance(Stage::TargetScanned); + return Ok(()); + } + tracing::debug!(job = %job.id, missing, "waiting for episodes to appear"); + } + if Instant::now() > deadline { + bail!( + "Jellyfin hadn't indexed everything after {} s. Check the library on this server, \ + then retry: the copied files are in place and nothing has been deleted from the source", + state.cfg.transfer.scan_timeout_secs + ); + } + // Halfway through, nudge again in case the first update was dropped. + if !nudged + && deadline.saturating_duration_since(Instant::now()).as_secs() + < state.cfg.transfer.scan_timeout_secs / 2 + { + let _ = state + .jellyfin + .media_updated(std::slice::from_ref(&target_str)) + .await; + nudged = true; + } + tokio::time::sleep(Duration::from_secs(5)).await; + } +} + +/// Find the item Jellyfin created for the moved folder, by path. +async fn find_new_item( + state: &Shared, + job: &Job, + info: &ExportInfo, + target: &Path, +) -> anyhow::Result> { + let lib_name = job.target_library.as_deref().context("no target library")?; + let libs = state.jellyfin.virtual_folders().await?; + let lib = libs + .iter() + .find(|l| l.name == lib_name) + .context("target library disappeared")?; + let kind = match info.kind { + ItemKind::Movie => "Movie", + ItemKind::Series => "Series", + }; + let matches = |p: &str| match info.kind { + ItemKind::Movie => Path::new(p).parent() == Some(target), + ItemKind::Series => Path::new(p) == target, + }; + // Search by name first (cheap), then fall back to listing the library. + for search in [Some(info.name.as_str()), None] { + let items = state + .jellyfin + .items(&ItemQuery { + parent_id: Some(&lib.item_id), + include_types: &[kind], + recursive: true, + search, + ..Default::default() + }) + .await?; + if let Some(found) = items + .into_iter() + .find(|i| i.path.as_deref().is_some_and(matches)) + { + return Ok(Some(found.id)); + } + } + Ok(None) +} + +async fn episode_ids(state: &Shared, series_id: &str) -> anyhow::Result> { + let eps = state + .jellyfin + .items(&ItemQuery { + parent_id: Some(series_id), + include_types: &["Episode"], + recursive: true, + ..Default::default() + }) + .await?; + Ok(eps + .into_iter() + .filter_map(|e| { + Some(( + ItemKey::Episode { + season: e.parent_index_number?, + episode: e.index_number?, + }, + e.id, + )) + }) + .collect()) +} + +async fn missing_episodes( + state: &Shared, + series_id: &str, + info: &ExportInfo, +) -> anyhow::Result { + if info.kind != ItemKind::Series || info.episode_keys.is_empty() { + return Ok(0); + } + let found = episode_ids(state, series_id).await?; + Ok(info + .episode_keys + .iter() + .filter(|k| !found.contains_key(k)) + .count()) +} + +async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> { + let info = info(job)?.clone(); + let root_id = job.target_item_id.clone().context("no target item")?; + let episodes = if info.kind == ItemKind::Series { + episode_ids(state, &root_id).await? + } else { + HashMap::new() + }; + let users = state.jellyfin.users().await?; + + let (mut applied, mut no_user, mut no_item) = (0, 0, 0); + let mut unknown_users: Vec = Vec::new(); + for rec in &info.user_data { + let Some(user) = users.iter().find(|u| same_user(&u.name, &rec.user_name)) else { + no_user += 1; + if !unknown_users.contains(&rec.user_name) { + unknown_users.push(rec.user_name.clone()); + } + continue; + }; + let item_id = match rec.key { + ItemKey::Root => Some(&root_id), + key => episodes.get(&key), + }; + let Some(item_id) = item_id else { + no_item += 1; + continue; + }; + state + .jellyfin + .set_user_data(&user.id, item_id, &rec.data) + .await?; + applied += 1; + } + job.note(format!("restored {applied} watch-state records")); + if no_user > 0 { + job.note(format!( + "skipped {no_user} records for users missing on this server: {}", + unknown_users.join(", ") + )); + } + if no_item > 0 { + job.note(format!( + "skipped {no_item} records whose episode wasn't found" + )); + } + job.advance(Stage::UserDataApplied); + Ok(()) +} + +async fn clean_source(state: &Shared, job: &mut Job) -> anyhow::Result<()> { + let export_id = job.export_id.clone().context("no export")?; + state.peer()?.complete_export(&export_id).await?; + job.note("source folder moved to its trash and source library rescanned"); + job.advance(Stage::SourceCleaned); + Ok(()) +} + +async fn finish(state: &Shared, job: &mut Job) -> anyhow::Result<()> { + if let Some(cmd) = state + .cfg + .hooks + .post_move + .as_deref() + .filter(|c| !c.trim().is_empty()) + { + let mut command = if cfg!(windows) { + let mut c = tokio::process::Command::new("cmd"); + c.arg("/C").arg(cmd); + c + } else { + let mut c = tokio::process::Command::new("sh"); + c.arg("-c").arg(cmd); + c + }; + command.env("JELLYMOVE_ITEM_NAME", &job.name).env( + "JELLYMOVE_TARGET_FOLDER", + job.target_folder_jellyfin.as_deref().unwrap_or_default(), + ); + // A failing hook is reported but doesn't undo a finished move. + match tokio::time::timeout(Duration::from_secs(300), command.output()).await { + Ok(Ok(out)) if out.status.success() => job.note("post-move hook ran"), + Ok(Ok(out)) => job.note(format!( + "post-move hook exited with {}: {}", + out.status, + String::from_utf8_lossy(&out.stderr).trim() + )), + Ok(Err(e)) => job.note(format!("post-move hook could not start: {e}")), + Err(_) => job.note("post-move hook timed out after 5 minutes"), + } + } + job.advance(Stage::Done); + Ok(()) +} + +pub fn human_bytes(b: u64) -> String { + const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; + let mut v = b as f64; + let mut u = 0; + while v >= 1000.0 && u < UNITS.len() - 1 { + v /= 1000.0; + u += 1; + } + if u == 0 { + format!("{b} B") + } else { + format!("{v:.1} {}", UNITS[u]) + } +} diff --git a/crates/jm-server/src/state.rs b/crates/jm-server/src/state.rs new file mode 100644 index 0000000..650eaa6 --- /dev/null +++ b/crates/jm-server/src/state.rs @@ -0,0 +1,76 @@ +use std::collections::HashSet; +use std::sync::{Arc, Mutex}; + +use jm_core::{Job, JobId}; +use jm_store::Store; +use jm_transfer::{Puller, PullerOptions}; +use tokio::sync::{Semaphore, broadcast}; + +use crate::config::Config; +use crate::peer::PeerClient; + +pub struct AppState { + pub cfg: Config, + pub store: Store, + pub jellyfin: jm_jellyfin::Client, + pub peer: Option, + pub puller: Puller, + /// Job snapshots for the UI's live view. + pub events: broadcast::Sender, + pub job_slots: Arc, + pub running: Mutex>, + /// Exports currently being hashed, so a duplicate request doesn't start a second pass. + pub preparing: Mutex>, +} + +pub type Shared = Arc; + +impl AppState { + pub fn new(cfg: Config, store: Store) -> anyhow::Result { + let jellyfin = jm_jellyfin::Client::new(&cfg.jellyfin.url, &cfg.jellyfin.api_key)?; + // Transfers can run for hours; only bound the connect phase. + let http = reqwest::Client::builder() + .connect_timeout(std::time::Duration::from_secs(20)) + .read_timeout(std::time::Duration::from_secs(120)) + .build()?; + let peer = cfg + .peer + .as_ref() + .map(|p| PeerClient::new(http.clone(), &p.url, &p.token)); + let puller = Puller::new( + http, + PullerOptions { + token: cfg.peer.as_ref().map(|p| p.token.clone()), + bytes_per_sec: cfg.bytes_per_sec(), + attempts: cfg.transfer.retries.max(1), + ..Default::default() + }, + ); + let (events, _) = broadcast::channel(256); + let slots = cfg.transfer.max_concurrent_jobs.max(1); + Ok(Self { + cfg, + store, + jellyfin, + peer, + puller, + events, + job_slots: Arc::new(Semaphore::new(slots)), + running: Mutex::new(HashSet::new()), + preparing: Mutex::new(HashSet::new()), + }) + } + + pub fn peer(&self) -> anyhow::Result<&PeerClient> { + self.peer + .as_ref() + .ok_or_else(|| anyhow::anyhow!("no peer is configured on this node")) + } + + /// Save a job and tell anyone watching. + pub async fn save(&self, job: &Job) -> anyhow::Result<()> { + self.store.put_job(job).await?; + let _ = self.events.send(job.clone()); + Ok(()) + } +} diff --git a/crates/jm-server/src/ui.rs b/crates/jm-server/src/ui.rs new file mode 100644 index 0000000..93670c0 --- /dev/null +++ b/crates/jm-server/src/ui.rs @@ -0,0 +1,50 @@ +//! The web UI, compiled into the binary. Build it with `npm --prefix ui run build` +//! before `cargo build --release`; in debug builds files are read from disk. + +use axum::body::Body; +use axum::http::{StatusCode, Uri, header}; +use axum::response::{IntoResponse, Response}; +use rust_embed::RustEmbed; + +#[derive(RustEmbed)] +#[folder = "../../ui/dist"] +#[allow_missing = true] +struct Assets; + +pub async fn serve(uri: Uri) -> Response { + let path = uri.path().trim_start_matches('/'); + if path.starts_with("api/") || path.starts_with("peer/") { + return StatusCode::NOT_FOUND.into_response(); + } + if let Some(r) = asset(if path.is_empty() { "index.html" } else { path }) { + return r; + } + // Single-page app: unknown paths get the shell. + asset("index.html").unwrap_or_else(|| { + ( + StatusCode::OK, + [(header::CONTENT_TYPE, "text/html; charset=utf-8")], + "

jellymove

The web UI wasn't built into this binary. \ + Run npm --prefix ui ci && npm --prefix ui run build, then rebuild.

", + ) + .into_response() + }) +} + +fn asset(path: &str) -> Option { + let file = Assets::get(path)?; + let mime = mime_guess::from_path(path).first_or_octet_stream(); + // Vite fingerprints everything under assets/, so it can be cached forever. + let cache = if path.starts_with("assets/") { + "public, max-age=31536000, immutable" + } else { + "no-cache" + }; + Some( + Response::builder() + .header(header::CONTENT_TYPE, mime.as_ref()) + .header(header::CACHE_CONTROL, cache) + .body(Body::from(file.data.into_owned())) + .expect("valid response"), + ) +} diff --git a/crates/jm-server/tests/e2e.rs b/crates/jm-server/tests/e2e.rs new file mode 100644 index 0000000..7b8b85f --- /dev/null +++ b/crates/jm-server/tests/e2e.rs @@ -0,0 +1,412 @@ +//! Two real jellymove agents, each with its own fake Jellyfin and media +//! folders, moving items between them through the same HTTP APIs the UI uses. + +#[allow(dead_code)] +mod fake_jellyfin; + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use fake_jellyfin::{Fake, Lib}; +use jm_server::config::{ + Config, HooksConfig, JellyfinConfig, PeerConfig, TransferConfig, UiConfig, +}; +use serde_json::{Value, json}; + +const TOKEN: &str = "test-token"; + +struct Node { + _tmp: tempfile::TempDir, + root: PathBuf, + fake: Fake, + url: String, +} + +impl Node { + fn movies(&self) -> PathBuf { + self.root.join("movies") + } + fn tv(&self) -> PathBuf { + self.root.join("tv") + } +} + +fn libs(root: &Path) -> Vec { + vec![ + Lib { + name: "Movies".into(), + collection_type: "movies", + location: root.join("movies"), + }, + Lib { + name: "TV Shows".into(), + collection_type: "tvshows", + location: root.join("tv"), + }, + ] +} + +fn write(path: &Path, data: &[u8]) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, data).unwrap(); +} + +/// Start two peered agents. `seed` fills the first node's media folders. +async fn pair(seed: impl FnOnce(&Path)) -> (Node, Node) { + let tmp_a = tempfile::tempdir().unwrap(); + let tmp_b = tempfile::tempdir().unwrap(); + for t in [&tmp_a, &tmp_b] { + std::fs::create_dir_all(t.path().join("movies")).unwrap(); + std::fs::create_dir_all(t.path().join("tv")).unwrap(); + } + seed(tmp_a.path()); + + let fake_a = Fake::new(libs(tmp_a.path())); + let fake_b = Fake::new(libs(tmp_b.path())); + let jf_a = fake_a.clone().serve().await; + let jf_b = fake_b.clone().serve().await; + + let la = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let lb = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url_a = format!("http://{}", la.local_addr().unwrap()); + let url_b = format!("http://{}", lb.local_addr().unwrap()); + + for (name, tmp, jf, listener, peer_url) in [ + ("cloud", &tmp_a, jf_a, la, url_b.clone()), + ("home", &tmp_b, jf_b, lb, url_a.clone()), + ] { + let cfg = Config { + node_name: name.into(), + listen: listener.local_addr().unwrap(), + data_dir: tmp.path().join("state"), + jellyfin: JellyfinConfig { + url: jf, + api_key: "k".into(), + }, + path_map: Default::default(), + peer: Some(PeerConfig { + url: peer_url, + token: TOKEN.into(), + }), + incoming_libraries: Default::default(), + transfer: TransferConfig { + scan_timeout_secs: 60, + ..Default::default() + }, + ui: UiConfig::default(), + hooks: HooksConfig::default(), + }; + std::fs::create_dir_all(&cfg.data_dir).unwrap(); + let store = jm_store::Store::open(&cfg.data_dir.join("db")).unwrap(); + let state = Arc::new(jm_server::state::AppState::new(cfg, store).unwrap()); + let app = jm_server::api::router(state); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + } + + let a = Node { + root: tmp_a.path().to_path_buf(), + _tmp: tmp_a, + fake: fake_a, + url: url_a, + }; + let b = Node { + root: tmp_b.path().to_path_buf(), + _tmp: tmp_b, + fake: fake_b, + url: url_b, + }; + (a, b) +} + +async fn post(base: &str, path: &str, body: Value) -> reqwest::Response { + reqwest::Client::new() + .post(format!("{base}{path}")) + .header("X-Jellymove", "1") + .json(&body) + .send() + .await + .unwrap() +} + +async fn get(base: &str, path: &str) -> Value { + reqwest::get(format!("{base}{path}")) + .await + .unwrap() + .json() + .await + .unwrap() +} + +/// Wait for the job to leave the active states; returns its final JSON. +async fn wait_job(base: &str, id: &str) -> Value { + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let jobs = get(base, "/api/jobs").await; + let all: Vec = [ + jobs["local"].as_array().unwrap().clone(), + jobs["peer"].as_array().unwrap().clone(), + ] + .concat(); + if let Some(j) = all.iter().find(|j| j["id"] == id) { + let kind = j["status"]["kind"].as_str().unwrap(); + if !matches!(kind, "Queued" | "Running") { + return j.clone(); + } + } + assert!(Instant::now() < deadline, "job {id} didn't finish in time"); + tokio::time::sleep(Duration::from_millis(250)).await; + } +} + +fn seed_movie(root: &Path) { + let m = root.join("movies/Alien (1979)"); + write(&m.join("Alien (1979).mkv"), &vec![7u8; 2 * 1024 * 1024]); + write( + &m.join("Alien (1979).nfo"), + b"Alien", + ); + write( + &m.join("Alien (1979).en.srt"), + b"1\n00:00:01,000 --> 00:00:02,000\nIn space...\n", + ); + write(&m.join("extras/Making of.mkv"), b"extra"); +} + +fn seed_series(root: &Path) { + let s = root.join("tv/Severance"); + write(&s.join("tvshow.nfo"), b""); + write(&s.join("Season 01/Severance S01E01.mkv"), b"episode one"); + write(&s.join("Season 01/Severance S01E02.mkv"), b"episode two"); + write(&s.join("Season 02/Severance S02E01.mkv"), b"episode three"); +} + +#[tokio::test] +async fn moves_a_movie_with_sidecars_and_watch_state() { + let (cloud, home) = pair(seed_movie).await; + let movie = cloud.fake.find("Movie", "Alien").unwrap(); + cloud.fake.set_user_data( + &movie, + json!({"Played": true, "PlayCount": 2, "IsFavorite": true}), + ); + + // Started from the cloud UI: "move this local item to the peer". + let resp = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": movie, "name": "Alien"}), + ) + .await; + assert!(resp.status().is_success(), "{}", resp.text().await.unwrap()); + let job: Value = resp.json().await.unwrap(); + let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await; + assert_eq!(done["status"]["kind"], "Done", "{done:#}"); + assert_eq!(done["target_node"], "home"); + + // Files arrived intact, sidecars included. + let dest = home.movies().join("Alien (1979)"); + assert_eq!( + std::fs::read(dest.join("Alien (1979).mkv")).unwrap(), + vec![7u8; 2 * 1024 * 1024] + ); + assert!(dest.join("Alien (1979).en.srt").exists()); + assert!(dest.join("extras/Making of.mkv").exists()); + // Nothing left in the partial area. + assert_eq!( + std::fs::read_dir(home.movies().join(".jellymove-partial")) + .unwrap() + .filter(|e| e.as_ref().unwrap().file_name() != ".ignore") + .count(), + 0 + ); + + // Source moved to the hidden trash, not deleted outright. + assert!(!cloud.movies().join("Alien (1979)").exists()); + let trash = cloud.movies().join(".jellymove-trash"); + assert!( + trash + .join(format!("item-{movie}/Alien (1979)/Alien (1979).mkv")) + .exists() + ); + + // Watch state followed the move to the new item ID. + let new_id = home.fake.find("Movie", "Alien").unwrap(); + assert_ne!(new_id, movie); + let ud = home.fake.get_user_data(&new_id).expect("user data applied"); + assert_eq!(ud["Played"], true); + assert_eq!(ud["PlayCount"], 2); + assert_eq!(ud["IsFavorite"], true); +} + +#[tokio::test] +async fn moves_a_series_and_maps_episode_watch_state() { + let (cloud, home) = pair(seed_series).await; + let series = cloud.fake.find("Series", "Severance").unwrap(); + let e1 = cloud.fake.episode_id("Severance", 1, 1).unwrap(); + let e3 = cloud.fake.episode_id("Severance", 2, 1).unwrap(); + cloud + .fake + .set_user_data(&e1, json!({"Played": true, "PlayCount": 1})); + cloud + .fake + .set_user_data(&e3, json!({"PlaybackPositionTicks": 123456789})); + + // Started from the *home* UI this time: "pull this item from the peer". + let resp = post( + &home.url, + "/api/moves", + json!({"from": "peer", "item_id": series, "name": "Severance"}), + ) + .await; + let job: Value = resp.json().await.unwrap(); + let done = wait_job(&home.url, job["id"].as_str().unwrap()).await; + assert_eq!(done["status"]["kind"], "Done", "{done:#}"); + + assert!( + home.tv() + .join("Severance/Season 02/Severance S02E01.mkv") + .exists() + ); + assert!(!cloud.tv().join("Severance").exists()); + + let new_e1 = home.fake.episode_id("Severance", 1, 1).unwrap(); + let new_e3 = home.fake.episode_id("Severance", 2, 1).unwrap(); + assert_eq!(home.fake.get_user_data(&new_e1).unwrap()["Played"], true); + assert_eq!( + home.fake.get_user_data(&new_e3).unwrap()["PlaybackPositionTicks"], + 123456789 + ); + // Untouched episode gets nothing written. + let new_e2 = home.fake.episode_id("Severance", 1, 2).unwrap(); + assert!(home.fake.get_user_data(&new_e2).is_none()); +} + +#[tokio::test] +async fn dry_run_changes_nothing() { + let (cloud, home) = pair(seed_movie).await; + let movie = cloud.fake.find("Movie", "Alien").unwrap(); + let job: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": movie, "name": "Alien", "dry_run": true}), + ) + .await + .json() + .await + .unwrap(); + let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await; + assert_eq!(done["status"]["kind"], "Planned", "{done:#}"); + assert!( + done["log"] + .as_array() + .unwrap() + .iter() + .any(|l| l.as_str().unwrap().contains("plan: 4 files")) + ); + assert!( + cloud + .movies() + .join("Alien (1979)/Alien (1979).mkv") + .exists() + ); + assert!(!home.movies().join("Alien (1979)").exists()); +} + +#[tokio::test] +async fn refuses_flat_movie_folder() { + let (cloud, home) = pair(|root| { + // Two movies sharing one folder: moving "the folder" would take both. + write(&root.join("movies/Unsorted/Heat (1995).mkv"), b"heat"); + write(&root.join("movies/Unsorted/Ronin (1998).mkv"), b"ronin"); + }) + .await; + let heat = cloud.fake.find("Movie", "Unsorted").unwrap(); + let job: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": heat, "name": "Heat"}), + ) + .await + .json() + .await + .unwrap(); + let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await; + assert_eq!(done["status"]["kind"], "Failed"); + assert!( + done["status"]["detail"] + .as_str() + .unwrap() + .contains("other videos"), + "{done:#}" + ); + assert!(cloud.movies().join("Unsorted/Ronin (1998).mkv").exists()); + assert!(!home.movies().join("Unsorted").exists()); +} + +#[tokio::test] +async fn refuses_when_destination_exists() { + let (cloud, home) = pair(seed_movie).await; + write( + &home.movies().join("Alien (1979)/Alien (1979).mkv"), + b"a different copy", + ); + let movie = cloud.fake.find("Movie", "Alien").unwrap(); + let job: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": movie, "name": "Alien"}), + ) + .await + .json() + .await + .unwrap(); + let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await; + assert_eq!(done["status"]["kind"], "Failed"); + assert!( + done["status"]["detail"] + .as_str() + .unwrap() + .contains("already exists") + ); + assert_eq!( + std::fs::read(home.movies().join("Alien (1979)/Alien (1979).mkv")).unwrap(), + b"a different copy" + ); + assert!(cloud.movies().join("Alien (1979)").exists()); +} + +#[tokio::test] +async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() { + let (cloud, _home) = pair(|_| {}).await; + let r = reqwest::Client::new() + .get(format!("{}/peer/v1/libraries", cloud.url)) + .bearer_auth("wrong") + .send() + .await + .unwrap(); + assert_eq!(r.status(), 401); + + let r = reqwest::Client::new() + .post(format!("{}/api/moves", cloud.url)) + .json(&json!({"from": "local", "item_id": "x", "name": "x"})) + .send() + .await + .unwrap(); + assert_eq!(r.status(), 403); +} + +#[tokio::test] +async fn export_files_are_only_reachable_by_index() { + let (cloud, _home) = pair(seed_movie).await; + // Path traversal attempts through the file route go nowhere. + let r = reqwest::Client::new() + .get(format!( + "{}/peer/v1/exports/..%2F..%2Fetc/files/0", + cloud.url + )) + .bearer_auth(TOKEN) + .send() + .await + .unwrap(); + assert_eq!(r.status(), 404); +} diff --git a/crates/jm-server/tests/fake_jellyfin/mod.rs b/crates/jm-server/tests/fake_jellyfin/mod.rs new file mode 100644 index 0000000..c9f12c4 --- /dev/null +++ b/crates/jm-server/tests/fake_jellyfin/mod.rs @@ -0,0 +1,296 @@ +//! A tiny filesystem-backed stand-in for Jellyfin, good enough to drive a +//! real move end to end. Like real Jellyfin, item IDs are derived from paths, +//! scans happen a moment after `/Library/Media/Updated`, and user data is +//! keyed by (user, item). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::extract::{Path as AxPath, Query, State}; +use axum::http::StatusCode; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use serde_json::{Value, json}; + +#[derive(Clone)] +pub struct Lib { + pub name: String, + pub collection_type: &'static str, + pub location: PathBuf, +} + +impl Lib { + pub fn id(&self) -> String { + format!("lib-{}", self.name.to_lowercase().replace(' ', "-")) + } +} + +#[derive(Clone, Debug)] +struct FakeItem { + id: String, + name: String, + kind: &'static str, + path: String, + parent: String, + season: Option, + episode: Option, +} + +#[derive(Clone)] +pub struct Fake { + libs: Arc>, + items: Arc>>, + /// (user id, item id) → UserData JSON + pub user_data: Arc>>, +} + +pub fn id_for(path: &Path) -> String { + blake3::hash(path.to_string_lossy().as_bytes()).to_hex()[..32].to_string() +} + +fn parse_sxxexx(name: &str) -> Option<(i32, i32)> { + // Find the first "SE" anywhere in the name. + let up = name.to_uppercase(); + let b = up.as_bytes(); + for i in 0..b.len() { + if b[i] != b'S' { + continue; + } + let s: String = up[i + 1..] + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect(); + let after = i + 1 + s.len(); + if s.is_empty() || b.get(after) != Some(&b'E') { + continue; + } + let e: String = up[after + 1..] + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect(); + if let (Ok(season), Ok(ep)) = (s.parse(), e.parse()) { + return Some((season, ep)); + } + } + None +} + +fn walk(dir: &Path, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { + return; + }; + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().to_string(); + if name.starts_with('.') { + continue; // Jellyfin skips hidden folders + } + if e.file_type().unwrap().is_dir() { + walk(&e.path(), out); + } else { + out.push(e.path()); + } + } +} + +impl Fake { + pub fn new(libs: Vec) -> Self { + let f = Self { + libs: Arc::new(libs), + items: Default::default(), + user_data: Default::default(), + }; + f.scan(); + f + } + + pub fn scan(&self) { + let mut items = Vec::new(); + for lib in self.libs.iter() { + let Ok(rd) = std::fs::read_dir(&lib.location) else { + continue; + }; + for entry in rd.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with('.') || !entry.file_type().unwrap().is_dir() { + continue; + } + let folder = entry.path(); + let mut files = Vec::new(); + walk(&folder, &mut files); + if lib.collection_type == "movies" { + for f in files + .iter() + .filter(|f| f.extension().is_some_and(|e| e == "mkv")) + { + if f.parent() != Some(folder.as_path()) { + continue; // extras + } + items.push(FakeItem { + id: id_for(f), + name: name.split(" (").next().unwrap().to_string(), + kind: "Movie", + path: f.display().to_string(), + parent: lib.id(), + season: None, + episode: None, + }); + } + } else { + let series_id = id_for(&folder); + items.push(FakeItem { + id: series_id.clone(), + name: name.clone(), + kind: "Series", + path: folder.display().to_string(), + parent: lib.id(), + season: None, + episode: None, + }); + for f in files + .iter() + .filter(|f| f.extension().is_some_and(|e| e == "mkv")) + { + let fname = f.file_name().unwrap().to_string_lossy(); + if let Some((s, e)) = parse_sxxexx(&fname) { + items.push(FakeItem { + id: id_for(f), + name: fname.to_string(), + kind: "Episode", + path: f.display().to_string(), + parent: series_id.clone(), + season: Some(s), + episode: Some(e), + }); + } + } + } + } + } + *self.items.lock().unwrap() = items; + } + + pub fn find(&self, kind: &str, name: &str) -> Option { + self.items + .lock() + .unwrap() + .iter() + .find(|i| i.kind == kind && i.name == name) + .map(|i| i.id.clone()) + } + + pub fn episode_id(&self, series: &str, season: i32, ep: i32) -> Option { + let series_id = self.find("Series", series)?; + self.items + .lock() + .unwrap() + .iter() + .find(|i| i.parent == series_id && i.season == Some(season) && i.episode == Some(ep)) + .map(|i| i.id.clone()) + } + + pub fn set_user_data(&self, item: &str, data: Value) { + self.user_data + .lock() + .unwrap() + .insert(("u1".into(), item.into()), data); + } + + pub fn get_user_data(&self, item: &str) -> Option { + self.user_data + .lock() + .unwrap() + .get(&("u1".to_string(), item.to_string())) + .cloned() + } + + pub async fn serve(self) -> String { + let app = Router::new() + .route( + "/System/Info", + get(|| async { + Json(json!({"ServerName": "fake", "Version": "10.11.0", "Id": "x"})) + }), + ) + .route( + "/Users", + get(|| async { Json(json!([{"Id": "u1", "Name": "Alice"}])) }), + ) + .route("/Library/VirtualFolders", get(virtual_folders)) + .route("/Items", get(items)) + .route("/Library/Media/Updated", post(media_updated)) + .route("/UserItems/{id}/UserData", post(set_user_data)) + .with_state(self); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } +} + +async fn virtual_folders(State(f): State) -> Json { + Json(Value::Array( + f.libs + .iter() + .map(|l| { + json!({"Name": l.name, "Locations": [l.location.display().to_string()], + "CollectionType": l.collection_type, "ItemId": l.id()}) + }) + .collect(), + )) +} + +async fn items(State(f): State, Query(q): Query>) -> Json { + let all = f.items.lock().unwrap().clone(); + let types: Option> = q.get("includeItemTypes").map(|t| t.split(',').collect()); + let ids: Option> = q.get("ids").map(|t| t.split(',').collect()); + let ud = f.user_data.lock().unwrap().clone(); + let user = q.get("userId"); + 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| types.as_ref().is_none_or(|t| t.contains(&i.kind))) + .filter(|i| { + q.get("searchTerm") + .is_none_or(|s| i.name.to_lowercase().contains(&s.to_lowercase())) + }) + .map(|i| { + let mut v = json!({"Id": i.id, "Name": i.name, "Type": i.kind, "Path": i.path, + "ParentIndexNumber": i.season, "IndexNumber": i.episode, + "MediaSources": [{"Path": i.path}]}); + if let Some(u) = user { + v["UserData"] = ud + .get(&(u.clone(), i.id.clone())) + .cloned() + .unwrap_or(json!({"Played": false})); + } + v + }) + .collect(); + let n = out.len(); + Json(json!({"Items": out, "TotalRecordCount": n})) +} + +async fn media_updated(State(f): State) -> StatusCode { + // Like Jellyfin's LibraryMonitorDelay, but much shorter. + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(300)).await; + f.scan(); + }); + StatusCode::NO_CONTENT +} + +async fn set_user_data( + State(f): State, + AxPath(id): AxPath, + Query(q): Query>, + Json(body): Json, +) -> StatusCode { + f.user_data + .lock() + .unwrap() + .insert((q["userId"].clone(), id), body); + StatusCode::OK +} diff --git a/crates/jm-store/Cargo.toml b/crates/jm-store/Cargo.toml new file mode 100644 index 0000000..998676c --- /dev/null +++ b/crates/jm-store/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "jm-store" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +jm-core = { version = "0.1.0", path = "../jm-core" } +rusqlite = { version = "0.40.2", features = ["bundled"] } +serde = "1.0.229" +serde_json = "1.0.154" +thiserror = "2.0.21" +tokio = { version = "1.54.1", features = ["macros", "rt", "rt-multi-thread", "sync"] } + +[dev-dependencies] +tempfile = "3.27.0" diff --git a/crates/jm-store/src/lib.rs b/crates/jm-store/src/lib.rs new file mode 100644 index 0000000..440cc3c --- /dev/null +++ b/crates/jm-store/src/lib.rs @@ -0,0 +1,208 @@ +//! Persistent state in SQLite (WAL mode). +//! +//! Jobs and exports are stored as JSON documents with a few indexed columns. +//! The schema is deliberately small; the job struct is the source of truth. + +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use jm_core::{Job, JobId}; +use rusqlite::{Connection, OptionalExtension, params}; +use serde::{Serialize, de::DeserializeOwned}; + +#[derive(Debug, thiserror::Error)] +pub enum StoreError { + #[error("database error: {0}")] + Sql(#[from] rusqlite::Error), + #[error("corrupt record: {0}")] + Json(#[from] serde_json::Error), +} + +type Result = std::result::Result; + +const MIGRATIONS: &[&str] = &[ + // v1 + "CREATE TABLE jobs ( + id TEXT PRIMARY KEY, + active INTEGER NOT NULL, + created TEXT NOT NULL, + body TEXT NOT NULL + ); + CREATE INDEX jobs_active ON jobs(active); + CREATE TABLE exports ( + id TEXT PRIMARY KEY, + body TEXT NOT NULL + );", +]; + +#[derive(Clone)] +pub struct Store { + conn: Arc>, +} + +impl Store { + pub fn open(path: &Path) -> Result { + Self::init(Connection::open(path)?) + } + + pub fn in_memory() -> Result { + Self::init(Connection::open_in_memory()?) + } + + fn init(conn: Connection) -> Result { + conn.pragma_update(None, "journal_mode", "WAL")?; + conn.pragma_update(None, "synchronous", "NORMAL")?; + let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?; + for (i, sql) in MIGRATIONS.iter().enumerate().skip(version as usize) { + conn.execute_batch(sql)?; + conn.pragma_update(None, "user_version", (i + 1) as i64)?; + } + Ok(Self { + conn: Arc::new(Mutex::new(conn)), + }) + } + + async fn with( + &self, + f: impl FnOnce(&Connection) -> Result + Send + 'static, + ) -> Result { + let conn = self.conn.clone(); + tokio::task::spawn_blocking(move || f(&conn.lock().expect("store mutex poisoned"))) + .await + .expect("store task panicked") + } + + pub async fn put_job(&self, job: &Job) -> Result<()> { + let id = job.id.to_string(); + let active = job.status.is_active(); + let created = job.created.unix_timestamp().to_string(); + let body = serde_json::to_string(job)?; + self.with(move |c| { + c.execute( + "INSERT INTO jobs (id, active, created, body) VALUES (?1, ?2, ?3, ?4) + ON CONFLICT(id) DO UPDATE SET active = excluded.active, body = excluded.body", + params![id, active, created, body], + )?; + Ok(()) + }) + .await + } + + pub async fn get_job(&self, id: JobId) -> Result> { + let id = id.to_string(); + let body: Option = self + .with(move |c| { + Ok( + c.query_row("SELECT body FROM jobs WHERE id = ?1", [id], |r| r.get(0)) + .optional()?, + ) + }) + .await?; + body.map(|b| serde_json::from_str(&b).map_err(Into::into)) + .transpose() + } + + /// Most recent jobs first. + pub async fn list_jobs(&self, limit: usize) -> Result> { + self.query_jobs( + "SELECT body FROM jobs ORDER BY created DESC, rowid DESC LIMIT ?1", + limit, + ) + .await + } + + /// Jobs that were queued or running, e.g. when the daemon last stopped. + pub async fn active_jobs(&self) -> Result> { + self.query_jobs( + "SELECT body FROM jobs WHERE active = 1 ORDER BY created ASC LIMIT ?1", + 10_000, + ) + .await + } + + async fn query_jobs(&self, sql: &'static str, limit: usize) -> Result> { + let bodies: Vec = self + .with(move |c| { + let mut stmt = c.prepare(sql)?; + let rows = stmt.query_map([limit as i64], |r| r.get(0))?; + Ok(rows.collect::>()?) + }) + .await?; + bodies + .iter() + .map(|b| serde_json::from_str(b).map_err(Into::into)) + .collect() + } + + pub async fn put_export(&self, id: &str, export: &T) -> Result<()> { + let id = id.to_string(); + let body = serde_json::to_string(export)?; + self.with(move |c| { + c.execute( + "INSERT INTO exports (id, body) VALUES (?1, ?2) + ON CONFLICT(id) DO UPDATE SET body = excluded.body", + params![id, body], + )?; + Ok(()) + }) + .await + } + + pub async fn get_export(&self, id: &str) -> Result> { + let id = id.to_string(); + let body: Option = self + .with(move |c| { + Ok( + c.query_row("SELECT body FROM exports WHERE id = ?1", [id], |r| r.get(0)) + .optional()?, + ) + }) + .await?; + body.map(|b| serde_json::from_str(&b).map_err(Into::into)) + .transpose() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use jm_core::JobStatus; + + #[tokio::test] + async fn jobs_roundtrip_and_track_activity() { + let store = Store::in_memory().unwrap(); + let mut a = Job::new("1", "A", "cloud", "home", false); + let b = Job::new("2", "B", "cloud", "home", false); + store.put_job(&a).await.unwrap(); + store.put_job(&b).await.unwrap(); + assert_eq!(store.active_jobs().await.unwrap().len(), 2); + + a.status = JobStatus::Done; + store.put_job(&a).await.unwrap(); + let active = store.active_jobs().await.unwrap(); + assert_eq!(active.len(), 1); + assert_eq!(active[0].name, "B"); + + let got = store.get_job(a.id).await.unwrap().unwrap(); + assert_eq!(got.status, JobStatus::Done); + assert_eq!(store.list_jobs(10).await.unwrap().len(), 2); + } + + #[tokio::test] + async fn survives_reopen() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("state.db"); + let job = Job::new("1", "A", "cloud", "home", false); + { + let s = Store::open(&path).unwrap(); + s.put_job(&job).await.unwrap(); + s.put_export("e1", &serde_json::json!({"x": 1})) + .await + .unwrap(); + } + let s = Store::open(&path).unwrap(); + assert!(s.get_job(job.id).await.unwrap().is_some()); + let e: serde_json::Value = s.get_export("e1").await.unwrap().unwrap(); + assert_eq!(e["x"], 1); + } +} diff --git a/crates/jm-transfer/Cargo.toml b/crates/jm-transfer/Cargo.toml new file mode 100644 index 0000000..3029129 --- /dev/null +++ b/crates/jm-transfer/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "jm-transfer" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +axum = "0.8.9" +blake3 = { version = "1.8.7", features = ["mmap", "rayon"] } +bytes = "1.12.1" +futures = "0.3.34" +governor = "0.10.4" +jm-core = { version = "0.1.0", path = "../jm-core" } +reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "stream", "http2"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +thiserror = "2.0.21" +tokio = { version = "1.54.1", features = ["full"] } +tokio-util = "0.7.20" +tracing = "0.1.44" + +[dev-dependencies] +tempfile = "3.27.0" diff --git a/crates/jm-transfer/src/lib.rs b/crates/jm-transfer/src/lib.rs new file mode 100644 index 0000000..9046b62 --- /dev/null +++ b/crates/jm-transfer/src/lib.rs @@ -0,0 +1,60 @@ +//! Moving bytes between agents. +//! +//! The destination *pulls* each file from the source over HTTP with `Range` +//! requests, writing to a `.part` file in a hidden partial area inside the +//! destination library. The length of the `.part` file is the resume point, so +//! a dropped link or a restart continues where it stopped. When a file is +//! complete it is hashed with BLAKE3 and compared with the source's hash; only +//! verified files are renamed into the library. + +pub mod manifest; +pub mod promote; +pub mod pull; +pub mod serve; + +pub use manifest::{build_manifest, hash_file, list_relative}; +pub use promote::{part_path, partial_dir, prepare_partial, promote}; +pub use pull::{Puller, PullerOptions}; +pub use serve::range_response; + +/// Prefix for jellymove's own hidden folders inside libraries. Jellyfin skips +/// folders whose names start with a dot, and we also drop a `.ignore` file in +/// them for good measure. +pub const HIDDEN_PREFIX: &str = ".jellymove-"; + +#[derive(Debug, thiserror::Error)] +pub enum TransferError { + #[error("i/o error: {0}")] + Io(#[from] std::io::Error), + #[error("http error: {0}")] + Http(#[from] reqwest::Error), + #[error("peer returned HTTP {0}")] + Status(u16), + #[error("hash mismatch for {file}: expected {expected}, got {actual}")] + Integrity { + file: String, + expected: String, + actual: String, + }, + #[error("size mismatch for {file}: expected {expected} bytes, got {actual}")] + Size { + file: String, + expected: u64, + actual: u64, + }, + #[error("refusing to overwrite existing file {0}")] + Exists(String), + #[error("unsafe path in manifest: {0}")] + UnsafePath(String), +} + +impl TransferError { + /// Errors that a retry cannot fix. + pub fn is_permanent(&self) -> bool { + match self { + TransferError::Status(code) => matches!(code, 400 | 401 | 403 | 404 | 410 | 416), + TransferError::Exists(_) | TransferError::UnsafePath(_) => true, + _ => false, + } + } +} diff --git a/crates/jm-transfer/src/manifest.rs b/crates/jm-transfer/src/manifest.rs new file mode 100644 index 0000000..4341df1 --- /dev/null +++ b/crates/jm-transfer/src/manifest.rs @@ -0,0 +1,104 @@ +use std::path::{Path, PathBuf}; + +use jm_core::job::{Manifest, ManifestEntry}; + +use crate::{HIDDEN_PREFIX, TransferError}; + +/// Hash a file with BLAKE3, memory-mapped and multithreaded for large files. +pub async fn hash_file(path: &Path) -> Result { + let path = path.to_path_buf(); + tokio::task::spawn_blocking(move || -> Result { + let mut hasher = blake3::Hasher::new(); + hasher.update_mmap_rayon(&path)?; + Ok(hasher.finalize().to_hex().to_string()) + }) + .await + .expect("hash task panicked") +} + +/// List every regular file below `root` (recursively), hash each, and return +/// them sorted by relative path. Symlinks and jellymove's own hidden folders +/// are skipped. +pub async fn build_manifest(root: &Path) -> Result { + let root_owned = root.to_path_buf(); + let listed = tokio::task::spawn_blocking(move || list_files(&root_owned)) + .await + .expect("list task panicked")?; + + let mut files = Vec::with_capacity(listed.len()); + for (rel, abs, size) in listed { + let blake3 = hash_file(&abs).await?; + files.push(ManifestEntry { + rel_path: rel, + size, + blake3, + }); + } + Ok(Manifest { files }) +} + +/// Relative paths (`/` separated) of every regular file below `root`, without +/// hashing. Used for the folder safety check before we spend time hashing. +pub fn list_relative(root: &Path) -> Result, TransferError> { + Ok(list_files(root)? + .into_iter() + .map(|(rel, _, _)| rel) + .collect()) +} + +fn list_files(root: &Path) -> Result, TransferError> { + let mut out = Vec::new(); + let mut stack = vec![PathBuf::new()]; + while let Some(rel_dir) = stack.pop() { + for entry in std::fs::read_dir(root.join(&rel_dir))? { + let entry = entry?; + let name = entry.file_name(); + let name_str = name.to_string_lossy(); + if name_str.starts_with(HIDDEN_PREFIX) { + continue; + } + let ft = entry.file_type()?; + let rel = rel_dir.join(&name); + if ft.is_dir() { + stack.push(rel); + } else if ft.is_file() { + let size = entry.metadata()?.len(); + let rel_str = rel + .components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/"); + out.push((rel_str, entry.path(), size)); + } else { + tracing::warn!(path = %entry.path().display(), "skipping symlink or special file"); + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn manifest_lists_nested_files_and_skips_hidden() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("Season 01")).unwrap(); + std::fs::create_dir_all(root.join(".jellymove-partial")).unwrap(); + std::fs::write(root.join("tvshow.nfo"), b"").unwrap(); + std::fs::write(root.join("Season 01/S01E01.mkv"), b"video").unwrap(); + std::fs::write(root.join(".jellymove-partial/0.part"), b"junk").unwrap(); + + let m = build_manifest(root).await.unwrap(); + let names: Vec<_> = m.files.iter().map(|f| f.rel_path.as_str()).collect(); + assert_eq!(names, ["Season 01/S01E01.mkv", "tvshow.nfo"]); + assert_eq!(m.files[0].size, 5); + assert_eq!( + m.files[0].blake3, + blake3::hash(b"video").to_hex().to_string() + ); + } +} diff --git a/crates/jm-transfer/src/promote.rs b/crates/jm-transfer/src/promote.rs new file mode 100644 index 0000000..cdf7e02 --- /dev/null +++ b/crates/jm-transfer/src/promote.rs @@ -0,0 +1,75 @@ +use std::path::{Path, PathBuf}; + +use jm_core::job::Manifest; +use jm_core::paths::join_relative; + +use crate::{HIDDEN_PREFIX, TransferError}; + +/// Hidden staging folder for one job, inside the destination library root so +/// the final rename stays on the same filesystem (and is therefore atomic). +pub fn partial_dir(library_root: &Path, job_id: &str) -> PathBuf { + library_root + .join(format!("{HIDDEN_PREFIX}partial")) + .join(job_id) +} + +pub fn part_path(partial: &Path, idx: usize) -> PathBuf { + partial.join(format!("{idx}.part")) +} + +/// Create the partial folder and mark it so Jellyfin ignores it. +pub async fn prepare_partial(partial: &Path) -> Result<(), TransferError> { + tokio::fs::create_dir_all(partial).await?; + if let Some(parent) = partial.parent() { + let marker = parent.join(".ignore"); + if tokio::fs::metadata(&marker).await.is_err() { + tokio::fs::write(&marker, b"").await?; + } + } + Ok(()) +} + +/// Rename every verified `.part` into `target_folder`. Safe to run again after +/// a crash: files already in place (part gone, target present with the right +/// size) are skipped. Refuses to overwrite anything it didn't put there. +pub async fn promote( + partial: &Path, + target_folder: &Path, + manifest: &Manifest, +) -> Result<(), TransferError> { + // Check every destination first so we never half-promote into a clash. + for (idx, entry) in manifest.files.iter().enumerate() { + let dest = join_relative(target_folder, &entry.rel_path) + .ok_or_else(|| TransferError::UnsafePath(entry.rel_path.clone()))?; + let part_exists = tokio::fs::metadata(part_path(partial, idx)).await.is_ok(); + if part_exists && tokio::fs::metadata(&dest).await.is_ok() { + return Err(TransferError::Exists(dest.display().to_string())); + } + } + + for (idx, entry) in manifest.files.iter().enumerate() { + let part = part_path(partial, idx); + let dest = join_relative(target_folder, &entry.rel_path).expect("checked above"); + match tokio::fs::metadata(&part).await { + Ok(_) => { + if let Some(parent) = dest.parent() { + tokio::fs::create_dir_all(parent).await?; + } + tokio::fs::rename(&part, &dest).await?; + } + Err(_) => { + // Already promoted on an earlier run? + let meta = tokio::fs::metadata(&dest).await?; + if meta.len() != entry.size { + return Err(TransferError::Size { + file: entry.rel_path.clone(), + expected: entry.size, + actual: meta.len(), + }); + } + } + } + } + let _ = tokio::fs::remove_dir(partial).await; + Ok(()) +} diff --git a/crates/jm-transfer/src/pull.rs b/crates/jm-transfer/src/pull.rs new file mode 100644 index 0000000..976ba41 --- /dev/null +++ b/crates/jm-transfer/src/pull.rs @@ -0,0 +1,185 @@ +use std::num::NonZeroU32; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use futures::StreamExt; +use governor::{DefaultDirectRateLimiter, Quota, RateLimiter}; +use jm_core::job::ManifestEntry; +use reqwest::StatusCode; +use reqwest::header::{AUTHORIZATION, RANGE}; +use tokio::io::AsyncWriteExt; + +use crate::{TransferError, hash_file}; + +#[derive(Debug, Clone)] +pub struct PullerOptions { + /// Bearer token presented to the peer. + pub token: Option, + /// Bytes per second across every transfer this puller makes. `None` = unlimited. + pub bytes_per_sec: Option, + /// Attempts per file before giving up (resumes between attempts). + pub attempts: u32, + /// First backoff delay; doubles each attempt, capped at one minute. + pub initial_backoff: Duration, +} + +impl Default for PullerOptions { + fn default() -> Self { + Self { + token: None, + bytes_per_sec: None, + attempts: 10, + initial_backoff: Duration::from_secs(2), + } + } +} + +#[derive(Clone)] +pub struct Puller { + http: reqwest::Client, + opts: PullerOptions, + limiter: Option>, +} + +impl Puller { + pub fn new(http: reqwest::Client, opts: PullerOptions) -> Self { + let limiter = opts + .bytes_per_sec + .map(|bps| Arc::new(RateLimiter::direct(Quota::per_second(bps)))); + Self { + http, + opts, + limiter, + } + } + + /// Pull one file into `part`, resuming and retrying as needed, then verify + /// its BLAKE3 hash. `on_progress` receives the bytes held for this file. + pub async fn pull_verified( + &self, + url: &str, + entry: &ManifestEntry, + part: &Path, + on_progress: &mut (dyn FnMut(u64) + Send), + ) -> Result<(), TransferError> { + let mut delay = self.opts.initial_backoff; + let mut attempt = 1; + loop { + match self.pull_once(url, entry, part, on_progress).await { + Ok(()) => return Ok(()), + Err(e) if e.is_permanent() || attempt >= self.opts.attempts => return Err(e), + Err(e) => { + tracing::warn!(file = %entry.rel_path, attempt, error = %e, "transfer failed; will resume"); + tokio::time::sleep(delay).await; + delay = (delay * 2).min(Duration::from_secs(60)); + attempt += 1; + } + } + } + } + + async fn pull_once( + &self, + url: &str, + entry: &ManifestEntry, + part: &Path, + on_progress: &mut (dyn FnMut(u64) + Send), + ) -> Result<(), TransferError> { + if let Some(parent) = part.parent() { + tokio::fs::create_dir_all(parent).await?; + } + let mut have = match tokio::fs::metadata(part).await { + Ok(m) => m.len(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if entry.size == 0 { + // Nothing to fetch; an empty file is still part of the folder. + tokio::fs::File::create(part).await?; + } + 0 + } + Err(e) => return Err(e.into()), + }; + if have > entry.size { + // Can't be ours; start again. + tokio::fs::remove_file(part).await?; + have = 0; + } + + if have < entry.size { + let mut req = self.http.get(url); + if let Some(t) = &self.opts.token { + req = req.header(AUTHORIZATION, format!("Bearer {t}")); + } + if have > 0 { + req = req.header(RANGE, format!("bytes={have}-")); + } + let resp = req.send().await?; + let mut file = match resp.status() { + StatusCode::PARTIAL_CONTENT if have > 0 => { + tokio::fs::OpenOptions::new() + .append(true) + .open(part) + .await? + } + StatusCode::OK => { + // Server ignored the range (or we asked from zero): rewrite. + have = 0; + tokio::fs::File::create(part).await? + } + s => return Err(TransferError::Status(s.as_u16())), + }; + on_progress(have); + + let mut stream = resp.bytes_stream(); + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + self.throttle(chunk.len()).await; + file.write_all(&chunk).await?; + have += chunk.len() as u64; + on_progress(have); + if have > entry.size { + break; + } + } + file.flush().await?; + file.sync_all().await?; + } + + if have != entry.size { + if have > entry.size { + tokio::fs::remove_file(part).await?; + } + return Err(TransferError::Size { + file: entry.rel_path.clone(), + expected: entry.size, + actual: have, + }); + } + + let actual = hash_file(part).await?; + if actual != entry.blake3 { + // Corrupt; discard so the next attempt starts from scratch. + tokio::fs::remove_file(part).await?; + return Err(TransferError::Integrity { + file: entry.rel_path.clone(), + expected: entry.blake3.clone(), + actual, + }); + } + Ok(()) + } + + async fn throttle(&self, len: usize) { + let Some(limiter) = &self.limiter else { return }; + let burst = self.opts.bytes_per_sec.map(|b| b.get()).unwrap_or(u32::MAX) as usize; + let mut remaining = len; + while remaining > 0 { + let n = remaining.min(burst); + let n32 = NonZeroU32::new(n as u32).expect("n > 0"); + // Can't fail: n never exceeds the burst size. + let _ = limiter.until_n_ready(n32).await; + remaining -= n; + } + } +} diff --git a/crates/jm-transfer/src/serve.rs b/crates/jm-transfer/src/serve.rs new file mode 100644 index 0000000..b21a7c4 --- /dev/null +++ b/crates/jm-transfer/src/serve.rs @@ -0,0 +1,100 @@ +use std::io::SeekFrom; +use std::path::Path; + +use axum::body::Body; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use tokio::io::{AsyncReadExt, AsyncSeekExt}; +use tokio_util::io::ReaderStream; + +/// Serve a file with support for a single `Range: bytes=start-[end]` header. +/// The caller is responsible for deciding *which* file may be served. +pub async fn range_response(path: &Path, headers: &HeaderMap) -> Response { + let mut file = match tokio::fs::File::open(path).await { + Ok(f) => f, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return StatusCode::NOT_FOUND.into_response(); + } + Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(), + }; + let len = match file.metadata().await { + Ok(m) => m.len(), + Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(), + }; + + let range = headers.get(header::RANGE).and_then(|v| v.to_str().ok()); + let (start, end) = match range.map(|r| parse_range(r, len)) { + None => (0, len.saturating_sub(1)), + Some(Some(r)) => r, + Some(None) => { + let mut resp = StatusCode::RANGE_NOT_SATISFIABLE.into_response(); + resp.headers_mut().insert( + header::CONTENT_RANGE, + HeaderValue::from_str(&format!("bytes */{len}")).expect("valid header"), + ); + return resp; + } + }; + + if start > 0 { + if let Err(e) = file.seek(SeekFrom::Start(start)).await { + return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(); + } + } + let count = if len == 0 { 0 } else { end - start + 1 }; + let stream = ReaderStream::with_capacity(file.take(count), 256 * 1024); + + let mut builder = Response::builder() + .header(header::ACCEPT_RANGES, "bytes") + .header(header::CONTENT_LENGTH, count) + .header(header::CONTENT_TYPE, "application/octet-stream"); + if range.is_some() { + builder = builder + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, format!("bytes {start}-{end}/{len}")); + } else { + builder = builder.status(StatusCode::OK); + } + builder + .body(Body::from_stream(stream)) + .expect("valid response") +} + +/// Parse `bytes=start-` or `bytes=start-end` against a file of `len` bytes. +/// Returns an inclusive range, or `None` if unsatisfiable or malformed. +/// Suffix ranges (`bytes=-500`) and multi-range requests aren't needed by our +/// puller and are rejected. +fn parse_range(value: &str, len: u64) -> Option<(u64, u64)> { + let spec = value.strip_prefix("bytes=")?; + if spec.contains(',') { + return None; + } + let (s, e) = spec.split_once('-')?; + let start: u64 = s.trim().parse().ok()?; + if start >= len { + return None; + } + let end = match e.trim() { + "" => len - 1, + e => e.parse::().ok()?.min(len - 1), + }; + (start <= end).then_some((start, end)) +} + +#[cfg(test)] +mod tests { + use super::parse_range; + + #[test] + fn ranges() { + assert_eq!(parse_range("bytes=0-", 10), Some((0, 9))); + assert_eq!(parse_range("bytes=4-", 10), Some((4, 9))); + assert_eq!(parse_range("bytes=4-6", 10), Some((4, 6))); + assert_eq!(parse_range("bytes=4-100", 10), Some((4, 9))); + assert_eq!(parse_range("bytes=10-", 10), None); + assert_eq!(parse_range("bytes=-5", 10), None); + assert_eq!(parse_range("bytes=0-1,4-5", 10), None); + assert_eq!(parse_range("items=0-", 10), None); + assert_eq!(parse_range("bytes=6-4", 10), None); + } +} diff --git a/crates/jm-transfer/tests/transfer.rs b/crates/jm-transfer/tests/transfer.rs new file mode 100644 index 0000000..19ba3ba --- /dev/null +++ b/crates/jm-transfer/tests/transfer.rs @@ -0,0 +1,243 @@ +//! End-to-end tests: a real axum source, a real puller, real files on disk. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use axum::Router; +use axum::body::{Body, Bytes}; +use axum::extract::{Path, State}; +use axum::http::{HeaderMap, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use axum::routing::get; +use jm_transfer::{ + Puller, PullerOptions, build_manifest, part_path, partial_dir, prepare_partial, promote, +}; + +#[derive(Clone)] +struct Src { + root: PathBuf, + rels: Arc>, + /// When non-zero, the next request is cut off after this many bytes. + cut_after: Arc, + requests: Arc, + /// Requests that asked to resume with a Range header. + ranged: Arc, +} + +async fn file(State(s): State, Path(idx): Path, headers: HeaderMap) -> Response { + s.requests.fetch_add(1, Ordering::SeqCst); + if headers.contains_key(header::RANGE) { + s.ranged.fetch_add(1, Ordering::SeqCst); + } + let Some(rel) = s.rels.get(idx) else { + return StatusCode::NOT_FOUND.into_response(); + }; + let path = s.root.join(rel); + let cut = s.cut_after.swap(0, Ordering::SeqCst); + if cut == 0 { + return jm_transfer::range_response(&path, &headers).await; + } + // Simulate a dropped link: promise the whole file, send part, then error. + let data = std::fs::read(&path).unwrap(); + let head = Bytes::from(data[..cut].to_vec()); + let stream = futures::stream::iter(vec![ + Ok::<_, std::io::Error>(head), + Err(std::io::Error::other("link dropped")), + ]); + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_LENGTH, data.len()) + .body(Body::from_stream(stream)) + .unwrap() +} + +struct Fixture { + _src_dir: tempfile::TempDir, + dst_dir: tempfile::TempDir, + src: Src, + base: String, +} + +async fn fixture() -> Fixture { + let src_dir = tempfile::tempdir().unwrap(); + let item = src_dir.path().join("Alien (1979)"); + std::fs::create_dir_all(item.join("extras")).unwrap(); + // 3 MiB of non-repeating bytes so a resume at the wrong offset is detected. + let big: Vec = (0..3 * 1024 * 1024u32) + .map(|i| (i.wrapping_mul(2654435761) >> 13) as u8) + .collect(); + std::fs::write(item.join("Alien (1979).mkv"), &big).unwrap(); + std::fs::write(item.join("Alien (1979).nfo"), b"").unwrap(); + std::fs::write(item.join("extras/Making of.mkv"), b"extra").unwrap(); + std::fs::write(item.join("empty.txt"), b"").unwrap(); + + let manifest = build_manifest(&item).await.unwrap(); + let src = Src { + root: item, + rels: Arc::new(manifest.files.iter().map(|f| f.rel_path.clone()).collect()), + cut_after: Arc::new(AtomicUsize::new(0)), + requests: Arc::new(AtomicUsize::new(0)), + ranged: Arc::new(AtomicUsize::new(0)), + }; + let app = Router::new() + .route("/files/{idx}", get(file)) + .with_state(src.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + Fixture { + _src_dir: src_dir, + dst_dir: tempfile::tempdir().unwrap(), + src, + base: format!("http://{addr}"), + } +} + +fn puller() -> Puller { + Puller::new( + reqwest::Client::new(), + PullerOptions { + initial_backoff: Duration::from_millis(10), + attempts: 5, + ..Default::default() + }, + ) +} + +async fn pull_all(fx: &Fixture, p: &Puller) -> PathBuf { + let manifest = build_manifest(&fx.src.root).await.unwrap(); + let lib_root = fx.dst_dir.path(); + let partial = partial_dir(lib_root, "job1"); + prepare_partial(&partial).await.unwrap(); + for (idx, entry) in manifest.files.iter().enumerate() { + let url = format!("{}/files/{idx}", fx.base); + p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {}) + .await + .unwrap(); + } + let target = lib_root.join("Alien (1979)"); + promote(&partial, &target, &manifest).await.unwrap(); + target +} + +fn assert_same_tree(a: &std::path::Path, b: &std::path::Path) { + for rel in [ + "Alien (1979).mkv", + "Alien (1979).nfo", + "extras/Making of.mkv", + "empty.txt", + ] { + assert_eq!( + std::fs::read(a.join(rel)).unwrap(), + std::fs::read(b.join(rel)).unwrap(), + "{rel}" + ); + } +} + +#[tokio::test] +async fn copies_folder_with_sidecars() { + let fx = fixture().await; + let target = pull_all(&fx, &puller()).await; + assert_same_tree(&fx.src.root, &target); + // Partial area is cleaned up and hidden from Jellyfin. + assert!(!partial_dir(fx.dst_dir.path(), "job1").exists()); + assert!( + fx.dst_dir + .path() + .join(".jellymove-partial/.ignore") + .exists() + ); +} + +#[tokio::test] +async fn resumes_after_dropped_connection() { + let fx = fixture().await; + fx.src.cut_after.store(1024 * 1024, Ordering::SeqCst); // first request dies at 1 MiB + let target = pull_all(&fx, &puller()).await; + assert_same_tree(&fx.src.root, &target); + // 3 non-empty files (the empty one needs no request) + 1 resume. + assert_eq!(fx.src.requests.load(Ordering::SeqCst), 4); + // The retry continued from where the link dropped rather than restarting. + assert_eq!(fx.src.ranged.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn corrupt_partial_is_discarded_and_refetched() { + let fx = fixture().await; + let manifest = build_manifest(&fx.src.root).await.unwrap(); + let idx = manifest + .files + .iter() + .position(|f| f.rel_path.ends_with(".mkv") && f.size > 100) + .unwrap(); + let partial = partial_dir(fx.dst_dir.path(), "job1"); + prepare_partial(&partial).await.unwrap(); + // Plant a half-file of garbage, as if a previous run wrote bad bytes. + std::fs::write(part_path(&partial, idx), vec![0u8; 1024 * 1024]).unwrap(); + + let target = pull_all(&fx, &puller()).await; + assert_same_tree(&fx.src.root, &target); +} + +#[tokio::test] +async fn refuses_to_overwrite_existing_files() { + let fx = fixture().await; + let target = fx.dst_dir.path().join("Alien (1979)"); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("Alien (1979).nfo"), b"someone else's").unwrap(); + + let manifest = build_manifest(&fx.src.root).await.unwrap(); + let partial = partial_dir(fx.dst_dir.path(), "job1"); + prepare_partial(&partial).await.unwrap(); + let p = puller(); + for (idx, entry) in manifest.files.iter().enumerate() { + let url = format!("{}/files/{idx}", fx.base); + p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {}) + .await + .unwrap(); + } + let err = promote(&partial, &target, &manifest).await.unwrap_err(); + assert!(matches!(err, jm_transfer::TransferError::Exists(_))); + // Nothing was moved: the stranger's file is untouched and no video landed. + assert_eq!( + std::fs::read(target.join("Alien (1979).nfo")).unwrap(), + b"someone else's" + ); + assert!(!target.join("Alien (1979).mkv").exists()); +} + +#[tokio::test] +async fn promote_is_idempotent() { + let fx = fixture().await; + let target = pull_all(&fx, &puller()).await; + let manifest = build_manifest(&fx.src.root).await.unwrap(); + // A second promote after a "crash" finds everything already in place. + promote(&partial_dir(fx.dst_dir.path(), "job1"), &target, &manifest) + .await + .unwrap(); +} + +#[tokio::test] +async fn bandwidth_limit_is_applied() { + let fx = fixture().await; + let p = Puller::new( + reqwest::Client::new(), + PullerOptions { + bytes_per_sec: std::num::NonZeroU32::new(2 * 1024 * 1024), + initial_backoff: Duration::from_millis(10), + ..Default::default() + }, + ); + let start = std::time::Instant::now(); + pull_all(&fx, &p).await; + // ~3 MiB at 2 MiB/s with a one-second burst: at least ~0.5 s. + assert!( + start.elapsed() >= Duration::from_millis(400), + "took {:?}", + start.elapsed() + ); +} diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml new file mode 100644 index 0000000..ff36744 --- /dev/null +++ b/deploy/docker-compose.yml @@ -0,0 +1,24 @@ +# One of these per server. Mount media at the SAME paths as your Jellyfin +# container so the paths Jellyfin reports are the paths jellymove sees. +services: + jellymove: + image: jellymove:latest + build: .. + container_name: jellymove + restart: unless-stopped + # Same UID:GID as Jellyfin so moved files keep the right ownership. + user: "1000:1000" + ports: + - "8097:8097" + volumes: + - ./jellymove.toml:/config/jellymove.toml:ro + - ./jellymove-data:/data + - /srv/media/movies:/media/movies # ← match your jellyfin service + - /srv/media/tv:/media/tv + environment: + # Secrets can come from the environment instead of the file: + # JELLYMOVE_JELLYFIN__API_KEY: ... + # JELLYMOVE_PEER__TOKEN: ... + JELLYMOVE_LOG: info + # Only needed for a post_move hook like `docker restart jellyswarrm`: + # - /var/run/docker.sock:/var/run/docker.sock diff --git a/deploy/jellymove.service b/deploy/jellymove.service new file mode 100644 index 0000000..0d537ea --- /dev/null +++ b/deploy/jellymove.service @@ -0,0 +1,23 @@ +[Unit] +Description=jellymove agent +After=network-online.target +Wants=network-online.target + +[Service] +# Run as the same user that owns your media (usually the jellyfin user). +User=jellyfin +Group=jellyfin +ExecStart=/usr/local/bin/jellymove --config /etc/jellymove/jellymove.toml run +Environment=JELLYMOVE_LOG=info +# systemd creates /var/lib/jellymove owned by User=; set data_dir to it. +StateDirectory=jellymove +Restart=on-failure +RestartSec=5 +# Transfers resume after a restart, so a plain stop is safe. +KillSignal=SIGTERM +NoNewPrivileges=true +ProtectSystem=full +PrivateTmp=true + +[Install] +WantedBy=multi-user.target diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..0289615 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,99 @@ +# Architecture + +## Why this exists + +As of November 2026 nothing published moves media between two Jellyfin +servers while understanding their libraries. Adjacent tools each cover one part: + +| Need | Closest existing tool | Gap | +|---|---|---| +| Show two servers as one | Jellyswarrm (v0.3.1 deduplicates across servers) | Presentation only; media management not implemented | +| Move bytes hot ↔ cold | mergerfs cache movers, rclone union, rsync, Syncthing | Path- and size-based, single host or blind to Jellyfin; no rescans, no watch state | +| Carry watch state | JellySync, JellyPlex-Watched | No file movement | +| Policy-driven cleanup | Janitorr / Maintainerr | Deletes rather than demotes | + +jellymove joins these into one flow that knows about libraries. + +## Topology + +One binary, run as an agent next to each Jellyfin. Each agent has: + +- local filesystem access at the same paths Jellyfin uses +- an admin API key for its own Jellyfin +- the other agent's URL and a shared token + +Jobs always run on the **destination**, which pulls. Whichever UI the user +starts from, the job ends up there: `POST /api/moves {from: "local"}` asks the +peer to create the job, and `{from: "peer"}` creates it locally. This keeps the +code that copies, verifies, promotes and deletes next to the disk it touches, +and lets a NATed home server pull from a public cloud server with no port +forwarding. + +## Peer protocol (`/peer/v1`, Bearer token) + +| Route | Purpose | +|---|---| +| `GET /info` | Node name, version, Jellyfin version | +| `GET /libraries`, `GET /items?library=&search=` | Browse the peer's Jellyfin | +| `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 /jobs`, `GET /jobs` | Create or list jobs on the peer (destination) | + +## Job stages + +`Job.stage` is the last *completed* milestone. The runner performs the next step: + +``` +Created ──plan──▶ ExportReady ──copy──▶ Copied ──promote──▶ Promoted + ──wait for scan──▶ TargetScanned ──apply user data──▶ UserDataApplied + ──clean source──▶ SourceCleaned ──hook──▶ Done +``` + +`JobStatus` is orthogonal: Queued / Running / Planned (dry run) / Failed / Done. +Retrying a failed job re-runs from its stage. Interrupted jobs resume on start. + +## Transfer + +- HTTP `Range` pull into `/.jellymove-partial//.part`. + The `.part` length is the resume offset, so no extra state is needed. +- BLAKE3 hash computed by the source (memory-mapped, multithreaded) and checked + by the destination after the last byte. A mismatch discards the part. +- Exponential backoff, 20 attempts by default; 4xx errors are permanent. +- Token-bucket bandwidth cap (`governor`) shared across transfers. +- Delta sync is deliberately absent: media is written once, so whole-file + transfer with resume beats rolling checksums. +- Alternatives kept open behind the pull/serve split: iroh (QUIC, NAT + traversal) once iroh-blobs reaches 1.0; rclone as a pluggable transport. + +## 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. +- 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. + This is more reliable than provider IDs, which may be missing or differ. + Episodes are matched by (season, episode). +- User data: captured per user from `GET /Items?userId=…`, written with + `POST /UserItems/{id}/UserData?userId=…`, users matched by name. + +## Why Svelte rather than Slint + +Slint is a native GUI toolkit. A headless daemon needs a browser UI, so the UI +is a Svelte 5 SPA compiled into the binary with `rust-embed`, the same +single-binary model Jellyswarrm uses. Live progress uses Server-Sent Events +for jobs on this node, and polling for jobs on the peer. + +## Known risks + +1. New item IDs after a move break anything keyed by ID: playlists, + collections, Jellyseerr links, Jellyswarrm's cache (#216). +2. Jellyswarrm's merge key for movies and series isn't documented upstream, + and its pipeline is being rewritten. +3. PUID/PGID and mount mismatches. The Status tab probes every location for + existence and write access. +4. Large scans: some Jellyfin versions re-save thousands of items on a full + scan, so jellymove only ever requests path-scoped updates. diff --git a/ui/.gitignore b/ui/.gitignore new file mode 100644 index 0000000..b947077 --- /dev/null +++ b/ui/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +dist/ diff --git a/ui/index.html b/ui/index.html new file mode 100644 index 0000000..6630211 --- /dev/null +++ b/ui/index.html @@ -0,0 +1,13 @@ + + + + + + + jellymove + + +
+ + + diff --git a/ui/package-lock.json b/ui/package-lock.json new file mode 100644 index 0000000..48040db --- /dev/null +++ b/ui/package-lock.json @@ -0,0 +1,1189 @@ +{ + "name": "jellymove-ui", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "jellymove-ui", + "version": "0.1.0", + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^7.3.1", + "@tsconfig/svelte": "^5.0.8", + "svelte": "^5.57.3", + "svelte-check": "^4.7.8", + "typescript": "^6.0.3", + "vite": "^8.3.5" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.16.tgz", + "integrity": "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.16.tgz", + "integrity": "sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.16.tgz", + "integrity": "sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.16.tgz", + "integrity": "sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.16.tgz", + "integrity": "sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.16.tgz", + "integrity": "sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.16.tgz", + "integrity": "sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.16.tgz", + "integrity": "sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.16.tgz", + "integrity": "sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.16.tgz", + "integrity": "sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.16.tgz", + "integrity": "sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.16.tgz", + "integrity": "sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.16.tgz", + "integrity": "sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.16.tgz", + "integrity": "sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.16.tgz", + "integrity": "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sveltejs/acorn-typescript": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz", + "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^8.9.0" + } + }, + "node_modules/@sveltejs/load-config": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.3.tgz", + "integrity": "sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-7.3.1.tgz", + "integrity": "sha512-ZPsLN8B1e/En+Ak5s4V7srFDT532oS0qieLsQwu63NGKsS+iAjoO2Js1BochlHlglcU+Pt7WAO3C5Ee+4f6gVA==", + "dev": true, + "license": "MIT", + "dependencies": { + "deepmerge": "^4.3.1", + "magic-string": "^1.0.0", + "obug": "^2.1.0", + "vitefu": "^1.1.2" + }, + "engines": { + "node": "^20.19 || ^22.12 || >=24" + }, + "peerDependencies": { + "svelte": "^5.46.4", + "vite": "^8.0.0-beta.7 || ^8.0.0" + } + }, + "node_modules/@tsconfig/svelte": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-5.0.8.tgz", + "integrity": "sha512-UkNnw1/oFEfecR8ypyHIQuWYdkPvHiwcQ78sh+ymIiYoF+uc5H1UBetbjyqT+vgGJ3qQN6nhucJviX6HesWtKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", + "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/devalue": { + "version": "5.9.4", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz", + "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==", + "dev": true, + "license": "MIT" + }, + "node_modules/esm-env": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", + "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esrap": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz", + "integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "peerDependencies": { + "@typescript-eslint/types": "^8.2.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/types": { + "optional": true + } + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/is-reference": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", + "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.6" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/rolldown": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.16.tgz", + "integrity": "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.16", + "@rolldown/binding-android-arm64": "1.2.16", + "@rolldown/binding-darwin-arm64": "1.2.16", + "@rolldown/binding-darwin-x64": "1.2.16", + "@rolldown/binding-freebsd-x64": "1.2.16", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", + "@rolldown/binding-linux-arm64-gnu": "1.2.16", + "@rolldown/binding-linux-arm64-musl": "1.2.16", + "@rolldown/binding-linux-ppc64-gnu": "1.2.16", + "@rolldown/binding-linux-s390x-gnu": "1.2.16", + "@rolldown/binding-linux-x64-gnu": "1.2.16", + "@rolldown/binding-linux-x64-musl": "1.2.16", + "@rolldown/binding-openharmony-arm64": "1.2.16", + "@rolldown/binding-win32-arm64-msvc": "1.2.16", + "@rolldown/binding-win32-x64-msvc": "1.2.16" + } + }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/svelte": { + "version": "5.57.3", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz", + "integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "@jridgewell/sourcemap-codec": "^1.6.0", + "@sveltejs/acorn-typescript": "^1.0.13", + "@types/estree": "^1.0.9", + "acorn": "^8.18.0", + "aria-query": "5.3.1", + "axobject-query": "^4.1.0", + "clsx": "^2.1.1", + "devalue": "^5.9.2", + "esm-env": "^1.2.1", + "esrap": "^2.3.6", + "is-reference": "^3.0.3", + "locate-character": "^3.0.0", + "magic-string": "^0.30.11", + "zimmerframe": "^1.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/svelte-check": { + "version": "4.7.8", + "resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-4.7.8.tgz", + "integrity": "sha512-laZ49GFHZ3b0z2PWinJWL0syehc/PTR8aHaUaTiBkWJ+4Y38nhxjmXsSz7CbGa3VdKopViVbrBH3bGNqIAI0bQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "@sveltejs/load-config": "^0.2.3", + "chokidar": "^4.0.1", + "fdir": "^6.2.0", + "picocolors": "^1.0.0", + "sade": "^1.7.4" + }, + "bin": { + "svelte-check": "bin/svelte-check" + }, + "engines": { + "node": ">= 18.0.0" + }, + "peerDependencies": { + "svelte": "^4.0.0 || ^5.0.0-next.0", + "typescript": "^5.0.0 || ^6.0.0" + } + }, + "node_modules/svelte/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vite": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", + "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.30", + "rolldown": "~1.2.14", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitefu": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", + "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==", + "dev": true, + "license": "MIT", + "workspaces": [ + "tests/deps/*", + "tests/projects/*", + "tests/projects/workspace/packages/*" + ], + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, + "node_modules/zimmerframe": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz", + "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/ui/package.json b/ui/package.json new file mode 100644 index 0000000..10fc860 --- /dev/null +++ b/ui/package.json @@ -0,0 +1,19 @@ +{ + "name": "jellymove-ui", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "check": "svelte-check --tsconfig ./tsconfig.json" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^7.3.1", + "@tsconfig/svelte": "^5.0.8", + "svelte": "^5.57.3", + "svelte-check": "^4.7.8", + "typescript": "^6.0.3", + "vite": "^8.3.5" + } +} diff --git a/ui/src/App.svelte b/ui/src/App.svelte new file mode 100644 index 0000000..c60f623 --- /dev/null +++ b/ui/src/App.svelte @@ -0,0 +1,146 @@ + + +
+
+ + jellymove +
+
+ {localName} + {status?.peer_error ? '╳' : '⟷'} + {peerName} +
+ +
+ +
+ {#if statusError} + + {/if} + + {#if tab === 'library'} + (tab = 'jobs')} /> + {:else if tab === 'jobs'} + + {:else} + + {/if} +
+ + diff --git a/ui/src/app.css b/ui/src/app.css new file mode 100644 index 0000000..90fc4ea --- /dev/null +++ b/ui/src/app.css @@ -0,0 +1,113 @@ +:root { + --bg: #0f1216; + --panel: #161b21; + --panel-2: #1c232b; + --line: #2a333d; + --text: #e6e9ee; + --muted: #8b96a3; + --local: #f2a541; /* this node */ + --peer: #4cc3d9; /* the other node */ + --ok: #5ccf8a; + --bad: #ef6b6b; + --radius: 10px; + --mono: ui-monospace, 'SF Mono', 'Cascadia Code', 'JetBrains Mono', Menlo, monospace; + font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif; + font-size: 15px; + line-height: 1.45; + color: var(--text); + background: var(--bg); +} + +@media (prefers-color-scheme: light) { + :root { + --bg: #f4f5f7; + --panel: #ffffff; + --panel-2: #f0f2f5; + --line: #dde1e6; + --text: #1b2027; + --muted: #5f6b78; + --local: #c77a12; + --peer: #1a8ea3; + --ok: #23874d; + --bad: #c43c3c; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; +} + +button { + font: inherit; + color: inherit; + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 8px; + padding: 0.45rem 0.85rem; + cursor: pointer; +} + +button:hover:not(:disabled) { + border-color: var(--muted); +} + +button:disabled { + opacity: 0.5; + cursor: default; +} + +button.primary { + background: var(--text); + color: var(--bg); + border-color: var(--text); + font-weight: 600; +} + +input, +select { + font: inherit; + color: inherit; + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 8px; + padding: 0.45rem 0.7rem; +} + +input:focus-visible, +select:focus-visible, +button:focus-visible { + outline: 2px solid var(--peer); + outline-offset: 1px; +} + +code, +.mono { + font-family: var(--mono); + font-size: 0.85em; +} + +.muted { + color: var(--muted); +} + +.error { + color: var(--bad); +} + +.panel { + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); +} + +.dot { + display: inline-block; + width: 0.55rem; + height: 0.55rem; + border-radius: 50%; + vertical-align: middle; +} diff --git a/ui/src/lib/Jobs.svelte b/ui/src/lib/Jobs.svelte new file mode 100644 index 0000000..3b1ed96 --- /dev/null +++ b/ui/src/lib/Jobs.svelte @@ -0,0 +1,278 @@ + + +{#if error}

{error}

{/if} +{#if peerError}

Couldn't load moves running on the peer: {peerError}

{/if} + +{#if !sorted.length} +

No moves yet. Pick something in Library to get started.

+{/if} + +
    + {#each sorted as j (j.id)} +
  • +
    +
    +
    {j.name}
    +
    + {j.source_node} + → + {j.target_node} + {#if j.target_library}· {j.target_library}{/if} + {#if j.dry_run}dry run{/if} +
    +
    +
    + {statusText(j)} + {#if (j.status.kind === 'Failed' || j.status.kind === 'Planned') && j.target_node === localName} + + {/if} +
    +
    + + + + {#if j.progress.bytes_total} +
    +
    +
    +
    + {bytes(j.progress.bytes_done)} of {bytes(j.progress.bytes_total)} + {#if j.progress.current_file && j.status.kind === 'Running'} + · {j.progress.current_file} + {/if} +
    + {/if} + + {#if j.status.kind === 'Failed'} +

    {j.status.detail}

    + {/if} + + + {#if open[j.id]} +
    {j.log.join('\n')}
    + {/if} +
  • + {/each} +
+ + diff --git a/ui/src/lib/Library.svelte b/ui/src/lib/Library.svelte new file mode 100644 index 0000000..77d0987 --- /dev/null +++ b/ui/src/lib/Library.svelte @@ -0,0 +1,239 @@ + + +
+
+ + +
+ + +
+ +

+ Moving from {sourceName} to + {destName}. The whole folder moves, including + subtitles, artwork, NFOs and extras, along with everyone's watch history. +

+ +{#if error}

{error}

{/if} +{#if notice}

{notice}

{/if} + +
    + {#if loading && !items.length} +
  • Loading…
  • + {:else if !items.length} +
  • {libraryId ? 'Nothing here.' : 'No movie or TV libraries found.'}
  • + {/if} + {#each items as item (item.id)} +
  • + {item.kind === 'Series' ? 'TV' : 'Film'} +
    + {item.name} + {#if item.year}{item.year}{/if} + {#if item.path}
    {item.path}
    {/if} +
    +
    + + +
    +
  • + {/each} +
+ + diff --git a/ui/src/lib/StatusView.svelte b/ui/src/lib/StatusView.svelte new file mode 100644 index 0000000..8a48219 --- /dev/null +++ b/ui/src/lib/StatusView.svelte @@ -0,0 +1,169 @@ + + +{#if !status} +

Loading…

+{:else} +
+
+

This agent

+
+
Node
+
{status.node.node_name} v{status.node.version}
+
Jellyfin
+
+ {#if status.jellyfin_error} + {status.jellyfin_error} + {:else} + {status.node.jellyfin_server} + {status.node.jellyfin_version} + {/if} +
+
+
+ +
+

Peer

+
+
URL
+
{status.peer_url ?? 'not configured'}
+
Connection
+
+ {#if status.peer_error} + {status.peer_error} + {:else if status.peer} + {status.peer.node_name} + v{status.peer.version} · Jellyfin {status.peer.jellyfin_version ?? '?'} + {:else} + No peer configured + {/if} +
+
+
+
+ +
+
+

Library folders

+ +
+

+ jellymove must see each library folder Jellyfin uses, and be able to write to it. If a folder fails, check + the container's volume mounts, PUID/PGID, or path_map. +

+ + + + {#each status.locations as loc (loc.library + loc.jellyfin_path)} + + + + + + + {:else} + + {/each} + +
LibraryJellyfin pathSeen here asStatus
{loc.library}{loc.jellyfin_path}{loc.local_path} + {#if !loc.exists}not found + {:else if !loc.writable}read-only + {:else}OK{/if} +
No libraries reported.
+
+ +
+ Effective configuration (secrets hidden) +
{JSON.stringify(status.config, null, 2)}
+
+{/if} + + diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts new file mode 100644 index 0000000..6c49d93 --- /dev/null +++ b/ui/src/lib/api.ts @@ -0,0 +1,145 @@ +// Types mirror the Rust structs in jm-core / jm-server. + +export type Side = 'local' | 'peer'; + +export interface NodeInfo { + node_name: string; + version: string; + jellyfin_server: string | null; + jellyfin_version: string | null; +} + +export interface LocationCheck { + library: string; + jellyfin_path: string; + local_path: string; + exists: boolean; + writable: boolean; +} + +export interface Status { + node: NodeInfo; + jellyfin_error: string | null; + locations: LocationCheck[]; + peer_url: string | null; + peer: NodeInfo | null; + peer_error: string | null; + config: unknown; +} + +export interface Library { + id: string; + name: string; + collection_type: string | null; + locations: string[]; +} + +export interface LibraryItem { + id: string; + name: string; + kind: 'Movie' | 'Series' | string; + year: number | null; + path: string | null; +} + +export type Stage = + | 'Created' + | 'ExportReady' + | 'Copied' + | 'Promoted' + | 'TargetScanned' + | 'UserDataApplied' + | 'SourceCleaned' + | 'Done'; + +export type JobStatus = + | { kind: 'Queued' } + | { kind: 'Running' } + | { kind: 'Planned' } + | { kind: 'Failed'; detail: string } + | { kind: 'Done' }; + +export interface Job { + id: string; + created: string; + updated: string; + source_item_id: string; + name: string; + source_node: string; + target_node: string; + dry_run: boolean; + stage: Stage; + status: JobStatus; + target_library: string | null; + target_folder_jellyfin: string | null; + progress: { bytes_done: number; bytes_total: number; current_file: string | null }; + log: string[]; +} + +export interface JobsView { + local: Job[]; + peer: Job[]; + peer_error: string | null; +} + +export class ApiError extends Error {} + +async function call(method: string, path: string, body?: unknown): Promise { + const res = await fetch(`/api${path}`, { + method, + headers: { + // Required on POSTs; stops cross-site form submissions (CSRF). + 'X-Jellymove': '1', + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + if (!res.ok) { + let msg = `HTTP ${res.status}`; + try { + msg = (await res.json()).error ?? msg; + } catch { + /* not JSON */ + } + throw new ApiError(msg); + } + return res.json() as Promise; +} + +export const api = { + status: () => call('GET', '/status'), + libraries: (node: Side) => call('GET', `/libraries?node=${node}`), + items: (node: Side, library: string, search: string) => + call( + 'GET', + `/items?${new URLSearchParams({ node, library, ...(search ? { search } : {}) })}`, + ), + move: (from: Side, item: LibraryItem, dry_run: boolean) => + call('POST', '/moves', { from, item_id: item.id, name: item.name, dry_run }), + jobs: () => call('GET', '/jobs'), + retry: (id: string) => call('POST', `/jobs/${id}/retry`), +}; + +export const STAGE_LABEL: Record = { + Created: 'Preparing at source', + ExportReady: 'Copying', + Copied: 'Moving into library', + Promoted: 'Waiting for Jellyfin scan', + TargetScanned: 'Restoring watch history', + UserDataApplied: 'Cleaning up source', + SourceCleaned: 'Finishing', + Done: 'Done', +}; + +export const STAGES: Stage[] = Object.keys(STAGE_LABEL) as Stage[]; + +export function bytes(n: number): string { + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + let v = n; + let u = 0; + while (v >= 1000 && u < units.length - 1) { + v /= 1000; + u++; + } + return u === 0 ? `${n} B` : `${v.toFixed(1)} ${units[u]}`; +} diff --git a/ui/src/main.ts b/ui/src/main.ts new file mode 100644 index 0000000..dd41642 --- /dev/null +++ b/ui/src/main.ts @@ -0,0 +1,5 @@ +import { mount } from 'svelte'; +import './app.css'; +import App from './App.svelte'; + +export default mount(App, { target: document.getElementById('app')! }); diff --git a/ui/src/vite-env.d.ts b/ui/src/vite-env.d.ts new file mode 100644 index 0000000..4078e74 --- /dev/null +++ b/ui/src/vite-env.d.ts @@ -0,0 +1,2 @@ +/// +/// diff --git a/ui/svelte.config.js b/ui/svelte.config.js new file mode 100644 index 0000000..0378127 --- /dev/null +++ b/ui/svelte.config.js @@ -0,0 +1,2 @@ +import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; +export default { preprocess: vitePreprocess() }; diff --git a/ui/tsconfig.json b/ui/tsconfig.json new file mode 100644 index 0000000..bdf0831 --- /dev/null +++ b/ui/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "@tsconfig/svelte/tsconfig.json", + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "types": ["svelte", "vite/client"] + }, + "include": ["src/**/*.ts", "src/**/*.svelte"] +} diff --git a/ui/vite.config.ts b/ui/vite.config.ts new file mode 100644 index 0000000..5979016 --- /dev/null +++ b/ui/vite.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; + +// `npm run dev` proxies the API to a locally running daemon. +const daemon = process.env.JELLYMOVE_URL ?? 'http://127.0.0.1:8097'; + +export default defineConfig({ + plugins: [svelte()], + server: { proxy: { '/api': daemon } }, + build: { outDir: 'dist', emptyOutDir: true }, +});