From 4c6217bd4062985af47c1beab771d69c0b9a3aec Mon Sep 17 00:00:00 2001 From: IxianPixel Date: Fri, 6 Nov 2026 16:30:54 +0000 Subject: [PATCH] Add a Trash view to see and empty .jellymove-trash (#3) 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 --- .claude/launch.json | 11 ++ CHANGELOG.md | 14 ++ CLAUDE.md | 5 +- README.md | 8 +- crates/jm-server/Cargo.toml | 2 +- crates/jm-server/src/api.rs | 56 +++++- crates/jm-server/src/export.rs | 56 ++++-- crates/jm-server/src/lib.rs | 1 + crates/jm-server/src/peer.rs | 24 ++- crates/jm-server/src/runner.rs | 6 +- crates/jm-server/src/trash.rs | 314 +++++++++++++++++++++++++++++++++ crates/jm-server/tests/e2e.rs | 142 +++++++++++++++ docs/ARCHITECTURE.md | 3 +- ui/src/App.svelte | 6 +- ui/src/lib/Trash.svelte | 288 ++++++++++++++++++++++++++++++ ui/src/lib/api.ts | 22 +++ 16 files changed, 935 insertions(+), 23 deletions(-) create mode 100644 .claude/launch.json create mode 100644 crates/jm-server/src/trash.rs create mode 100644 ui/src/lib/Trash.svelte diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..fb06d5d --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "demo", + "runtimeExecutable": "cargo", + "runtimeArgs": ["run", "-p", "jm-server", "--example", "demo"], + "port": 8097 + } + ] +} diff --git a/CHANGELOG.md b/CHANGELOG.md index d777d76..5a1c9b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # 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) + +### 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. + ## v0.1.1 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 73985a1..32b7a93 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,7 +45,10 @@ enough while developing. - **Nothing is deleted from the source until the destination has indexed every file** (`Stage::TargetScanned`) and user data is applied. Source "deletion" is - a rename into `/.jellymove-trash/`, never `remove_dir_all`. + a rename into `/.jellymove-trash//`, never `remove_dir_all`. + The only code that deletes is `trash::empty`, which resolves opaque entry + IDs by scanning the trash folders and only removes real folders directly + inside them. - **Every runner step is idempotent.** `Job.stage` is the last *completed* milestone; the runner re-executes from there after a crash. If you add a stage, make re-running it safe. diff --git a/README.md b/README.md index 5a8865d..e0ceb6e 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,9 @@ One agent runs next to each Jellyfin and sees the same media folders. The 5. **Restore watch history.** Jellyfin gives moved files new item IDs, so jellymove re-applies each user's data to the new items, matching users by name. 6. **Clean up.** The source moves its folder to `.jellymove-trash/` in the same - library and rescans. It is not deleted. + 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. @@ -168,7 +170,7 @@ 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. - A movie must be in **its own folder**. jellymove refuses flat folders like @@ -188,7 +190,7 @@ 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 +- Automatic trash retention (e.g. empty after N days) - Pairing codes and pinned TLS instead of a shared token - Outbound-only control channel so a NATed home agent needs no inbound port - Automatic tiering rules ("demote anything unwatched for 90 days when the cloud disk is over 80%") diff --git a/crates/jm-server/Cargo.toml b/crates/jm-server/Cargo.toml index 8049027..168eccd 100644 --- a/crates/jm-server/Cargo.toml +++ b/crates/jm-server/Cargo.toml @@ -9,6 +9,7 @@ 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" } @@ -29,7 +30,6 @@ uuid = { version = "1.26.1", features = ["v4"] } [dev-dependencies] anyhow = "1.0.104" -blake3 = "1.8.7" reqwest = { version = "0.13.5", default-features = false, features = ["json"] } serde_json = "1.0.154" tempfile = "3.27.0" diff --git a/crates/jm-server/src/api.rs b/crates/jm-server/src/api.rs index acc6984..90ce051 100644 --- a/crates/jm-server/src/api.rs +++ b/crates/jm-server/src/api.rs @@ -19,11 +19,12 @@ use serde_json::json; use tokio_stream::StreamExt; use tokio_stream::wrappers::BroadcastStream; -use crate::export::{self, Export, ExportStatus}; +use crate::export::{self, CompleteRequest, Export, ExportStatus}; use crate::library::{self, Library, LibraryItem, LocationCheck}; use crate::peer::{CreateJob, NodeInfo}; use crate::runner; use crate::state::Shared; +use crate::trash::{self, EmptyResult, TrashEntry}; pub struct ApiError(StatusCode, String); @@ -61,6 +62,8 @@ pub fn router(state: Shared) -> Router { .route("/moves", post(ui_move)) .route("/jobs", get(ui_jobs)) .route("/jobs/{id}/retry", post(ui_retry)) + .route("/trash", get(ui_trash)) + .route("/trash/empty", post(ui_empty_trash)) .route("/events", get(events)); let peer_api = Router::new() @@ -72,6 +75,8 @@ pub fn router(state: Shared) -> Router { .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("/trash", get(peer_trash)) + .route("/trash/empty", post(peer_empty_trash)) .layer(middleware::from_fn_with_state( state.clone(), require_peer_token, @@ -333,6 +338,35 @@ async fn ui_retry(State(state): State, Path(id): Path) -> ApiRes Ok(Json(job)) } +async fn ui_trash( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(match q.node { + Side::Local => trash::list(&state).await?, + Side::Peer => state.peer()?.trash().await?, + })) +} + +#[derive(Deserialize)] +struct EmptyTrashRequest { + #[serde(default)] + node: Side, + ids: Vec, +} + +/// Delete trash entries for good, by ID. Each node only ever deletes its own +/// files; for the peer's trash the request is passed on. +async fn ui_empty_trash( + State(state): State, + Json(req): Json, +) -> ApiResult { + Ok(Json(match req.node { + Side::Local => trash::empty(&state, &req.ids).await?, + Side::Peer => state.peer()?.empty_trash(&req.ids).await?, + })) +} + async fn events(State(state): State) -> Sse>> { let stream = BroadcastStream::new(state.events.subscribe()).filter_map(|msg| { msg.ok().and_then(|mut job| { @@ -409,8 +443,26 @@ async fn peer_file( async fn peer_complete_export( State(state): State, Path(id): Path, + body: Option>, ) -> ApiResult { - Ok(Json(export::complete(&state, &id).await?)) + let req = body.map(|Json(r)| r).unwrap_or_default(); + Ok(Json(export::complete(&state, &id, req).await?)) +} + +async fn peer_trash(State(state): State) -> ApiResult> { + Ok(Json(trash::list(&state).await?)) +} + +#[derive(Deserialize)] +struct PeerEmptyTrash { + ids: Vec, +} + +async fn peer_empty_trash( + State(state): State, + Json(req): Json, +) -> ApiResult { + Ok(Json(trash::empty(&state, &req.ids).await?)) } async fn peer_create_job( diff --git a/crates/jm-server/src/export.rs b/crates/jm-server/src/export.rs index ce21bf0..93dfa42 100644 --- a/crates/jm-server/src/export.rs +++ b/crates/jm-server/src/export.rs @@ -15,6 +15,7 @@ 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")] @@ -272,9 +273,17 @@ fn push_record( } } +/// Who finished the move; recorded with the trash entry. Older peers send +/// nothing. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct CompleteRequest { + pub job_id: Option, + pub moved_to: Option, +} + /// Final step on the source: move the folder into a hidden trash folder in /// the same library (same filesystem, so it's a rename) and rescan. -pub async fn complete(state: &Shared, id: &str) -> anyhow::Result { +pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow::Result { let mut export: Export = state .store .get_export(id) @@ -291,21 +300,48 @@ pub async fn complete(state: &Shared, id: &str) -> anyhow::Result { .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); + // Re-running after a crash: if the folder is already gone it was moved + // last time, so only the rescan and status update remain. if tokio::fs::metadata(&local_folder).await.is_ok() { - if let Some(parent) = trash.parent() { - tokio::fs::create_dir_all(parent).await?; - } + 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()))?; + // 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 = trash::new_entry_dir(&trash_root, &export.id); + let trash = join_relative(&entry_dir, &info.rel_folder).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: info.rel_folder.clone(), + moved_at: time::OffsetDateTime::now_utc(), + moved_to: req.moved_to, + job_id: req.job_id, + }, + )?; + if let Err(e) = tokio::fs::rename(&local_folder, &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", local_folder.display())); + } tracing::info!(from = %local_folder.display(), to = %trash.display(), "source moved to trash"); } diff --git a/crates/jm-server/src/lib.rs b/crates/jm-server/src/lib.rs index 41054d2..8933703 100644 --- a/crates/jm-server/src/lib.rs +++ b/crates/jm-server/src/lib.rs @@ -7,6 +7,7 @@ pub mod library; pub mod peer; pub mod runner; pub mod state; +pub mod trash; pub mod ui; use std::sync::Arc; diff --git a/crates/jm-server/src/peer.rs b/crates/jm-server/src/peer.rs index 43ec8b7..9d6bcea 100644 --- a/crates/jm-server/src/peer.rs +++ b/crates/jm-server/src/peer.rs @@ -4,8 +4,9 @@ use jm_core::Job; use reqwest::header::AUTHORIZATION; use serde::{Deserialize, Serialize, de::DeserializeOwned}; -use crate::export::Export; +use crate::export::{CompleteRequest, Export}; use crate::library::{Library, LibraryItem}; +use crate::trash::{EmptyResult, TrashEntry}; #[derive(Clone)] pub struct PeerClient { @@ -106,14 +107,31 @@ impl PeerClient { self.url(&format!("/exports/{export_id}/files/{idx}")) } - pub async fn complete_export(&self, id: &str) -> anyhow::Result { + pub async fn complete_export(&self, id: &str, req: &CompleteRequest) -> anyhow::Result { self.send( - self.http.post(self.url(&format!("/exports/{id}/complete"))), + self.http + .post(self.url(&format!("/exports/{id}/complete"))) + .json(req), "clean up source", ) .await } + pub async fn trash(&self) -> anyhow::Result> { + self.send(self.http.get(self.url("/trash")), "list trash") + .await + } + + pub async fn empty_trash(&self, ids: &[String]) -> anyhow::Result { + self.send( + self.http + .post(self.url("/trash/empty")) + .json(&serde_json::json!({ "ids": ids })), + "empty trash", + ) + .await + } + pub async fn create_job(&self, req: &CreateJob) -> anyhow::Result { self.send(self.http.post(self.url("/jobs")).json(req), "start job") .await diff --git a/crates/jm-server/src/runner.rs b/crates/jm-server/src/runner.rs index 42c66cc..a154f91 100644 --- a/crates/jm-server/src/runner.rs +++ b/crates/jm-server/src/runner.rs @@ -444,7 +444,11 @@ async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> { async fn clean_source(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let export_id = job.export_id.clone().context("no export")?; - state.peer()?.complete_export(&export_id).await?; + let req = crate::export::CompleteRequest { + job_id: Some(job.id.to_string()), + moved_to: Some(state.cfg.node_name.clone()), + }; + state.peer()?.complete_export(&export_id, &req).await?; job.note("source folder moved to its trash and source library rescanned"); job.advance(Stage::SourceCleaned); Ok(()) diff --git a/crates/jm-server/src/trash.rs b/crates/jm-server/src/trash.rs new file mode 100644 index 0000000..55cb217 --- /dev/null +++ b/crates/jm-server/src/trash.rs @@ -0,0 +1,314 @@ +//! The source's trash. When a move finishes, the source renames the item's +//! folder to `/.jellymove-trash//` rather than +//! deleting it. Entries stay there until someone empties them from the UI. +//! +//! Each entry folder also holds a small metadata file describing the move. +//! Entries are only ever referred to by an opaque ID derived from their path, +//! and are resolved by scanning the trash folders, so neither the UI nor the +//! peer can name a path to delete. + +use std::path::{Path, PathBuf}; + +use anyhow::Context; +use jm_core::ItemKind; +use serde::{Deserialize, Serialize}; +use time::OffsetDateTime; + +use crate::library; +use crate::state::AppState; + +/// Folder inside each library location that holds the trash. +pub const TRASH_DIR: &str = ".jellymove-trash"; +/// Metadata file written into each entry folder. +pub const META_FILE: &str = ".jellymove-entry.json"; + +/// What the source records about a move when it trashes the folder. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EntryMeta { + pub name: String, + pub kind: ItemKind, + pub library: String, + /// The folder's path inside its library, e.g. `Alien (1979)`. + pub rel_folder: String, + #[serde(with = "time::serde::rfc3339")] + pub moved_at: OffsetDateTime, + /// Node the item was moved to. + pub moved_to: Option, + /// The job on that node that moved it. + pub job_id: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TrashEntry { + /// Opaque, stable while the entry exists. The only way to refer to it. + pub id: String, + pub name: String, + /// Missing for entries trashed before v0.2.0, which have no metadata. + pub kind: Option, + pub library: String, + pub folder: String, + #[serde(with = "time::serde::rfc3339::option")] + pub moved_at: Option, + pub moved_to: Option, + pub job_id: Option, + pub size: u64, + pub files: u64, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct EmptyResult { + pub removed: usize, + pub freed: u64, + /// IDs that weren't in the trash (already emptied, or never existed). + pub missing: Vec, +} + +struct Found { + entry: TrashEntry, + path: PathBuf, +} + +/// Pick a folder for a new entry under `trash_root`, starting with `base` and +/// adding `-2`, `-3`, ... if an item with the same ID was trashed before. +pub fn new_entry_dir(trash_root: &Path, base: &str) -> PathBuf { + let first = trash_root.join(base); + if std::fs::symlink_metadata(&first).is_err() { + return first; + } + (2u32..) + .map(|n| trash_root.join(format!("{base}-{n}"))) + .find(|p| std::fs::symlink_metadata(p).is_err()) + .expect("a free name exists") +} + +pub fn write_meta(entry_dir: &Path, meta: &EntryMeta) -> anyhow::Result<()> { + let json = serde_json::to_vec_pretty(meta)?; + std::fs::write(entry_dir.join(META_FILE), json) + .with_context(|| format!("writing trash metadata in {}", entry_dir.display())) +} + +/// Every entry in this node's trash, newest first. +pub async fn list(state: &AppState) -> anyhow::Result> { + Ok(scan(state).await?.into_iter().map(|f| f.entry).collect()) +} + +/// Delete the given entries for good. Unknown IDs are reported, not errors, +/// so emptying twice (e.g. from both UIs) is harmless. +pub async fn empty(state: &AppState, ids: &[String]) -> anyhow::Result { + let found = scan(state).await?; + let mut result = EmptyResult::default(); + let mut doomed = Vec::new(); + for id in ids { + match found.iter().find(|f| &f.entry.id == id) { + Some(f) => doomed.push((f.path.clone(), f.entry.size, f.entry.name.clone())), + None => result.missing.push(id.clone()), + } + } + for (path, size, name) in doomed { + // Belt and braces: scan only returns real folders directly inside a + // trash folder, but never delete anything else. + let in_trash = path + .parent() + .and_then(Path::file_name) + .is_some_and(|n| n == TRASH_DIR); + anyhow::ensure!(in_trash, "refusing to delete {}", path.display()); + let p = path.clone(); + tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&p)) + .await? + .with_context(|| format!("emptying {} from the trash", path.display()))?; + tracing::info!(item = %name, path = %path.display(), "emptied from trash"); + result.removed += 1; + result.freed += size; + } + Ok(result) +} + +async fn scan(state: &AppState) -> anyhow::Result> { + let mut roots: Vec<(String, PathBuf)> = Vec::new(); + for lib in library::libraries(state).await? { + for loc in &lib.locations { + let root = state.cfg.path_map.to_local(Path::new(loc)).join(TRASH_DIR); + if !roots.iter().any(|(_, r)| r == &root) { + roots.push((lib.name.clone(), root)); + } + } + } + let mut found = tokio::task::spawn_blocking(move || { + roots + .iter() + .flat_map(|(library, root)| scan_root(library, root)) + .collect::>() + }) + .await?; + found.sort_by_key(|f| std::cmp::Reverse(f.entry.moved_at)); + Ok(found) +} + +fn scan_root(library: &str, root: &Path) -> Vec { + // The trash folder itself must be a real folder, not a link elsewhere. + if !std::fs::symlink_metadata(root).is_ok_and(|m| m.is_dir()) { + return vec![]; + } + let Ok(rd) = std::fs::read_dir(root) else { + return vec![]; + }; + let mut out = Vec::new(); + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + // `.ignore` and anything else hidden is ours, not an entry. Links + // are skipped so emptying can't reach outside the trash. + if name.starts_with('.') || !e.file_type().is_ok_and(|t| t.is_dir()) { + continue; + } + let path = e.path(); + let meta: Option = std::fs::read(path.join(META_FILE)) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()); + let (size, files) = dir_size(&path); + let entry = match meta { + Some(m) => TrashEntry { + id: entry_id(&path), + name: m.name, + kind: Some(m.kind), + library: library.to_string(), + folder: m.rel_folder, + moved_at: Some(m.moved_at), + moved_to: m.moved_to, + job_id: m.job_id, + size, + files, + }, + None => { + // Trashed before metadata existed: the entry holds the + // folder at its path inside the library. + let folder = first_visible_child(&path).unwrap_or_else(|| name.clone()); + TrashEntry { + id: entry_id(&path), + name: folder.clone(), + kind: None, + library: library.to_string(), + folder, + moved_at: std::fs::metadata(&path) + .and_then(|m| m.modified()) + .ok() + .map(OffsetDateTime::from), + moved_to: None, + job_id: None, + size, + files, + } + } + }; + out.push(Found { entry, path }); + } + out +} + +fn first_visible_child(dir: &Path) -> Option { + std::fs::read_dir(dir) + .ok()? + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .find(|n| !n.starts_with('.')) +} + +/// Total bytes and file count below `dir`, not following links and not +/// counting the entry's metadata file. +fn dir_size(dir: &Path) -> (u64, u64) { + let mut bytes = 0; + let mut files = 0; + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { + continue; + }; + for e in rd.flatten() { + let Ok(t) = e.file_type() else { continue }; + if t.is_dir() { + stack.push(e.path()); + } else if t.is_file() && !(d == dir && e.file_name() == META_FILE) { + bytes += e.metadata().map(|m| m.len()).unwrap_or(0); + files += 1; + } + } + } + (bytes, files) +} + +fn entry_id(path: &Path) -> String { + let hash = blake3::hash(path.as_os_str().as_encoded_bytes()); + hash.to_hex()[..16].to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn new_entry_dir_avoids_existing_names() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1")); + std::fs::create_dir(root.join("item-1")).unwrap(); + assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1-2")); + std::fs::create_dir(root.join("item-1-2")).unwrap(); + assert_eq!(new_entry_dir(root, "item-1"), root.join("item-1-3")); + } + + #[test] + fn scan_lists_entries_and_skips_links_and_hidden_files() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(TRASH_DIR); + let entry = root.join("item-1"); + std::fs::create_dir_all(entry.join("Alien (1979)/extras")).unwrap(); + std::fs::write(entry.join("Alien (1979)/Alien.mkv"), b"12345").unwrap(); + std::fs::write(entry.join("Alien (1979)/extras/x.mkv"), b"123").unwrap(); + write_meta( + &entry, + &EntryMeta { + name: "Alien".into(), + kind: ItemKind::Movie, + library: "Movies".into(), + rel_folder: "Alien (1979)".into(), + moved_at: OffsetDateTime::now_utc(), + moved_to: Some("home".into()), + job_id: Some("j1".into()), + }, + ) + .unwrap(); + // An old entry without metadata. + std::fs::create_dir_all(root.join("item-2/Heat (1995)")).unwrap(); + std::fs::write(root.join("item-2/Heat (1995)/Heat.mkv"), b"1").unwrap(); + std::fs::write(root.join(".ignore"), b"").unwrap(); + #[cfg(unix)] + { + let outside = tmp.path().join("outside"); + std::fs::create_dir(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("sneaky")).unwrap(); + } + + let mut found = scan_root("Movies", &root); + found.sort_by(|a, b| a.entry.name.cmp(&b.entry.name)); + let names: Vec<_> = found.iter().map(|f| f.entry.name.as_str()).collect(); + assert_eq!(names, ["Alien", "Heat (1995)"]); + let alien = &found[0].entry; + assert_eq!((alien.size, alien.files), (8, 2)); + assert_eq!(alien.moved_to.as_deref(), Some("home")); + assert_eq!(alien.kind, Some(ItemKind::Movie)); + assert_eq!(found[1].entry.kind, None); + assert!(found[1].entry.moved_at.is_some()); + assert_ne!(alien.id, found[1].entry.id); + } + + #[test] + fn scan_ignores_a_trash_folder_that_is_a_link() { + let tmp = tempfile::tempdir().unwrap(); + let real = tmp.path().join("elsewhere"); + std::fs::create_dir_all(real.join("item-1/Movie")).unwrap(); + #[cfg(unix)] + { + std::os::unix::fs::symlink(&real, tmp.path().join(TRASH_DIR)).unwrap(); + assert!(scan_root("Movies", &tmp.path().join(TRASH_DIR)).is_empty()); + } + } +} diff --git a/crates/jm-server/tests/e2e.rs b/crates/jm-server/tests/e2e.rs index 7b8b85f..c696e9c 100644 --- a/crates/jm-server/tests/e2e.rs +++ b/crates/jm-server/tests/e2e.rs @@ -375,6 +375,148 @@ 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"); +} + #[tokio::test] async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() { let (cloud, _home) = pair(|_| {}).await; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0289615..de679b5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -38,7 +38,8 @@ forwarding. | `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) | ## Job stages diff --git a/ui/src/App.svelte b/ui/src/App.svelte index c60f623..ecfdc06 100644 --- a/ui/src/App.svelte +++ b/ui/src/App.svelte @@ -4,8 +4,9 @@ import Library from './lib/Library.svelte'; import Jobs from './lib/Jobs.svelte'; import StatusView from './lib/StatusView.svelte'; + import Trash from './lib/Trash.svelte'; - type Tab = 'library' | 'jobs' | 'status'; + type Tab = 'library' | 'jobs' | 'trash' | 'status'; let tab = $state('library'); let status = $state(null); let statusError = $state(null); @@ -48,6 +49,7 @@