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
This commit is contained in:
IxianPixel committed 2026-11-06 16:30:54 +00:00
1 parent 38319e0987
commit 4c6217bd40
16 files changed
+935 -23

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
}
]
}
+14
View File
@@ -1,5 +1,19 @@
# Changelog # 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 ## v0.1.1
### Added ### Added
+4 -1
View File
@@ -45,7 +45,10 @@ enough while developing.
- **Nothing is deleted from the source until the destination has indexed every - **Nothing is deleted from the source until the destination has indexed every
file** (`Stage::TargetScanned`) and user data is applied. Source "deletion" is 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* - **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 milestone; the runner re-executes from there after a crash. If you add a
stage, make re-running it safe. stage, make re-running it safe.
+5 -3
View File
@@ -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 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.
6. **Clean up.** The source moves its folder to `.jellymove-trash/` in the same 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. 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 ## Safety rules
- Nothing leaves the source until the destination has indexed every file. - 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). happy (automatic retention is on the roadmap).
- Nothing at the destination is ever overwritten. - Nothing at the destination is ever overwritten.
- A movie must be in **its own folder**. jellymove refuses flat folders like - 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 ## Roadmap
- Season-level moves; "promote" (pre-warm) shortcuts - 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 - Pairing codes and pinned TLS instead of a shared token
- Outbound-only control channel so a NATed home agent needs no inbound port - 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%") - Automatic tiering rules ("demote anything unwatched for 90 days when the cloud disk is over 80%")
+1 -1
View File
@@ -9,6 +9,7 @@ rust-version.workspace = true
anyhow = "1.0.104" anyhow = "1.0.104"
axum = { version = "0.8.9", features = ["macros"] } axum = { version = "0.8.9", features = ["macros"] }
base64 = "0.23.1" base64 = "0.23.1"
blake3 = "1.8.7"
futures = "0.3.34" futures = "0.3.34"
jm-core = { version = "0.1.0", path = "../jm-core" } jm-core = { version = "0.1.0", path = "../jm-core" }
jm-jellyfin = { version = "0.1.0", path = "../jm-jellyfin" } jm-jellyfin = { version = "0.1.0", path = "../jm-jellyfin" }
@@ -29,7 +30,6 @@ uuid = { version = "1.26.1", features = ["v4"] }
[dev-dependencies] [dev-dependencies]
anyhow = "1.0.104" anyhow = "1.0.104"
blake3 = "1.8.7"
reqwest = { version = "0.13.5", default-features = false, features = ["json"] } reqwest = { version = "0.13.5", default-features = false, features = ["json"] }
serde_json = "1.0.154" serde_json = "1.0.154"
tempfile = "3.27.0" tempfile = "3.27.0"
+54 -2
View File
@@ -19,11 +19,12 @@ use serde_json::json;
use tokio_stream::StreamExt; use tokio_stream::StreamExt;
use tokio_stream::wrappers::BroadcastStream; 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::library::{self, Library, LibraryItem, LocationCheck};
use crate::peer::{CreateJob, NodeInfo}; use crate::peer::{CreateJob, NodeInfo};
use crate::runner; use crate::runner;
use crate::state::Shared; use crate::state::Shared;
use crate::trash::{self, EmptyResult, TrashEntry};
pub struct ApiError(StatusCode, String); pub struct ApiError(StatusCode, String);
@@ -61,6 +62,8 @@ pub fn router(state: Shared) -> Router {
.route("/moves", post(ui_move)) .route("/moves", post(ui_move))
.route("/jobs", get(ui_jobs)) .route("/jobs", get(ui_jobs))
.route("/jobs/{id}/retry", post(ui_retry)) .route("/jobs/{id}/retry", post(ui_retry))
.route("/trash", get(ui_trash))
.route("/trash/empty", post(ui_empty_trash))
.route("/events", get(events)); .route("/events", get(events));
let peer_api = Router::new() 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}/files/{idx}", get(peer_file))
.route("/exports/{id}/complete", post(peer_complete_export)) .route("/exports/{id}/complete", post(peer_complete_export))
.route("/jobs", get(peer_jobs).post(peer_create_job)) .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( .layer(middleware::from_fn_with_state(
state.clone(), state.clone(),
require_peer_token, require_peer_token,
@@ -333,6 +338,35 @@ async fn ui_retry(State(state): State<Shared>, Path(id): Path<String>) -> ApiRes
Ok(Json(job)) 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>>> { async fn events(State(state): State<Shared>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = BroadcastStream::new(state.events.subscribe()).filter_map(|msg| { let stream = BroadcastStream::new(state.events.subscribe()).filter_map(|msg| {
msg.ok().and_then(|mut job| { msg.ok().and_then(|mut job| {
@@ -409,8 +443,26 @@ async fn peer_file(
async fn peer_complete_export( async fn peer_complete_export(
State(state): State<Shared>, State(state): State<Shared>,
Path(id): Path<String>, Path(id): Path<String>,
body: Option<Json<CompleteRequest>>,
) -> ApiResult<Export> { ) -> 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( async fn peer_create_job(
+46 -10
View File
@@ -15,6 +15,7 @@ use jm_jellyfin::ItemQuery;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::state::{AppState, Shared}; use crate::state::{AppState, Shared};
use crate::trash;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "detail")] #[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<String>,
pub moved_to: Option<String>,
}
/// Final step on the source: move the folder into a hidden trash folder in /// 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. /// 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 let mut export: Export = state
.store .store
.get_export(id) .get_export(id)
@@ -291,21 +300,48 @@ pub async fn complete(state: &Shared, id: &str) -> anyhow::Result<Export> {
.cfg .cfg
.path_map .path_map
.to_local(Path::new(&export.jellyfin_location)); .to_local(Path::new(&export.jellyfin_location));
let trash_root = location_local.join(".jellymove-trash"); let trash_root = location_local.join(trash::TRASH_DIR);
let trash = join_relative(&trash_root.join(&export.id), &info.rel_folder)
.context("unsafe folder name")?;
// 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 tokio::fs::metadata(&local_folder).await.is_ok() {
if let Some(parent) = trash.parent() { tokio::fs::create_dir_all(&trash_root).await?;
tokio::fs::create_dir_all(parent).await?;
}
let marker = trash_root.join(".ignore"); let marker = trash_root.join(".ignore");
if tokio::fs::metadata(&marker).await.is_err() { if tokio::fs::metadata(&marker).await.is_err() {
tokio::fs::write(&marker, b"").await?; tokio::fs::write(&marker, b"").await?;
} }
tokio::fs::rename(&local_folder, &trash) // The same item can be trashed more than once (moved away, back,
.await // and away again), so each move gets its own entry folder.
.with_context(|| format!("moving {} to the trash", local_folder.display()))?; 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"); tracing::info!(from = %local_folder.display(), to = %trash.display(), "source moved to trash");
} }
+1
View File
@@ -7,6 +7,7 @@ pub mod library;
pub mod peer; pub mod peer;
pub mod runner; pub mod runner;
pub mod state; pub mod state;
pub mod trash;
pub mod ui; pub mod ui;
use std::sync::Arc; use std::sync::Arc;
+21 -3
View File
@@ -4,8 +4,9 @@ use jm_core::Job;
use reqwest::header::AUTHORIZATION; use reqwest::header::AUTHORIZATION;
use serde::{Deserialize, Serialize, de::DeserializeOwned}; use serde::{Deserialize, Serialize, de::DeserializeOwned};
use crate::export::Export; use crate::export::{CompleteRequest, Export};
use crate::library::{Library, LibraryItem}; use crate::library::{Library, LibraryItem};
use crate::trash::{EmptyResult, TrashEntry};
#[derive(Clone)] #[derive(Clone)]
pub struct PeerClient { pub struct PeerClient {
@@ -106,14 +107,31 @@ impl PeerClient {
self.url(&format!("/exports/{export_id}/files/{idx}")) 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.send(
self.http.post(self.url(&format!("/exports/{id}/complete"))), self.http
.post(self.url(&format!("/exports/{id}/complete")))
.json(req),
"clean up source", "clean up source",
) )
.await .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> { pub async fn create_job(&self, req: &CreateJob) -> anyhow::Result<Job> {
self.send(self.http.post(self.url("/jobs")).json(req), "start job") self.send(self.http.post(self.url("/jobs")).json(req), "start job")
.await .await
+5 -1
View File
@@ -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<()> { async fn clean_source(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
let export_id = job.export_id.clone().context("no export")?; 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.note("source folder moved to its trash and source library rescanned");
job.advance(Stage::SourceCleaned); job.advance(Stage::SourceCleaned);
Ok(()) Ok(())
+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());
}
}
}
+142
View File
@@ -375,6 +375,148 @@ async fn refuses_when_destination_exists() {
assert!(cloud.movies().join("Alien (1979)").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] #[tokio::test]
async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() { async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() {
let (cloud, _home) = pair(|_| {}).await; let (cloud, _home) = pair(|_| {}).await;
+2 -1
View File
@@ -38,7 +38,8 @@ forwarding.
| `POST /exports {item_id}` | Source: start checking, hashing and capturing user data. Idempotent per item. | | `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}` | Poll: `Preparing` → `Ready` (with `ExportInfo`) or `Failed` |
| `GET /exports/{id}/files/{idx}` | Range-capable download of manifest entry `idx` | | `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`, `GET /jobs` | Create or list jobs on the peer (destination) |
## Job stages ## Job stages
+5 -1
View File
@@ -4,8 +4,9 @@
import Library from './lib/Library.svelte'; import Library from './lib/Library.svelte';
import Jobs from './lib/Jobs.svelte'; import Jobs from './lib/Jobs.svelte';
import StatusView from './lib/StatusView.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<Tab>('library'); let tab = $state<Tab>('library');
let status = $state<Status | null>(null); let status = $state<Status | null>(null);
let statusError = $state<string | null>(null); let statusError = $state<string | null>(null);
@@ -48,6 +49,7 @@
<nav> <nav>
<button class:active={tab === 'library'} onclick={() => (tab = 'library')}>Library</button> <button class:active={tab === 'library'} onclick={() => (tab = 'library')}>Library</button>
<button class:active={tab === 'jobs'} onclick={() => (tab = 'jobs')}>Moves</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')}> <button class:active={tab === 'status'} onclick={() => (tab = 'status')}>
Status Status
{#if status && !healthy}<span class="dot warn" title="Something needs attention"></span>{/if} {#if status && !healthy}<span class="dot warn" title="Something needs attention"></span>{/if}
@@ -64,6 +66,8 @@
<Library {localName} {peerName} onmoved={() => (tab = 'jobs')} /> <Library {localName} {peerName} onmoved={() => (tab = 'jobs')} />
{:else if tab === 'jobs'} {:else if tab === 'jobs'}
<Jobs {localName} /> <Jobs {localName} />
{:else if tab === 'trash'}
<Trash {localName} {peerName} />
{:else} {:else}
<StatusView {status} reload={loadStatus} /> <StatusView {status} reload={loadStatus} />
{/if} {/if}
+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') 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>
+22
View File
@@ -82,6 +82,26 @@ export interface JobsView {
peer_error: string | null; peer_error: string | null;
} }
export interface TrashEntry {
id: string;
name: string;
/** Missing for items trashed before v0.2.0. */
kind: 'Movie' | 'Series' | 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 {} export class ApiError extends Error {}
async function call<T>(method: string, path: string, body?: unknown): Promise<T> { async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
@@ -118,6 +138,8 @@ export const api = {
call<Job>('POST', '/moves', { from, item_id: item.id, name: item.name, dry_run }), call<Job>('POST', '/moves', { from, item_id: item.id, name: item.name, dry_run }),
jobs: () => call<JobsView>('GET', '/jobs'), jobs: () => call<JobsView>('GET', '/jobs'),
retry: (id: string) => call<Job>('POST', `/jobs/${id}/retry`), retry: (id: string) => call<Job>('POST', `/jobs/${id}/retry`),
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> = { export const STAGE_LABEL: Record<Stage, string> = {