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

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

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
target
ui/node_modules
ui/dist
data
.git
.claude
**/.DS_Store
jellymove.toml
cloud.toml
home.toml
+15
View File
@@ -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
+77
View File
@@ -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"
+9
View File
@@ -0,0 +1,9 @@
/target
/data
jellymove.toml
cloud.toml
home.toml
ui/node_modules
ui/dist
.DS_Store
.claude/settings.local.json
+87
View File
@@ -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 `<library>/.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.
Generated
+2977
View File
File diff suppressed because it is too large. Load diff
+9
View File
@@ -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"
+21
View File
@@ -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"]
+160
View File
@@ -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.
+57
View File
@@ -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_<KEY>,
# 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"
+18
View File
@@ -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"] }
+77
View File
@@ -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<Command>,
}
#[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<jm_server::Config> {
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(())
}
+13
View File
@@ -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"] }
+263
View File
@@ -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<Self, Self::Err> {
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<ManifestEntry>,
}
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<UserDataRecord>,
/// 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<ItemKey>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Progress {
pub bytes_done: u64,
pub bytes_total: u64,
pub current_file: Option<String>,
}
/// 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<String>,
pub export: Option<ExportInfo>,
/// Destination library chosen for the item.
pub target_library: Option<String>,
/// Final item folder in the destination's *Jellyfin* path namespace.
pub target_folder_jellyfin: Option<String>,
/// Item ID Jellyfin assigned on the destination after the scan.
pub target_item_id: Option<String>,
pub progress: Progress,
/// Human-readable log of what happened, newest last.
pub log: Vec<String>,
}
impl Job {
pub fn new(
source_item_id: impl Into<String>,
name: impl Into<String>,
source_node: impl Into<String>,
target_node: impl Into<String>,
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<String>) {
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"));
}
}
+11
View File
@@ -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;
+168
View File
@@ -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<PathMapping>);
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<Item = (&'a PathBuf, &'a PathBuf)>) -> 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<String> {
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<PathBuf> {
// 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);
}
}
+187
View File
@@ -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<String> = 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<String> {
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)
);
}
}
+82
View File
@@ -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<String>,
}
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"));
}
}
+18
View File
@@ -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"] }
+425
View File
@@ -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<T> = std::result::Result<T, JellyfinError>;
#[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<String>,
#[serde(default)]
pub collection_type: Option<String>,
#[serde(default)]
pub item_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct MediaSource {
#[serde(default)]
pub path: Option<String>,
}
#[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<String>,
}
impl From<ItemUserData> 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<String>,
#[serde(default)]
pub production_year: Option<i32>,
#[serde(default)]
pub provider_ids: HashMap<String, String>,
#[serde(default)]
pub media_sources: Option<Vec<MediaSource>>,
/// Season number for episodes.
#[serde(default)]
pub parent_index_number: Option<i32>,
/// Episode number for episodes.
#[serde(default)]
pub index_number: Option<i32>,
#[serde(default)]
pub user_data: Option<ItemUserData>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct ItemsPage {
#[serde(default)]
items: Vec<Item>,
#[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<Self> {
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<T: for<'de> Deserialize<'de>>(
&self,
path: &str,
query: &[(&str, String)],
) -> Result<T> {
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<B: Serialize>(
&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<SystemInfo> {
self.get("/System/Info", &[]).await
}
pub async fn virtual_folders(&self) -> Result<Vec<VirtualFolder>> {
self.get("/Library/VirtualFolders", &[]).await
}
pub async fn users(&self) -> Result<Vec<User>> {
self.get("/Users", &[]).await
}
pub async fn item(&self, id: &str) -> Result<Item> {
let mut items = self
.get::<ItemsPage>(
"/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<Vec<Item>> {
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<Update<'a>>,
}
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<reqwest::Response> {
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<HashMap<String, String>>,
) -> std::result::Result<Json<Value>, 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<Value> = (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<Value>) -> 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());
}
}
+37
View File
@@ -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"
+132
View File
@@ -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<u8> = (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<Lib> {
vec![
Lib {
name: "Movies".into(),
collection_type: "movies",
location: root.join("movies"),
},
Lib {
name: "TV Shows".into(),
collection_type: "tvshows",
location: root.join("tv"),
},
]
}
#[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)");
}
}
+444
View File
@@ -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<anyhow::Error> for ApiError {
fn from(e: anyhow::Error) -> Self {
ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}"))
}
}
impl From<jm_store::StoreError> for ApiError {
fn from(e: jm_store::StoreError) -> Self {
ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
}
}
impl From<jm_jellyfin::JellyfinError> for ApiError {
fn from(e: jm_jellyfin::JellyfinError) -> Self {
ApiError(StatusCode::BAD_GATEWAY, e.to_string())
}
}
type ApiResult<T> = Result<Json<T>, 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<Shared>, 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<Shared>, 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<String>,
locations: Vec<LocationCheck>,
peer_url: Option<String>,
peer: Option<NodeInfo>,
peer_error: Option<String>,
config: crate::config::Config,
}
async fn node_info(state: &Shared) -> (NodeInfo, Option<String>) {
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<Shared>) -> ApiResult<Status> {
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<Shared>,
Query(q): Query<NodeQuery>,
) -> ApiResult<Vec<Library>> {
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<String>,
}
async fn ui_items(
State(state): State<Shared>,
Query(q): Query<ItemsQuery>,
) -> ApiResult<Vec<LibraryItem>> {
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<Shared>, Json(req): Json<MoveRequest>) -> ApiResult<Job> {
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<Job>,
/// Jobs the peer is running (items moving *from* here).
peer: Vec<Job>,
peer_error: Option<String>,
}
async fn ui_jobs(State(state): State<Shared>) -> ApiResult<JobsView> {
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<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
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<Shared>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
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<Shared>) -> Json<NodeInfo> {
Json(node_info(&state).await.0)
}
async fn peer_libraries(State(state): State<Shared>) -> ApiResult<Vec<Library>> {
Ok(Json(library::libraries(&state).await?))
}
#[derive(Deserialize)]
struct PeerItemsQuery {
library: String,
search: Option<String>,
}
async fn peer_items(
State(state): State<Shared>,
Query(q): Query<PeerItemsQuery>,
) -> ApiResult<Vec<LibraryItem>> {
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<Shared>,
Json(req): Json<CreateExport>,
) -> ApiResult<Export> {
Ok(Json(export::create(&state, &req.item_id).await?))
}
async fn peer_get_export(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Export> {
export::get(&state, &id)
.await?
.map(Json)
.ok_or(ApiError(StatusCode::NOT_FOUND, "no such export".into()))
}
async fn peer_file(
State(state): State<Shared>,
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<Shared>,
Path(id): Path<String>,
) -> ApiResult<Export> {
Ok(Json(export::complete(&state, &id).await?))
}
async fn peer_create_job(
State(state): State<Shared>,
Json(req): Json<CreateJob>,
) -> ApiResult<Job> {
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<Shared>) -> ApiResult<Vec<Job>> {
let mut jobs = state.store.list_jobs(100).await?;
for j in &mut jobs {
j.export = None;
}
Ok(Json(jobs))
}
+121
View File
@@ -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<PeerConfig>,
/// 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<String, String>,
#[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<String>,
pub password: Option<String>,
}
#[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<String>,
}
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<std::num::NonZeroU32> {
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
}
}
+322
View File
@@ -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<ExportInfo>,
/// 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<PathBuf> {
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<Export> {
// 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::<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<Option<Export>> {
let export: Option<Export> = 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<String> = 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<String> = 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<UserDataRecord>,
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<Export> {
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)
}
+58
View File
@@ -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");
}
+114
View File
@@ -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<String>,
pub locations: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LibraryItem {
pub id: String,
pub name: String,
/// "Movie" or "Series".
pub kind: String,
pub year: Option<i32>,
pub path: Option<String>,
}
#[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<Vec<Library>> {
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<Vec<LibraryItem>> {
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<Vec<LocationCheck>> {
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)
}
+126
View File
@@ -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<String>,
pub jellyfin_version: Option<String>,
}
#[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<T: DeserializeOwned>(
&self,
req: reqwest::RequestBuilder,
what: &str,
) -> anyhow::Result<T> {
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<NodeInfo> {
self.send(self.http.get(self.url("/info")), "info").await
}
pub async fn libraries(&self) -> anyhow::Result<Vec<Library>> {
self.send(self.http.get(self.url("/libraries")), "list libraries")
.await
}
pub async fn items(
&self,
library: &str,
search: Option<&str>,
) -> anyhow::Result<Vec<LibraryItem>> {
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<Export> {
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<Export> {
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<Export> {
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<Job> {
self.send(self.http.post(self.url("/jobs")).json(req), "start job")
.await
}
pub async fn jobs(&self) -> anyhow::Result<Vec<Job>> {
self.send(self.http.get(self.url("/jobs")), "list jobs")
.await
}
}
+503
View File
@@ -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<Flow> {
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<PathBuf> {
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<PathBuf> {
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<Flow> {
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.\"{}\" = \"<local library>\"",
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<Option<String>> {
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<HashMap<ItemKey, String>> {
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<usize> {
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<String> = 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])
}
}
+76
View File
@@ -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<PeerClient>,
pub puller: Puller,
/// Job snapshots for the UI's live view.
pub events: broadcast::Sender<Job>,
pub job_slots: Arc<Semaphore>,
pub running: Mutex<HashSet<JobId>>,
/// Exports currently being hashed, so a duplicate request doesn't start a second pass.
pub preparing: Mutex<HashSet<String>>,
}
pub type Shared = Arc<AppState>;
impl AppState {
pub fn new(cfg: Config, store: Store) -> anyhow::Result<Self> {
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(())
}
}
+50
View File
@@ -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")],
"<h1>jellymove</h1><p>The web UI wasn't built into this binary. \
Run <code>npm --prefix ui ci &amp;&amp; npm --prefix ui run build</code>, then rebuild.</p>",
)
.into_response()
})
}
fn asset(path: &str) -> Option<Response> {
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"),
)
}
+412
View File
@@ -0,0 +1,412 @@
//! Two real jellymove agents, each with its own fake Jellyfin and media
//! folders, moving items between them through the same HTTP APIs the UI uses.
#[allow(dead_code)]
mod fake_jellyfin;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use fake_jellyfin::{Fake, Lib};
use jm_server::config::{
Config, HooksConfig, JellyfinConfig, PeerConfig, TransferConfig, UiConfig,
};
use serde_json::{Value, json};
const TOKEN: &str = "test-token";
struct Node {
_tmp: tempfile::TempDir,
root: PathBuf,
fake: Fake,
url: String,
}
impl Node {
fn movies(&self) -> PathBuf {
self.root.join("movies")
}
fn tv(&self) -> PathBuf {
self.root.join("tv")
}
}
fn libs(root: &Path) -> Vec<Lib> {
vec![
Lib {
name: "Movies".into(),
collection_type: "movies",
location: root.join("movies"),
},
Lib {
name: "TV Shows".into(),
collection_type: "tvshows",
location: root.join("tv"),
},
]
}
fn write(path: &Path, data: &[u8]) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, data).unwrap();
}
/// Start two peered agents. `seed` fills the first node's media folders.
async fn pair(seed: impl FnOnce(&Path)) -> (Node, Node) {
let tmp_a = tempfile::tempdir().unwrap();
let tmp_b = tempfile::tempdir().unwrap();
for t in [&tmp_a, &tmp_b] {
std::fs::create_dir_all(t.path().join("movies")).unwrap();
std::fs::create_dir_all(t.path().join("tv")).unwrap();
}
seed(tmp_a.path());
let fake_a = Fake::new(libs(tmp_a.path()));
let fake_b = Fake::new(libs(tmp_b.path()));
let jf_a = fake_a.clone().serve().await;
let jf_b = fake_b.clone().serve().await;
let la = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let lb = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url_a = format!("http://{}", la.local_addr().unwrap());
let url_b = format!("http://{}", lb.local_addr().unwrap());
for (name, tmp, jf, listener, peer_url) in [
("cloud", &tmp_a, jf_a, la, url_b.clone()),
("home", &tmp_b, jf_b, lb, url_a.clone()),
] {
let cfg = Config {
node_name: name.into(),
listen: listener.local_addr().unwrap(),
data_dir: tmp.path().join("state"),
jellyfin: JellyfinConfig {
url: jf,
api_key: "k".into(),
},
path_map: Default::default(),
peer: Some(PeerConfig {
url: peer_url,
token: TOKEN.into(),
}),
incoming_libraries: Default::default(),
transfer: TransferConfig {
scan_timeout_secs: 60,
..Default::default()
},
ui: UiConfig::default(),
hooks: HooksConfig::default(),
};
std::fs::create_dir_all(&cfg.data_dir).unwrap();
let store = jm_store::Store::open(&cfg.data_dir.join("db")).unwrap();
let state = Arc::new(jm_server::state::AppState::new(cfg, store).unwrap());
let app = jm_server::api::router(state);
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
}
let a = Node {
root: tmp_a.path().to_path_buf(),
_tmp: tmp_a,
fake: fake_a,
url: url_a,
};
let b = Node {
root: tmp_b.path().to_path_buf(),
_tmp: tmp_b,
fake: fake_b,
url: url_b,
};
(a, b)
}
async fn post(base: &str, path: &str, body: Value) -> reqwest::Response {
reqwest::Client::new()
.post(format!("{base}{path}"))
.header("X-Jellymove", "1")
.json(&body)
.send()
.await
.unwrap()
}
async fn get(base: &str, path: &str) -> Value {
reqwest::get(format!("{base}{path}"))
.await
.unwrap()
.json()
.await
.unwrap()
}
/// Wait for the job to leave the active states; returns its final JSON.
async fn wait_job(base: &str, id: &str) -> Value {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let jobs = get(base, "/api/jobs").await;
let all: Vec<Value> = [
jobs["local"].as_array().unwrap().clone(),
jobs["peer"].as_array().unwrap().clone(),
]
.concat();
if let Some(j) = all.iter().find(|j| j["id"] == id) {
let kind = j["status"]["kind"].as_str().unwrap();
if !matches!(kind, "Queued" | "Running") {
return j.clone();
}
}
assert!(Instant::now() < deadline, "job {id} didn't finish in time");
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
fn seed_movie(root: &Path) {
let m = root.join("movies/Alien (1979)");
write(&m.join("Alien (1979).mkv"), &vec![7u8; 2 * 1024 * 1024]);
write(
&m.join("Alien (1979).nfo"),
b"<movie><title>Alien</title></movie>",
);
write(
&m.join("Alien (1979).en.srt"),
b"1\n00:00:01,000 --> 00:00:02,000\nIn space...\n",
);
write(&m.join("extras/Making of.mkv"), b"extra");
}
fn seed_series(root: &Path) {
let s = root.join("tv/Severance");
write(&s.join("tvshow.nfo"), b"<tvshow/>");
write(&s.join("Season 01/Severance S01E01.mkv"), b"episode one");
write(&s.join("Season 01/Severance S01E02.mkv"), b"episode two");
write(&s.join("Season 02/Severance S02E01.mkv"), b"episode three");
}
#[tokio::test]
async fn moves_a_movie_with_sidecars_and_watch_state() {
let (cloud, home) = pair(seed_movie).await;
let movie = cloud.fake.find("Movie", "Alien").unwrap();
cloud.fake.set_user_data(
&movie,
json!({"Played": true, "PlayCount": 2, "IsFavorite": true}),
);
// Started from the cloud UI: "move this local item to the peer".
let resp = post(
&cloud.url,
"/api/moves",
json!({"from": "local", "item_id": movie, "name": "Alien"}),
)
.await;
assert!(resp.status().is_success(), "{}", resp.text().await.unwrap());
let job: Value = resp.json().await.unwrap();
let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Done", "{done:#}");
assert_eq!(done["target_node"], "home");
// Files arrived intact, sidecars included.
let dest = home.movies().join("Alien (1979)");
assert_eq!(
std::fs::read(dest.join("Alien (1979).mkv")).unwrap(),
vec![7u8; 2 * 1024 * 1024]
);
assert!(dest.join("Alien (1979).en.srt").exists());
assert!(dest.join("extras/Making of.mkv").exists());
// Nothing left in the partial area.
assert_eq!(
std::fs::read_dir(home.movies().join(".jellymove-partial"))
.unwrap()
.filter(|e| e.as_ref().unwrap().file_name() != ".ignore")
.count(),
0
);
// Source moved to the hidden trash, not deleted outright.
assert!(!cloud.movies().join("Alien (1979)").exists());
let trash = cloud.movies().join(".jellymove-trash");
assert!(
trash
.join(format!("item-{movie}/Alien (1979)/Alien (1979).mkv"))
.exists()
);
// Watch state followed the move to the new item ID.
let new_id = home.fake.find("Movie", "Alien").unwrap();
assert_ne!(new_id, movie);
let ud = home.fake.get_user_data(&new_id).expect("user data applied");
assert_eq!(ud["Played"], true);
assert_eq!(ud["PlayCount"], 2);
assert_eq!(ud["IsFavorite"], true);
}
#[tokio::test]
async fn moves_a_series_and_maps_episode_watch_state() {
let (cloud, home) = pair(seed_series).await;
let series = cloud.fake.find("Series", "Severance").unwrap();
let e1 = cloud.fake.episode_id("Severance", 1, 1).unwrap();
let e3 = cloud.fake.episode_id("Severance", 2, 1).unwrap();
cloud
.fake
.set_user_data(&e1, json!({"Played": true, "PlayCount": 1}));
cloud
.fake
.set_user_data(&e3, json!({"PlaybackPositionTicks": 123456789}));
// Started from the *home* UI this time: "pull this item from the peer".
let resp = post(
&home.url,
"/api/moves",
json!({"from": "peer", "item_id": series, "name": "Severance"}),
)
.await;
let job: Value = resp.json().await.unwrap();
let done = wait_job(&home.url, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Done", "{done:#}");
assert!(
home.tv()
.join("Severance/Season 02/Severance S02E01.mkv")
.exists()
);
assert!(!cloud.tv().join("Severance").exists());
let new_e1 = home.fake.episode_id("Severance", 1, 1).unwrap();
let new_e3 = home.fake.episode_id("Severance", 2, 1).unwrap();
assert_eq!(home.fake.get_user_data(&new_e1).unwrap()["Played"], true);
assert_eq!(
home.fake.get_user_data(&new_e3).unwrap()["PlaybackPositionTicks"],
123456789
);
// Untouched episode gets nothing written.
let new_e2 = home.fake.episode_id("Severance", 1, 2).unwrap();
assert!(home.fake.get_user_data(&new_e2).is_none());
}
#[tokio::test]
async fn dry_run_changes_nothing() {
let (cloud, home) = pair(seed_movie).await;
let movie = cloud.fake.find("Movie", "Alien").unwrap();
let job: Value = post(
&cloud.url,
"/api/moves",
json!({"from": "local", "item_id": movie, "name": "Alien", "dry_run": true}),
)
.await
.json()
.await
.unwrap();
let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Planned", "{done:#}");
assert!(
done["log"]
.as_array()
.unwrap()
.iter()
.any(|l| l.as_str().unwrap().contains("plan: 4 files"))
);
assert!(
cloud
.movies()
.join("Alien (1979)/Alien (1979).mkv")
.exists()
);
assert!(!home.movies().join("Alien (1979)").exists());
}
#[tokio::test]
async fn refuses_flat_movie_folder() {
let (cloud, home) = pair(|root| {
// Two movies sharing one folder: moving "the folder" would take both.
write(&root.join("movies/Unsorted/Heat (1995).mkv"), b"heat");
write(&root.join("movies/Unsorted/Ronin (1998).mkv"), b"ronin");
})
.await;
let heat = cloud.fake.find("Movie", "Unsorted").unwrap();
let job: Value = post(
&cloud.url,
"/api/moves",
json!({"from": "local", "item_id": heat, "name": "Heat"}),
)
.await
.json()
.await
.unwrap();
let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Failed");
assert!(
done["status"]["detail"]
.as_str()
.unwrap()
.contains("other videos"),
"{done:#}"
);
assert!(cloud.movies().join("Unsorted/Ronin (1998).mkv").exists());
assert!(!home.movies().join("Unsorted").exists());
}
#[tokio::test]
async fn refuses_when_destination_exists() {
let (cloud, home) = pair(seed_movie).await;
write(
&home.movies().join("Alien (1979)/Alien (1979).mkv"),
b"a different copy",
);
let movie = cloud.fake.find("Movie", "Alien").unwrap();
let job: Value = post(
&cloud.url,
"/api/moves",
json!({"from": "local", "item_id": movie, "name": "Alien"}),
)
.await
.json()
.await
.unwrap();
let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Failed");
assert!(
done["status"]["detail"]
.as_str()
.unwrap()
.contains("already exists")
);
assert_eq!(
std::fs::read(home.movies().join("Alien (1979)/Alien (1979).mkv")).unwrap(),
b"a different copy"
);
assert!(cloud.movies().join("Alien (1979)").exists());
}
#[tokio::test]
async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() {
let (cloud, _home) = pair(|_| {}).await;
let r = reqwest::Client::new()
.get(format!("{}/peer/v1/libraries", cloud.url))
.bearer_auth("wrong")
.send()
.await
.unwrap();
assert_eq!(r.status(), 401);
let r = reqwest::Client::new()
.post(format!("{}/api/moves", cloud.url))
.json(&json!({"from": "local", "item_id": "x", "name": "x"}))
.send()
.await
.unwrap();
assert_eq!(r.status(), 403);
}
#[tokio::test]
async fn export_files_are_only_reachable_by_index() {
let (cloud, _home) = pair(seed_movie).await;
// Path traversal attempts through the file route go nowhere.
let r = reqwest::Client::new()
.get(format!(
"{}/peer/v1/exports/..%2F..%2Fetc/files/0",
cloud.url
))
.bearer_auth(TOKEN)
.send()
.await
.unwrap();
assert_eq!(r.status(), 404);
}
+296
View File
@@ -0,0 +1,296 @@
//! A tiny filesystem-backed stand-in for Jellyfin, good enough to drive a
//! real move end to end. Like real Jellyfin, item IDs are derived from paths,
//! scans happen a moment after `/Library/Media/Updated`, and user data is
//! keyed by (user, item).
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use axum::extract::{Path as AxPath, Query, State};
use axum::http::StatusCode;
use axum::routing::{get, post};
use axum::{Json, Router};
use serde_json::{Value, json};
#[derive(Clone)]
pub struct Lib {
pub name: String,
pub collection_type: &'static str,
pub location: PathBuf,
}
impl Lib {
pub fn id(&self) -> String {
format!("lib-{}", self.name.to_lowercase().replace(' ', "-"))
}
}
#[derive(Clone, Debug)]
struct FakeItem {
id: String,
name: String,
kind: &'static str,
path: String,
parent: String,
season: Option<i32>,
episode: Option<i32>,
}
#[derive(Clone)]
pub struct Fake {
libs: Arc<Vec<Lib>>,
items: Arc<Mutex<Vec<FakeItem>>>,
/// (user id, item id) → UserData JSON
pub user_data: Arc<Mutex<HashMap<(String, String), Value>>>,
}
pub fn id_for(path: &Path) -> String {
blake3::hash(path.to_string_lossy().as_bytes()).to_hex()[..32].to_string()
}
fn parse_sxxexx(name: &str) -> Option<(i32, i32)> {
// Find the first "S<digits>E<digits>" anywhere in the name.
let up = name.to_uppercase();
let b = up.as_bytes();
for i in 0..b.len() {
if b[i] != b'S' {
continue;
}
let s: String = up[i + 1..]
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
let after = i + 1 + s.len();
if s.is_empty() || b.get(after) != Some(&b'E') {
continue;
}
let e: String = up[after + 1..]
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
if let (Ok(season), Ok(ep)) = (s.parse(), e.parse()) {
return Some((season, ep));
}
}
None
}
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(rd) = std::fs::read_dir(dir) else {
return;
};
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if name.starts_with('.') {
continue; // Jellyfin skips hidden folders
}
if e.file_type().unwrap().is_dir() {
walk(&e.path(), out);
} else {
out.push(e.path());
}
}
}
impl Fake {
pub fn new(libs: Vec<Lib>) -> Self {
let f = Self {
libs: Arc::new(libs),
items: Default::default(),
user_data: Default::default(),
};
f.scan();
f
}
pub fn scan(&self) {
let mut items = Vec::new();
for lib in self.libs.iter() {
let Ok(rd) = std::fs::read_dir(&lib.location) else {
continue;
};
for entry in rd.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with('.') || !entry.file_type().unwrap().is_dir() {
continue;
}
let folder = entry.path();
let mut files = Vec::new();
walk(&folder, &mut files);
if lib.collection_type == "movies" {
for f in files
.iter()
.filter(|f| f.extension().is_some_and(|e| e == "mkv"))
{
if f.parent() != Some(folder.as_path()) {
continue; // extras
}
items.push(FakeItem {
id: id_for(f),
name: name.split(" (").next().unwrap().to_string(),
kind: "Movie",
path: f.display().to_string(),
parent: lib.id(),
season: None,
episode: None,
});
}
} else {
let series_id = id_for(&folder);
items.push(FakeItem {
id: series_id.clone(),
name: name.clone(),
kind: "Series",
path: folder.display().to_string(),
parent: lib.id(),
season: None,
episode: None,
});
for f in files
.iter()
.filter(|f| f.extension().is_some_and(|e| e == "mkv"))
{
let fname = f.file_name().unwrap().to_string_lossy();
if let Some((s, e)) = parse_sxxexx(&fname) {
items.push(FakeItem {
id: id_for(f),
name: fname.to_string(),
kind: "Episode",
path: f.display().to_string(),
parent: series_id.clone(),
season: Some(s),
episode: Some(e),
});
}
}
}
}
}
*self.items.lock().unwrap() = items;
}
pub fn find(&self, kind: &str, name: &str) -> Option<String> {
self.items
.lock()
.unwrap()
.iter()
.find(|i| i.kind == kind && i.name == name)
.map(|i| i.id.clone())
}
pub fn episode_id(&self, series: &str, season: i32, ep: i32) -> Option<String> {
let series_id = self.find("Series", series)?;
self.items
.lock()
.unwrap()
.iter()
.find(|i| i.parent == series_id && i.season == Some(season) && i.episode == Some(ep))
.map(|i| i.id.clone())
}
pub fn set_user_data(&self, item: &str, data: Value) {
self.user_data
.lock()
.unwrap()
.insert(("u1".into(), item.into()), data);
}
pub fn get_user_data(&self, item: &str) -> Option<Value> {
self.user_data
.lock()
.unwrap()
.get(&("u1".to_string(), item.to_string()))
.cloned()
}
pub async fn serve(self) -> String {
let app = Router::new()
.route(
"/System/Info",
get(|| async {
Json(json!({"ServerName": "fake", "Version": "10.11.0", "Id": "x"}))
}),
)
.route(
"/Users",
get(|| async { Json(json!([{"Id": "u1", "Name": "Alice"}])) }),
)
.route("/Library/VirtualFolders", get(virtual_folders))
.route("/Items", get(items))
.route("/Library/Media/Updated", post(media_updated))
.route("/UserItems/{id}/UserData", post(set_user_data))
.with_state(self);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
}
async fn virtual_folders(State(f): State<Fake>) -> Json<Value> {
Json(Value::Array(
f.libs
.iter()
.map(|l| {
json!({"Name": l.name, "Locations": [l.location.display().to_string()],
"CollectionType": l.collection_type, "ItemId": l.id()})
})
.collect(),
))
}
async fn items(State(f): State<Fake>, Query(q): Query<HashMap<String, String>>) -> Json<Value> {
let all = f.items.lock().unwrap().clone();
let types: Option<Vec<&str>> = q.get("includeItemTypes").map(|t| t.split(',').collect());
let ids: Option<Vec<&str>> = q.get("ids").map(|t| t.split(',').collect());
let ud = f.user_data.lock().unwrap().clone();
let user = q.get("userId");
let out: Vec<Value> = all
.iter()
.filter(|i| ids.as_ref().is_none_or(|ids| ids.contains(&i.id.as_str())))
.filter(|i| q.get("parentId").is_none_or(|p| &i.parent == p))
.filter(|i| types.as_ref().is_none_or(|t| t.contains(&i.kind)))
.filter(|i| {
q.get("searchTerm")
.is_none_or(|s| i.name.to_lowercase().contains(&s.to_lowercase()))
})
.map(|i| {
let mut v = json!({"Id": i.id, "Name": i.name, "Type": i.kind, "Path": i.path,
"ParentIndexNumber": i.season, "IndexNumber": i.episode,
"MediaSources": [{"Path": i.path}]});
if let Some(u) = user {
v["UserData"] = ud
.get(&(u.clone(), i.id.clone()))
.cloned()
.unwrap_or(json!({"Played": false}));
}
v
})
.collect();
let n = out.len();
Json(json!({"Items": out, "TotalRecordCount": n}))
}
async fn media_updated(State(f): State<Fake>) -> StatusCode {
// Like Jellyfin's LibraryMonitorDelay, but much shorter.
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(300)).await;
f.scan();
});
StatusCode::NO_CONTENT
}
async fn set_user_data(
State(f): State<Fake>,
AxPath(id): AxPath<String>,
Query(q): Query<HashMap<String, String>>,
Json(body): Json<Value>,
) -> StatusCode {
f.user_data
.lock()
.unwrap()
.insert((q["userId"].clone(), id), body);
StatusCode::OK
}
+17
View File
@@ -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"
+208
View File
@@ -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<T> = std::result::Result<T, StoreError>;
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<Mutex<Connection>>,
}
impl Store {
pub fn open(path: &Path) -> Result<Self> {
Self::init(Connection::open(path)?)
}
pub fn in_memory() -> Result<Self> {
Self::init(Connection::open_in_memory()?)
}
fn init(conn: Connection) -> Result<Self> {
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<T: Send + 'static>(
&self,
f: impl FnOnce(&Connection) -> Result<T> + Send + 'static,
) -> Result<T> {
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<Option<Job>> {
let id = id.to_string();
let body: Option<String> = 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<Vec<Job>> {
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<Vec<Job>> {
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<Vec<Job>> {
let bodies: Vec<String> = 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::<rusqlite::Result<_>>()?)
})
.await?;
bodies
.iter()
.map(|b| serde_json::from_str(b).map_err(Into::into))
.collect()
}
pub async fn put_export<T: Serialize>(&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<T: DeserializeOwned>(&self, id: &str) -> Result<Option<T>> {
let id = id.to_string();
let body: Option<String> = 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);
}
}
+24
View File
@@ -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"
+60
View File
@@ -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,
}
}
}
+104
View File
@@ -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<String, TransferError> {
let path = path.to_path_buf();
tokio::task::spawn_blocking(move || -> Result<String, TransferError> {
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<Manifest, TransferError> {
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<Vec<String>, TransferError> {
Ok(list_files(root)?
.into_iter()
.map(|(rel, _, _)| rel)
.collect())
}
fn list_files(root: &Path) -> Result<Vec<(String, PathBuf, u64)>, 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::<Vec<_>>()
.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"<tvshow/>").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()
);
}
}
+75
View File
@@ -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(())
}
+185
View File
@@ -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<String>,
/// Bytes per second across every transfer this puller makes. `None` = unlimited.
pub bytes_per_sec: Option<NonZeroU32>,
/// 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<Arc<DefaultDirectRateLimiter>>,
}
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;
}
}
}
+100
View File
@@ -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::<u64>().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);
}
}
+243
View File
@@ -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<Vec<String>>,
/// When non-zero, the next request is cut off after this many bytes.
cut_after: Arc<AtomicUsize>,
requests: Arc<AtomicUsize>,
/// Requests that asked to resume with a Range header.
ranged: Arc<AtomicUsize>,
}
async fn file(State(s): State<Src>, Path(idx): Path<usize>, 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<u8> = (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"<movie/>").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()
);
}
+24
View File
@@ -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
+23
View File
@@ -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
+99
View File
@@ -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 `<dest library>/.jellymove-partial/<job>/<idx>.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=<library>&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.
+2
View File
@@ -0,0 +1,2 @@
node_modules/
dist/
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="dark light" />
<title>jellymove</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1189
View File
File diff suppressed because it is too large. Load diff
+19
View File
@@ -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"
}
}
+146
View File
@@ -0,0 +1,146 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, type Status } from './lib/api';
import Library from './lib/Library.svelte';
import Jobs from './lib/Jobs.svelte';
import StatusView from './lib/StatusView.svelte';
type Tab = 'library' | 'jobs' | 'status';
let tab = $state<Tab>('library');
let status = $state<Status | null>(null);
let statusError = $state<string | null>(null);
async function loadStatus() {
try {
status = await api.status();
statusError = null;
} catch (e) {
statusError = (e as Error).message;
}
}
onMount(() => {
loadStatus();
const t = setInterval(loadStatus, 30_000);
return () => clearInterval(t);
});
const localName = $derived(status?.node.node_name ?? 'this server');
const peerName = $derived(status?.peer?.node_name ?? 'peer');
const healthy = $derived(
!!status &&
!status.jellyfin_error &&
!status.peer_error &&
status.locations.every((l) => l.exists && l.writable),
);
</script>
<header>
<div class="brand">
<span class="logo" aria-hidden="true">⇄</span>
<span>jellymove</span>
</div>
<div class="nodes" aria-label="Connected servers">
<span class="node local"><span class="dot"></span>{localName}</span>
<span class="link" class:down={!!status?.peer_error}>{status?.peer_error ? '╳' : '⟷'}</span>
<span class="node peer"><span class="dot"></span>{peerName}</span>
</div>
<nav>
<button class:active={tab === 'library'} onclick={() => (tab = 'library')}>Library</button>
<button class:active={tab === 'jobs'} onclick={() => (tab = 'jobs')}>Moves</button>
<button class:active={tab === 'status'} onclick={() => (tab = 'status')}>
Status
{#if status && !healthy}<span class="dot warn" title="Something needs attention"></span>{/if}
</button>
</nav>
</header>
<main>
{#if statusError}
<p class="panel banner error">Can't reach this jellymove agent: {statusError}</p>
{/if}
{#if tab === 'library'}
<Library {localName} {peerName} onmoved={() => (tab = 'jobs')} />
{:else if tab === 'jobs'}
<Jobs {localName} />
{:else}
<StatusView {status} reload={loadStatus} />
{/if}
</main>
<style>
header {
display: flex;
align-items: center;
gap: 1.5rem;
padding: 0.8rem 1.5rem;
border-bottom: 1px solid var(--line);
background: var(--panel);
flex-wrap: wrap;
}
.brand {
display: flex;
align-items: center;
gap: 0.5rem;
font-weight: 700;
letter-spacing: -0.01em;
font-size: 1.1rem;
}
.logo {
color: var(--local);
}
.nodes {
display: flex;
align-items: center;
gap: 0.6rem;
font-size: 0.9rem;
}
.node {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.2rem 0.65rem;
border-radius: 999px;
border: 1px solid var(--line);
}
.node.local .dot {
background: var(--local);
}
.node.peer .dot {
background: var(--peer);
}
.link {
color: var(--muted);
}
.link.down {
color: var(--bad);
}
nav {
margin-left: auto;
display: flex;
gap: 0.25rem;
}
nav button {
background: transparent;
border-color: transparent;
color: var(--muted);
}
nav button.active {
color: var(--text);
background: var(--panel-2);
border-color: var(--line);
}
.dot.warn {
background: var(--bad);
margin-left: 0.3rem;
}
main {
max-width: 1100px;
margin: 0 auto;
padding: 1.5rem;
}
.banner {
padding: 0.8rem 1rem;
}
</style>
+113
View File
@@ -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;
}
+278
View File
@@ -0,0 +1,278 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, bytes, STAGE_LABEL, STAGES, type Job } from './api';
interface Props {
localName: string;
}
let { localName }: Props = $props();
let jobs = $state<Record<string, Job>>({});
let peerError = $state<string | null>(null);
let error = $state<string | null>(null);
let open = $state<Record<string, boolean>>({});
const sorted = $derived(Object.values(jobs).sort((a, b) => b.created.localeCompare(a.created)));
async function load() {
try {
const view = await api.jobs();
const next: Record<string, Job> = {};
for (const j of [...view.local, ...view.peer]) next[j.id] = j;
jobs = next;
peerError = view.peer_error;
error = null;
} catch (e) {
error = (e as Error).message;
}
}
onMount(() => {
load();
// Live progress for jobs running here; poll for jobs running on the peer.
const es = new EventSource('/api/events');
es.addEventListener('job', (ev) => {
const j = JSON.parse((ev as MessageEvent).data) as Job;
jobs[j.id] = j;
});
const t = setInterval(load, 2000);
return () => {
es.close();
clearInterval(t);
};
});
async function retry(id: string) {
try {
jobs[id] = await api.retry(id);
} catch (e) {
error = (e as Error).message;
}
}
function pct(j: Job): number {
if (j.status.kind === 'Done') return 100;
if (!j.progress.bytes_total) return 0;
return Math.min(100, (j.progress.bytes_done / j.progress.bytes_total) * 100);
}
function statusText(j: Job): string {
switch (j.status.kind) {
case 'Done':
return 'Moved';
case 'Planned':
return 'Dry run complete';
case 'Failed':
return 'Failed';
case 'Queued':
return 'Queued';
default:
return STAGE_LABEL[j.stage];
}
}
const sideClass = (node: string) => (node === localName ? 'local' : 'peer');
</script>
{#if error}<p class="panel msg error">{error}</p>{/if}
{#if peerError}<p class="panel msg muted">Couldn't load moves running on the peer: {peerError}</p>{/if}
{#if !sorted.length}
<p class="panel empty muted">No moves yet. Pick something in Library to get started.</p>
{/if}
<ul class="jobs">
{#each sorted as j (j.id)}
<li class="panel job" class:failed={j.status.kind === 'Failed'}>
<div class="top">
<div class="what">
<div class="name">{j.name}</div>
<div class="route">
<span class={sideClass(j.source_node)}>{j.source_node}</span>
<span class="muted">→</span>
<span class={sideClass(j.target_node)}>{j.target_node}</span>
{#if j.target_library}<span class="muted">· {j.target_library}</span>{/if}
{#if j.dry_run}<span class="tag">dry run</span>{/if}
</div>
</div>
<div class="state">
<span class="label s-{j.status.kind.toLowerCase()}">{statusText(j)}</span>
{#if (j.status.kind === 'Failed' || j.status.kind === 'Planned') && j.target_node === localName}
<button onclick={() => retry(j.id)}>{j.status.kind === 'Planned' ? 'Run for real' : 'Retry'}</button>
{/if}
</div>
</div>
<div class="steps" aria-hidden="true">
{#each STAGES.slice(0, -1) as s, i (s)}
<span class="step" class:done={STAGES.indexOf(j.stage) > i} class:now={STAGES.indexOf(j.stage) === i && j.status.kind === 'Running'}></span>
{/each}
</div>
{#if j.progress.bytes_total}
<div class="bar" role="progressbar" aria-valuenow={Math.round(pct(j))} aria-valuemin={0} aria-valuemax={100}>
<div style:width="{pct(j)}%"></div>
</div>
<div class="meta muted">
{bytes(j.progress.bytes_done)} of {bytes(j.progress.bytes_total)}
{#if j.progress.current_file && j.status.kind === 'Running'}
· <span class="mono">{j.progress.current_file}</span>
{/if}
</div>
{/if}
{#if j.status.kind === 'Failed'}
<p class="error why">{j.status.detail}</p>
{/if}
<button class="logtoggle" onclick={() => (open[j.id] = !open[j.id])} aria-expanded={!!open[j.id]}>
{open[j.id] ? 'Hide' : 'Show'} log ({j.log.length})
</button>
{#if open[j.id]}
<pre class="log">{j.log.join('\n')}</pre>
{/if}
</li>
{/each}
</ul>
<style>
.msg,
.empty {
padding: 0.8rem 1rem;
}
.empty {
text-align: center;
padding: 2rem;
}
.jobs {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.8rem;
}
.job {
padding: 1rem 1.1rem;
}
.job.failed {
border-color: color-mix(in srgb, var(--bad) 50%, var(--line));
}
.top {
display: flex;
gap: 1rem;
align-items: flex-start;
justify-content: space-between;
}
.name {
font-weight: 650;
font-size: 1.05rem;
}
.route {
font-size: 0.88rem;
display: flex;
gap: 0.35rem;
align-items: center;
flex-wrap: wrap;
}
.route .local {
color: var(--local);
}
.route .peer {
color: var(--peer);
}
.tag {
font-size: 0.72rem;
border: 1px solid var(--line);
border-radius: 5px;
padding: 0 0.35rem;
color: var(--muted);
}
.state {
display: flex;
gap: 0.6rem;
align-items: center;
flex-shrink: 0;
}
.label {
font-size: 0.85rem;
font-weight: 600;
}
.s-done {
color: var(--ok);
}
.s-failed {
color: var(--bad);
}
.s-running {
color: var(--peer);
}
.steps {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 4px;
margin: 0.8rem 0 0.5rem;
}
.step {
height: 4px;
border-radius: 2px;
background: var(--line);
}
.step.done {
background: var(--ok);
}
.step.now {
background: var(--peer);
animation: pulse 1.4s ease-in-out infinite;
}
@keyframes pulse {
50% {
opacity: 0.45;
}
}
@media (prefers-reduced-motion: reduce) {
.step.now {
animation: none;
}
}
.bar {
height: 8px;
border-radius: 4px;
background: var(--panel-2);
overflow: hidden;
margin-top: 0.6rem;
}
.bar div {
height: 100%;
background: linear-gradient(90deg, var(--local), var(--peer));
transition: width 0.4s ease;
}
.meta {
font-size: 0.82rem;
margin-top: 0.35rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.why {
margin: 0.7rem 0 0;
font-size: 0.9rem;
}
.logtoggle {
margin-top: 0.7rem;
font-size: 0.8rem;
padding: 0.2rem 0.6rem;
background: transparent;
color: var(--muted);
}
.log {
margin: 0.5rem 0 0;
padding: 0.7rem;
background: var(--panel-2);
border-radius: 8px;
font-family: var(--mono);
font-size: 0.78rem;
max-height: 18rem;
overflow: auto;
white-space: pre-wrap;
}
</style>
+239
View File
@@ -0,0 +1,239 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, type Library, type LibraryItem, type Side } from './api';
interface Props {
localName: string;
peerName: string;
onmoved: () => void;
}
let { localName, peerName, onmoved }: Props = $props();
let side = $state<Side>('local');
let libraries = $state<Library[]>([]);
let libraryId = $state('');
let search = $state('');
let items = $state<LibraryItem[]>([]);
let loading = $state(false);
let error = $state<string | null>(null);
let busy = $state<string | null>(null); // item id being submitted
let notice = $state<string | null>(null);
const sourceName = $derived(side === 'local' ? localName : peerName);
const destName = $derived(side === 'local' ? peerName : localName);
async function loadLibraries(s: Side) {
error = null;
items = [];
libraries = [];
try {
libraries = await api.libraries(s);
libraryId = libraries[0]?.id ?? '';
} catch (e) {
error = (e as Error).message;
}
}
async function loadItems() {
if (!libraryId) return;
loading = true;
error = null;
try {
items = await api.items(side, libraryId, search.trim());
} catch (e) {
error = (e as Error).message;
items = [];
} finally {
loading = false;
}
}
function choose(s: Side) {
if (s === side) return;
side = s;
loadLibraries(s);
}
onMount(() => {
loadLibraries(side);
});
// Reload items when the library or search text changes, debounced.
$effect(() => {
void libraryId;
void search;
const timer = setTimeout(loadItems, 250);
return () => clearTimeout(timer);
});
async function move(item: LibraryItem, dryRun: boolean) {
busy = item.id;
notice = null;
error = null;
try {
await api.move(side, item, dryRun);
if (dryRun) {
notice = `Planning a dry run for “${item.name}”. Check Moves for the plan.`;
} else {
onmoved();
}
} catch (e) {
error = (e as Error).message;
} finally {
busy = null;
}
}
</script>
<section class="toolbar">
<div class="sides" role="radiogroup" aria-label="Browse which server">
<button role="radio" aria-checked={side === 'local'} class="local" class:on={side === 'local'} onclick={() => choose('local')}>
<span class="dot"></span>{localName}
</button>
<button role="radio" aria-checked={side === 'peer'} class="peer" class:on={side === 'peer'} onclick={() => choose('peer')}>
<span class="dot"></span>{peerName}
</button>
</div>
<select bind:value={libraryId} aria-label="Library" disabled={!libraries.length}>
{#each libraries as lib (lib.id)}
<option value={lib.id}>{lib.name}</option>
{/each}
</select>
<input type="search" placeholder="Search titles…" bind:value={search} aria-label="Search" />
</section>
<p class="direction muted">
Moving from <strong class={side}>{sourceName}</strong> to
<strong class={side === 'local' ? 'peer' : 'local'}>{destName}</strong>. The whole folder moves, including
subtitles, artwork, NFOs and extras, along with everyone's watch history.
</p>
{#if error}<p class="panel msg error">{error}</p>{/if}
{#if notice}<p class="panel msg">{notice}</p>{/if}
<ul class="panel list" aria-busy={loading}>
{#if loading && !items.length}
<li class="empty muted">Loading…</li>
{:else if !items.length}
<li class="empty muted">{libraryId ? 'Nothing here.' : 'No movie or TV libraries found.'}</li>
{/if}
{#each items as item (item.id)}
<li>
<span class="kind" title={item.kind}>{item.kind === 'Series' ? 'TV' : 'Film'}</span>
<div class="title">
<span class="name">{item.name}</span>
{#if item.year}<span class="muted">{item.year}</span>{/if}
{#if item.path}<div class="path mono muted" title={item.path}>{item.path}</div>{/if}
</div>
<div class="actions">
<button disabled={busy === item.id} onclick={() => move(item, true)} title="Check and plan without copying anything">
Dry run
</button>
<button class="primary" disabled={busy === item.id} onclick={() => move(item, false)}>
Move to {destName} →
</button>
</div>
</li>
{/each}
</ul>
<style>
.toolbar {
display: flex;
gap: 0.6rem;
flex-wrap: wrap;
align-items: center;
}
.toolbar input {
flex: 1;
min-width: 12rem;
}
.sides {
display: inline-flex;
border: 1px solid var(--line);
border-radius: 8px;
overflow: hidden;
}
.sides button {
border: none;
border-radius: 0;
background: transparent;
display: inline-flex;
align-items: center;
gap: 0.4rem;
color: var(--muted);
}
.sides button.on {
background: var(--panel-2);
color: var(--text);
}
.sides .local .dot {
background: var(--local);
}
.sides .peer .dot {
background: var(--peer);
}
strong.local {
color: var(--local);
}
strong.peer {
color: var(--peer);
}
.direction {
margin: 0.9rem 0;
font-size: 0.9rem;
}
.msg {
padding: 0.7rem 1rem;
}
.list {
list-style: none;
margin: 0;
padding: 0;
}
.list li {
display: flex;
align-items: center;
gap: 0.9rem;
padding: 0.7rem 1rem;
border-top: 1px solid var(--line);
}
.list li:first-child {
border-top: none;
}
.empty {
justify-content: center;
padding: 2rem !important;
}
.kind {
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--muted);
border: 1px solid var(--line);
border-radius: 5px;
padding: 0.1rem 0.35rem;
min-width: 2.6rem;
text-align: center;
}
.title {
flex: 1;
min-width: 0;
}
.name {
font-weight: 600;
margin-right: 0.4rem;
}
.path {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-top: 0.1rem;
}
.actions {
display: flex;
gap: 0.4rem;
flex-shrink: 0;
}
</style>
+169
View File
@@ -0,0 +1,169 @@
<script lang="ts">
import type { Status } from './api';
interface Props {
status: Status | null;
reload: () => Promise<void>;
}
let { status, reload }: Props = $props();
let checking = $state(false);
async function recheck() {
checking = true;
await reload();
checking = false;
}
</script>
{#if !status}
<p class="panel box muted">Loading…</p>
{:else}
<div class="grid">
<section class="panel box">
<h2>This agent</h2>
<dl>
<dt>Node</dt>
<dd>{status.node.node_name} <span class="muted">v{status.node.version}</span></dd>
<dt>Jellyfin</dt>
<dd>
{#if status.jellyfin_error}
<span class="error">{status.jellyfin_error}</span>
{:else}
<span class="dot ok"></span> {status.node.jellyfin_server}
<span class="muted">{status.node.jellyfin_version}</span>
{/if}
</dd>
</dl>
</section>
<section class="panel box">
<h2>Peer</h2>
<dl>
<dt>URL</dt>
<dd class="mono">{status.peer_url ?? 'not configured'}</dd>
<dt>Connection</dt>
<dd>
{#if status.peer_error}
<span class="error">{status.peer_error}</span>
{:else if status.peer}
<span class="dot ok"></span> {status.peer.node_name}
<span class="muted">v{status.peer.version} · Jellyfin {status.peer.jellyfin_version ?? '?'}</span>
{:else}
<span class="muted">No peer configured</span>
{/if}
</dd>
</dl>
</section>
</div>
<section class="panel box">
<div class="head">
<h2>Library folders</h2>
<button onclick={recheck} disabled={checking}>{checking ? 'Checking…' : 'Check again'}</button>
</div>
<p class="muted small">
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 <code>path_map</code>.
</p>
<table>
<thead><tr><th>Library</th><th>Jellyfin path</th><th>Seen here as</th><th>Status</th></tr></thead>
<tbody>
{#each status.locations as loc (loc.library + loc.jellyfin_path)}
<tr>
<td>{loc.library}</td>
<td class="mono">{loc.jellyfin_path}</td>
<td class="mono">{loc.local_path}</td>
<td>
{#if !loc.exists}<span class="error">not found</span>
{:else if !loc.writable}<span class="error">read-only</span>
{:else}<span class="okt">OK</span>{/if}
</td>
</tr>
{:else}
<tr><td colspan="4" class="muted">No libraries reported.</td></tr>
{/each}
</tbody>
</table>
</section>
<details class="panel box">
<summary>Effective configuration (secrets hidden)</summary>
<pre>{JSON.stringify(status.config, null, 2)}</pre>
</details>
{/if}
<style>
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 0.8rem;
margin-bottom: 0.8rem;
}
.box {
padding: 1rem 1.2rem;
margin-bottom: 0.8rem;
}
.grid .box {
margin-bottom: 0;
}
h2 {
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--muted);
margin: 0 0 0.7rem;
}
.head {
display: flex;
justify-content: space-between;
align-items: center;
}
.small {
font-size: 0.88rem;
}
dl {
display: grid;
grid-template-columns: 7rem 1fr;
gap: 0.4rem;
margin: 0;
}
dt {
color: var(--muted);
}
dd {
margin: 0;
overflow-wrap: anywhere;
}
.dot.ok {
background: var(--ok);
}
.okt {
color: var(--ok);
font-weight: 600;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
th {
text-align: left;
color: var(--muted);
font-weight: 500;
border-bottom: 1px solid var(--line);
padding: 0.4rem 0.5rem;
}
td {
padding: 0.45rem 0.5rem;
border-bottom: 1px solid var(--line);
}
summary {
cursor: pointer;
color: var(--muted);
}
pre {
font-family: var(--mono);
font-size: 0.8rem;
overflow: auto;
}
</style>
+145
View File
@@ -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<T>(method: string, path: string, body?: unknown): Promise<T> {
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<T>;
}
export const api = {
status: () => call<Status>('GET', '/status'),
libraries: (node: Side) => call<Library[]>('GET', `/libraries?node=${node}`),
items: (node: Side, library: string, search: string) =>
call<LibraryItem[]>(
'GET',
`/items?${new URLSearchParams({ node, library, ...(search ? { search } : {}) })}`,
),
move: (from: Side, item: LibraryItem, dry_run: boolean) =>
call<Job>('POST', '/moves', { from, item_id: item.id, name: item.name, dry_run }),
jobs: () => call<JobsView>('GET', '/jobs'),
retry: (id: string) => call<Job>('POST', `/jobs/${id}/retry`),
};
export const STAGE_LABEL: Record<Stage, string> = {
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]}`;
}
+5
View File
@@ -0,0 +1,5 @@
import { mount } from 'svelte';
import './app.css';
import App from './App.svelte';
export default mount(App, { target: document.getElementById('app')! });
+2
View File
@@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />
+2
View File
@@ -0,0 +1,2 @@
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default { preprocess: vitePreprocess() };
+14
View File
@@ -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"]
}
+11
View File
@@ -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 },
});