Add a Trash view to see and empty .jellymove-trash (#3)
CI / test (push) Successful in 1m18s
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:
1 parent
38319e0987
commit
4c6217bd40
16 files changed
+935
-23
No files matched your search
@@ -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"
|
||||
|
||||
@@ -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<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| {
|
||||
@@ -409,8 +443,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(
|
||||
|
||||
@@ -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<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)
|
||||
@@ -291,21 +300,48 @@ pub async fn complete(state: &Shared, id: &str) -> anyhow::Result<Export> {
|
||||
.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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<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
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user