Show folder sizes for movies, shows and seasons. Closes #5
CI / test (push) Successful in 1m12s

The library lists now show how much space each movie and show takes on disk, counting everything a move copies, with a per-season breakdown for shows, a running total and a "Largest first" sort.

- sizes.rs: a single background worker measures one folder at a time. Listing returns cached sizes straight away and queues folders; the UI
  polls until every size has arrived.
- Cached in a new folder_sizes table (store migration v2). A size is kept while the folder's signature (mtimes of the folder and its direct
  subfolders) is unchanged, checked at most hourly and re-measured after 7 days.
- Each agent measures its own folders, so peer listings carry the peer's sizes.
- Tests for measuring, signatures, natural season order, the migration, and an e2e test covering both sides and a moved item.
This commit is contained in:
IxianPixel committed 2026-11-06 16:43:52 +00:00
1 parent 4c6217bd40
commit 25a743b350
11 files changed
+672 -26

No files matched your search

+4
View File
@@ -8,6 +8,10 @@
on either server: the item, its size and file count, when it was moved and 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. where to. Empty one item, a whole library or everything, with a confirmation.
Entries are deleted by ID only, never by path. (#3) Entries are deleted by ID only, never by path. (#3)
- **Folder sizes in the library.** Every movie and show now shows how much
space it takes, counting everything a move copies, with a per-season
breakdown for shows and a "Largest first" sort. Sizes are measured in the
background and cached, so big libraries open straight away. (#5)
### Fixed ### Fixed
+1 -1
View File
@@ -36,7 +36,7 @@ enough while developing.
| `jm-core` | Pure domain: `Job`/`Stage`/`JobStatus`, `ExportInfo`/`Manifest`, `PathMap`, folder safety rules, user-data types. No I/O. | | `jm-core` | Pure domain: `Job`/`Stage`/`JobStatus`, `ExportInfo`/`Manifest`, `PathMap`, folder safety rules, user-data types. No I/O. |
| `jm-transfer` | Manifest building + BLAKE3, `range_response` (serve), `Puller` (resume/retry/throttle/verify), `promote` (atomic rename). | | `jm-transfer` | Manifest building + BLAKE3, `range_response` (serve), `Puller` (resume/retry/throttle/verify), `promote` (atomic rename). |
| `jm-jellyfin` | Thin typed client for the ~10 Jellyfin endpoints used. | | `jm-jellyfin` | Thin typed client for the ~10 Jellyfin endpoints used. |
| `jm-store` | SQLite (rusqlite, WAL). Jobs and exports as JSON blobs. Migrations are the `MIGRATIONS` array; append only. | | `jm-store` | SQLite (rusqlite, WAL). Jobs, exports and cached folder sizes as JSON blobs. Migrations are the `MIGRATIONS` array; append only. |
| `jm-server` | axum app: `/api/*` (UI), `/peer/v1/*` (agent↔agent), `export.rs` (source side), `runner.rs` (destination side), embedded UI. | | `jm-server` | axum app: `/api/*` (UI), `/peer/v1/*` (agent↔agent), `export.rs` (source side), `runner.rs` (destination side), embedded UI. |
| `jellymove` | Binary: clap + figment config loading, tracing setup. | | `jellymove` | Binary: clap + figment config loading, tracing setup. |
| `ui/` | Svelte 5 (runes) + Vite + TS SPA. No SvelteKit. | | `ui/` | Svelte 5 (runes) + Vite + TS SPA. No SvelteKit. |
+1
View File
@@ -6,6 +6,7 @@ pub mod export;
pub mod library; pub mod library;
pub mod peer; pub mod peer;
pub mod runner; pub mod runner;
pub mod sizes;
pub mod state; pub mod state;
pub mod trash; pub mod trash;
pub mod ui; pub mod ui;
+37 -5
View File
@@ -1,11 +1,12 @@
//! Browsing the local Jellyfin libraries. //! Browsing the local Jellyfin libraries.
use std::path::Path; use std::path::{Path, PathBuf};
use jm_jellyfin::ItemQuery; use jm_jellyfin::ItemQuery;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::state::AppState; use crate::sizes::{self, FolderSize};
use crate::state::{AppState, Shared};
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Library { pub struct Library {
@@ -23,6 +24,9 @@ pub struct LibraryItem {
pub kind: String, pub kind: String,
pub year: Option<i32>, pub year: Option<i32>,
pub path: Option<String>, pub path: Option<String>,
/// Size of the item's folder on disk; `None` until it has been measured.
#[serde(default)]
pub size: Option<FolderSize>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -55,8 +59,10 @@ pub async fn libraries(state: &AppState) -> anyhow::Result<Vec<Library>> {
.collect()) .collect())
} }
/// The movies and series in a library, with the size of each one's folder if
/// it's known yet. Sizes still missing are being measured in the background.
pub async fn items( pub async fn items(
state: &AppState, state: &Shared,
library_id: &str, library_id: &str,
search: Option<&str>, search: Option<&str>,
) -> anyhow::Result<Vec<LibraryItem>> { ) -> anyhow::Result<Vec<LibraryItem>> {
@@ -71,7 +77,7 @@ pub async fn items(
..Default::default() ..Default::default()
}) })
.await?; .await?;
Ok(items let mut out: Vec<LibraryItem> = items
.into_iter() .into_iter()
.map(|i| LibraryItem { .map(|i| LibraryItem {
id: i.id, id: i.id,
@@ -79,8 +85,34 @@ pub async fn items(
kind: i.kind, kind: i.kind,
year: i.production_year, year: i.production_year,
path: i.path, path: i.path,
size: None,
}) })
.collect()) .collect();
// Only items whose folder we can place are measured.
let folders: Vec<(usize, PathBuf)> = out
.iter()
.enumerate()
.filter_map(|(n, i)| Some((n, item_folder(state, i)?)))
.collect();
let paths: Vec<PathBuf> = folders.iter().map(|(_, p)| p.clone()).collect();
let sizes = sizes::lookup(state, &paths).await?;
for ((n, _), size) in folders.into_iter().zip(sizes) {
out[n].size = size;
}
Ok(out)
}
/// The folder a move would take, as this agent sees it: a movie's parent
/// folder, or the series folder itself.
fn item_folder(state: &AppState, item: &LibraryItem) -> Option<PathBuf> {
let path = Path::new(item.path.as_deref()?);
let folder = match item.kind.as_str() {
"Movie" => path.parent()?,
"Series" => path,
_ => return None,
};
Some(state.cfg.path_map.to_local(folder))
} }
/// Confirm every library location exists and is writable from this agent. /// Confirm every library location exists and is writable from this agent.
+313
View File
@@ -0,0 +1,313 @@
//! Sizes of item folders on disk, for the library lists.
//!
//! Adding up a big library is slow on a NAS, so sizes are cached in the store
//! and worked out by a single background worker, one folder at a time. Listing
//! a library returns whatever is cached straight away and queues every folder
//! for checking; the UI asks again until every size has arrived.
//!
//! A cached size is trusted until the folder's *signature* changes (the
//! modified times of the folder and its direct subfolders, which change when
//! files are added, removed or renamed in them), and is measured again anyway
//! after [`MAX_AGE`] to catch changes deeper down. The signature itself is
//! only re-read every [`RECHECK`], so opening a library doesn't touch every
//! folder on disk each time.
use std::collections::{HashSet, VecDeque};
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use crate::state::Shared;
/// How often a cached size's signature is checked against the disk.
pub const RECHECK: time::Duration = time::Duration::hours(1);
/// How long a size is trusted even if the signature hasn't changed.
pub const MAX_AGE: time::Duration = time::Duration::days(7);
/// Size of an item folder: what a move would copy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FolderSize {
pub bytes: u64,
pub files: u64,
/// Direct subfolders, e.g. a show's seasons or a movie's extras. Bytes in
/// files directly inside the folder are `bytes` minus these.
pub parts: Vec<PartSize>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartSize {
pub name: String,
pub bytes: u64,
pub files: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Record {
size: FolderSize,
signature: u64,
#[serde(with = "time::serde::rfc3339")]
measured_at: OffsetDateTime,
#[serde(with = "time::serde::rfc3339")]
checked_at: OffsetDateTime,
}
#[derive(Default)]
pub struct SizeQueue {
inner: Mutex<QueueState>,
}
#[derive(Default)]
struct QueueState {
queue: VecDeque<PathBuf>,
queued: HashSet<PathBuf>,
running: bool,
}
/// Cached sizes for these local folders, in the same order (`None` where
/// nothing is cached yet). Every folder is queued for checking.
pub async fn lookup(state: &Shared, folders: &[PathBuf]) -> anyhow::Result<Vec<Option<FolderSize>>> {
let keys: Vec<String> = folders.iter().map(|p| key(p)).collect();
let mut cached: std::collections::HashMap<String, Record> =
state.store.get_folder_sizes(keys.clone()).await?;
enqueue(state, folders.iter().cloned());
Ok(keys
.iter()
.map(|k| cached.remove(k).map(|r| r.size))
.collect())
}
fn enqueue(state: &Shared, folders: impl IntoIterator<Item = PathBuf>) {
let mut q = state.sizes.inner.lock().expect("size queue");
for f in folders {
if q.queued.insert(f.clone()) {
q.queue.push_back(f);
}
}
if !q.running && !q.queue.is_empty() {
q.running = true;
tokio::spawn(worker(state.clone()));
}
}
/// One folder at a time, so a NAS isn't asked to walk several at once.
async fn worker(state: Shared) {
loop {
let next = {
let mut q = state.sizes.inner.lock().expect("size queue");
match q.queue.pop_front() {
Some(p) => {
q.queued.remove(&p);
p
}
None => {
q.running = false;
return;
}
}
};
if let Err(e) = refresh(&state, &next).await {
tracing::warn!(folder = %next.display(), error = %format!("{e:#}"), "could not measure folder");
}
}
}
async fn refresh(state: &Shared, folder: &Path) -> anyhow::Result<()> {
let k = key(folder);
let cached: Option<Record> = state
.store
.get_folder_sizes(vec![k.clone()])
.await?
.remove(&k);
let now = OffsetDateTime::now_utc();
if cached.as_ref().is_some_and(|r| now - r.checked_at < RECHECK) {
return Ok(());
}
let f = folder.to_path_buf();
let Some(sig) = tokio::task::spawn_blocking(move || signature(&f)).await? else {
// Gone, e.g. moved away. Forget it.
state.store.delete_folder_size(&k).await?;
return Ok(());
};
let record = match cached {
Some(mut r) if r.signature == sig && now - r.measured_at < MAX_AGE => {
r.checked_at = now;
r
}
_ => {
let f = folder.to_path_buf();
let size = tokio::task::spawn_blocking(move || measure(&f)).await?;
Record {
size,
signature: sig,
measured_at: now,
checked_at: now,
}
}
};
state.store.put_folder_size(&k, &record).await?;
Ok(())
}
fn key(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
fn skipped(name: &std::ffi::OsStr) -> bool {
name.to_string_lossy().starts_with(jm_transfer::HIDDEN_PREFIX)
}
/// Modified times of the folder and its direct subfolders, hashed. `None` if
/// the folder doesn't exist.
pub fn signature(folder: &Path) -> Option<u64> {
let meta = std::fs::symlink_metadata(folder).ok()?;
if !meta.is_dir() {
return None;
}
let mut h = std::collections::hash_map::DefaultHasher::new();
meta.modified().ok().hash(&mut h);
let mut subdirs: Vec<(std::ffi::OsString, Option<std::time::SystemTime>)> =
std::fs::read_dir(folder)
.ok()?
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !skipped(&e.file_name()))
.map(|e| (e.file_name(), e.metadata().and_then(|m| m.modified()).ok()))
.collect();
subdirs.sort();
subdirs.hash(&mut h);
Some(h.finish())
}
/// Add up every regular file below `folder`, counting the same files a move
/// copies: links and jellymove's own `.jellymove-*` entries are skipped.
pub fn measure(folder: &Path) -> FolderSize {
let mut total = PartSize {
name: String::new(),
bytes: 0,
files: 0,
};
let mut parts = Vec::new();
for e in std::fs::read_dir(folder).into_iter().flatten().flatten() {
if skipped(&e.file_name()) {
continue;
}
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
let (bytes, files) = tree(&e.path());
parts.push(PartSize {
name: e.file_name().to_string_lossy().into_owned(),
bytes,
files,
});
total.bytes += bytes;
total.files += files;
} else if t.is_file() {
total.bytes += e.metadata().map(|m| m.len()).unwrap_or(0);
total.files += 1;
}
}
parts.sort_by_key(|p| natural_key(&p.name));
FolderSize {
bytes: total.bytes,
files: total.files,
parts,
}
}
fn tree(dir: &Path) -> (u64, u64) {
let mut bytes = 0;
let mut files = 0;
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
if skipped(&e.file_name()) {
continue;
}
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
stack.push(e.path());
} else if t.is_file() {
bytes += e.metadata().map(|m| m.len()).unwrap_or(0);
files += 1;
}
}
}
(bytes, files)
}
/// Sort "Season 2" before "Season 10".
fn natural_key(s: &str) -> Vec<(String, u64)> {
let mut out = Vec::new();
let mut text = String::new();
let mut num = String::new();
for c in s.chars() {
if c.is_ascii_digit() {
num.push(c);
} else {
if !num.is_empty() {
out.push((std::mem::take(&mut text), num.parse().unwrap_or(u64::MAX)));
num.clear();
}
text.extend(c.to_lowercase());
}
}
out.push((text, num.parse().unwrap_or(0)));
out
}
#[cfg(test)]
mod tests {
use super::*;
fn write(p: &Path, len: usize) {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, vec![0u8; len]).unwrap();
}
#[test]
fn measures_files_and_direct_subfolders() {
let tmp = tempfile::tempdir().unwrap();
let show = tmp.path().join("Severance");
write(&show.join("tvshow.nfo"), 10);
write(&show.join("Season 10/e.mkv"), 300);
write(&show.join("Season 2/e1.mkv"), 100);
write(&show.join("Season 2/e2.mkv"), 200);
write(&show.join("Season 2/subs/e1.srt"), 5);
write(&show.join(".jellymove-partial/x.part"), 999);
#[cfg(unix)]
std::os::unix::fs::symlink(show.join("Season 2/e1.mkv"), show.join("link.mkv")).unwrap();
let s = measure(&show);
assert_eq!((s.bytes, s.files), (615, 5));
let parts: Vec<_> = s.parts.iter().map(|p| (p.name.as_str(), p.bytes, p.files)).collect();
assert_eq!(parts, [("Season 2", 305, 3), ("Season 10", 300, 1)]);
}
#[test]
fn signature_changes_when_a_season_changes() {
let tmp = tempfile::tempdir().unwrap();
let show = tmp.path().join("Show");
write(&show.join("Season 1/e1.mkv"), 1);
let before = signature(&show).unwrap();
assert_eq!(signature(&show), Some(before));
// Adding an episode changes the season folder's modified time.
let s1 = show.join("Season 1");
let old = std::fs::metadata(&s1).unwrap().modified().unwrap();
write(&s1.join("e2.mkv"), 1);
let file = std::fs::File::open(&s1).unwrap();
file.set_modified(old + std::time::Duration::from_secs(5)).unwrap();
assert_ne!(signature(&show), Some(before));
assert_eq!(signature(&tmp.path().join("missing")), None);
}
#[test]
fn natural_order() {
let mut v = vec!["Season 10", "Specials", "Season 2", "Season 1"];
v.sort_by_key(|s| natural_key(s));
assert_eq!(v, ["Season 1", "Season 2", "Season 10", "Specials"]);
}
}
+3
View File
@@ -21,6 +21,8 @@ pub struct AppState {
pub running: Mutex<HashSet<JobId>>, pub running: Mutex<HashSet<JobId>>,
/// Exports currently being hashed, so a duplicate request doesn't start a second pass. /// Exports currently being hashed, so a duplicate request doesn't start a second pass.
pub preparing: Mutex<HashSet<String>>, pub preparing: Mutex<HashSet<String>>,
/// Folders waiting to have their size measured.
pub sizes: crate::sizes::SizeQueue,
} }
pub type Shared = Arc<AppState>; pub type Shared = Arc<AppState>;
@@ -58,6 +60,7 @@ impl AppState {
job_slots: Arc::new(Semaphore::new(slots)), job_slots: Arc::new(Semaphore::new(slots)),
running: Mutex::new(HashSet::new()), running: Mutex::new(HashSet::new()),
preparing: Mutex::new(HashSet::new()), preparing: Mutex::new(HashSet::new()),
sizes: Default::default(),
}) })
} }
+50
View File
@@ -517,6 +517,56 @@ async fn an_item_moved_away_twice_gets_two_trash_entries() {
assert_eq!(home_trash[0]["moved_to"], "cloud"); assert_eq!(home_trash[0]["moved_to"], "cloud");
} }
/// List a library until every item has a size, like the UI does.
async fn items_with_sizes(base: &str, query: &str) -> Vec<Value> {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let items = get(base, &format!("/api/items?{query}")).await;
let items = items.as_array().unwrap().clone();
if !items.is_empty() && items.iter().all(|i| i["size"].is_object()) {
return items;
}
assert!(Instant::now() < deadline, "sizes never arrived: {items:#?}");
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
#[tokio::test]
async fn lists_folder_sizes_for_movies_shows_and_seasons() {
let (cloud, home) = pair(|root| {
seed_movie(root);
seed_series(root);
})
.await;
// A movie's size is its whole folder: video, subtitles, NFO and extras.
let movies = items_with_sizes(&cloud.url, "node=local&library=lib-movies").await;
let alien = &movies[0]["size"];
assert_eq!(alien["bytes"], tree_size(&cloud.movies().join("Alien (1979)")));
assert_eq!(alien["files"], 4);
// A show has a total plus one part per season folder; loose files such
// as tvshow.nfo count towards the total only.
let shows = items_with_sizes(&home.url, "node=peer&library=lib-tv-shows").await;
let s = &shows[0]["size"];
assert_eq!(shows[0]["name"], "Severance");
assert_eq!(s["bytes"], tree_size(&cloud.tv().join("Severance")));
assert_eq!(s["files"], 4);
assert_eq!(
s["parts"],
json!([
{"name": "Season 01", "bytes": 22, "files": 2},
{"name": "Season 02", "bytes": 13, "files": 1},
])
);
// After a move the item is measured where it now lives.
let movie = cloud.fake.find("Movie", "Alien").unwrap();
move_item(&cloud.url, "local", &movie, "Alien").await;
let on_home = items_with_sizes(&home.url, "node=local&library=lib-movies").await;
assert_eq!(on_home[0]["size"], *alien);
}
#[tokio::test] #[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;
+100
View File
@@ -3,6 +3,7 @@
//! Jobs and exports are stored as JSON documents with a few indexed columns. //! Jobs and exports are stored as JSON documents with a few indexed columns.
//! The schema is deliberately small; the job struct is the source of truth. //! The schema is deliberately small; the job struct is the source of truth.
use std::collections::HashMap;
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -33,6 +34,11 @@ const MIGRATIONS: &[&str] = &[
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
body TEXT NOT NULL body TEXT NOT NULL
);", );",
// v2: cached sizes of item folders, keyed by local path.
"CREATE TABLE folder_sizes (
path TEXT PRIMARY KEY,
body TEXT NOT NULL
);",
]; ];
#[derive(Clone)] #[derive(Clone)]
@@ -161,6 +167,54 @@ impl Store {
body.map(|b| serde_json::from_str(&b).map_err(Into::into)) body.map(|b| serde_json::from_str(&b).map_err(Into::into))
.transpose() .transpose()
} }
/// Cached folder sizes for `paths`. Paths with no record are left out.
pub async fn get_folder_sizes<T: DeserializeOwned>(
&self,
paths: Vec<String>,
) -> Result<HashMap<String, T>> {
let rows: Vec<(String, String)> = self
.with(move |c| {
let mut out = Vec::new();
let mut stmt = c.prepare_cached("SELECT path, body FROM folder_sizes WHERE path = ?1")?;
for p in &paths {
if let Some(row) = stmt
.query_row([p], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?
{
out.push(row);
}
}
Ok(out)
})
.await?;
rows.into_iter()
.map(|(p, b)| Ok((p, serde_json::from_str(&b)?)))
.collect()
}
pub async fn put_folder_size<T: Serialize>(&self, path: &str, size: &T) -> Result<()> {
let path = path.to_string();
let body = serde_json::to_string(size)?;
self.with(move |c| {
c.execute(
"INSERT INTO folder_sizes (path, body) VALUES (?1, ?2)
ON CONFLICT(path) DO UPDATE SET body = excluded.body",
params![path, body],
)?;
Ok(())
})
.await
}
pub async fn delete_folder_size(&self, path: &str) -> Result<()> {
let path = path.to_string();
self.with(move |c| {
c.execute("DELETE FROM folder_sizes WHERE path = ?1", [path])?;
Ok(())
})
.await
}
} }
#[cfg(test)] #[cfg(test)]
@@ -205,4 +259,50 @@ mod tests {
let e: serde_json::Value = s.get_export("e1").await.unwrap().unwrap(); let e: serde_json::Value = s.get_export("e1").await.unwrap().unwrap();
assert_eq!(e["x"], 1); assert_eq!(e["x"], 1);
} }
#[tokio::test]
async fn folder_sizes_roundtrip() {
let store = Store::in_memory().unwrap();
store
.put_folder_size("/m/A", &serde_json::json!({"bytes": 1}))
.await
.unwrap();
store
.put_folder_size("/m/A", &serde_json::json!({"bytes": 2}))
.await
.unwrap();
store
.put_folder_size("/m/B", &serde_json::json!({"bytes": 3}))
.await
.unwrap();
let got: HashMap<String, serde_json::Value> = store
.get_folder_sizes(vec!["/m/A".into(), "/m/B".into(), "/m/C".into()])
.await
.unwrap();
assert_eq!(got.len(), 2);
assert_eq!(got["/m/A"]["bytes"], 2);
store.delete_folder_size("/m/A").await.unwrap();
let got: HashMap<String, serde_json::Value> =
store.get_folder_sizes(vec!["/m/A".into()]).await.unwrap();
assert!(got.is_empty());
}
#[test]
fn upgrades_a_v1_database() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("state.db");
{
let c = Connection::open(&path).unwrap();
c.execute_batch(MIGRATIONS[0]).unwrap();
c.pragma_update(None, "user_version", 1).unwrap();
}
Store::open(&path).unwrap();
let c = Connection::open(&path).unwrap();
let v: i64 = c
.pragma_query_value(None, "user_version", |r| r.get(0))
.unwrap();
assert_eq!(v as usize, MIGRATIONS.len());
c.execute("INSERT INTO folder_sizes (path, body) VALUES ('p', '{}')", [])
.unwrap();
}
} }
+10
View File
@@ -68,6 +68,16 @@ Retrying a failed job re-runs from its stage. Interrupted jobs resume on start.
- Alternatives kept open behind the pull/serve split: iroh (QUIC, NAT - Alternatives kept open behind the pull/serve split: iroh (QUIC, NAT
traversal) once iroh-blobs reaches 1.0; rclone as a pluggable transport. traversal) once iroh-blobs reaches 1.0; rclone as a pluggable transport.
## Folder sizes
Library items carry the size of their folder on disk, counting the same files a
move copies. Each agent measures its own folders (`sizes.rs`): listing a library
returns cached sizes at once and queues every folder for a single background
worker, so a NAS is never asked to walk several folders at once. A cached size
is kept while the folder's signature (modified times of the folder and its
direct subfolders) is unchanged, re-checked at most hourly, and measured again
after seven days regardless. The UI polls the list until every size is in.
## Jellyfin integration ## Jellyfin integration
- Browse: `GET /Items?parentId=<library>&includeItemTypes=Movie,Series&recursive=true&fields=Path,…` - Browse: `GET /Items?parentId=<library>&includeItemTypes=Movie,Series&recursive=true&fields=Path,…`
+138 -20
View File
@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { api, type Library, type LibraryItem, type Side } from './api'; import { api, bytes, type Library, type LibraryItem, type Side } from './api';
interface Props { interface Props {
localName: string; localName: string;
@@ -18,11 +18,53 @@
let error = $state<string | null>(null); let error = $state<string | null>(null);
let busy = $state<string | null>(null); // item id being submitted let busy = $state<string | null>(null); // item id being submitted
let notice = $state<string | null>(null); let notice = $state<string | null>(null);
let sort = $state<'name' | 'size'>('name');
let open = $state<Record<string, boolean>>({}); // shows with seasons expanded
const sourceName = $derived(side === 'local' ? localName : peerName); const sourceName = $derived(side === 'local' ? localName : peerName);
const destName = $derived(side === 'local' ? peerName : localName); const destName = $derived(side === 'local' ? peerName : localName);
const shown = $derived(
sort === 'size' ? [...items].sort((a, b) => (b.size?.bytes ?? -1) - (a.size?.bytes ?? -1)) : items,
);
const measuring = $derived(items.filter((i) => !i.size).length);
const total = $derived(items.reduce((n, i) => n + (i.size?.bytes ?? 0), 0));
// Sizes are worked out in the background on the server that has the
// files; ask again until they've all arrived.
let poll: ReturnType<typeof setTimeout> | undefined;
let generation = 0;
function stopPolling() {
clearTimeout(poll);
poll = undefined;
}
function pollSizes(gen: number, attempt = 0) {
stopPolling();
if (!items.some((i) => !i.size) || attempt >= 150) return;
poll = setTimeout(async () => {
try {
const fresh = await api.items(side, libraryId, search.trim());
if (gen !== generation) return;
const byId = Object.fromEntries(fresh.map((i) => [i.id, i.size]));
items = items.map((i) => (i.size ? i : { ...i, size: byId[i.id] ?? null }));
} catch {
/* keep what we have; try again */
}
if (gen === generation) pollSizes(gen, attempt + 1);
}, 2000);
}
function loose(item: LibraryItem): number {
if (!item.size) return 0;
return item.size.bytes - item.size.parts.reduce((n, p) => n + p.bytes, 0);
}
const fileCount = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`;
async function loadLibraries(s: Side) { async function loadLibraries(s: Side) {
generation++;
stopPolling();
error = null; error = null;
items = []; items = [];
libraries = []; libraries = [];
@@ -35,16 +77,22 @@
} }
async function loadItems() { async function loadItems() {
stopPolling();
const gen = ++generation;
if (!libraryId) return; if (!libraryId) return;
loading = true; loading = true;
error = null; error = null;
try { try {
items = await api.items(side, libraryId, search.trim()); const got = await api.items(side, libraryId, search.trim());
if (gen !== generation) return;
items = got;
pollSizes(gen);
} catch (e) { } catch (e) {
if (gen !== generation) return;
error = (e as Error).message; error = (e as Error).message;
items = []; items = [];
} finally { } finally {
loading = false; if (gen === generation) loading = false;
} }
} }
@@ -56,6 +104,10 @@
onMount(() => { onMount(() => {
loadLibraries(side); loadLibraries(side);
return () => {
generation++;
stopPolling();
};
}); });
// Reload items when the library or search text changes, debounced. // Reload items when the library or search text changes, debounced.
@@ -100,12 +152,22 @@
{/each} {/each}
</select> </select>
<input type="search" placeholder="Search titles…" bind:value={search} aria-label="Search" /> <input type="search" placeholder="Search titles…" bind:value={search} aria-label="Search" />
<select bind:value={sort} aria-label="Sort by">
<option value="name">By name</option>
<option value="size">Largest first</option>
</select>
</section> </section>
<p class="direction muted"> <p class="direction muted">
Moving from <strong class={side}>{sourceName}</strong> to Moving from <strong class={side}>{sourceName}</strong> to
<strong class={side === 'local' ? 'peer' : 'local'}>{destName}</strong>. The whole folder moves, including <strong class={side === 'local' ? 'peer' : 'local'}>{destName}</strong>. The whole folder moves, including
subtitles, artwork, NFOs and extras, along with everyone's watch history. subtitles, artwork, NFOs and extras, along with everyone's watch history.
{#if items.length}
<span class="totals">
{items.length} {items.length === 1 ? 'item' : 'items'}, {bytes(total)}{#if measuring}
so far, measuring {measuring} more…{/if}
</span>
{/if}
</p> </p>
{#if error}<p class="panel msg error">{error}</p>{/if} {#if error}<p class="panel msg error">{error}</p>{/if}
@@ -117,22 +179,44 @@
{:else if !items.length} {:else if !items.length}
<li class="empty muted">{libraryId ? 'Nothing here.' : 'No movie or TV libraries found.'}</li> <li class="empty muted">{libraryId ? 'Nothing here.' : 'No movie or TV libraries found.'}</li>
{/if} {/if}
{#each items as item (item.id)} {#each shown as item (item.id)}
<li> <li>
<span class="kind" title={item.kind}>{item.kind === 'Series' ? 'TV' : 'Film'}</span> <div class="row">
<div class="title"> <span class="kind" title={item.kind}>{item.kind === 'Series' ? 'TV' : 'Film'}</span>
<span class="name">{item.name}</span> <div class="title">
{#if item.year}<span class="muted">{item.year}</span>{/if} <span class="name">{item.name}</span>
{#if item.path}<div class="path mono muted" title={item.path}>{item.path}</div>{/if} {#if item.year}<span class="muted">{item.year}</span>{/if}
</div> {#if item.path}<div class="path mono muted" title={item.path}>{item.path}</div>{/if}
<div class="actions"> {#if item.kind === 'Series' && item.size?.parts.length}
<button disabled={busy === item.id} onclick={() => move(item, true)} title="Check and plan without copying anything"> <button class="disclose" aria-expanded={!!open[item.id]} onclick={() => (open[item.id] = !open[item.id])}>
Dry run {open[item.id] ? 'Hide' : 'Show'} sizes by season ({item.size.parts.length})
</button> </button>
<button class="primary" disabled={busy === item.id} onclick={() => move(item, false)}> {/if}
Move to {destName} → </div>
</button> <span class="size" title={item.size ? fileCount(item.size.files) : 'Working out the size…'}>
{#if item.size}{bytes(item.size.bytes)}{:else}<span class="muted">measuring…</span>{/if}
</span>
<div class="actions">
<button disabled={busy === item.id} onclick={() => move(item, true)} title="Check and plan without copying anything">
Dry run
</button>
<button class="primary" disabled={busy === item.id} onclick={() => move(item, false)}>
Move to {destName} →
</button>
</div>
</div> </div>
{#if open[item.id] && item.size}
<table class="parts">
<tbody>
{#each item.size.parts as p (p.name)}
<tr><td>{p.name}</td><td class="muted">{fileCount(p.files)}</td><td class="num">{bytes(p.bytes)}</td></tr>
{/each}
{#if loose(item) > 0}
<tr><td class="muted">Other files in the show folder</td><td></td><td class="num">{bytes(loose(item))}</td></tr>
{/if}
</tbody>
</table>
{/if}
</li> </li>
{/each} {/each}
</ul> </ul>
@@ -192,17 +276,51 @@
padding: 0; padding: 0;
} }
.list li { .list li {
padding: 0.7rem 1rem;
border-top: 1px solid var(--line);
}
.row {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.9rem; gap: 0.9rem;
padding: 0.7rem 1rem; }
border-top: 1px solid var(--line); .totals {
display: block;
margin-top: 0.2rem;
}
.size {
font-variant-numeric: tabular-nums;
white-space: nowrap;
min-width: 5.5rem;
text-align: right;
}
.disclose {
display: block;
margin-top: 0.25rem;
padding: 0;
border: none;
background: transparent;
color: var(--peer);
font-size: 0.82rem;
}
.parts {
margin: 0.5rem 0 0.1rem 3.5rem;
border-collapse: collapse;
font-size: 0.88rem;
}
.parts td {
padding: 0.2rem 1.2rem 0.2rem 0;
}
.parts .num {
text-align: right;
font-variant-numeric: tabular-nums;
padding-right: 0;
} }
.list li:first-child { .list li:first-child {
border-top: none; border-top: none;
} }
.empty { .empty {
justify-content: center; text-align: center;
padding: 2rem !important; padding: 2rem !important;
} }
.kind { .kind {
+15
View File
@@ -34,12 +34,27 @@ export interface Library {
locations: string[]; locations: string[];
} }
export interface PartSize {
name: string;
bytes: number;
files: number;
}
export interface FolderSize {
bytes: number;
files: number;
/** Direct subfolders: a show's seasons, a movie's extras. */
parts: PartSize[];
}
export interface LibraryItem { export interface LibraryItem {
id: string; id: string;
name: string; name: string;
kind: 'Movie' | 'Series' | string; kind: 'Movie' | 'Series' | string;
year: number | null; year: number | null;
path: string | null; path: string | null;
/** Null until the agent has measured the folder. */
size: FolderSize | null;
} }
export type Stage = export type Stage =