Compare commits

9 Commits
Author SHA1 Message Date
IxianPixel d351875daa Merge pull request 'Release/0.2.0' (#6) from release/0.2.0 into master
CI / test (push) Successful in 1m26s
Release / release (push) Successful in 5m32s
Reviewed-on: #6
2026-11-09 10:15:21 +01:00
IxianPixel 235c2bf63f Bump version to 0.2.0
CI / test (push) Skipped
CI / test (pull_request) Successful in 1m23s
2026-11-06 17:45:50 +00:00
IxianPixel 8cfa0f05eb Warn before watch history is left behind, and re-apply it later (#2)
CI / test (push) Successful in 1m16s
2026-11-06 17:34:22 +00:00
IxianPixel 2bd4489b1a Update library lists when a move finishes (#1)
CI / test (push) Successful in 1m14s
The Library now follows moves on both servers: an item shows "Moving to …" while it moves and "Moved to …" until the source's Jellyfin drops
it after its rescan; the list reloads when a move finishes and checks again every 20 s for a few minutes. The destination shows the new item
straight away.
2026-11-06 17:21:22 +00:00
IxianPixel 484ac50508 Move a single season of a TV show (#4)
CI / test (push) Successful in 1m14s
Shows can be expanded to list their seasons, each with its size and its own Dry run / Move buttons. A season joins the same show on the other
server, so finished seasons can go to the big server while the current one stays on the fast one.

- Source exports a season from the show folder, with a manifest of just that season's folder plus the show's loose non-video files. Refuses
  seasons with no folder of their own, or whose folder holds otherseasons' episodes.
- Destination finds the show by provider ID, then name. If it already has the show, the show's own files are skipped (Job.skip_files) and
  never overwritten; otherwise they come with the season. Refuses if the season folder already exists.
- Only episode watch state is carried for a season.
- Source trashes just the season folder; after the last season, the leftover show folder joins it in the same trash entry if no videos
  remain. The chosen trash entry is saved so a re-run after a crash finishes in the same place.
- New GET /seasons (UI and peer). Fake Jellyfin gains season items.
- e2e tests: season into a new show, into an existing show, last season leaving, destination already has the season, misfiled episodes.
2026-11-06 17:02:40 +00:00
IxianPixel 25a743b350 Show folder sizes for movies, shows and seasons. Closes #5
CI / test (push) Successful in 1m12s
The library lists now show how much space each movie and show takes on disk, counting everything a move copies, with a per-season breakdown for shows, a running total and a "Largest first" sort.

- sizes.rs: a single background worker measures one folder at a time. Listing returns cached sizes straight away and queues folders; the UI
  polls until every size has arrived.
- Cached in a new folder_sizes table (store migration v2). A size is kept while the folder's signature (mtimes of the folder and its direct
  subfolders) is unchanged, checked at most hourly and re-measured after 7 days.
- Each agent measures its own folders, so peer listings carry the peer's sizes.
- Tests for measuring, signatures, natural season order, the migration, and an e2e test covering both sides and a moved item.
2026-11-06 16:43:52 +00:00
IxianPixel 4c6217bd40 Add a Trash view to see and empty .jellymove-trash (#3)
CI / test (push) Successful in 1m18s
Moved folders sat in each library's .jellymove-trash until removed by hand on the server. The new Trash tab lists them on either server with
size, file count, when and where they went, and empties one item, a library or everything after a confirmation.
- trash.rs: list and empty entries. Entries are referred to by an opaque ID and resolved by scanning; only real folders directly inside a trash folder can be deleted.
- Each move now gets its own trash entry folder, with a small metadata file. Fixes moves failing when the same item had been trashed before.
- Peer API: GET /trash, POST /trash/empty, and /exports/{id}/complete now records the job and destination.
- e2e tests for listing, emptying from either side, refusing paths as IDs, and moving the same item away twice.

Closes #3
2026-11-06 16:30:54 +00:00
IxianPixel 38319e0987 Updated workflow for Gitflow
CI / test (push) Successful in 54s
2026-11-06 15:32:39 +00:00
IxianPixel 35a26a285d Updated docker-compose to use environmental variables instead
CI / test (push) Successful in 56s
2026-11-06 15:25:41 +00:00
41 changed files with 3379 additions and 208 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "demo",
"runtimeExecutable": "cargo",
"runtimeArgs": ["run", "-p", "jm-server", "--example", "demo"],
"port": 8097
}
]
}
+4 -3
View File
@@ -1,9 +1,10 @@
name: CI
# Branch pushes only: a version tag points at a commit CI has already checked
# on its branch, and release.yml runs the tests again for tags.
# Gitflow: pushes to master and develop run here. Feature, release and hotfix
# branches are checked through their pull request, so they don't run twice.
# Tags aren't matched: release.yml runs the tests again for them.
on:
push:
branches: ["**"]
branches: [master, develop]
pull_request:
jobs:
test:
+16 -4
View File
@@ -51,6 +51,19 @@ jobs:
node .github/scripts/changelog.mjs "$GITHUB_REF_NAME" > dist/release-notes.md
cat dist/release-notes.md
# Gitea doesn't let the workflow's own token push packages, so the image
# needs a personal access token. Checked here so a missing secret fails
# before the long build, not after the release is published.
- name: Check the registry secrets are set
env:
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
if [ -z "$REGISTRY_USER" ] || [ -z "$REGISTRY_TOKEN" ]; then
echo "::error::Set the REGISTRY_USER (your Gitea username) and REGISTRY_TOKEN (a token with package read and write) secrets under the repo's Settings → Actions → Secrets, then re-run."
exit 1
fi
- name: Build the UI
run: |
npm --prefix ui ci
@@ -103,12 +116,11 @@ jobs:
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
# Pushes <gitea host>/<owner>/jellymove:<version>, plus :latest unless the
# tag is a pre-release. The workflow's own token is tried first; if Gitea
# refuses it, add REGISTRY_USER and REGISTRY_TOKEN (write:package) secrets.
# tag is a pre-release.
- name: Publish the Docker image
env:
REGISTRY_USER: ${{ secrets.REGISTRY_USER || github.actor }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN || secrets.GITHUB_TOKEN }}
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
registry="${GITHUB_SERVER_URL#*://}"
registry="${registry%%/*}"
+50
View File
@@ -1,5 +1,55 @@
# Changelog
## v0.2.0
### Added
- **Trash view.** A new Trash tab lists what's waiting in `.jellymove-trash/`
on either server: the item, its size and file count, when it was moved and
where to. Empty one item, a whole library or everything, with a confirmation.
Entries are deleted by ID only, never by path. (#3)
- **Folder sizes in the library.** Every movie and show now shows how much
space it takes, counting everything a move copies, with a per-season
breakdown for shows and a "Largest first" sort. Sizes are measured in the
background and cached, so big libraries open straight away. (#5)
- **Move a single season.** Shows list their seasons with sizes and a move
button each. A season joins the same show on the other server (matched by
TVDB/TMDB/IMDb ID, then name), bringing the show's NFO and artwork only if
that server doesn't have the show. Moving the last season also trashes the
leftover show folder on the source. (#4)
- **Warning before watch history is left behind.** Moving something asks
first if anyone with watch history for it has no account on the other
server. Dry runs and the move itself say so too. (#2)
- **Re-apply watch history.** A finished move remembers whose history it
couldn't apply. Once their account exists, one button in Moves applies it,
without touching anyone else's. (#2)
### Updated
- **Update both agents together.** The agents use new routes to talk to each
other (seasons, trash, watch-history checks), so a v0.1.x agent can't drive
these features. Each agent's database upgrades itself on first start.
- **Starting a move keeps you in the Library.** The item shows "Moving to …"
while it moves, rather than the app switching to the Moves tab.
- **The Docker Compose example uses environment variables only.** No
`jellymove.toml` is needed: every setting can be a `JELLYMOVE_*` variable.
- **Releases need registry secrets.** The release workflow pushes the Docker
image with `REGISTRY_USER` and `REGISTRY_TOKEN`, and stops straight away if
either is missing.
### Fixed
- **Moving an item away a second time failed** if its first trip was still in
the trash. Each move now gets its own trash entry.
- **Library lists didn't update after a move.** They now reload when a move
finishes: the item appears on the destination straight away, and is marked
"Moved to …" on the source until that server's Jellyfin drops it after its
next scan. Sizes of folders a move touched are measured again at once. (#1)
- **Switching servers in the Library could show an empty list** when both
libraries had the same ID.
- **Errors passed on from the other server** now show its message rather than
raw JSON and an HTTP status.
## v0.1.1
### Added
+8 -3
View File
@@ -36,7 +36,7 @@ enough while developing.
| `jm-core` | Pure domain: `Job`/`Stage`/`JobStatus`, `ExportInfo`/`Manifest`, `PathMap`, folder safety rules, user-data types. No I/O. |
| `jm-transfer` | Manifest building + BLAKE3, `range_response` (serve), `Puller` (resume/retry/throttle/verify), `promote` (atomic rename). |
| `jm-jellyfin` | Thin typed client for the ~10 Jellyfin endpoints used. |
| `jm-store` | SQLite (rusqlite, WAL). Jobs and exports as JSON blobs. Migrations are the `MIGRATIONS` array; append only. |
| `jm-store` | SQLite (rusqlite, WAL). Jobs, exports and cached folder sizes as JSON blobs. Migrations are the `MIGRATIONS` array; append only. |
| `jm-server` | axum app: `/api/*` (UI), `/peer/v1/*` (agent↔agent), `export.rs` (source side), `runner.rs` (destination side), embedded UI. |
| `jellymove` | Binary: clap + figment config loading, tracing setup. |
| `ui/` | Svelte 5 (runes) + Vite + TS SPA. No SvelteKit. |
@@ -45,7 +45,10 @@ enough while developing.
- **Nothing is deleted from the source until the destination has indexed every
file** (`Stage::TargetScanned`) and user data is applied. Source "deletion" is
a rename into `<library>/.jellymove-trash/`, never `remove_dir_all`.
a rename into `<library>/.jellymove-trash/<entry>/`, never `remove_dir_all`.
The only code that deletes is `trash::empty`, which resolves opaque entry
IDs by scanning the trash folders and only removes real folders directly
inside them.
- **Every runner step is idempotent.** `Job.stage` is the last *completed*
milestone; the runner re-executes from there after a crash. If you add a
stage, make re-running it safe.
@@ -53,7 +56,9 @@ enough while developing.
never by path. Relative paths from a peer always go through
`jm_core::paths::join_relative`, which rejects `..`, absolute paths and `\`.
- **Never overwrite** at the destination: `plan` refuses if the target folder
exists; `promote` refuses on any clash before renaming anything.
exists (for a season, the season's folder inside the show); `promote`
refuses on any clash before renaming anything. A season going into a show
the destination already has skips the show's own files (`Job.skip_files`).
- Partial/trash folders start with `.jellymove-` (Jellyfin skips dot-folders)
and get a `.ignore` file.
- Two path namespaces: what Jellyfin reports vs. what the agent sees.
Generated
+6 -6
View File
@@ -1010,7 +1010,7 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jellymove"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"anyhow",
"clap",
@@ -1026,7 +1026,7 @@ dependencies = [
[[package]]
name = "jm-core"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"serde",
"serde_json",
@@ -1037,7 +1037,7 @@ dependencies = [
[[package]]
name = "jm-jellyfin"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"axum",
"jm-core",
@@ -1051,7 +1051,7 @@ dependencies = [
[[package]]
name = "jm-server"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"anyhow",
"axum",
@@ -1080,7 +1080,7 @@ dependencies = [
[[package]]
name = "jm-store"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"jm-core",
"rusqlite",
@@ -1093,7 +1093,7 @@ dependencies = [
[[package]]
name = "jm-transfer"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"axum",
"blake3",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.1.1"
version = "0.2.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.85"
+47 -11
View File
@@ -31,12 +31,33 @@ One agent runs next to each Jellyfin and sees the same media folders. The
4. **Index.** The destination asks Jellyfin to scan that folder, then waits
until the item and every episode appear.
5. **Restore watch history.** Jellyfin gives moved files new item IDs, so
jellymove re-applies each user's data to the new items, matching users by name.
jellymove re-applies each user's data to the new items, matching users by
name. Before a move starts, jellymove warns if someone with watch history
has no account on the other server. If you move anyway, their history is
kept with the move: create the user there, then use **Re-apply watch
history** on the move in Moves. Only their history is applied, so anything
others have watched since is left alone.
6. **Clean up.** The source moves its folder to `.jellymove-trash/` in the same
library and rescans. It is not deleted.
library and rescans. It is not deleted: the **Trash** tab shows what's
waiting on each server, how much space it uses, and empties it when you're
ready.
A crash or restart at any point resumes from the last completed step.
### Moving a single season
In TV Shows, **Show seasons** lists a show's seasons with their sizes, each
with its own move button. A season moves into the same show on the other
server, found by its TVDB/TMDB/IMDb ID or its name, and its episodes keep
their watch history. If the other server doesn't have the show yet, the show's
own files (`tvshow.nfo`, posters) are copied with the season; if it does, they
are left alone. When the last season leaves a server, what's left of the show
folder goes to the trash with it.
A season can only move on its own if it has its own folder (`Show/Season 02/`)
holding just that season's episodes. Specials (`Season 00` or `Specials`) work
the same way.
## Quick look (no Jellyfin needed)
```sh
@@ -50,11 +71,22 @@ cargo run -p jm-server --example demo
Install one agent per server. **Mount media at the same paths as the Jellyfin
container**, so the paths Jellyfin reports are the paths jellymove sees.
With Docker, copy [deploy/docker-compose.yml](deploy/docker-compose.yml),
fill in the `environment:` section, fix the volumes and `user:`, then:
```sh
cp config.example.toml jellymove.toml # edit: node_name, jellyfin.api_key, peer.url, peer.token
docker compose -f deploy/docker-compose.yml up -d
mkdir jellymove-data && sudo chown 1000:1000 jellymove-data # same IDs as user:
docker compose run --rm jellymove check-config # prints the settings, secrets hidden
docker compose up -d
```
Every setting in [config.example.toml](config.example.toml) can be set as
`JELLYMOVE_<KEY>`, with `__` between a section and its key
(`[peer] token` → `JELLYMOVE_PEER__TOKEN`). There's no config file in this
setup, so the "config file not found; using environment only" warning at
start-up is expected. If you'd rather use a file, mount it at
`/config/jellymove.toml`. Environment variables still override it.
Each release publishes an image (x86_64) to the Gitea container registry:
`git.malgra.com/ixianpixel/jellymove:<version>`, and `:latest` for anything
that isn't a pre-release. It's the same static binary as the systemd tarball,
@@ -77,7 +109,8 @@ To upgrade, run `docker compose pull && docker compose up -d`.
the roadmap.
- Run the container as the same user as Jellyfin (`user: "1000:1000"`) so
moved files keep the right ownership.
- Set a UI password (`[ui]`) unless the port is only reachable privately.
- Set a UI password (`[ui]`, or `JELLYMOVE_UI__USERNAME`/`__PASSWORD`)
unless the port is only reachable privately.
- The **Status** tab checks that every library folder is visible and writable.
### Without Docker (systemd)
@@ -117,8 +150,10 @@ git tag v0.1.1 && git push origin v0.1.1
The workflow runs the tests, builds the UI and binary, attaches the tarball
and its `.sha256` to a Gitea release for that tag, then pushes the Docker
image. It builds the image with `crane`, so the runner needs no Docker
socket. It pushes with the workflow's own token; if Gitea refuses that, add
`REGISTRY_USER` and `REGISTRY_TOKEN` (`write:package`) secrets. The release notes
socket. Gitea won't let the workflow's own token push packages, so the repo
needs two Actions secrets: `REGISTRY_USER` (your Gitea username) and
`REGISTRY_TOKEN` (a personal access token with only package read and write).
The workflow stops straight away if either is missing. The release notes
are that version's section of `CHANGELOG.md`; the workflow stops straight
away if there isn't one. Re-running it replaces the files and refreshes the
notes. Tags with a `-` (`v0.2.0-rc1`) are marked pre-release.
@@ -154,9 +189,10 @@ host. Prefer a socket proxy that only allows restarts, or restart by hand.
## Safety rules
- Nothing leaves the source until the destination has indexed every file.
- The source copy goes to `.jellymove-trash/`. Empty it yourself once you're
- The source copy goes to `.jellymove-trash/`. Empty it from the **Trash** tab once you're
happy (automatic retention is on the roadmap).
- Nothing at the destination is ever overwritten.
- Nothing at the destination is ever overwritten. A season move refuses if
that season's folder already exists there.
- A movie must be in **its own folder**. jellymove refuses flat folders like
`Movies/Heat.mkv` + `Movies/Ronin.mkv`, because moving "the folder" would take both.
- Peers can only fetch files the source has explicitly exported, by index.
@@ -173,8 +209,8 @@ host. Prefer a socket proxy that only allows restarts, or restart by hand.
## Roadmap
- Season-level moves; "promote" (pre-warm) shortcuts
- Trash retention and a trash view in the UI
- "Promote" (pre-warm) shortcuts
- Automatic trash retention (e.g. empty after N days)
- Pairing codes and pinned TLS instead of a shared token
- Outbound-only control channel so a NATed home agent needs no inbound port
- Automatic tiering rules ("demote anything unwatched for 90 days when the cloud disk is over 80%")
+2 -2
View File
@@ -9,8 +9,8 @@ rust-version.workspace = true
anyhow = "1.0.104"
clap = { version = "4.6.7", features = ["derive", "env"] }
figment = { version = "0.10.19", features = ["toml", "env"] }
jm-core = { version = "0.1.0", path = "../jm-core" }
jm-server = { version = "0.1.0", path = "../jm-server" }
jm-core = { path = "../jm-core" }
jm-server = { path = "../jm-server" }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
tokio = { version = "1.54.1", features = ["full"] }
+49 -2
View File
@@ -38,6 +38,16 @@ impl std::str::FromStr for JobId {
pub enum ItemKind {
Movie,
Series,
/// One season of a series, moved on its own into the show's folder.
Season,
}
impl ItemKind {
/// Whether the item has episodes whose watch state is mapped by
/// (season, episode).
pub fn has_episodes(self) -> bool {
matches!(self, ItemKind::Series | ItemKind::Season)
}
}
/// The last milestone a job has *completed*. The runner looks at the stage,
@@ -129,10 +139,31 @@ pub struct ExportInfo {
pub rel_folder: String,
pub manifest: Manifest,
pub user_data: Vec<UserDataRecord>,
/// Every episode the source knows about (series only). The destination
/// waits until its scan has found all of them before anything is deleted.
/// Every episode the source knows about (series and seasons). The
/// destination waits until its scan has found all of them before anything
/// is deleted.
#[serde(default)]
pub episode_keys: Vec<ItemKey>,
/// Set for a season move. `rel_folder` and the manifest are then the
/// show's folder, holding only this season's folder and the show's own
/// loose files.
#[serde(default)]
pub season: Option<SeasonInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeasonInfo {
pub number: i32,
/// The season's folder inside the show folder, e.g. `Season 02`.
pub folder: String,
pub show_name: String,
/// The show's provider IDs (Tvdb, Tmdb, Imdb...), for finding the same
/// show on the destination.
#[serde(default)]
pub show_provider_ids: std::collections::HashMap<String, String>,
/// Manifest indexes of the show's own files (tvshow.nfo, artwork). Only
/// copied when the destination doesn't have the show yet.
pub show_files: Vec<usize>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -167,6 +198,19 @@ pub struct Job {
pub target_folder_jellyfin: Option<String>,
/// Item ID Jellyfin assigned on the destination after the scan.
pub target_item_id: Option<String>,
/// Destination library location (Jellyfin namespace) holding the target
/// folder. Missing on jobs from before v0.2.0.
#[serde(default)]
pub target_location: Option<String>,
/// Manifest indexes not to copy, e.g. a show's files when a season goes
/// into a show the destination already has.
#[serde(default)]
pub skip_files: Vec<usize>,
/// Users with watch state on the source who have no account here, so
/// their watch state wasn't (or won't be) applied. Their records stay in
/// `export.user_data` and can be re-applied once the account exists.
#[serde(default)]
pub missing_users: Vec<String>,
pub progress: Progress,
/// Human-readable log of what happened, newest last.
pub log: Vec<String>,
@@ -197,6 +241,9 @@ impl Job {
target_library: None,
target_folder_jellyfin: None,
target_item_id: None,
target_location: None,
skip_files: Vec::new(),
missing_users: Vec::new(),
progress: Progress::default(),
log: Vec::new(),
}
+29
View File
@@ -51,10 +51,39 @@ pub fn same_user(a: &str, b: &str) -> bool {
a.trim().eq_ignore_ascii_case(b.trim())
}
/// Users with watch state in `records` who have no account among `users`,
/// each named once, in the order they first appear.
pub fn missing_users<'a>(
records: &'a [UserDataRecord],
users: impl IntoIterator<Item = &'a str> + Clone,
) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for r in records {
let known = users.clone().into_iter().any(|u| same_user(u, &r.user_name));
if !known && !out.iter().any(|m| same_user(m, &r.user_name)) {
out.push(r.user_name.clone());
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_users_with_no_account() {
let rec = |name: &str| UserDataRecord {
user_name: name.into(),
key: ItemKey::Root,
data: UserData::default(),
};
let records = [rec("Alice"), rec("Bob"), rec("bob "), rec("Carol")];
let here = ["alice", "Carol"];
assert_eq!(missing_users(&records, here.iter().copied()), ["Bob"]);
assert!(missing_users(&records[..1], here.iter().copied()).is_empty());
}
#[test]
fn empty_detection() {
assert!(UserData::default().is_empty());
+1 -1
View File
@@ -6,7 +6,7 @@ license.workspace = true
rust-version.workspace = true
[dependencies]
jm-core = { version = "0.1.0", path = "../jm-core" }
jm-core = { path = "../jm-core" }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "query", "http2"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
+4 -1
View File
@@ -103,9 +103,12 @@ pub struct Item {
/// Season number for episodes.
#[serde(default)]
pub parent_index_number: Option<i32>,
/// Episode number for episodes.
/// Episode number for episodes; season number for seasons.
#[serde(default)]
pub index_number: Option<i32>,
/// The series a season or episode belongs to.
#[serde(default)]
pub series_id: Option<String>,
#[serde(default)]
pub user_data: Option<ItemUserData>,
}
+5 -5
View File
@@ -9,11 +9,12 @@ rust-version.workspace = true
anyhow = "1.0.104"
axum = { version = "0.8.9", features = ["macros"] }
base64 = "0.23.1"
blake3 = "1.8.7"
futures = "0.3.34"
jm-core = { version = "0.1.0", path = "../jm-core" }
jm-jellyfin = { version = "0.1.0", path = "../jm-jellyfin" }
jm-store = { version = "0.1.0", path = "../jm-store" }
jm-transfer = { version = "0.1.0", path = "../jm-transfer" }
jm-core = { path = "../jm-core" }
jm-jellyfin = { path = "../jm-jellyfin" }
jm-store = { path = "../jm-store" }
jm-transfer = { path = "../jm-transfer" }
mime_guess = "2.0.5"
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "stream", "http2"] }
rust-embed = "8.13.0"
@@ -29,7 +30,6 @@ uuid = { version = "1.26.1", features = ["v4"] }
[dev-dependencies]
anyhow = "1.0.104"
blake3 = "1.8.7"
reqwest = { version = "0.13.5", default-features = false, features = ["json"] }
serde_json = "1.0.154"
tempfile = "3.27.0"
+21 -6
View File
@@ -44,9 +44,14 @@ fn libs(root: &Path) -> Vec<Lib> {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber_init();
let tmp = tempfile::tempdir()?;
let cloud = tmp.path().join("cloud");
let home = tmp.path().join("home");
// One fixed folder, emptied on each start: a temp folder per run would
// be left behind (hundreds of MB) whenever the demo is killed.
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/demo");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root)?;
let root = root.canonicalize()?;
let cloud = root.join("cloud");
let home = root.join("home");
for r in [&cloud, &home] {
std::fs::create_dir_all(r.join("movies"))?;
std::fs::create_dir_all(r.join("tv"))?;
@@ -63,12 +68,18 @@ async fn main() -> anyhow::Result<()> {
write(&base.join(format!("{folder}.en.srt")), 40_000);
write(&base.join("poster.jpg"), 200_000);
}
for ep in 1..=6 {
for (season, eps) in [(1, 6), (2, 4)] {
for ep in 1..=eps {
write(
&cloud.join(format!("tv/Severance/Season 01/Severance S01E{ep:02}.mkv")),
&cloud.join(format!(
"tv/Severance/Season {season:02}/Severance S{season:02}E{ep:02}.mkv"
)),
20 * MB,
);
}
}
write(&cloud.join("tv/Severance/tvshow.nfo"), 2_000);
write(&cloud.join("tv/Severance/poster.jpg"), 300_000);
write(
&home.join("movies/The Thing (1982)/The Thing (1982).mkv"),
40 * MB,
@@ -76,7 +87,11 @@ async fn main() -> anyhow::Result<()> {
let fake_cloud = Fake::new(libs(&cloud));
let fake_home = Fake::new(libs(&home));
// Bob only has an account on cloud, so his watch history can't follow a
// move to home until one is created there.
fake_cloud.add_user("u2", "Bob");
if let Some(id) = fake_cloud.find("Movie", "Arrival") {
fake_cloud.set_user_data_for("u2", &id, serde_json::json!({"PlaybackPositionTicks": 36_000_000_000i64}));
fake_cloud.set_user_data(&id, serde_json::json!({"Played": true, "PlayCount": 1}));
}
let jf_cloud = fake_cloud.serve().await;
@@ -118,7 +133,7 @@ async fn main() -> anyhow::Result<()> {
axum::serve(listener, jm_server::api::router(state)).await
}));
}
println!("demo media in {}", tmp.path().display());
println!("demo media in {}", root.display());
println!("cloud: http://127.0.0.1:8097 home: http://127.0.0.1:8098 (Ctrl+C to stop)");
tokio::signal::ctrl_c().await?;
Ok(())
+195 -3
View File
@@ -19,11 +19,12 @@ use serde_json::json;
use tokio_stream::StreamExt;
use tokio_stream::wrappers::BroadcastStream;
use crate::export::{self, Export, ExportStatus};
use crate::library::{self, Library, LibraryItem, LocationCheck};
use crate::export::{self, CompleteRequest, Export, ExportStatus};
use crate::library::{self, Library, LibraryItem, LocationCheck, SeasonItem};
use crate::peer::{CreateJob, NodeInfo};
use crate::runner;
use crate::state::Shared;
use crate::trash::{self, EmptyResult, TrashEntry};
pub struct ApiError(StatusCode, String);
@@ -58,20 +59,31 @@ pub fn router(state: Shared) -> Router {
.route("/status", get(status))
.route("/libraries", get(ui_libraries))
.route("/items", get(ui_items))
.route("/seasons", get(ui_seasons))
.route("/moves", post(ui_move))
.route("/moves/check", get(ui_check_move))
.route("/jobs", get(ui_jobs))
.route("/jobs/{id}/retry", post(ui_retry))
.route("/jobs/{id}/reapply", post(ui_reapply))
.route("/trash", get(ui_trash))
.route("/trash/empty", post(ui_empty_trash))
.route("/events", get(events));
let peer_api = Router::new()
.route("/info", get(peer_info))
.route("/libraries", get(peer_libraries))
.route("/items", get(peer_items))
.route("/seasons", get(peer_seasons))
.route("/exports", post(peer_create_export))
.route("/exports/{id}", get(peer_get_export))
.route("/exports/{id}/files/{idx}", get(peer_file))
.route("/exports/{id}/complete", post(peer_complete_export))
.route("/jobs", get(peer_jobs).post(peer_create_job))
.route("/jobs/{id}/reapply", post(peer_reapply))
.route("/users", get(peer_users))
.route("/watchers", get(peer_watchers))
.route("/trash", get(peer_trash))
.route("/trash/empty", post(peer_empty_trash))
.layer(middleware::from_fn_with_state(
state.clone(),
require_peer_token,
@@ -248,6 +260,23 @@ async fn ui_items(
}))
}
#[derive(Deserialize)]
struct SeasonsQuery {
#[serde(default)]
node: Side,
series: String,
}
async fn ui_seasons(
State(state): State<Shared>,
Query(q): Query<SeasonsQuery>,
) -> ApiResult<Vec<SeasonItem>> {
Ok(Json(match q.node {
Side::Local => library::seasons(&state, &q.series).await?,
Side::Peer => state.peer()?.seasons(&q.series).await?,
}))
}
#[derive(Deserialize)]
struct MoveRequest {
/// Where the item is now.
@@ -313,6 +342,72 @@ async fn ui_jobs(State(state): State<Shared>) -> ApiResult<JobsView> {
}))
}
#[derive(Deserialize)]
struct CheckMoveQuery {
/// Where the item is now.
from: Side,
item_id: String,
}
#[derive(Serialize)]
struct MoveCheck {
/// Users with watch state for the item on the source.
watchers: Vec<String>,
/// Those of them with no account on the destination, whose watch state
/// won't carry over.
missing_users: Vec<String>,
}
/// Before a move: whose watch history wouldn't carry over, because the
/// destination has no user with that name.
async fn ui_check_move(
State(state): State<Shared>,
Query(q): Query<CheckMoveQuery>,
) -> ApiResult<MoveCheck> {
let peer = state.peer()?;
let (watchers, dest_users) = match q.from {
Side::Local => (
export::watchers(&state, &q.item_id).await?,
peer.users().await?,
),
Side::Peer => (
peer.watchers(&q.item_id).await?,
state
.jellyfin
.users()
.await?
.into_iter()
.map(|u| u.name)
.collect(),
),
};
let missing_users = watchers
.iter()
.filter(|w| !dest_users.iter().any(|u| jm_core::userdata::same_user(u, w)))
.cloned()
.collect();
Ok(Json(MoveCheck {
watchers,
missing_users,
}))
}
/// Re-apply skipped watch history on a finished move. The job lives on the
/// destination, which may be the peer.
async fn ui_reapply(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
let job_id: JobId = id
.parse()
.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?;
match state.store.get_job(job_id).await? {
Some(job) => {
let mut job = runner::reapply_user_data(&state, job).await?;
job.export = None;
Ok(Json(job))
}
None => Ok(Json(state.peer()?.reapply(&id).await?)),
}
}
async fn ui_retry(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
let id: JobId = id
.parse()
@@ -333,6 +428,35 @@ async fn ui_retry(State(state): State<Shared>, Path(id): Path<String>) -> ApiRes
Ok(Json(job))
}
async fn ui_trash(
State(state): State<Shared>,
Query(q): Query<NodeQuery>,
) -> ApiResult<Vec<TrashEntry>> {
Ok(Json(match q.node {
Side::Local => trash::list(&state).await?,
Side::Peer => state.peer()?.trash().await?,
}))
}
#[derive(Deserialize)]
struct EmptyTrashRequest {
#[serde(default)]
node: Side,
ids: Vec<String>,
}
/// Delete trash entries for good, by ID. Each node only ever deletes its own
/// files; for the peer's trash the request is passed on.
async fn ui_empty_trash(
State(state): State<Shared>,
Json(req): Json<EmptyTrashRequest>,
) -> ApiResult<EmptyResult> {
Ok(Json(match req.node {
Side::Local => trash::empty(&state, &req.ids).await?,
Side::Peer => state.peer()?.empty_trash(&req.ids).await?,
}))
}
async fn events(State(state): State<Shared>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = BroadcastStream::new(state.events.subscribe()).filter_map(|msg| {
msg.ok().and_then(|mut job| {
@@ -368,6 +492,18 @@ async fn peer_items(
))
}
#[derive(Deserialize)]
struct PeerSeasonsQuery {
series: String,
}
async fn peer_seasons(
State(state): State<Shared>,
Query(q): Query<PeerSeasonsQuery>,
) -> ApiResult<Vec<SeasonItem>> {
Ok(Json(library::seasons(&state, &q.series).await?))
}
#[derive(Deserialize)]
struct CreateExport {
item_id: String,
@@ -409,8 +545,26 @@ async fn peer_file(
async fn peer_complete_export(
State(state): State<Shared>,
Path(id): Path<String>,
body: Option<Json<CompleteRequest>>,
) -> ApiResult<Export> {
Ok(Json(export::complete(&state, &id).await?))
let req = body.map(|Json(r)| r).unwrap_or_default();
Ok(Json(export::complete(&state, &id, req).await?))
}
async fn peer_trash(State(state): State<Shared>) -> ApiResult<Vec<TrashEntry>> {
Ok(Json(trash::list(&state).await?))
}
#[derive(Deserialize)]
struct PeerEmptyTrash {
ids: Vec<String>,
}
async fn peer_empty_trash(
State(state): State<Shared>,
Json(req): Json<PeerEmptyTrash>,
) -> ApiResult<EmptyResult> {
Ok(Json(trash::empty(&state, &req.ids).await?))
}
async fn peer_create_job(
@@ -435,6 +589,44 @@ async fn peer_create_job(
Ok(Json(job))
}
async fn peer_reapply(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
let job_id: JobId = id
.parse()
.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?;
let job = state
.store
.get_job(job_id)
.await?
.ok_or(ApiError(StatusCode::NOT_FOUND, "no such job".into()))?;
let mut job = runner::reapply_user_data(&state, job).await?;
job.export = None;
Ok(Json(job))
}
async fn peer_users(State(state): State<Shared>) -> ApiResult<Vec<String>> {
Ok(Json(
state
.jellyfin
.users()
.await?
.into_iter()
.map(|u| u.name)
.collect(),
))
}
#[derive(Deserialize)]
struct WatchersQuery {
item: String,
}
async fn peer_watchers(
State(state): State<Shared>,
Query(q): Query<WatchersQuery>,
) -> ApiResult<Vec<String>> {
Ok(Json(export::watchers(&state, &q.item).await?))
}
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 {
+301 -33
View File
@@ -7,14 +7,15 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, bail};
use jm_core::ItemKind;
use jm_core::job::ExportInfo;
use jm_core::job::{ExportInfo, SeasonInfo};
use jm_core::paths::{join_relative, relative_inside};
use jm_core::safety::{check_inside_library, check_movie_folder};
use jm_core::safety::{FolderProblem, check_inside_library, check_movie_folder, is_video};
use jm_core::userdata::{ItemKey, UserDataRecord};
use jm_jellyfin::ItemQuery;
use serde::{Deserialize, Serialize};
use crate::state::{AppState, Shared};
use crate::trash;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "detail")]
@@ -39,6 +40,10 @@ pub struct Export {
/// Library location (Jellyfin namespace) containing the folder.
#[serde(default)]
pub jellyfin_location: String,
/// Trash entry folder chosen when completing, kept so a re-run after a
/// crash finishes in the same entry.
#[serde(default)]
pub trash_entry: Option<PathBuf>,
}
impl Export {
@@ -79,6 +84,7 @@ pub async fn create(state: &Shared, item_id: &str) -> anyhow::Result<Export> {
info: None,
jellyfin_folder: String::new(),
jellyfin_location: String::new(),
trash_entry: None,
};
state.store.put_export(&id, &export).await?;
spawn_prepare(state.clone(), export.clone());
@@ -136,19 +142,57 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo,
let kind = match item.kind.as_str() {
"Movie" => ItemKind::Movie,
"Series" => ItemKind::Series,
other => bail!("can only move movies and series, not {other}"),
"Season" => ItemKind::Season,
other => bail!("can only move movies, shows and seasons, not {other}"),
};
let item_path = PathBuf::from(
item.path
.clone()
.context("Jellyfin did not report a path for this item")?,
);
let item_path = match (&item.path, kind) {
(Some(p), _) => PathBuf::from(p),
(None, ItemKind::Season) => bail!(
"{} has no folder of its own (its episodes sit in the show folder); move the whole show instead",
item.name
),
(None, _) => bail!("Jellyfin did not report a path for this item"),
};
// The folder handed over. For a season it's the show's folder, and the
// manifest is narrowed to the season's folder and the show's own files.
let mut season: Option<(jm_jellyfin::Item, String)> = None;
let folder = match kind {
ItemKind::Movie => item_path
.parent()
.context("movie path has no parent folder")?
.to_path_buf(),
ItemKind::Series => item_path.clone(),
ItemKind::Season => {
let series_id = item
.series_id
.clone()
.context("Jellyfin did not say which show this season belongs to")?;
let series = jf
.item(&series_id)
.await
.context("looking up the season's show on Jellyfin")?;
let show = PathBuf::from(
series
.path
.clone()
.context("Jellyfin did not report a path for the show")?,
);
if item_path.parent() != Some(show.as_path()) {
bail!(
"{} has no folder of its own directly inside {}; move the whole show instead",
item.name,
show.display()
);
}
let name = item_path
.file_name()
.and_then(|n| n.to_str())
.context("season folder has no name")?
.to_string();
season = Some((series, name));
show
}
};
let libraries = jf.virtual_folders().await?;
@@ -197,17 +241,106 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo,
check_movie_folder(&files, &own)?;
}
let manifest = jm_transfer::build_manifest(&local_folder)
let manifest = match &season {
None => jm_transfer::build_manifest(&local_folder).await,
Some((_, season_folder)) => {
// Other seasons' episodes must not ride along with this one.
let episodes = jf
.items(&ItemQuery {
parent_id: Some(item_id),
include_types: &["Episode"],
recursive: true,
..Default::default()
})
.await?;
let sl = local_folder.join(season_folder);
let files = tokio::task::spawn_blocking(move || jm_transfer::list_relative(&sl)).await??;
let own: Vec<String> = episodes
.iter()
.flat_map(|e| {
e.media_sources
.iter()
.flatten()
.filter_map(|m| m.path.clone())
.chain(e.path.clone())
})
.filter_map(|p| relative_inside(&item_path, Path::new(&p)))
.collect();
if let Err(FolderProblem::SharedFolder(list)) = check_movie_folder(&files, &own) {
bail!(
"the {} folder also holds videos that aren't its episodes ({list}); \
sort them into their own season folders first",
item.name
);
}
// The season's folder, plus the show's own loose files (NFO,
// artwork). Loose videos belong to other seasons, so they stay.
let prefix = format!("{season_folder}/");
jm_transfer::build_manifest_filtered(&local_folder, move |rel| {
rel.starts_with(&prefix) || (!rel.contains('/') && !is_video(rel))
})
.await
}
}
.context("hashing files")?;
if manifest.files.is_empty() {
bail!("the item folder is empty");
}
// Capture each user's watch state now, before anything moves.
let (user_data, episode_keys) = capture_user_data(state, item_id, kind).await?;
let (name, season) = match season {
None => (item.name, None),
Some((series, season_folder)) => {
let show_files = manifest
.files
.iter()
.enumerate()
.filter(|(_, f)| !f.rel_path.contains('/'))
.map(|(i, _)| i)
.collect();
(
format!("{} – {}", series.name, item.name),
Some(SeasonInfo {
number: item
.index_number
.with_context(|| format!("Jellyfin gave {} no season number", item.name))?,
folder: season_folder,
show_name: series.name,
show_provider_ids: series.provider_ids,
show_files,
}),
)
}
};
let info = ExportInfo {
item_id: item_id.to_string(),
name,
kind,
library_name: library.name.clone(),
rel_folder,
manifest,
user_data,
episode_keys,
season,
};
Ok((info, folder.display().to_string(), location))
}
/// Every user's watch state for an item: the item itself (not for a season,
/// whose own state would land on the whole show at the destination) and, for
/// shows and seasons, each episode. Also returns every episode's key.
pub async fn capture_user_data(
state: &AppState,
item_id: &str,
kind: ItemKind,
) -> anyhow::Result<(Vec<UserDataRecord>, Vec<ItemKey>)> {
let jf = &state.jellyfin;
let mut user_data = Vec::new();
let mut episode_keys = Vec::new();
for user in jf.users().await? {
if kind != ItemKind::Season {
let root = jf
.items(&ItemQuery {
ids: Some(item_id),
@@ -218,7 +351,8 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo,
if let Some(ud) = root.into_iter().next().and_then(|i| i.user_data) {
push_record(&mut user_data, &user.name, ItemKey::Root, ud.into());
}
if kind == ItemKind::Series {
}
if kind.has_episodes() {
let episodes = jf
.items(&ItemQuery {
parent_id: Some(item_id),
@@ -243,18 +377,27 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo,
}
}
}
Ok((user_data, episode_keys))
}
let info = ExportInfo {
item_id: item_id.to_string(),
name: item.name,
kind,
library_name: library.name.clone(),
rel_folder,
manifest,
user_data,
episode_keys,
/// Names of the users who have watch state for an item, for the check before
/// a move.
pub async fn watchers(state: &AppState, item_id: &str) -> anyhow::Result<Vec<String>> {
let item = state.jellyfin.item(item_id).await?;
let kind = match item.kind.as_str() {
"Movie" => ItemKind::Movie,
"Series" => ItemKind::Series,
"Season" => ItemKind::Season,
other => bail!("can only move movies, shows and seasons, not {other}"),
};
Ok((info, folder.display().to_string(), location))
let (records, _) = capture_user_data(state, item_id, kind).await?;
let mut names: Vec<String> = Vec::new();
for r in records {
if !names.contains(&r.user_name) {
names.push(r.user_name);
}
}
Ok(names)
}
fn push_record(
@@ -272,9 +415,17 @@ fn push_record(
}
}
/// Who finished the move; recorded with the trash entry. Older peers send
/// nothing.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CompleteRequest {
pub job_id: Option<String>,
pub moved_to: Option<String>,
}
/// 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> {
pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow::Result<Export> {
let mut export: Export = state
.store
.get_export(id)
@@ -285,30 +436,87 @@ pub async fn complete(state: &Shared, id: &str) -> anyhow::Result<Export> {
ExportStatus::Ready => {}
other => bail!("export is not ready to complete ({other:?})"),
}
let info = export.info.as_ref().context("export has no info")?;
let info = export.info.clone().context("export has no info")?;
let local_folder = export.local_folder(state);
let location_local = state
.cfg
.path_map
.to_local(Path::new(&export.jellyfin_location));
let trash_root = location_local.join(".jellymove-trash");
let trash = join_relative(&trash_root.join(&export.id), &info.rel_folder)
.context("unsafe folder name")?;
let trash_root = location_local.join(trash::TRASH_DIR);
if tokio::fs::metadata(&local_folder).await.is_ok() {
if let Some(parent) = trash.parent() {
tokio::fs::create_dir_all(parent).await?;
}
// What leaves: the item's folder, or for a season just the season's folder.
let (moving, rel_moving) = match &info.season {
None => (local_folder.clone(), info.rel_folder.clone()),
Some(s) => (
join_relative(&local_folder, &s.folder).context("unsafe season folder name")?,
format!("{}/{}", info.rel_folder, s.folder),
),
};
// Re-running after a crash: if the folder is already gone it was moved
// last time, so only the steps after it remain.
if tokio::fs::metadata(&moving).await.is_ok() {
tokio::fs::create_dir_all(&trash_root).await?;
let marker = trash_root.join(".ignore");
if tokio::fs::metadata(&marker).await.is_err() {
tokio::fs::write(&marker, b"").await?;
}
tokio::fs::rename(&local_folder, &trash)
.await
.with_context(|| format!("moving {} to the trash", local_folder.display()))?;
tracing::info!(from = %local_folder.display(), to = %trash.display(), "source moved to trash");
// The same item can be trashed more than once (moved away, back,
// and away again), so each move gets its own entry folder.
let entry_dir = match &export.trash_entry {
Some(d) => d.clone(),
None => {
let d = trash::new_entry_dir(&trash_root, &export.id);
export.trash_entry = Some(d.clone());
state.store.put_export(&export.id, &export).await?;
d
}
};
let trash = join_relative(&entry_dir, &rel_moving).context("unsafe folder name")?;
if let Some(parent) = trash.parent() {
tokio::fs::create_dir_all(parent).await?;
}
trash::write_meta(
&entry_dir,
&trash::EntryMeta {
name: info.name.clone(),
kind: info.kind,
library: info.library_name.clone(),
rel_folder: rel_moving.clone(),
moved_at: time::OffsetDateTime::now_utc(),
moved_to: req.moved_to,
job_id: req.job_id,
},
)?;
if let Err(e) = tokio::fs::rename(&moving, &trash).await {
// Don't leave an empty entry behind in the trash view. Only the
// metadata file and empty folders are removed, never contents.
let _ = tokio::fs::remove_file(entry_dir.join(trash::META_FILE)).await;
let mut dir = trash.parent();
while let Some(d) = dir {
if !d.starts_with(&entry_dir) || tokio::fs::remove_dir(d).await.is_err() {
break;
}
dir = d.parent();
}
return Err(e).with_context(|| format!("moving {} to the trash", moving.display()));
}
tracing::info!(from = %moving.display(), to = %trash.display(), "source moved to trash");
}
// If that was the show's last season, what's left of the show folder
// (its NFO and artwork) joins the season in the same trash entry.
if let (Some(_), Some(entry_dir)) = (&info.season, &export.trash_entry) {
let show = local_folder.clone();
let dest = join_relative(entry_dir, &info.rel_folder).context("unsafe folder name")?;
let emptied = tokio::task::spawn_blocking(move || trash_leftover_show(&show, &dest)).await??;
if emptied {
tracing::info!(folder = %local_folder.display(), "last season moved; show folder moved to trash");
}
}
// After a season move the show is still listed here, but smaller.
crate::sizes::forget(state, &local_folder).await;
if let Err(e) = state
.jellyfin
.media_updated(std::slice::from_ref(&export.jellyfin_folder))
@@ -320,3 +528,63 @@ pub async fn complete(state: &Shared, id: &str) -> anyhow::Result<Export> {
state.store.put_export(&export.id, &export).await?;
Ok(export)
}
/// Move everything left in `show` into `dest` and remove `show`, but only if
/// no videos are left in it (so no seasons, episodes or extras remain).
/// Returns whether it did.
fn trash_leftover_show(show: &Path, dest: &Path) -> anyhow::Result<bool> {
if !std::fs::symlink_metadata(show).is_ok_and(|m| m.is_dir()) || has_videos(show) {
return Ok(false);
}
std::fs::create_dir_all(dest)?;
for e in std::fs::read_dir(show)?.flatten() {
let to = dest.join(e.file_name());
if std::fs::symlink_metadata(&to).is_ok() {
bail!("{} is already in the trash", to.display());
}
std::fs::rename(e.path(), &to)
.with_context(|| format!("moving {} to the trash", e.path().display()))?;
}
std::fs::remove_dir(show).with_context(|| format!("removing {}", show.display()))?;
Ok(true)
}
fn has_videos(dir: &Path) -> bool {
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
stack.push(e.path());
} else if is_video(&e.file_name().to_string_lossy()) {
return true;
}
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn leftover_show_is_trashed_only_without_videos() {
let tmp = tempfile::tempdir().unwrap();
let show = tmp.path().join("Show");
let dest = tmp.path().join("trash/Show");
std::fs::create_dir_all(show.join("Season 02")).unwrap();
std::fs::write(show.join("tvshow.nfo"), b"n").unwrap();
std::fs::write(show.join("Season 02/S02E01.mkv"), b"v").unwrap();
assert!(!trash_leftover_show(&show, &dest).unwrap());
assert!(show.join("tvshow.nfo").exists());
std::fs::remove_dir_all(show.join("Season 02")).unwrap();
std::fs::create_dir_all(show.join("extrafanart")).unwrap();
std::fs::write(show.join("extrafanart/1.jpg"), b"j").unwrap();
assert!(trash_leftover_show(&show, &dest).unwrap());
assert!(!show.exists());
assert!(dest.join("tvshow.nfo").exists());
assert!(dest.join("extrafanart/1.jpg").exists());
}
}
+2
View File
@@ -6,7 +6,9 @@ pub mod export;
pub mod library;
pub mod peer;
pub mod runner;
pub mod sizes;
pub mod state;
pub mod trash;
pub mod ui;
use std::sync::Arc;
+86 -5
View File
@@ -1,11 +1,12 @@
//! Browsing the local Jellyfin libraries.
use std::path::Path;
use std::path::{Path, PathBuf};
use jm_jellyfin::ItemQuery;
use serde::{Deserialize, Serialize};
use crate::state::AppState;
use crate::sizes::{self, FolderSize};
use crate::state::{AppState, Shared};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Library {
@@ -23,6 +24,23 @@ pub struct LibraryItem {
pub kind: String,
pub year: Option<i32>,
pub path: Option<String>,
/// Size of the item's folder on disk; `None` until it has been measured.
#[serde(default)]
pub size: Option<FolderSize>,
}
/// A season of a show, as Jellyfin lists it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SeasonItem {
pub id: String,
pub name: String,
pub number: Option<i32>,
/// The season's own folder. `None` when its episodes sit directly in the
/// show folder, in which case it can't be moved on its own.
pub path: Option<String>,
/// Name of that folder inside the show folder, to match it with the
/// show's per-folder sizes.
pub folder: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -55,8 +73,10 @@ pub async fn libraries(state: &AppState) -> anyhow::Result<Vec<Library>> {
.collect())
}
/// The movies and series in a library, with the size of each one's folder if
/// it's known yet. Sizes still missing are being measured in the background.
pub async fn items(
state: &AppState,
state: &Shared,
library_id: &str,
search: Option<&str>,
) -> anyhow::Result<Vec<LibraryItem>> {
@@ -71,7 +91,7 @@ pub async fn items(
..Default::default()
})
.await?;
Ok(items
let mut out: Vec<LibraryItem> = items
.into_iter()
.map(|i| LibraryItem {
id: i.id,
@@ -79,8 +99,69 @@ pub async fn items(
kind: i.kind,
year: i.production_year,
path: i.path,
size: None,
})
.collect())
.collect();
// Only items whose folder we can place are measured.
let folders: Vec<(usize, PathBuf)> = out
.iter()
.enumerate()
.filter_map(|(n, i)| Some((n, item_folder(state, i)?)))
.collect();
let paths: Vec<PathBuf> = folders.iter().map(|(_, p)| p.clone()).collect();
let sizes = sizes::lookup(state, &paths).await?;
for ((n, _), size) in folders.into_iter().zip(sizes) {
out[n].size = size;
}
Ok(out)
}
/// The seasons of a show, in order. Seasons without a folder of their own
/// inside the show folder are listed with no path.
pub async fn seasons(state: &AppState, series_id: &str) -> anyhow::Result<Vec<SeasonItem>> {
let series = state.jellyfin.item(series_id).await?;
let show = series.path.map(PathBuf::from);
let mut out: Vec<SeasonItem> = state
.jellyfin
.items(&ItemQuery {
parent_id: Some(series_id),
include_types: &["Season"],
..Default::default()
})
.await?
.into_iter()
.map(|s| {
let path = s
.path
.filter(|p| show.as_deref().is_some_and(|show| Path::new(p).parent() == Some(show)));
let folder = path
.as_deref()
.and_then(|p| Path::new(p).file_name())
.map(|n| n.to_string_lossy().into_owned());
SeasonItem {
id: s.id,
name: s.name,
number: s.index_number,
path,
folder,
}
})
.collect();
out.sort_by_key(|s| s.number.unwrap_or(i32::MAX));
Ok(out)
}
/// The folder a move would take, as this agent sees it: a movie's parent
/// folder, or the series folder itself.
fn item_folder(state: &AppState, item: &LibraryItem) -> Option<PathBuf> {
let path = Path::new(item.path.as_deref()?);
let folder = match item.kind.as_str() {
"Movie" => path.parent()?,
"Series" => path,
_ => return None,
};
Some(state.cfg.path_map.to_local(folder))
}
/// Confirm every library location exists and is writable from this agent.
+61 -5
View File
@@ -4,8 +4,9 @@ use jm_core::Job;
use reqwest::header::AUTHORIZATION;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use crate::export::Export;
use crate::library::{Library, LibraryItem};
use crate::export::{CompleteRequest, Export};
use crate::library::{Library, LibraryItem, SeasonItem};
use crate::trash::{EmptyResult, TrashEntry};
#[derive(Clone)]
pub struct PeerClient {
@@ -57,7 +58,14 @@ impl PeerClient {
let status = resp.status();
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("peer refused {what}: HTTP {status}: {body}");
// Our own API answers {"error": "..."}; pass on just the message.
let message = serde_json::from_str::<serde_json::Value>(&body)
.ok()
.and_then(|v| v.get("error")?.as_str().map(str::to_string));
match message {
Some(m) => anyhow::bail!("peer refused {what}: {m}"),
None => anyhow::bail!("peer refused {what}: HTTP {status}: {body}"),
}
}
Ok(resp.json().await?)
}
@@ -84,6 +92,14 @@ impl PeerClient {
.await
}
pub async fn seasons(&self, series: &str) -> anyhow::Result<Vec<SeasonItem>> {
self.send(
self.http.get(self.url("/seasons")).query(&[("series", series)]),
"list seasons",
)
.await
}
pub async fn create_export(&self, item_id: &str) -> anyhow::Result<Export> {
self.send(
self.http
@@ -106,19 +122,59 @@ impl PeerClient {
self.url(&format!("/exports/{export_id}/files/{idx}"))
}
pub async fn complete_export(&self, id: &str) -> anyhow::Result<Export> {
pub async fn complete_export(&self, id: &str, req: &CompleteRequest) -> anyhow::Result<Export> {
self.send(
self.http.post(self.url(&format!("/exports/{id}/complete"))),
self.http
.post(self.url(&format!("/exports/{id}/complete")))
.json(req),
"clean up source",
)
.await
}
pub async fn trash(&self) -> anyhow::Result<Vec<TrashEntry>> {
self.send(self.http.get(self.url("/trash")), "list trash")
.await
}
pub async fn empty_trash(&self, ids: &[String]) -> anyhow::Result<EmptyResult> {
self.send(
self.http
.post(self.url("/trash/empty"))
.json(&serde_json::json!({ "ids": ids })),
"empty trash",
)
.await
}
pub async fn create_job(&self, req: &CreateJob) -> anyhow::Result<Job> {
self.send(self.http.post(self.url("/jobs")).json(req), "start job")
.await
}
/// Names of the users on the peer's Jellyfin.
pub async fn users(&self) -> anyhow::Result<Vec<String>> {
self.send(self.http.get(self.url("/users")), "list users")
.await
}
/// Users on the peer with watch state for one of its items.
pub async fn watchers(&self, item_id: &str) -> anyhow::Result<Vec<String>> {
self.send(
self.http.get(self.url("/watchers")).query(&[("item", item_id)]),
"check watch history",
)
.await
}
pub async fn reapply(&self, job_id: &str) -> anyhow::Result<Job> {
self.send(
self.http.post(self.url(&format!("/jobs/{job_id}/reapply"))),
"re-apply watch history",
)
.await
}
pub async fn jobs(&self) -> anyhow::Result<Vec<Job>> {
self.send(self.http.get(self.url("/jobs")), "list jobs")
.await
+219 -42
View File
@@ -5,9 +5,10 @@ use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use anyhow::{Context, bail};
use jm_core::job::ExportInfo;
use jm_core::job::{ExportInfo, SeasonInfo};
use jm_core::paths::join_relative;
use jm_core::userdata::{ItemKey, same_user};
use jm_core::safety::check_inside_library;
use jm_core::userdata::{ItemKey, UserDataRecord, missing_users, same_user};
use jm_core::{ItemKind, Job, JobStatus, Stage};
use jm_jellyfin::ItemQuery;
@@ -100,6 +101,10 @@ fn target_jellyfin(job: &Job) -> anyhow::Result<PathBuf> {
/// Destination library location (local path) that holds the target folder.
fn target_library_root(state: &Shared, job: &Job) -> anyhow::Result<PathBuf> {
if let Some(loc) = &job.target_location {
return Ok(state.cfg.path_map.to_local(Path::new(loc)));
}
// Jobs planned before v0.2.0: work it out from the folder's depth.
let info = info(job)?;
let target = target_jellyfin(job)?;
let depth = info.rel_folder.split('/').count();
@@ -154,7 +159,7 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result<Flow> {
})?;
let expected = match info.kind {
ItemKind::Movie => "movies",
ItemKind::Series => "tvshows",
ItemKind::Series | ItemKind::Season => "tvshows",
};
if let Some(ct) = &lib.collection_type {
if ct != expected {
@@ -166,31 +171,76 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result<Flow> {
);
}
}
let location = lib
let first_location = lib
.locations
.first()
.context("destination library has no folders")?;
let target = join_relative(Path::new(location), &info.rel_folder)
let (target, location, skip, place) = match &info.season {
None => {
let target = join_relative(Path::new(first_location), &info.rel_folder)
.context("unsafe folder name from source")?;
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()
);
refuse_if_exists(state, &target)?;
let place = target.display().to_string();
(target, first_location.clone(), Vec::new(), place)
}
Some(season) => {
// A season joins the show if this server already has it.
let existing = find_show(state, &lib.item_id, season).await?;
let show = match &existing {
Some(path) => PathBuf::from(path),
None => join_relative(Path::new(first_location), &info.rel_folder)
.context("unsafe folder name from source")?,
};
let location = check_inside_library(&show, &lib.locations)
.map(str::to_string)
.unwrap_or_else(|_| first_location.clone());
let season_target =
join_relative(&show, &season.folder).context("unsafe season folder name from source")?;
refuse_if_exists(state, &season_target)?;
let show_here = tokio::fs::metadata(state.cfg.path_map.to_local(&show))
.await
.is_ok();
// Never overwrite the show's own files here; only bring them for a new show.
let (skip, how) = if show_here {
(season.show_files.clone(), "adding to the show already here")
} else {
(Vec::new(), "a new show, with its NFO and artwork")
};
let place = format!("{} ({how})", season_target.display());
(show, location, skip, place)
}
};
job.name = info.name.clone();
job.progress.bytes_total = info.manifest.total_bytes();
job.progress.bytes_total = info
.manifest
.files
.iter()
.enumerate()
.filter(|(i, _)| !skip.contains(i))
.map(|(_, f)| f.size)
.sum();
job.target_library = Some(lib.name.clone());
job.target_folder_jellyfin = Some(target.display().to_string());
job.target_location = Some(location);
job.note(format!(
"plan: {} files, {} into \"{}\" at {}",
info.manifest.files.len(),
"plan: {} files, {} into \"{}\" at {place}",
info.manifest.files.len() - skip.len(),
human_bytes(job.progress.bytes_total),
lib.name,
target.display()
));
job.skip_files = skip;
// Watch state is matched to users by name; say now whose won't carry over.
let users = state.jellyfin.users().await?;
job.missing_users = missing_users(&info.user_data, users.iter().map(|u| u.name.as_str()));
if !job.missing_users.is_empty() {
job.note(format!(
"watch history won't carry over for {}: no user with that name on this server. \
Create them in Jellyfin here first, or re-apply it from Moves afterwards",
job.missing_users.join(", ")
));
}
job.export = Some(info);
if job.dry_run {
@@ -202,6 +252,50 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result<Flow> {
Ok(Flow::Continue)
}
/// Refuse to plan a move into a folder that already exists here.
fn refuse_if_exists(state: &Shared, target: &Path) -> anyhow::Result<()> {
let local = state.cfg.path_map.to_local(target);
if std::fs::symlink_metadata(&local).is_ok() {
bail!(
"{} already exists on this server; refusing to merge into it",
local.display()
);
}
Ok(())
}
/// The folder of the show a season belongs to, if this library has it:
/// matched by provider ID (TVDB, TMDB, IMDb...) first, then by name.
async fn find_show(
state: &Shared,
library_id: &str,
season: &SeasonInfo,
) -> anyhow::Result<Option<String>> {
let shows = state
.jellyfin
.items(&ItemQuery {
parent_id: Some(library_id),
include_types: &["Series"],
recursive: true,
..Default::default()
})
.await?;
let same_id = |s: &&jm_jellyfin::Item| {
season.show_provider_ids.iter().any(|(k, v)| {
!v.trim().is_empty()
&& s.provider_ids
.iter()
.any(|(k2, v2)| k2.eq_ignore_ascii_case(k) && v2.trim().eq_ignore_ascii_case(v.trim()))
})
};
let same_name = |s: &&jm_jellyfin::Item| s.name.trim().eq_ignore_ascii_case(season.show_name.trim());
Ok(shows
.iter()
.find(same_id)
.or_else(|| shows.iter().find(same_name))
.and_then(|s| s.path.clone()))
}
async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
let peer = state.peer()?;
let export_id = job.export_id.clone().context("no export")?;
@@ -209,10 +303,14 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string());
jm_transfer::prepare_partial(&partial).await?;
let skip = job.skip_files.clone();
let mut done_before: u64 = 0;
let mut last_emit = Instant::now();
let mut last_save = Instant::now();
for (idx, entry) in files.iter().enumerate() {
if skip.contains(&idx) {
continue;
}
job.progress.current_file = Some(entry.rel_path.clone());
let url = peer.file_url(&export_id, idx);
let part = jm_transfer::part_path(&partial, idx);
@@ -247,7 +345,7 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
}
}
job.progress.current_file = None;
job.note(format!("copied and verified {} files", files.len()));
job.note(format!("copied and verified {} files", files.len() - skip.len()));
job.advance(Stage::Copied);
Ok(())
}
@@ -255,8 +353,14 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
async fn promote(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string());
let target_local = state.cfg.path_map.to_local(&target_jellyfin(job)?);
jm_transfer::promote(&partial, &target_local, &info(job)?.manifest).await?;
job.note(format!("moved into {}", target_local.display()));
jm_transfer::promote(&partial, &target_local, &info(job)?.manifest, &job.skip_files).await?;
let placed = match &info(job)?.season {
Some(season) => target_local.join(&season.folder),
None => target_local.clone(),
};
// A season changes the size of a show that may already be listed here.
crate::sizes::forget(state, &target_local).await;
job.note(format!("moved into {}", placed.display()));
job.advance(Stage::Promoted);
Ok(())
}
@@ -322,16 +426,22 @@ async fn find_new_item(
.iter()
.find(|l| l.name == lib_name)
.context("target library disappeared")?;
// A season's target is its show's folder: wait for the show, then for
// the season's episodes inside it.
let kind = match info.kind {
ItemKind::Movie => "Movie",
ItemKind::Series => "Series",
ItemKind::Series | ItemKind::Season => "Series",
};
let matches = |p: &str| match info.kind {
ItemKind::Movie => Path::new(p).parent() == Some(target),
ItemKind::Series => Path::new(p) == target,
ItemKind::Series | ItemKind::Season => Path::new(p) == target,
};
// Search by name first (cheap), then fall back to listing the library.
for search in [Some(info.name.as_str()), None] {
let name = info
.season
.as_ref()
.map_or(info.name.as_str(), |s| s.show_name.as_str());
for search in [Some(name), None] {
let items = state
.jellyfin
.items(&ItemQuery {
@@ -381,7 +491,7 @@ async fn missing_episodes(
series_id: &str,
info: &ExportInfo,
) -> anyhow::Result<usize> {
if info.kind != ItemKind::Series || info.episode_keys.is_empty() {
if !info.kind.has_episodes() || info.episode_keys.is_empty() {
return Ok(0);
}
let found = episode_ids(state, series_id).await?;
@@ -394,22 +504,46 @@ async fn missing_episodes(
async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
let info = info(job)?.clone();
let (applied, no_item, missing) = apply_records(state, job, &info.user_data).await?;
job.note(format!("restored {applied} watch-state records"));
if !missing.is_empty() {
job.note(format!(
"skipped watch history for users missing on this server: {}. \
Create them in Jellyfin, then use Re-apply watch history in Moves",
missing.join(", ")
));
}
if no_item > 0 {
job.note(format!(
"skipped {no_item} records whose episode wasn't found"
));
}
job.missing_users = missing;
job.advance(Stage::UserDataApplied);
Ok(())
}
/// Write `records` to the moved item and its episodes for every user who has
/// an account here. Returns (records applied, records whose episode wasn't
/// found, users with no account).
async fn apply_records(
state: &Shared,
job: &Job,
records: &[UserDataRecord],
) -> anyhow::Result<(usize, usize, Vec<String>)> {
let info = info(job)?;
let root_id = job.target_item_id.clone().context("no target item")?;
let episodes = if info.kind == ItemKind::Series {
let episodes = if info.kind.has_episodes() {
episode_ids(state, &root_id).await?
} else {
HashMap::new()
};
let users = state.jellyfin.users().await?;
let missing = missing_users(records, users.iter().map(|u| u.name.as_str()));
let (mut applied, mut no_user, mut no_item) = (0, 0, 0);
let mut unknown_users: Vec<String> = Vec::new();
for rec in &info.user_data {
let (mut applied, mut no_item) = (0, 0);
for rec in records {
let Some(user) = users.iter().find(|u| same_user(&u.name, &rec.user_name)) else {
no_user += 1;
if !unknown_users.contains(&rec.user_name) {
unknown_users.push(rec.user_name.clone());
}
continue;
};
let item_id = match rec.key {
@@ -426,25 +560,68 @@ async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
.await?;
applied += 1;
}
job.note(format!("restored {applied} watch-state records"));
if no_user > 0 {
job.note(format!(
"skipped {no_user} records for users missing on this server: {}",
unknown_users.join(", ")
));
Ok((applied, no_item, missing))
}
/// After a move, apply the watch state of users who had no account here at
/// the time, once their accounts exist. Only their records are applied, so
/// anything other users have watched since is left alone.
pub async fn reapply_user_data(state: &Shared, mut job: Job) -> anyhow::Result<Job> {
if job.dry_run || job.status != JobStatus::Done {
bail!("watch history can only be re-applied to a finished move");
}
if job.missing_users.is_empty() {
bail!("this move has no skipped watch history to re-apply");
}
let info = info(&job)?.clone();
let root_id = job.target_item_id.clone().context("no target item")?;
if state.jellyfin.item(&root_id).await.is_err() {
bail!(
"{} is no longer where it was moved to on {} (moved again?), \
so its watch history can't be re-applied",
job.name,
state.cfg.node_name
);
}
let users = state.jellyfin.users().await?;
let records: Vec<UserDataRecord> = info
.user_data
.iter()
.filter(|r| job.missing_users.iter().any(|m| same_user(m, &r.user_name)))
.cloned()
.collect();
let still_missing = missing_users(&records, users.iter().map(|u| u.name.as_str()));
let here = &state.cfg.node_name;
if still_missing.len() == job.missing_users.len() {
bail!(
"there's no user called {} on {here} yet; create them in Jellyfin on {here} first",
still_missing.join(" or ")
);
}
let (applied, no_item, missing) = apply_records(state, &job, &records).await?;
job.note(format!(
"re-applied {applied} watch-state records{}",
if no_item > 0 {
job.note(format!(
"skipped {no_item} records whose episode wasn't found"
));
format!(" ({no_item} episodes not found)")
} else {
String::new()
}
job.advance(Stage::UserDataApplied);
Ok(())
));
if !missing.is_empty() {
job.note(format!("still no user here called: {}", missing.join(", ")));
}
job.missing_users = missing;
state.save(&job).await?;
Ok(job)
}
async fn clean_source(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
let export_id = job.export_id.clone().context("no export")?;
state.peer()?.complete_export(&export_id).await?;
let req = crate::export::CompleteRequest {
job_id: Some(job.id.to_string()),
moved_to: Some(state.cfg.node_name.clone()),
};
state.peer()?.complete_export(&export_id, &req).await?;
job.note("source folder moved to its trash and source library rescanned");
job.advance(Stage::SourceCleaned);
Ok(())
+321
View File
@@ -0,0 +1,321 @@
//! Sizes of item folders on disk, for the library lists.
//!
//! Adding up a big library is slow on a NAS, so sizes are cached in the store
//! and worked out by a single background worker, one folder at a time. Listing
//! a library returns whatever is cached straight away and queues every folder
//! for checking; the UI asks again until every size has arrived.
//!
//! A cached size is trusted until the folder's *signature* changes (the
//! modified times of the folder and its direct subfolders, which change when
//! files are added, removed or renamed in them), and is measured again anyway
//! after [`MAX_AGE`] to catch changes deeper down. The signature itself is
//! only re-read every [`RECHECK`], so opening a library doesn't touch every
//! folder on disk each time.
use std::collections::{HashSet, VecDeque};
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use crate::state::{AppState, Shared};
/// How often a cached size's signature is checked against the disk.
pub const RECHECK: time::Duration = time::Duration::hours(1);
/// How long a size is trusted even if the signature hasn't changed.
pub const MAX_AGE: time::Duration = time::Duration::days(7);
/// Size of an item folder: what a move would copy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FolderSize {
pub bytes: u64,
pub files: u64,
/// Direct subfolders, e.g. a show's seasons or a movie's extras. Bytes in
/// files directly inside the folder are `bytes` minus these.
pub parts: Vec<PartSize>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartSize {
pub name: String,
pub bytes: u64,
pub files: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Record {
size: FolderSize,
signature: u64,
#[serde(with = "time::serde::rfc3339")]
measured_at: OffsetDateTime,
#[serde(with = "time::serde::rfc3339")]
checked_at: OffsetDateTime,
}
#[derive(Default)]
pub struct SizeQueue {
inner: Mutex<QueueState>,
}
#[derive(Default)]
struct QueueState {
queue: VecDeque<PathBuf>,
queued: HashSet<PathBuf>,
running: bool,
}
/// Cached sizes for these local folders, in the same order (`None` where
/// nothing is cached yet). Every folder is queued for checking.
pub async fn lookup(state: &Shared, folders: &[PathBuf]) -> anyhow::Result<Vec<Option<FolderSize>>> {
let keys: Vec<String> = folders.iter().map(|p| key(p)).collect();
let mut cached: std::collections::HashMap<String, Record> =
state.store.get_folder_sizes(keys.clone()).await?;
enqueue(state, folders.iter().cloned());
Ok(keys
.iter()
.map(|k| cached.remove(k).map(|r| r.size))
.collect())
}
fn enqueue(state: &Shared, folders: impl IntoIterator<Item = PathBuf>) {
let mut q = state.sizes.inner.lock().expect("size queue");
for f in folders {
if q.queued.insert(f.clone()) {
q.queue.push_back(f);
}
}
if !q.running && !q.queue.is_empty() {
q.running = true;
tokio::spawn(worker(state.clone()));
}
}
/// One folder at a time, so a NAS isn't asked to walk several at once.
async fn worker(state: Shared) {
loop {
let next = {
let mut q = state.sizes.inner.lock().expect("size queue");
match q.queue.pop_front() {
Some(p) => {
q.queued.remove(&p);
p
}
None => {
q.running = false;
return;
}
}
};
if let Err(e) = refresh(&state, &next).await {
tracing::warn!(folder = %next.display(), error = %format!("{e:#}"), "could not measure folder");
}
}
}
async fn refresh(state: &Shared, folder: &Path) -> anyhow::Result<()> {
let k = key(folder);
let cached: Option<Record> = state
.store
.get_folder_sizes(vec![k.clone()])
.await?
.remove(&k);
let now = OffsetDateTime::now_utc();
if cached.as_ref().is_some_and(|r| now - r.checked_at < RECHECK) {
return Ok(());
}
let f = folder.to_path_buf();
let Some(sig) = tokio::task::spawn_blocking(move || signature(&f)).await? else {
// Gone, e.g. moved away. Forget it.
state.store.delete_folder_size(&k).await?;
return Ok(());
};
let record = match cached {
Some(mut r) if r.signature == sig && now - r.measured_at < MAX_AGE => {
r.checked_at = now;
r
}
_ => {
let f = folder.to_path_buf();
let size = tokio::task::spawn_blocking(move || measure(&f)).await?;
Record {
size,
signature: sig,
measured_at: now,
checked_at: now,
}
}
};
state.store.put_folder_size(&k, &record).await?;
Ok(())
}
/// Drop the cached size of a folder a move has just changed, so the next
/// listing measures it again instead of waiting for the hourly check.
pub async fn forget(state: &AppState, folder: &Path) {
if let Err(e) = state.store.delete_folder_size(&key(folder)).await {
tracing::warn!(folder = %folder.display(), error = %e, "could not forget folder size");
}
}
fn key(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
fn skipped(name: &std::ffi::OsStr) -> bool {
name.to_string_lossy().starts_with(jm_transfer::HIDDEN_PREFIX)
}
/// Modified times of the folder and its direct subfolders, hashed. `None` if
/// the folder doesn't exist.
pub fn signature(folder: &Path) -> Option<u64> {
let meta = std::fs::symlink_metadata(folder).ok()?;
if !meta.is_dir() {
return None;
}
let mut h = std::collections::hash_map::DefaultHasher::new();
meta.modified().ok().hash(&mut h);
let mut subdirs: Vec<(std::ffi::OsString, Option<std::time::SystemTime>)> =
std::fs::read_dir(folder)
.ok()?
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !skipped(&e.file_name()))
.map(|e| (e.file_name(), e.metadata().and_then(|m| m.modified()).ok()))
.collect();
subdirs.sort();
subdirs.hash(&mut h);
Some(h.finish())
}
/// Add up every regular file below `folder`, counting the same files a move
/// copies: links and jellymove's own `.jellymove-*` entries are skipped.
pub fn measure(folder: &Path) -> FolderSize {
let mut total = PartSize {
name: String::new(),
bytes: 0,
files: 0,
};
let mut parts = Vec::new();
for e in std::fs::read_dir(folder).into_iter().flatten().flatten() {
if skipped(&e.file_name()) {
continue;
}
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
let (bytes, files) = tree(&e.path());
parts.push(PartSize {
name: e.file_name().to_string_lossy().into_owned(),
bytes,
files,
});
total.bytes += bytes;
total.files += files;
} else if t.is_file() {
total.bytes += e.metadata().map(|m| m.len()).unwrap_or(0);
total.files += 1;
}
}
parts.sort_by_key(|p| natural_key(&p.name));
FolderSize {
bytes: total.bytes,
files: total.files,
parts,
}
}
fn tree(dir: &Path) -> (u64, u64) {
let mut bytes = 0;
let mut files = 0;
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
if skipped(&e.file_name()) {
continue;
}
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
stack.push(e.path());
} else if t.is_file() {
bytes += e.metadata().map(|m| m.len()).unwrap_or(0);
files += 1;
}
}
}
(bytes, files)
}
/// Sort "Season 2" before "Season 10".
fn natural_key(s: &str) -> Vec<(String, u64)> {
let mut out = Vec::new();
let mut text = String::new();
let mut num = String::new();
for c in s.chars() {
if c.is_ascii_digit() {
num.push(c);
} else {
if !num.is_empty() {
out.push((std::mem::take(&mut text), num.parse().unwrap_or(u64::MAX)));
num.clear();
}
text.extend(c.to_lowercase());
}
}
out.push((text, num.parse().unwrap_or(0)));
out
}
#[cfg(test)]
mod tests {
use super::*;
fn write(p: &Path, len: usize) {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, vec![0u8; len]).unwrap();
}
#[test]
fn measures_files_and_direct_subfolders() {
let tmp = tempfile::tempdir().unwrap();
let show = tmp.path().join("Severance");
write(&show.join("tvshow.nfo"), 10);
write(&show.join("Season 10/e.mkv"), 300);
write(&show.join("Season 2/e1.mkv"), 100);
write(&show.join("Season 2/e2.mkv"), 200);
write(&show.join("Season 2/subs/e1.srt"), 5);
write(&show.join(".jellymove-partial/x.part"), 999);
#[cfg(unix)]
std::os::unix::fs::symlink(show.join("Season 2/e1.mkv"), show.join("link.mkv")).unwrap();
let s = measure(&show);
assert_eq!((s.bytes, s.files), (615, 5));
let parts: Vec<_> = s.parts.iter().map(|p| (p.name.as_str(), p.bytes, p.files)).collect();
assert_eq!(parts, [("Season 2", 305, 3), ("Season 10", 300, 1)]);
}
#[test]
fn signature_changes_when_a_season_changes() {
let tmp = tempfile::tempdir().unwrap();
let show = tmp.path().join("Show");
write(&show.join("Season 1/e1.mkv"), 1);
let before = signature(&show).unwrap();
assert_eq!(signature(&show), Some(before));
// Adding an episode changes the season folder's modified time.
let s1 = show.join("Season 1");
let old = std::fs::metadata(&s1).unwrap().modified().unwrap();
write(&s1.join("e2.mkv"), 1);
let file = std::fs::File::open(&s1).unwrap();
file.set_modified(old + std::time::Duration::from_secs(5)).unwrap();
assert_ne!(signature(&show), Some(before));
assert_eq!(signature(&tmp.path().join("missing")), None);
}
#[test]
fn natural_order() {
let mut v = vec!["Season 10", "Specials", "Season 2", "Season 1"];
v.sort_by_key(|s| natural_key(s));
assert_eq!(v, ["Season 1", "Season 2", "Season 10", "Specials"]);
}
}
+3
View File
@@ -21,6 +21,8 @@ pub struct AppState {
pub running: Mutex<HashSet<JobId>>,
/// Exports currently being hashed, so a duplicate request doesn't start a second pass.
pub preparing: Mutex<HashSet<String>>,
/// Folders waiting to have their size measured.
pub sizes: crate::sizes::SizeQueue,
}
pub type Shared = Arc<AppState>;
@@ -58,6 +60,7 @@ impl AppState {
job_slots: Arc::new(Semaphore::new(slots)),
running: Mutex::new(HashSet::new()),
preparing: Mutex::new(HashSet::new()),
sizes: Default::default(),
})
}
+314
View File
@@ -0,0 +1,314 @@
//! The source's trash. When a move finishes, the source renames the item's
//! folder to `<library>/.jellymove-trash/<entry>/<folder>` rather than
//! deleting it. Entries stay there until someone empties them from the UI.
//!
//! Each entry folder also holds a small metadata file describing the move.
//! Entries are only ever referred to by an opaque ID derived from their path,
//! and are resolved by scanning the trash folders, so neither the UI nor the
//! peer can name a path to delete.
use std::path::{Path, PathBuf};
use anyhow::Context;
use jm_core::ItemKind;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use crate::library;
use crate::state::AppState;
/// Folder inside each library location that holds the trash.
pub const TRASH_DIR: &str = ".jellymove-trash";
/// Metadata file written into each entry folder.
pub const META_FILE: &str = ".jellymove-entry.json";
/// What the source records about a move when it trashes the folder.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntryMeta {
pub name: String,
pub kind: ItemKind,
pub library: String,
/// The folder's path inside its library, e.g. `Alien (1979)`.
pub rel_folder: String,
#[serde(with = "time::serde::rfc3339")]
pub moved_at: OffsetDateTime,
/// Node the item was moved to.
pub moved_to: Option<String>,
/// The job on that node that moved it.
pub job_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrashEntry {
/// Opaque, stable while the entry exists. The only way to refer to it.
pub id: String,
pub name: String,
/// Missing for entries trashed before v0.2.0, which have no metadata.
pub kind: Option<ItemKind>,
pub library: String,
pub folder: String,
#[serde(with = "time::serde::rfc3339::option")]
pub moved_at: Option<OffsetDateTime>,
pub moved_to: Option<String>,
pub job_id: Option<String>,
pub size: u64,
pub files: u64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EmptyResult {
pub removed: usize,
pub freed: u64,
/// IDs that weren't in the trash (already emptied, or never existed).
pub missing: Vec<String>,
}
struct Found {
entry: TrashEntry,
path: PathBuf,
}
/// Pick a folder for a new entry under `trash_root`, starting with `base` and
/// adding `-2`, `-3`, ... if an item with the same ID was trashed before.
pub fn new_entry_dir(trash_root: &Path, base: &str) -> PathBuf {
let first = trash_root.join(base);
if std::fs::symlink_metadata(&first).is_err() {
return first;
}
(2u32..)
.map(|n| trash_root.join(format!("{base}-{n}")))
.find(|p| std::fs::symlink_metadata(p).is_err())
.expect("a free name exists")
}
pub fn write_meta(entry_dir: &Path, meta: &EntryMeta) -> anyhow::Result<()> {
let json = serde_json::to_vec_pretty(meta)?;
std::fs::write(entry_dir.join(META_FILE), json)
.with_context(|| format!("writing trash metadata in {}", entry_dir.display()))
}
/// Every entry in this node's trash, newest first.
pub async fn list(state: &AppState) -> anyhow::Result<Vec<TrashEntry>> {
Ok(scan(state).await?.into_iter().map(|f| f.entry).collect())
}
/// Delete the given entries for good. Unknown IDs are reported, not errors,
/// so emptying twice (e.g. from both UIs) is harmless.
pub async fn empty(state: &AppState, ids: &[String]) -> anyhow::Result<EmptyResult> {
let found = scan(state).await?;
let mut result = EmptyResult::default();
let mut doomed = Vec::new();
for id in ids {
match found.iter().find(|f| &f.entry.id == id) {
Some(f) => doomed.push((f.path.clone(), f.entry.size, f.entry.name.clone())),
None => result.missing.push(id.clone()),
}
}
for (path, size, name) in doomed {
// Belt and braces: scan only returns real folders directly inside a
// trash folder, but never delete anything else.
let in_trash = path
.parent()
.and_then(Path::file_name)
.is_some_and(|n| n == TRASH_DIR);
anyhow::ensure!(in_trash, "refusing to delete {}", path.display());
let p = path.clone();
tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&p))
.await?
.with_context(|| format!("emptying {} from the trash", path.display()))?;
tracing::info!(item = %name, path = %path.display(), "emptied from trash");
result.removed += 1;
result.freed += size;
}
Ok(result)
}
async fn scan(state: &AppState) -> anyhow::Result<Vec<Found>> {
let mut roots: Vec<(String, PathBuf)> = Vec::new();
for lib in library::libraries(state).await? {
for loc in &lib.locations {
let root = state.cfg.path_map.to_local(Path::new(loc)).join(TRASH_DIR);
if !roots.iter().any(|(_, r)| r == &root) {
roots.push((lib.name.clone(), root));
}
}
}
let mut found = tokio::task::spawn_blocking(move || {
roots
.iter()
.flat_map(|(library, root)| scan_root(library, root))
.collect::<Vec<_>>()
})
.await?;
found.sort_by_key(|f| std::cmp::Reverse(f.entry.moved_at));
Ok(found)
}
fn scan_root(library: &str, root: &Path) -> Vec<Found> {
// The trash folder itself must be a real folder, not a link elsewhere.
if !std::fs::symlink_metadata(root).is_ok_and(|m| m.is_dir()) {
return vec![];
}
let Ok(rd) = std::fs::read_dir(root) else {
return vec![];
};
let mut out = Vec::new();
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
// `.ignore` and anything else hidden is ours, not an entry. Links
// are skipped so emptying can't reach outside the trash.
if name.starts_with('.') || !e.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let path = e.path();
let meta: Option<EntryMeta> = std::fs::read(path.join(META_FILE))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok());
let (size, files) = dir_size(&path);
let entry = match meta {
Some(m) => TrashEntry {
id: entry_id(&path),
name: m.name,
kind: Some(m.kind),
library: library.to_string(),
folder: m.rel_folder,
moved_at: Some(m.moved_at),
moved_to: m.moved_to,
job_id: m.job_id,
size,
files,
},
None => {
// Trashed before metadata existed: the entry holds the
// folder at its path inside the library.
let folder = first_visible_child(&path).unwrap_or_else(|| name.clone());
TrashEntry {
id: entry_id(&path),
name: folder.clone(),
kind: None,
library: library.to_string(),
folder,
moved_at: std::fs::metadata(&path)
.and_then(|m| m.modified())
.ok()
.map(OffsetDateTime::from),
moved_to: None,
job_id: None,
size,
files,
}
}
};
out.push(Found { entry, path });
}
out
}
fn first_visible_child(dir: &Path) -> Option<String> {
std::fs::read_dir(dir)
.ok()?
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.find(|n| !n.starts_with('.'))
}
/// Total bytes and file count below `dir`, not following links and not
/// counting the entry's metadata file.
fn dir_size(dir: &Path) -> (u64, u64) {
let mut bytes = 0;
let mut files = 0;
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&d) else {
continue;
};
for e in rd.flatten() {
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
stack.push(e.path());
} else if t.is_file() && !(d == dir && e.file_name() == META_FILE) {
bytes += e.metadata().map(|m| m.len()).unwrap_or(0);
files += 1;
}
}
}
(bytes, files)
}
fn entry_id(path: &Path) -> String {
let hash = blake3::hash(path.as_os_str().as_encoded_bytes());
hash.to_hex()[..16].to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_entry_dir_avoids_existing_names() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1"));
std::fs::create_dir(root.join("item-1")).unwrap();
assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1-2"));
std::fs::create_dir(root.join("item-1-2")).unwrap();
assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1-3"));
}
#[test]
fn scan_lists_entries_and_skips_links_and_hidden_files() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join(TRASH_DIR);
let entry = root.join("item-1");
std::fs::create_dir_all(entry.join("Alien (1979)/extras")).unwrap();
std::fs::write(entry.join("Alien (1979)/Alien.mkv"), b"12345").unwrap();
std::fs::write(entry.join("Alien (1979)/extras/x.mkv"), b"123").unwrap();
write_meta(
&entry,
&EntryMeta {
name: "Alien".into(),
kind: ItemKind::Movie,
library: "Movies".into(),
rel_folder: "Alien (1979)".into(),
moved_at: OffsetDateTime::now_utc(),
moved_to: Some("home".into()),
job_id: Some("j1".into()),
},
)
.unwrap();
// An old entry without metadata.
std::fs::create_dir_all(root.join("item-2/Heat (1995)")).unwrap();
std::fs::write(root.join("item-2/Heat (1995)/Heat.mkv"), b"1").unwrap();
std::fs::write(root.join(".ignore"), b"").unwrap();
#[cfg(unix)]
{
let outside = tmp.path().join("outside");
std::fs::create_dir(&outside).unwrap();
std::os::unix::fs::symlink(&outside, root.join("sneaky")).unwrap();
}
let mut found = scan_root("Movies", &root);
found.sort_by(|a, b| a.entry.name.cmp(&b.entry.name));
let names: Vec<_> = found.iter().map(|f| f.entry.name.as_str()).collect();
assert_eq!(names, ["Alien", "Heat (1995)"]);
let alien = &found[0].entry;
assert_eq!((alien.size, alien.files), (8, 2));
assert_eq!(alien.moved_to.as_deref(), Some("home"));
assert_eq!(alien.kind, Some(ItemKind::Movie));
assert_eq!(found[1].entry.kind, None);
assert!(found[1].entry.moved_at.is_some());
assert_ne!(alien.id, found[1].entry.id);
}
#[test]
fn scan_ignores_a_trash_folder_that_is_a_link() {
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().join("elsewhere");
std::fs::create_dir_all(real.join("item-1/Movie")).unwrap();
#[cfg(unix)]
{
std::os::unix::fs::symlink(&real, tmp.path().join(TRASH_DIR)).unwrap();
assert!(scan_root("Movies", &tmp.path().join(TRASH_DIR)).is_empty());
}
}
}
+440
View File
@@ -375,6 +375,446 @@ async fn refuses_when_destination_exists() {
assert!(cloud.movies().join("Alien (1979)").exists());
}
/// Total size of every file below `dir`.
fn tree_size(dir: &Path) -> u64 {
std::fs::read_dir(dir)
.unwrap()
.map(|e| {
let e = e.unwrap();
if e.file_type().unwrap().is_dir() {
tree_size(&e.path())
} else {
e.metadata().unwrap().len()
}
})
.sum()
}
async fn move_item(base: &str, from: &str, item_id: &str, name: &str) -> Value {
let resp = post(
base,
"/api/moves",
json!({"from": from, "item_id": item_id, "name": name}),
)
.await;
assert!(resp.status().is_success(), "{}", resp.text().await.unwrap());
let job: Value = resp.json().await.unwrap();
let done = wait_job(base, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Done", "{done:#}");
done
}
#[tokio::test]
async fn trash_can_be_listed_and_emptied_from_either_side() {
let (cloud, home) = pair(seed_movie).await;
let size = tree_size(&cloud.movies().join("Alien (1979)"));
let movie = cloud.fake.find("Movie", "Alien").unwrap();
let job = move_item(&cloud.url, "local", &movie, "Alien").await;
// The source lists its own trash, with what was moved, where and how big.
let local = get(&cloud.url, "/api/trash?node=local").await;
let entries = local.as_array().unwrap();
assert_eq!(entries.len(), 1, "{local:#}");
let e = &entries[0];
assert_eq!(e["name"], "Alien");
assert_eq!(e["kind"], "Movie");
assert_eq!(e["library"], "Movies");
assert_eq!(e["folder"], "Alien (1979)");
assert_eq!(e["moved_to"], "home");
assert_eq!(e["job_id"], job["id"]);
assert_eq!(e["size"], size);
assert_eq!(e["files"], 4);
assert!(e["moved_at"].is_string());
// The destination sees the same entry as the peer's trash, and its own is empty.
let peer = get(&home.url, "/api/trash?node=peer").await;
assert_eq!(peer, local);
assert_eq!(get(&home.url, "/api/trash?node=local").await, json!([]));
// Paths are never accepted as IDs.
let bogus = post(
&home.url,
"/api/trash/empty",
json!({"node": "peer", "ids": ["../Alien (1979)", "/etc"]}),
)
.await;
let bogus: Value = bogus.json().await.unwrap();
assert_eq!(bogus["removed"], 0);
assert_eq!(bogus["missing"].as_array().unwrap().len(), 2);
assert!(home.movies().join("Alien (1979)/Alien (1979).mkv").exists());
// Empty it from the destination's UI: the source deletes its own files.
let id = e["id"].clone();
let resp = post(
&home.url,
"/api/trash/empty",
json!({"node": "peer", "ids": [id]}),
)
.await;
assert!(resp.status().is_success(), "{}", resp.text().await.unwrap());
let result: Value = resp.json().await.unwrap();
assert_eq!(result["removed"], 1);
assert_eq!(result["freed"], size);
let trash = cloud.movies().join(".jellymove-trash");
let left: Vec<_> = std::fs::read_dir(&trash)
.unwrap()
.map(|e| e.unwrap().file_name())
.collect();
assert_eq!(left, [".ignore"]);
assert_eq!(get(&cloud.url, "/api/trash?node=local").await, json!([]));
// The moved copy is untouched.
assert!(home.movies().join("Alien (1979)/Alien (1979).mkv").exists());
// Emptying again is harmless.
let again: Value = post(
&cloud.url,
"/api/trash/empty",
json!({"node": "local", "ids": [id]}),
)
.await
.json()
.await
.unwrap();
assert_eq!(again["removed"], 0);
assert_eq!(again["missing"], json!([id]));
// Like every other UI write, emptying needs the CSRF header.
let r = reqwest::Client::new()
.post(format!("{}/api/trash/empty", cloud.url))
.json(&json!({"ids": []}))
.send()
.await
.unwrap();
assert_eq!(r.status(), 403);
}
#[tokio::test]
async fn an_item_moved_away_twice_gets_two_trash_entries() {
let (cloud, home) = pair(seed_movie).await;
// Jellyfin item IDs come from the path, so when the movie comes back to
// the same folder it gets the same ID, and so the same export ID.
let movie = cloud.fake.find("Movie", "Alien").unwrap();
move_item(&cloud.url, "local", &movie, "Alien").await;
let on_home = home.fake.find("Movie", "Alien").unwrap();
move_item(&cloud.url, "peer", &on_home, "Alien").await;
let back = cloud.fake.find("Movie", "Alien").unwrap();
assert_eq!(back, movie);
move_item(&cloud.url, "local", &back, "Alien").await;
assert!(home.movies().join("Alien (1979)/Alien (1979).mkv").exists());
let cloud_trash = get(&cloud.url, "/api/trash?node=local").await;
let entries = cloud_trash.as_array().unwrap();
assert_eq!(entries.len(), 2, "{cloud_trash:#}");
assert_ne!(entries[0]["id"], entries[1]["id"]);
assert!(
cloud
.movies()
.join(format!(".jellymove-trash/item-{movie}-2/Alien (1979)/Alien (1979).mkv"))
.exists()
);
let home_trash = get(&home.url, "/api/trash?node=local").await;
assert_eq!(home_trash.as_array().unwrap().len(), 1);
assert_eq!(home_trash[0]["moved_to"], "cloud");
}
/// List a library until every item has a size, like the UI does.
async fn items_with_sizes(base: &str, query: &str) -> Vec<Value> {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let items = get(base, &format!("/api/items?{query}")).await;
let items = items.as_array().unwrap().clone();
if !items.is_empty() && items.iter().all(|i| i["size"].is_object()) {
return items;
}
assert!(Instant::now() < deadline, "sizes never arrived: {items:#?}");
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
#[tokio::test]
async fn lists_folder_sizes_for_movies_shows_and_seasons() {
let (cloud, home) = pair(|root| {
seed_movie(root);
seed_series(root);
})
.await;
// A movie's size is its whole folder: video, subtitles, NFO and extras.
let movies = items_with_sizes(&cloud.url, "node=local&library=lib-movies").await;
let alien = &movies[0]["size"];
assert_eq!(alien["bytes"], tree_size(&cloud.movies().join("Alien (1979)")));
assert_eq!(alien["files"], 4);
// A show has a total plus one part per season folder; loose files such
// as tvshow.nfo count towards the total only.
let shows = items_with_sizes(&home.url, "node=peer&library=lib-tv-shows").await;
let s = &shows[0]["size"];
assert_eq!(shows[0]["name"], "Severance");
assert_eq!(s["bytes"], tree_size(&cloud.tv().join("Severance")));
assert_eq!(s["files"], 4);
assert_eq!(
s["parts"],
json!([
{"name": "Season 01", "bytes": 22, "files": 2},
{"name": "Season 02", "bytes": 13, "files": 1},
])
);
// After a move the item is measured where it now lives.
let movie = cloud.fake.find("Movie", "Alien").unwrap();
move_item(&cloud.url, "local", &movie, "Alien").await;
let on_home = items_with_sizes(&home.url, "node=local&library=lib-movies").await;
assert_eq!(on_home[0]["size"], *alien);
}
#[tokio::test]
async fn moves_seasons_one_at_a_time_and_trashes_the_empty_show() {
let (cloud, home) = pair(seed_series).await;
let e1 = cloud.fake.episode_id("Severance", 1, 1).unwrap();
let e3 = cloud.fake.episode_id("Severance", 2, 1).unwrap();
cloud.fake.set_user_data(&e1, json!({"Played": true}));
cloud
.fake
.set_user_data(&e3, json!({"PlaybackPositionTicks": 42}));
let series = cloud.fake.find("Series", "Severance").unwrap();
cloud.fake.set_user_data(&series, json!({"IsFavorite": true}));
// The UI lists the show's seasons with their folders.
let seasons = get(
&home.url,
&format!("/api/seasons?node=peer&series={series}"),
)
.await;
assert_eq!(seasons[0]["name"], "Season 1");
assert_eq!(seasons[0]["folder"], "Season 01");
assert_eq!(seasons[1]["number"], 2);
// List cloud's shows first so their sizes are cached.
items_with_sizes(&cloud.url, "node=local&library=lib-tv-shows").await;
// Season 2 into a show home doesn't have yet: the show's NFO comes too.
let s2 = cloud.fake.season_id("Severance", 2).unwrap();
assert_eq!(seasons[1]["id"], s2);
let job = move_item(&cloud.url, "local", &s2, "Season 2").await;
assert_eq!(job["name"], "Severance – Season 2");
let show_home = home.tv().join("Severance");
assert!(show_home.join("Season 02/Severance S02E01.mkv").exists());
assert!(show_home.join("tvshow.nfo").exists());
assert!(!show_home.join("Season 01").exists());
// The source keeps the rest of the show.
let show_cloud = cloud.tv().join("Severance");
assert!(!show_cloud.join("Season 02").exists());
assert!(show_cloud.join("Season 01/Severance S01E01.mkv").exists());
assert!(show_cloud.join("tvshow.nfo").exists());
// Episode watch state followed; the season's show-level state didn't.
let new_e3 = home.fake.episode_id("Severance", 2, 1).unwrap();
assert_eq!(
home.fake.get_user_data(&new_e3).unwrap()["PlaybackPositionTicks"],
42
);
let home_series = home.fake.find("Series", "Severance").unwrap();
assert!(home.fake.get_user_data(&home_series).is_none());
// The cached size of cloud's show was dropped, so it's measured again
// without waiting for the hourly check.
let shows = items_with_sizes(&cloud.url, "node=local&library=lib-tv-shows").await;
assert_eq!(shows[0]["size"]["bytes"], tree_size(&show_cloud));
assert_eq!(shows[0]["size"]["parts"].as_array().unwrap().len(), 1);
// Mark home's copy of the NFO so we can tell it isn't overwritten.
std::fs::write(show_home.join("tvshow.nfo"), b"home's own").unwrap();
items_with_sizes(&home.url, "node=local&library=lib-tv-shows").await;
// Season 1 joins the existing show, and was the last one on cloud.
let s1 = cloud.fake.season_id("Severance", 1).unwrap();
let job = move_item(&home.url, "peer", &s1, "Season 1").await;
assert!(
job["log"]
.as_array()
.unwrap()
.iter()
.any(|l| l.as_str().unwrap().contains("adding to the show already here")),
"{job:#}"
);
assert!(show_home.join("Season 01/Severance S01E02.mkv").exists());
assert_eq!(std::fs::read(show_home.join("tvshow.nfo")).unwrap(), b"home's own");
// Home's show grew, and its size says so straight away.
let shows = items_with_sizes(&home.url, "node=local&library=lib-tv-shows").await;
assert_eq!(shows[0]["size"]["bytes"], tree_size(&show_home));
assert_eq!(shows[0]["size"]["parts"].as_array().unwrap().len(), 2);
let new_e1 = home.fake.episode_id("Severance", 1, 1).unwrap();
assert_eq!(home.fake.get_user_data(&new_e1).unwrap()["Played"], true);
// Nothing is left of the show on cloud: its NFO went to the trash with
// the last season.
assert!(!show_cloud.exists());
let trash = get(&cloud.url, "/api/trash?node=local").await;
let entries = trash.as_array().unwrap();
assert_eq!(entries.len(), 2, "{trash:#}");
let last = entries
.iter()
.find(|e| e["name"] == "Severance – Season 1")
.unwrap();
assert_eq!(last["kind"], "Season");
assert_eq!(last["folder"], "Severance/Season 01");
assert_eq!(last["files"], 3);
}
#[tokio::test]
async fn refuses_a_season_the_destination_already_has() {
let (cloud, home) = pair(seed_series).await;
write(
&home.tv().join("Severance/Season 02/Severance S02E01.mkv"),
b"home's copy",
);
home.fake.scan();
let s2 = cloud.fake.season_id("Severance", 2).unwrap();
let job: Value = post(
&cloud.url,
"/api/moves",
json!({"from": "local", "item_id": s2, "name": "Season 2"}),
)
.await
.json()
.await
.unwrap();
let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Failed");
assert!(
done["status"]["detail"]
.as_str()
.unwrap()
.contains("already exists"),
"{done:#}"
);
assert_eq!(
std::fs::read(home.tv().join("Severance/Season 02/Severance S02E01.mkv")).unwrap(),
b"home's copy"
);
assert!(cloud.tv().join("Severance/Season 02").exists());
}
#[tokio::test]
async fn refuses_a_season_folder_holding_other_seasons() {
let (cloud, _home) = pair(|root| {
seed_series(root);
// A season 3 episode filed in the Season 02 folder.
write(
&root.join("tv/Severance/Season 02/Severance S03E01.mkv"),
b"misfiled",
);
})
.await;
let s2 = cloud.fake.season_id("Severance", 2).unwrap();
let job: Value = post(
&cloud.url,
"/api/moves",
json!({"from": "local", "item_id": s2, "name": "Season 2"}),
)
.await
.json()
.await
.unwrap();
let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Failed");
assert!(
done["status"]["detail"]
.as_str()
.unwrap()
.contains("aren't its episodes"),
"{done:#}"
);
}
#[tokio::test]
async fn warns_about_missing_users_and_reapplies_their_watch_state_later() {
let (cloud, home) = pair(seed_movie).await;
// Cloud has a second user, Bob, whom home doesn't know yet.
cloud.fake.add_user("u2", "Bob");
let movie = cloud.fake.find("Movie", "Alien").unwrap();
cloud.fake.set_user_data(&movie, json!({"Played": true}));
cloud
.fake
.set_user_data_for("u2", &movie, json!({"PlaybackPositionTicks": 777}));
// Before moving, the UI can see whose watch history won't carry over,
// whichever side it asks from.
let check = get(
&cloud.url,
&format!("/api/moves/check?from=local&item_id={movie}"),
)
.await;
assert_eq!(check["watchers"], json!(["Alice", "Bob"]));
assert_eq!(check["missing_users"], json!(["Bob"]));
let check = get(
&home.url,
&format!("/api/moves/check?from=peer&item_id={movie}"),
)
.await;
assert_eq!(check["missing_users"], json!(["Bob"]));
// A dry run says so too.
let dry: Value = post(
&cloud.url,
"/api/moves",
json!({"from": "local", "item_id": movie, "name": "Alien", "dry_run": true}),
)
.await
.json()
.await
.unwrap();
let dry = wait_job(&cloud.url, dry["id"].as_str().unwrap()).await;
assert_eq!(dry["status"]["kind"], "Planned");
assert_eq!(dry["missing_users"], json!(["Bob"]));
assert!(
dry["log"]
.as_array()
.unwrap()
.iter()
.any(|l| l.as_str().unwrap().contains("won't carry over for Bob")),
"{dry:#}"
);
// The move goes ahead; Alice's watch state follows, Bob's is kept.
let job = move_item(&cloud.url, "local", &movie, "Alien").await;
assert_eq!(job["missing_users"], json!(["Bob"]));
let new_id = home.fake.find("Movie", "Alien").unwrap();
assert_eq!(home.fake.get_user_data(&new_id).unwrap()["Played"], true);
let id = job["id"].as_str().unwrap();
// Re-applying before Bob has an account explains what to do.
let r = post(&cloud.url, &format!("/api/jobs/{id}/reapply"), json!({})).await;
assert!(!r.status().is_success());
let text = r.text().await.unwrap();
assert!(
text.contains("no user called Bob on home yet; create them in Jellyfin on home first"),
"{text}"
);
assert!(!text.contains("HTTP 502"), "{text}");
// Alice carries on watching on home in the meantime.
home.fake
.set_user_data(&new_id, json!({"Played": true, "PlayCount": 5}));
// Once home has a "bob" (names match ignoring case), re-apply from the
// cloud UI: the job runs on home, so the request is passed on.
home.fake.add_user("u9", "bob");
let r = post(&cloud.url, &format!("/api/jobs/{id}/reapply"), json!({})).await;
assert!(r.status().is_success(), "{}", r.text().await.unwrap());
let job: Value = r.json().await.unwrap();
assert_eq!(job["missing_users"], json!([]));
assert_eq!(
home.fake.get_user_data_for("u9", &new_id).unwrap()["PlaybackPositionTicks"],
777
);
// Alice's newer watch state wasn't overwritten by the old snapshot.
assert_eq!(home.fake.get_user_data(&new_id).unwrap()["PlayCount"], 5);
// Nothing left to re-apply.
let r = post(&home.url, &format!("/api/jobs/{id}/reapply"), json!({})).await;
assert!(r.text().await.unwrap().contains("no skipped watch history"));
}
#[tokio::test]
async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() {
let (cloud, _home) = pair(|_| {}).await;
+114 -9
View File
@@ -34,7 +34,10 @@ struct FakeItem {
kind: &'static str,
path: String,
parent: String,
/// The series a season or episode belongs to.
series: Option<String>,
season: Option<i32>,
/// Episode number, or a season's own number.
episode: Option<i32>,
}
@@ -44,6 +47,8 @@ pub struct Fake {
items: Arc<Mutex<Vec<FakeItem>>>,
/// (user id, item id) → UserData JSON
pub user_data: Arc<Mutex<HashMap<(String, String), Value>>>,
/// (user id, name)
users: Arc<Mutex<Vec<(String, String)>>>,
}
pub fn id_for(path: &Path) -> String {
@@ -100,6 +105,7 @@ impl Fake {
libs: Arc::new(libs),
items: Default::default(),
user_data: Default::default(),
users: Arc::new(Mutex::new(vec![("u1".into(), "Alice".into())])),
};
f.scan();
f
@@ -133,6 +139,7 @@ impl Fake {
kind: "Movie",
path: f.display().to_string(),
parent: lib.id(),
series: None,
season: None,
episode: None,
});
@@ -145,25 +152,74 @@ impl Fake {
kind: "Series",
path: folder.display().to_string(),
parent: lib.id(),
series: None,
season: None,
episode: None,
});
// Like Jellyfin: a season per season folder, holding its
// episodes; episodes loose in the show folder hang off
// the series.
let mut seasons: Vec<(PathBuf, i32, String)> = Vec::new();
for f in files
.iter()
.filter(|f| f.extension().is_some_and(|e| e == "mkv"))
{
let fname = f.file_name().unwrap().to_string_lossy();
if let Some((s, e)) = parse_sxxexx(&fname) {
let Some((s, e)) = parse_sxxexx(&fname) else {
continue;
};
let in_folder = f
.strip_prefix(&folder)
.ok()
.and_then(|r| r.components().next())
.map(|c| folder.join(c))
.filter(|p| p.is_dir());
// The folder name gives the season's number ("Season 02",
// "Specials"); an episode filed under the wrong season
// doesn't belong to it.
let folder_number = |p: &Path| {
let n = p.file_name()?.to_string_lossy().to_lowercase();
if n == "specials" {
return Some(0);
}
n.chars()
.filter(|c| c.is_ascii_digit())
.collect::<String>()
.parse::<i32>()
.ok()
};
let parent = match in_folder {
Some(season_folder) if folder_number(&season_folder) == Some(s) => {
let id = id_for(&season_folder);
if !seasons.iter().any(|(p, _, _)| p == &season_folder) {
seasons.push((season_folder, s, id.clone()));
}
id
}
_ => series_id.clone(),
};
items.push(FakeItem {
id: id_for(f),
name: fname.to_string(),
kind: "Episode",
path: f.display().to_string(),
parent: series_id.clone(),
parent,
series: Some(series_id.clone()),
season: Some(s),
episode: Some(e),
});
}
for (path, n, id) in seasons {
items.push(FakeItem {
id,
name: if n == 0 { "Specials".into() } else { format!("Season {n}") },
kind: "Season",
path: path.display().to_string(),
parent: series_id.clone(),
series: Some(series_id.clone()),
season: None,
episode: Some(n),
});
}
}
}
@@ -186,10 +242,44 @@ impl Fake {
.lock()
.unwrap()
.iter()
.find(|i| i.parent == series_id && i.season == Some(season) && i.episode == Some(ep))
.find(|i| {
i.kind == "Episode"
&& i.series.as_deref() == Some(&series_id)
&& i.season == Some(season)
&& i.episode == Some(ep)
})
.map(|i| i.id.clone())
}
pub fn season_id(&self, series: &str, season: i32) -> Option<String> {
let series_id = self.find("Series", series)?;
self.items
.lock()
.unwrap()
.iter()
.find(|i| i.kind == "Season" && i.parent == series_id && i.episode == Some(season))
.map(|i| i.id.clone())
}
pub fn add_user(&self, id: &str, name: &str) {
self.users.lock().unwrap().push((id.into(), name.into()));
}
pub fn set_user_data_for(&self, user: &str, item: &str, data: Value) {
self.user_data
.lock()
.unwrap()
.insert((user.into(), item.into()), data);
}
pub fn get_user_data_for(&self, user: &str, item: &str) -> Option<Value> {
self.user_data
.lock()
.unwrap()
.get(&(user.to_string(), item.to_string()))
.cloned()
}
pub fn set_user_data(&self, item: &str, data: Value) {
self.user_data
.lock()
@@ -213,10 +303,7 @@ impl Fake {
Json(json!({"ServerName": "fake", "Version": "10.11.0", "Id": "x"}))
}),
)
.route(
"/Users",
get(|| async { Json(json!([{"Id": "u1", "Name": "Alice"}])) }),
)
.route("/Users", get(users))
.route("/Library/VirtualFolders", get(virtual_folders))
.route("/Items", get(items))
.route("/Library/Media/Updated", post(media_updated))
@@ -229,6 +316,17 @@ impl Fake {
}
}
async fn users(State(f): State<Fake>) -> Json<Value> {
Json(Value::Array(
f.users
.lock()
.unwrap()
.iter()
.map(|(id, name)| json!({"Id": id, "Name": name}))
.collect(),
))
}
async fn virtual_folders(State(f): State<Fake>) -> Json<Value> {
Json(Value::Array(
f.libs
@@ -250,7 +348,14 @@ async fn items(State(f): State<Fake>, Query(q): Query<HashMap<String, String>>)
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| {
// Recursive queries under a series also reach its episodes,
// which hang off their seasons.
let recursive = q.get("recursive").is_some_and(|r| r == "true");
q.get("parentId").is_none_or(|p| {
&i.parent == p || (recursive && i.series.as_deref() == Some(p.as_str()))
})
})
.filter(|i| types.as_ref().is_none_or(|t| t.contains(&i.kind)))
.filter(|i| {
q.get("searchTerm")
@@ -258,7 +363,7 @@ async fn items(State(f): State<Fake>, Query(q): Query<HashMap<String, String>>)
})
.map(|i| {
let mut v = json!({"Id": i.id, "Name": i.name, "Type": i.kind, "Path": i.path,
"ParentIndexNumber": i.season, "IndexNumber": i.episode,
"ParentIndexNumber": i.season, "IndexNumber": i.episode, "SeriesId": i.series,
"MediaSources": [{"Path": i.path}]});
if let Some(u) = user {
v["UserData"] = ud
+1 -1
View File
@@ -6,7 +6,7 @@ license.workspace = true
rust-version.workspace = true
[dependencies]
jm-core = { version = "0.1.0", path = "../jm-core" }
jm-core = { path = "../jm-core" }
rusqlite = { version = "0.40.2", features = ["bundled"] }
serde = "1.0.229"
serde_json = "1.0.154"
+100
View File
@@ -3,6 +3,7 @@
//! Jobs and exports are stored as JSON documents with a few indexed columns.
//! The schema is deliberately small; the job struct is the source of truth.
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
@@ -33,6 +34,11 @@ const MIGRATIONS: &[&str] = &[
id TEXT PRIMARY KEY,
body TEXT NOT NULL
);",
// v2: cached sizes of item folders, keyed by local path.
"CREATE TABLE folder_sizes (
path TEXT PRIMARY KEY,
body TEXT NOT NULL
);",
];
#[derive(Clone)]
@@ -161,6 +167,54 @@ impl Store {
body.map(|b| serde_json::from_str(&b).map_err(Into::into))
.transpose()
}
/// Cached folder sizes for `paths`. Paths with no record are left out.
pub async fn get_folder_sizes<T: DeserializeOwned>(
&self,
paths: Vec<String>,
) -> Result<HashMap<String, T>> {
let rows: Vec<(String, String)> = self
.with(move |c| {
let mut out = Vec::new();
let mut stmt = c.prepare_cached("SELECT path, body FROM folder_sizes WHERE path = ?1")?;
for p in &paths {
if let Some(row) = stmt
.query_row([p], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?
{
out.push(row);
}
}
Ok(out)
})
.await?;
rows.into_iter()
.map(|(p, b)| Ok((p, serde_json::from_str(&b)?)))
.collect()
}
pub async fn put_folder_size<T: Serialize>(&self, path: &str, size: &T) -> Result<()> {
let path = path.to_string();
let body = serde_json::to_string(size)?;
self.with(move |c| {
c.execute(
"INSERT INTO folder_sizes (path, body) VALUES (?1, ?2)
ON CONFLICT(path) DO UPDATE SET body = excluded.body",
params![path, body],
)?;
Ok(())
})
.await
}
pub async fn delete_folder_size(&self, path: &str) -> Result<()> {
let path = path.to_string();
self.with(move |c| {
c.execute("DELETE FROM folder_sizes WHERE path = ?1", [path])?;
Ok(())
})
.await
}
}
#[cfg(test)]
@@ -205,4 +259,50 @@ mod tests {
let e: serde_json::Value = s.get_export("e1").await.unwrap().unwrap();
assert_eq!(e["x"], 1);
}
#[tokio::test]
async fn folder_sizes_roundtrip() {
let store = Store::in_memory().unwrap();
store
.put_folder_size("/m/A", &serde_json::json!({"bytes": 1}))
.await
.unwrap();
store
.put_folder_size("/m/A", &serde_json::json!({"bytes": 2}))
.await
.unwrap();
store
.put_folder_size("/m/B", &serde_json::json!({"bytes": 3}))
.await
.unwrap();
let got: HashMap<String, serde_json::Value> = store
.get_folder_sizes(vec!["/m/A".into(), "/m/B".into(), "/m/C".into()])
.await
.unwrap();
assert_eq!(got.len(), 2);
assert_eq!(got["/m/A"]["bytes"], 2);
store.delete_folder_size("/m/A").await.unwrap();
let got: HashMap<String, serde_json::Value> =
store.get_folder_sizes(vec!["/m/A".into()]).await.unwrap();
assert!(got.is_empty());
}
#[test]
fn upgrades_a_v1_database() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("state.db");
{
let c = Connection::open(&path).unwrap();
c.execute_batch(MIGRATIONS[0]).unwrap();
c.pragma_update(None, "user_version", 1).unwrap();
}
Store::open(&path).unwrap();
let c = Connection::open(&path).unwrap();
let v: i64 = c
.pragma_query_value(None, "user_version", |r| r.get(0))
.unwrap();
assert_eq!(v as usize, MIGRATIONS.len());
c.execute("INSERT INTO folder_sizes (path, body) VALUES ('p', '{}')", [])
.unwrap();
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ blake3 = { version = "1.8.7", features = ["mmap", "rayon"] }
bytes = "1.12.1"
futures = "0.3.34"
governor = "0.10.4"
jm-core = { version = "0.1.0", path = "../jm-core" }
jm-core = { path = "../jm-core" }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "stream", "http2"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
+1 -1
View File
@@ -12,7 +12,7 @@ pub mod promote;
pub mod pull;
pub mod serve;
pub use manifest::{build_manifest, hash_file, list_relative};
pub use manifest::{build_manifest, build_manifest_filtered, hash_file, list_relative};
pub use promote::{part_path, partial_dir, prepare_partial, promote};
pub use pull::{Puller, PullerOptions};
pub use serve::range_response;
+29 -1
View File
@@ -20,8 +20,19 @@ pub async fn hash_file(path: &Path) -> Result<String, TransferError> {
/// them sorted by relative path. Symlinks and jellymove's own hidden folders
/// are skipped.
pub async fn build_manifest(root: &Path) -> Result<Manifest, TransferError> {
build_manifest_filtered(root, |_| true).await
}
/// Like [`build_manifest`], but only for files whose relative path passes
/// `keep`, e.g. one season's folder plus the show's loose files.
pub async fn build_manifest_filtered(
root: &Path,
keep: impl Fn(&str) -> bool + Send + 'static,
) -> Result<Manifest, TransferError> {
let root_owned = root.to_path_buf();
let listed = tokio::task::spawn_blocking(move || list_files(&root_owned))
let listed = tokio::task::spawn_blocking(move || {
list_files(&root_owned).map(|l| l.into_iter().filter(|(rel, _, _)| keep(rel)).collect::<Vec<_>>())
})
.await
.expect("list task panicked")?;
@@ -101,4 +112,21 @@ mod tests {
blake3::hash(b"video").to_hex().to_string()
);
}
#[tokio::test]
async fn filtered_manifest_keeps_only_matching_files() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for f in ["tvshow.nfo", "Season 01/a.mkv", "Season 02/b.mkv"] {
std::fs::create_dir_all(root.join(f).parent().unwrap()).unwrap();
std::fs::write(root.join(f), b"x").unwrap();
}
let m = build_manifest_filtered(root, |rel| {
!rel.contains('/') || rel.starts_with("Season 02/")
})
.await
.unwrap();
let names: Vec<_> = m.files.iter().map(|f| f.rel_path.as_str()).collect();
assert_eq!(names, ["Season 02/b.mkv", "tvshow.nfo"]);
}
}
+12 -3
View File
@@ -29,16 +29,25 @@ pub async fn prepare_partial(partial: &Path) -> Result<(), TransferError> {
Ok(())
}
/// Rename every verified `.part` into `target_folder`. Safe to run again after
/// Rename every verified `.part` into `target_folder`, except the manifest
/// entries listed in `skip` (which were never copied). Safe to run again after
/// a crash: files already in place (part gone, target present with the right
/// size) are skipped. Refuses to overwrite anything it didn't put there.
pub async fn promote(
partial: &Path,
target_folder: &Path,
manifest: &Manifest,
skip: &[usize],
) -> Result<(), TransferError> {
let wanted = || {
manifest
.files
.iter()
.enumerate()
.filter(|(idx, _)| !skip.contains(idx))
};
// Check every destination first so we never half-promote into a clash.
for (idx, entry) in manifest.files.iter().enumerate() {
for (idx, entry) in wanted() {
let dest = join_relative(target_folder, &entry.rel_path)
.ok_or_else(|| TransferError::UnsafePath(entry.rel_path.clone()))?;
let part_exists = tokio::fs::metadata(part_path(partial, idx)).await.is_ok();
@@ -47,7 +56,7 @@ pub async fn promote(
}
}
for (idx, entry) in manifest.files.iter().enumerate() {
for (idx, entry) in wanted() {
let part = part_path(partial, idx);
let dest = join_relative(target_folder, &entry.rel_path).expect("checked above");
match tokio::fs::metadata(&part).await {
+35 -3
View File
@@ -119,7 +119,7 @@ async fn pull_all(fx: &Fixture, p: &Puller) -> PathBuf {
.unwrap();
}
let target = lib_root.join("Alien (1979)");
promote(&partial, &target, &manifest).await.unwrap();
promote(&partial, &target, &manifest, &[]).await.unwrap();
target
}
@@ -200,7 +200,7 @@ async fn refuses_to_overwrite_existing_files() {
.await
.unwrap();
}
let err = promote(&partial, &target, &manifest).await.unwrap_err();
let err = promote(&partial, &target, &manifest, &[]).await.unwrap_err();
assert!(matches!(err, jm_transfer::TransferError::Exists(_)));
// Nothing was moved: the stranger's file is untouched and no video landed.
assert_eq!(
@@ -216,11 +216,43 @@ async fn promote_is_idempotent() {
let target = pull_all(&fx, &puller()).await;
let manifest = build_manifest(&fx.src.root).await.unwrap();
// A second promote after a "crash" finds everything already in place.
promote(&partial_dir(fx.dst_dir.path(), "job1"), &target, &manifest)
promote(&partial_dir(fx.dst_dir.path(), "job1"), &target, &manifest, &[])
.await
.unwrap();
}
#[tokio::test]
async fn promote_leaves_skipped_files_alone() {
let fx = fixture().await;
let manifest = build_manifest(&fx.src.root).await.unwrap();
let nfo = manifest
.files
.iter()
.position(|f| f.rel_path == "Alien (1979).nfo")
.unwrap();
// The target already has its own NFO; that entry is skipped and never copied.
let target = fx.dst_dir.path().join("Alien (1979)");
std::fs::create_dir_all(&target).unwrap();
std::fs::write(target.join("Alien (1979).nfo"), b"mine").unwrap();
let partial = partial_dir(fx.dst_dir.path(), "job1");
prepare_partial(&partial).await.unwrap();
let p = puller();
for (idx, entry) in manifest.files.iter().enumerate() {
if idx == nfo {
continue;
}
let url = format!("{}/files/{idx}", fx.base);
p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {})
.await
.unwrap();
}
promote(&partial, &target, &manifest, &[nfo]).await.unwrap();
assert_eq!(std::fs::read(target.join("Alien (1979).nfo")).unwrap(), b"mine");
assert!(target.join("Alien (1979).mkv").exists());
// And it's still idempotent.
promote(&partial, &target, &manifest, &[nfo]).await.unwrap();
}
#[tokio::test]
async fn bandwidth_limit_is_applied() {
let fx = fixture().await;
+21 -4
View File
@@ -14,12 +14,29 @@ services:
ports:
- "8097:8097"
volumes:
- ./jellymove.toml:/config/jellymove.toml:ro
- ./jellymove-data:/data # must be writable by `user:` above
- /srv/media/movies:/media/movies # ← match your jellyfin service
- /srv/media/tv:/media/tv
# Every setting in config.example.toml works here as JELLYMOVE_<KEY>, with
# "__" between a section and its key. A value made only of digits needs
# inner quotes ('"123456"'), or it's read as a number. To keep secrets out
# of this file, put them in a .env file next to it and write ${NAME} here.
environment:
# Secrets can come from the environment instead of the file:
# JELLYMOVE_JELLYFIN__API_KEY: ...
# JELLYMOVE_PEER__TOKEN: ...
JELLYMOVE_NODE_NAME: home
JELLYMOVE_DATA_DIR: /data # the jellymove-data volume above
JELLYMOVE_JELLYFIN__URL: http://jellyfin:8096
# Jellyfin → Dashboard → API Keys. Needs an admin key.
JELLYMOVE_JELLYFIN__API_KEY: replace-me
# The other agent. Both sides use the same token (openssl rand -hex 32).
JELLYMOVE_PEER__URL: https://cloud.example.com
JELLYMOVE_PEER__TOKEN: replace-me
# Protect the web UI unless the port is only reachable privately.
JELLYMOVE_UI__USERNAME: admin
JELLYMOVE_UI__PASSWORD: replace-me
JELLYMOVE_LOG: info
# Optional. Incoming cap in megabits per second (0 = unlimited):
# JELLYMOVE_TRANSFER__BANDWIDTH_LIMIT_MBPS: 200
# Optional. File items from the peer's "TV Shows" library into "Series":
# JELLYMOVE_INCOMING_LIBRARIES: '{"TV Shows"="Series"}'
# Optional. Only if jellymove sees media at different paths from Jellyfin:
# JELLYMOVE_PATH_MAP: '[{jellyfin="/media",local="/mnt/user/media"}]'
+23 -1
View File
@@ -35,11 +35,15 @@ forwarding.
|---|---|
| `GET /info` | Node name, version, Jellyfin version |
| `GET /libraries`, `GET /items?library=&search=` | Browse the peer's Jellyfin |
| `GET /seasons?series=` | A show's seasons, with each one's folder if it has its own |
| `GET /users`, `GET /watchers?item=` | User names; users with watch state for an item. Used to warn before a move whose watch history wouldn't carry over |
| `POST /exports {item_id}` | Source: start checking, hashing and capturing user data. Idempotent per item. |
| `GET /exports/{id}` | Poll: `Preparing` → `Ready` (with `ExportInfo`) or `Failed` |
| `GET /exports/{id}/files/{idx}` | Range-capable download of manifest entry `idx` |
| `POST /exports/{id}/complete` | Source: move folder to trash and rescan. Idempotent. |
| `POST /exports/{id}/complete {job_id?, moved_to?}` | Source: move folder to a new trash entry and rescan. Idempotent. |
| `GET /trash`, `POST /trash/empty {ids}` | List the source's trash entries; delete entries by ID (never by path) |
| `POST /jobs`, `GET /jobs` | Create or list jobs on the peer (destination) |
| `POST /jobs/{id}/reapply` | Apply the watch state of users who had no account when the move ran (`Job.missing_users`), once they do |
## Job stages
@@ -67,11 +71,29 @@ Retrying a failed job re-runs from its stage. Interrupted jobs resume on start.
- Alternatives kept open behind the pull/serve split: iroh (QUIC, NAT
traversal) once iroh-blobs reaches 1.0; rclone as a pluggable transport.
## Folder sizes
Library items carry the size of their folder on disk, counting the same files a
move copies. Each agent measures its own folders (`sizes.rs`): listing a library
returns cached sizes at once and queues every folder for a single background
worker, so a NAS is never asked to walk several folders at once. A cached size
is kept while the folder's signature (modified times of the folder and its
direct subfolders) is unchanged, re-checked at most hourly, and measured again
after seven days regardless. The UI polls the list until every size is in.
## Jellyfin integration
- Browse: `GET /Items?parentId=<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.
- Seasons: `includeItemTypes=Season` under the series. A season export's folder
is the show's; its manifest holds only `<season folder>/…` plus the show's
loose non-video files (`SeasonInfo.show_files`). The destination finds the
show by provider ID, then name, and skips those show files if it already has
the show. A season's own user data isn't carried (it would land on the
whole show); its episodes' is. After the last season leaves, the source
moves what remains of the show folder into the same trash entry, but only if
no videos are left in it.
- Rescan: `POST /Library/Media/Updated` for the exact folder, then poll. The
first update can be lost, so it is re-sent halfway through the timeout.
- Finding the new item: by **path**, since we know exactly where we put it.
+12 -3
View File
@@ -4,8 +4,10 @@
import Library from './lib/Library.svelte';
import Jobs from './lib/Jobs.svelte';
import StatusView from './lib/StatusView.svelte';
import Trash from './lib/Trash.svelte';
import { watchMoves } from './lib/moves.svelte';
type Tab = 'library' | 'jobs' | 'status';
type Tab = 'library' | 'jobs' | 'trash' | 'status';
let tab = $state<Tab>('library');
let status = $state<Status | null>(null);
let statusError = $state<string | null>(null);
@@ -22,7 +24,11 @@
onMount(() => {
loadStatus();
const t = setInterval(loadStatus, 30_000);
return () => clearInterval(t);
const stopWatching = watchMoves();
return () => {
clearInterval(t);
stopWatching();
};
});
const localName = $derived(status?.node.node_name ?? 'this server');
@@ -48,6 +54,7 @@
<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 === 'trash'} onclick={() => (tab = 'trash')}>Trash</button>
<button class:active={tab === 'status'} onclick={() => (tab = 'status')}>
Status
{#if status && !healthy}<span class="dot warn" title="Something needs attention"></span>{/if}
@@ -61,9 +68,11 @@
{/if}
{#if tab === 'library'}
<Library {localName} {peerName} onmoved={() => (tab = 'jobs')} />
<Library {localName} {peerName} />
{:else if tab === 'jobs'}
<Jobs {localName} />
{:else if tab === 'trash'}
<Trash {localName} {peerName} />
{:else}
<StatusView {status} reload={loadStatus} />
{/if}
+49 -32
View File
@@ -1,52 +1,37 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, bytes, STAGE_LABEL, STAGES, type Job } from './api';
import { moves, trackMove } from './moves.svelte';
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 retryError = $state<string | null>(null);
let reapplying = $state<string | null>(null);
let open = $state<Record<string, boolean>>({});
const sorted = $derived(Object.values(jobs).sort((a, b) => b.created.localeCompare(a.created)));
const sorted = $derived(Object.values(moves.jobs).sort((a, b) => b.created.localeCompare(a.created)));
const error = $derived(retryError ?? moves.error);
async function load() {
async function reapply(id: string) {
reapplying = id;
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;
trackMove(await api.reapply(id));
retryError = null;
} catch (e) {
error = (e as Error).message;
retryError = (e as Error).message;
} finally {
reapplying = null;
}
}
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);
trackMove(await api.retry(id));
retryError = null;
} catch (e) {
error = (e as Error).message;
retryError = (e as Error).message;
}
}
@@ -75,9 +60,9 @@
</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 moves.peerError}<p class="panel msg muted">Couldn't load moves running on the peer: {moves.peerError}</p>{/if}
{#if !sorted.length}
{#if moves.loaded && !sorted.length}
<p class="panel empty muted">No moves yet. Pick something in Library to get started.</p>
{/if}
@@ -125,6 +110,21 @@
<p class="error why">{j.status.detail}</p>
{/if}
{#if j.missing_users?.length}
{@const one = j.missing_users.length === 1}
{@const done = j.status.kind === 'Done'}
<div class="missing">
<p>
Watch history {done ? "didn't" : "won't"} carry over for <strong>{j.missing_users.join(', ')}</strong>:
{j.target_node} has no user with {one ? 'that name' : 'those names'}.
{#if done}Create {one ? 'the user' : 'them'} in Jellyfin on {j.target_node}, then re-apply it.{/if}
</p>
{#if done}
<button disabled={reapplying === j.id} onclick={() => reapply(j.id)}>Re-apply watch history</button>
{/if}
</div>
{/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>
@@ -257,6 +257,23 @@
margin: 0.7rem 0 0;
font-size: 0.9rem;
}
.missing {
margin-top: 0.7rem;
padding: 0.6rem 0.8rem;
border: 1px solid color-mix(in srgb, var(--local) 55%, var(--line));
border-radius: 8px;
font-size: 0.9rem;
display: flex;
gap: 0.8rem;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
}
.missing p {
margin: 0;
flex: 1;
min-width: 16rem;
}
.logtoggle {
margin-top: 0.7rem;
font-size: 0.8rem;
+347 -15
View File
@@ -1,13 +1,13 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, type Library, type LibraryItem, type Side } from './api';
import { api, bytes, type Library, type LibraryItem, type Movable, type SeasonItem, type Side } from './api';
import { moves, onMoveDone, trackMove } from './moves.svelte';
interface Props {
localName: string;
peerName: string;
onmoved: () => void;
}
let { localName, peerName, onmoved }: Props = $props();
let { localName, peerName }: Props = $props();
let side = $state<Side>('local');
let libraries = $state<Library[]>([]);
@@ -18,44 +18,174 @@
let error = $state<string | null>(null);
let busy = $state<string | null>(null); // item id being submitted
let notice = $state<string | null>(null);
let sort = $state<'name' | 'size'>('name');
let open = $state<Record<string, boolean>>({}); // shows with seasons expanded
type Seasons = { loading: true } | { error: string } | { list: SeasonItem[] };
let seasons = $state<Record<string, Seasons>>({});
const sourceName = $derived(side === 'local' ? localName : peerName);
const destName = $derived(side === 'local' ? peerName : localName);
const shown = $derived(
sort === 'size' ? [...items].sort((a, b) => (b.size?.bytes ?? -1) - (a.size?.bytes ?? -1)) : items,
);
const total = $derived(items.reduce((n, i) => n + (i.size?.bytes ?? 0), 0));
// Sizes are worked out in the background on the server that has the
// files; ask again until they've all arrived.
// Items with a move under way, or one that finished recently but that the
// source's Jellyfin still lists (it drops them after its own rescan).
const RECENT_MS = 15 * 60_000;
type Mark = { moving: boolean; to: string };
const marks = $derived.by(() => {
const out: Record<string, Mark> = {};
const now = Date.now();
for (const j of Object.values(moves.jobs)) {
if (j.dry_run || j.source_node !== sourceName) continue;
const active = j.status.kind === 'Queued' || j.status.kind === 'Running';
if (active) {
out[j.source_item_id] = { moving: true, to: j.target_node };
} else if (j.status.kind === 'Done' && now - Date.parse(j.updated) < RECENT_MS) {
out[j.source_item_id] ??= { moving: false, to: j.target_node };
}
}
return out;
});
let poll: ReturnType<typeof setTimeout> | undefined;
let recheck: ReturnType<typeof setTimeout> | undefined;
let rechecks = 0;
let generation = 0;
function stopPolling() {
clearTimeout(poll);
clearTimeout(recheck);
poll = undefined;
recheck = undefined;
}
/** While a moved item is still listed, look again every 20 s for a few minutes. */
function recheckMoved(gen: number) {
if (rechecks >= 12 || !items.some(gone)) return;
rechecks++;
recheck = setTimeout(() => {
if (gen === generation) loadItems();
}, 20_000);
}
/** An item that has moved away: its folder is gone, so it has no size to wait for. */
const gone = (i: LibraryItem) => !!marks[i.id] && !marks[i.id].moving;
const measuring = $derived(items.filter((i) => !i.size && !gone(i)).length);
function pollSizes(gen: number, attempt = 0) {
clearTimeout(poll);
if (!items.some((i) => !i.size && !gone(i)) || attempt >= 150) return;
poll = setTimeout(async () => {
try {
const fresh = await api.items(side, libraryId, search.trim());
if (gen !== generation) return;
const byId = Object.fromEntries(fresh.map((i) => [i.id, i.size]));
items = items.map((i) => (i.size ? i : { ...i, size: byId[i.id] ?? null }));
} catch {
/* keep what we have; try again */
}
if (gen === generation) pollSizes(gen, attempt + 1);
}, 2000);
}
async function toggleSeasons(item: LibraryItem) {
open[item.id] = !open[item.id];
const have = seasons[item.id];
if (!open[item.id] || (have && 'list' in have)) return;
seasons[item.id] = { loading: true };
await loadSeasons(item.id);
}
async function loadSeasons(id: string) {
try {
const list = await api.seasons(side, id);
if (open[id]) seasons[id] = { list };
} catch (e) {
if (open[id]) seasons[id] = { error: (e as Error).message };
}
}
function partFor(item: LibraryItem, s: SeasonItem) {
return item.size?.parts.find((p) => p.name === s.folder);
}
/** Folders in the show that aren't a season Jellyfin knows, e.g. extras. */
function otherParts(item: LibraryItem, list: SeasonItem[]) {
return (item.size?.parts ?? []).filter((p) => !list.some((s) => s.folder === p.name));
}
function loose(item: LibraryItem): number {
if (!item.size) return 0;
return item.size.bytes - item.size.parts.reduce((n, p) => n + p.bytes, 0);
}
const fileCount = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`;
async function loadLibraries(s: Side) {
generation++;
stopPolling();
error = null;
items = [];
libraries = [];
try {
libraries = await api.libraries(s);
const prev = libraryId;
libraryId = libraries[0]?.id ?? '';
// Same library ID on the other server: the effect won't fire, so load here.
if (libraryId === prev) loadItems();
} catch (e) {
error = (e as Error).message;
}
}
async function loadItems() {
stopPolling();
const gen = ++generation;
if (!libraryId) return;
loading = true;
error = null;
try {
items = await api.items(side, libraryId, search.trim());
const got = await api.items(side, libraryId, search.trim());
if (gen !== generation) return;
items = got;
pollSizes(gen);
recheckMoved(gen);
} catch (e) {
if (gen !== generation) return;
error = (e as Error).message;
items = [];
} finally {
loading = false;
if (gen === generation) loading = false;
}
}
function choose(s: Side) {
if (s === side) return;
side = s;
open = {};
seasons = {};
loadLibraries(s);
}
onMount(() => {
loadLibraries(side);
// When a move to or from the server being browsed finishes, show the
// result: the item leaves the source and appears on the destination.
const unsubscribe = onMoveDone((job) => {
if (job.source_node !== sourceName && job.target_node !== sourceName) return;
rechecks = 0;
loadItems();
for (const id of Object.keys(open)) if (open[id]) loadSeasons(id);
});
return () => {
unsubscribe();
generation++;
stopPolling();
};
});
// Reload items when the library or search text changes, debounced.
@@ -66,17 +196,32 @@
return () => clearTimeout(timer);
});
async function move(item: LibraryItem, dryRun: boolean) {
/** A move waiting for the user to accept that some watch history won't carry over. */
type Confirm = { item: Movable; missing: string[] };
let confirming = $state<Confirm | null>(null);
function names(list: string[]): string {
return list.length < 2 ? list.join('') : `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`;
}
async function move(item: Movable, dryRun: boolean, checked = false) {
busy = item.id;
notice = null;
error = null;
confirming = 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();
// Watch history is matched by user name; warn before it gets left behind.
if (!dryRun && !checked) {
const check = await api.checkMove(side, item);
if (check.missing_users.length) {
confirming = { item, missing: check.missing_users };
return;
}
}
trackMove(await api.move(side, item, dryRun));
notice = dryRun
? `Planning a dry run for “${item.name}”. Check Moves for the plan.`
: `Moving “${item.name}” to ${destName}. Follow its progress in Moves.`;
} catch (e) {
error = (e as Error).message;
} finally {
@@ -85,6 +230,30 @@
}
</script>
{#snippet missingUsers(c: Confirm)}
{@const one = c.missing.length === 1}
<div class="confirm-move" role="alertdialog" aria-label="Some watch history won't carry over">
<p>
<strong>{names(c.missing)}</strong>
{one ? 'has' : 'have'} watch history for this, but {destName} has no user with {one ? 'that name' : 'those names'}, so
it won't carry over. Create {one ? 'the user' : 'them'} in Jellyfin on {destName} first, or move anyway and re-apply
it later from Moves.
</p>
<div class="confirm-buttons">
<button class="primary" disabled={busy === c.item.id} onclick={() => move(c.item, false, true)}>Move anyway</button>
<button onclick={() => (confirming = null)}>Cancel</button>
</div>
</div>
{/snippet}
{#snippet moveTag(mark: Mark)}
{#if mark.moving}
<span class="tag moving">Moving to {mark.to}…</span>
{:else}
<span class="tag" title="{sourceName}'s Jellyfin will drop it from this list after its next scan">Moved to {mark.to}</span>
{/if}
{/snippet}
<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')}>
@@ -100,12 +269,22 @@
{/each}
</select>
<input type="search" placeholder="Search titles…" bind:value={search} aria-label="Search" />
<select bind:value={sort} aria-label="Sort by">
<option value="name">By name</option>
<option value="size">Largest first</option>
</select>
</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.
{#if items.length}
<span class="totals">
{items.length} {items.length === 1 ? 'item' : 'items'}, {bytes(total)}{#if measuring}
so far, measuring {measuring} more…{/if}
</span>
{/if}
</p>
{#if error}<p class="panel msg error">{error}</p>{/if}
@@ -117,22 +296,86 @@
{: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)}
{#each shown as item (item.id)}
<li>
<div class="row">
<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}
{#if item.kind === 'Series'}
<button class="disclose" aria-expanded={!!open[item.id]} onclick={() => toggleSeasons(item)}>
{open[item.id] ? 'Hide' : 'Show'} seasons
</button>
{/if}
</div>
<span class="size" title={item.size ? fileCount(item.size.files) : 'Working out the size…'}>
{#if item.size}{bytes(item.size.bytes)}{:else if !gone(item)}<span class="muted">measuring…</span>{/if}
</span>
<div class="actions">
{#if marks[item.id]}
{@render moveTag(marks[item.id])}
{:else}
<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>
{/if}
</div>
</div>
{#if confirming?.item.id === item.id}
{@render missingUsers(confirming)}
{/if}
{#if open[item.id]}
{@const st = seasons[item.id]}
{#if !st || 'loading' in st}
<p class="seasons-msg muted">Loading seasons…</p>
{:else if 'error' in st}
<p class="seasons-msg error">{st.error}</p>
{:else}
<table class="parts">
<tbody>
{#each st.list as season (season.id)}
{@const part = partFor(item, season)}
{@const what = { id: season.id, name: `${item.name} – ${season.name}` }}
<tr>
<td>{season.name}</td>
<td class="muted">{part ? fileCount(part.files) : ''}</td>
<td class="num">{part ? bytes(part.bytes) : ''}</td>
<td class="acts">
{#if marks[season.id]}
{@render moveTag(marks[season.id])}
{:else if season.path}
<button class="small" disabled={busy === season.id} onclick={() => move(what, true)} title="Check and plan without copying anything">
Dry run
</button>
<button class="small primary" disabled={busy === season.id} onclick={() => move(what, false)}>
Move season →
</button>
{:else}
<span class="muted small-text" title="Its episodes sit directly in the show folder">No folder of its own; move the whole show</span>
{/if}
</td>
</tr>
{#if confirming?.item.id === season.id}
<tr><td colspan="4" class="wrap">{@render missingUsers(confirming)}</td></tr>
{/if}
{:else}
<tr><td colspan="4" class="muted">Jellyfin lists no seasons for this show.</td></tr>
{/each}
{#each otherParts(item, st.list) as p (p.name)}
<tr class="muted"><td>{p.name}</td><td>{fileCount(p.files)}</td><td class="num">{bytes(p.bytes)}</td><td class="small-text">Moves with the whole show</td></tr>
{/each}
{#if loose(item) > 0}
<tr class="muted"><td>Show files (NFO, artwork)</td><td></td><td class="num">{bytes(loose(item))}</td><td class="small-text">Copied with a season if {destName} doesn't have the show</td></tr>
{/if}
</tbody>
</table>
{/if}
{/if}
</li>
{/each}
</ul>
@@ -192,17 +435,106 @@
padding: 0;
}
.list li {
padding: 0.7rem 1rem;
border-top: 1px solid var(--line);
}
.row {
display: flex;
align-items: center;
gap: 0.9rem;
padding: 0.7rem 1rem;
border-top: 1px solid var(--line);
}
.totals {
display: block;
margin-top: 0.2rem;
}
.size {
font-variant-numeric: tabular-nums;
white-space: nowrap;
min-width: 5.5rem;
text-align: right;
}
.disclose {
display: block;
margin-top: 0.25rem;
padding: 0;
border: none;
background: transparent;
color: var(--peer);
font-size: 0.82rem;
}
.parts {
margin: 0.5rem 0 0.1rem 3.5rem;
border-collapse: collapse;
font-size: 0.88rem;
}
.parts td {
padding: 0.2rem 1.2rem 0.2rem 0;
}
.parts .num {
text-align: right;
font-variant-numeric: tabular-nums;
}
.parts td {
vertical-align: middle;
white-space: nowrap;
}
.parts td.small-text {
white-space: normal;
}
.parts .acts {
padding-right: 0;
white-space: nowrap;
}
.confirm-move {
margin: 0.6rem 0 0.1rem 3.5rem;
padding: 0.7rem 0.9rem;
border: 1px solid color-mix(in srgb, var(--local) 55%, var(--line));
border-radius: 8px;
font-size: 0.9rem;
white-space: normal;
}
.parts .confirm-move {
margin-left: 0;
}
.parts td.wrap {
white-space: normal;
}
.confirm-move p {
margin: 0;
}
.confirm-buttons {
display: flex;
gap: 0.4rem;
margin-top: 0.6rem;
}
.tag {
font-size: 0.82rem;
border: 1px solid var(--line);
border-radius: 6px;
padding: 0.2rem 0.55rem;
color: var(--muted);
white-space: nowrap;
}
.tag.moving {
color: var(--peer);
border-color: color-mix(in srgb, var(--peer) 50%, var(--line));
}
.seasons-msg {
margin: 0.5rem 0 0 3.5rem;
font-size: 0.88rem;
}
button.small {
padding: 0.2rem 0.6rem;
font-size: 0.82rem;
}
.small-text {
font-size: 0.8rem;
}
.list li:first-child {
border-top: none;
}
.empty {
justify-content: center;
text-align: center;
padding: 2rem !important;
}
.kind {
+288
View File
@@ -0,0 +1,288 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, bytes, type Side, type TrashEntry } from './api';
interface Props {
localName: string;
peerName: string;
}
let { localName, peerName }: Props = $props();
let side = $state<Side>('local');
let entries = $state<TrashEntry[]>([]);
let loading = $state(false);
let error = $state<string | null>(null);
let notice = $state<string | null>(null);
/** What's waiting for a second click: an entry ID, `lib:<name>` or `all`. */
let confirming = $state<string | null>(null);
let busy = $state(false);
const nodeName = $derived(side === 'local' ? localName : peerName);
const total = $derived(entries.reduce((n, e) => n + e.size, 0));
const groups = $derived(
[...new Set(entries.map((e) => e.library))].map((library) => {
const items = entries.filter((e) => e.library === library);
return { library, items, size: items.reduce((n, e) => n + e.size, 0) };
}),
);
async function load() {
loading = true;
error = null;
confirming = null;
try {
entries = await api.trash(side);
} catch (e) {
error = (e as Error).message;
entries = [];
} finally {
loading = false;
}
}
function choose(s: Side) {
if (s === side) return;
side = s;
notice = null;
entries = [];
load();
}
onMount(load);
async function empty(ids: string[], what: string) {
busy = true;
error = null;
notice = null;
try {
const r = await api.emptyTrash(side, ids);
notice = r.removed
? `Emptied ${what} on ${nodeName}, freeing ${bytes(r.freed)}.`
: `Nothing to empty: ${what} had already gone.`;
} catch (e) {
error = (e as Error).message;
} finally {
busy = false;
confirming = null;
await load();
}
}
function when(iso: string | null): string {
if (!iso) return 'an unknown date';
return new Date(iso).toLocaleString('en-GB', { dateStyle: 'medium', timeStyle: 'short' });
}
function kindLabel(e: TrashEntry): string {
if (e.kind === 'Series' || e.kind === 'Season') return 'TV';
if (e.kind === 'Movie') return 'Film';
return '—';
}
const fileCount = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`;
</script>
{#snippet emptyButton(key: string, ids: string[], what: string, label: string)}
{#if confirming === key}
<span class="confirm" role="group" aria-label="Confirm deletion">
<span class="error small">Delete for good?</span>
<button class="danger" disabled={busy} onclick={() => empty(ids, what)}>Yes, delete</button>
<button disabled={busy} onclick={() => (confirming = null)}>Cancel</button>
</span>
{:else}
<button disabled={busy || !ids.length} onclick={() => (confirming = key)}>{label}</button>
{/if}
{/snippet}
<section class="toolbar">
<div class="sides" role="radiogroup" aria-label="Show the trash on 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>
<span class="summary">
{#if loading}
<span class="muted">Loading…</span>
{:else if !error}
<strong>{bytes(total)}</strong> <span class="muted">in {entries.length} {entries.length === 1 ? 'item' : 'items'}</span>
{/if}
</span>
<button onclick={load} disabled={loading || busy}>Refresh</button>
{@render emptyButton('all', entries.map((e) => e.id), `the trash`, 'Empty all')}
</section>
<p class="intro muted">
When something moves off <strong class={side}>{nodeName}</strong>, its folder waits here in case anything went
wrong. Emptying deletes it for good. The moved copy on the other server isn't affected.
</p>
{#if error}<p class="panel msg error">{error}</p>{/if}
{#if notice}<p class="panel msg" role="status">{notice}</p>{/if}
{#if !loading && !error && !entries.length}
<p class="panel msg empty muted">The trash on {nodeName} is empty.</p>
{/if}
{#each groups as g (g.library)}
<section class="panel group">
<div class="head">
<h2>{g.library} <span class="muted">· {bytes(g.size)}</span></h2>
{@render emptyButton(`lib:${g.library}`, g.items.map((e) => e.id), `${g.library}'s trash`, `Empty ${g.library}`)}
</div>
<ul class="list">
{#each g.items as e (e.id)}
<li>
<span class="kind" title={e.kind ?? 'Unknown'}>{kindLabel(e)}</span>
<div class="title">
<span class="name">{e.name}</span>
<div class="meta muted">
Moved{#if e.moved_to}&nbsp;to {e.moved_to}{/if} on {when(e.moved_at)} · {fileCount(e.files)}
</div>
<div class="path mono muted" title={e.folder}>{e.folder}</div>
</div>
<span class="size">{bytes(e.size)}</span>
<div class="actions">
{@render emptyButton(e.id, [e.id], `“${e.name}”`, 'Empty')}
</div>
</li>
{/each}
</ul>
</section>
{/each}
<style>
.toolbar {
display: flex;
gap: 0.6rem;
flex-wrap: wrap;
align-items: center;
}
.summary {
flex: 1;
min-width: 8rem;
}
.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);
}
.intro {
margin: 0.9rem 0;
font-size: 0.9rem;
}
.msg {
padding: 0.7rem 1rem;
}
.empty {
text-align: center;
padding: 2rem;
}
.group {
margin-bottom: 0.8rem;
}
.head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.6rem;
padding: 0.7rem 1rem;
border-bottom: 1px solid var(--line);
}
h2 {
font-size: 0.95rem;
margin: 0;
}
.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;
}
.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;
}
.meta {
font-size: 0.85rem;
}
.path {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.size {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.actions {
flex-shrink: 0;
}
.confirm {
display: inline-flex;
gap: 0.4rem;
align-items: center;
flex-wrap: wrap;
}
.small {
font-size: 0.85rem;
}
button.danger {
background: var(--bad);
border-color: var(--bad);
color: #fff;
font-weight: 600;
}
</style>
+66 -1
View File
@@ -34,12 +34,43 @@ export interface Library {
locations: string[];
}
export interface PartSize {
name: string;
bytes: number;
files: number;
}
export interface FolderSize {
bytes: number;
files: number;
/** Direct subfolders: a show's seasons, a movie's extras. */
parts: PartSize[];
}
export interface LibraryItem {
id: string;
name: string;
kind: 'Movie' | 'Series' | string;
year: number | null;
path: string | null;
/** Null until the agent has measured the folder. */
size: FolderSize | null;
}
export interface SeasonItem {
id: string;
name: string;
number: number | null;
/** Null when the season has no folder of its own; it can't move alone. */
path: string | null;
/** The season's folder name inside the show folder. */
folder: string | null;
}
/** Anything that can be moved: a movie, a show or a season. */
export interface Movable {
id: string;
name: string;
}
export type Stage =
@@ -74,6 +105,13 @@ export interface Job {
target_folder_jellyfin: string | null;
progress: { bytes_done: number; bytes_total: number; current_file: string | null };
log: string[];
/** Users whose watch history didn't (or won't) carry over: no account on the target. */
missing_users?: string[];
}
export interface MoveCheck {
watchers: string[];
missing_users: string[];
}
export interface JobsView {
@@ -82,6 +120,26 @@ export interface JobsView {
peer_error: string | null;
}
export interface TrashEntry {
id: string;
name: string;
/** Missing for items trashed before v0.2.0. */
kind: 'Movie' | 'Series' | 'Season' | null;
library: string;
folder: string;
moved_at: string | null;
moved_to: string | null;
job_id: string | null;
size: number;
files: number;
}
export interface EmptyResult {
removed: number;
freed: number;
missing: string[];
}
export class ApiError extends Error {}
async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
@@ -114,10 +172,17 @@ export const api = {
'GET',
`/items?${new URLSearchParams({ node, library, ...(search ? { search } : {}) })}`,
),
move: (from: Side, item: LibraryItem, dry_run: boolean) =>
seasons: (node: Side, series: string) =>
call<SeasonItem[]>('GET', `/seasons?${new URLSearchParams({ node, series })}`),
checkMove: (from: Side, item: Movable) =>
call<MoveCheck>('GET', `/moves/check?${new URLSearchParams({ from, item_id: item.id })}`),
move: (from: Side, item: Movable, 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`),
reapply: (id: string) => call<Job>('POST', `/jobs/${id}/reapply`),
trash: (node: Side) => call<TrashEntry[]>('GET', `/trash?node=${node}`),
emptyTrash: (node: Side, ids: string[]) => call<EmptyResult>('POST', '/trash/empty', { node, ids }),
};
export const STAGE_LABEL: Record<Stage, string> = {
+84
View File
@@ -0,0 +1,84 @@
// Every move on either server, kept up to date for the whole app: live
// events for moves running here, and polling for moves running on the peer
// (fast while something is moving, slow otherwise).
import { api, type Job } from './api';
export const moves = $state({
jobs: {} as Record<string, Job>,
error: null as string | null,
peerError: null as string | null,
loaded: false,
});
type DoneListener = (job: Job) => void;
const listeners = new Set<DoneListener>();
/** Call `fn` whenever a move (not a dry run) finishes. Returns an unsubscribe. */
export function onMoveDone(fn: DoneListener): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
const isActive = (j: Job) => j.status.kind === 'Queued' || j.status.kind === 'Running';
/** Record a job snapshot and tell listeners if it has just finished. */
function put(job: Job) {
const before = moves.jobs[job.id];
moves.jobs[job.id] = job;
const finished = job.status.kind === 'Done' && !job.dry_run && before && before.status.kind !== 'Done';
// A move we only learn about once it's done (e.g. it finished between
// polls) still counts, as long as the list had loaded before.
const unseen = job.status.kind === 'Done' && !job.dry_run && !before && moves.loaded;
if (finished || unseen) for (const fn of listeners) fn(job);
}
export async function refreshMoves() {
try {
const view = await api.jobs();
const all = [...view.local, ...view.peer];
for (const j of all) put(j);
// Forget jobs that no longer exist anywhere.
const ids = new Set(all.map((j) => j.id));
for (const id of Object.keys(moves.jobs)) if (!ids.has(id)) delete moves.jobs[id];
moves.peerError = view.peer_error;
moves.error = null;
moves.loaded = true;
} catch (e) {
moves.error = (e as Error).message;
}
}
let timer: ReturnType<typeof setTimeout> | undefined;
let running = false;
async function tick() {
clearTimeout(timer);
await refreshMoves();
if (!running) return;
const busy = Object.values(moves.jobs).some(isActive);
timer = setTimeout(tick, busy ? 2000 : 10_000);
}
/** Note a move just started here, and check on it soon. */
export function trackMove(job: Job) {
put(job);
if (running) {
clearTimeout(timer);
timer = setTimeout(tick, 1000);
}
}
/** Start watching for the lifetime of the app. Returns a stop function. */
export function watchMoves(): () => void {
if (running) return () => {};
running = true;
const es = new EventSource('/api/events');
es.addEventListener('job', (ev) => put(JSON.parse((ev as MessageEvent).data) as Job));
tick();
return () => {
running = false;
clearTimeout(timer);
es.close();
};
}