From 2bd4489b1acbbbba87d49c5a6dda8322f7f5a25d Mon Sep 17 00:00:00 2001 From: IxianPixel Date: Fri, 6 Nov 2026 17:21:22 +0000 Subject: [PATCH] Update library lists when a move finishes (#1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Library now follows moves on both servers: an item shows "Moving to …" while it moves and "Moved to …" until the source's Jellyfin drops it after its rescan; the list reloads when a move finishes and checks again every 20 s for a few minutes. The destination shows the new item straight away. --- CHANGELOG.md | 11 +++ crates/jm-server/src/export.rs | 2 + crates/jm-server/src/runner.rs | 2 + crates/jm-server/src/sizes.rs | 10 ++- crates/jm-server/tests/e2e.rs | 14 ++++ ui/src/App.svelte | 9 ++- ui/src/lib/Jobs.svelte | 46 +++---------- ui/src/lib/Library.svelte | 119 +++++++++++++++++++++++++++------ ui/src/lib/moves.svelte.ts | 84 +++++++++++++++++++++++ 9 files changed, 236 insertions(+), 61 deletions(-) create mode 100644 ui/src/lib/moves.svelte.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d2c33b..706dd85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,10 +18,21 @@ that server doesn't have the show. Moving the last season also trashes the leftover show folder on the source. (#4) +### Updated + +- **Starting a move keeps you in the Library.** The item shows "Moving to …" + while it moves, rather than the app switching to the Moves tab. + ### Fixed - **Moving an item away a second time failed** if its first trip was still in the trash. Each move now gets its own trash entry. +- **Library lists didn't update after a move.** They now reload when a move + finishes: the item appears on the destination straight away, and is marked + "Moved to …" on the source until that server's Jellyfin drops it after its + next scan. Sizes of folders a move touched are measured again at once. (#1) +- **Switching servers in the Library could show an empty list** when both + libraries had the same ID. ## v0.1.1 diff --git a/crates/jm-server/src/export.rs b/crates/jm-server/src/export.rs index 97377af..a247bb6 100644 --- a/crates/jm-server/src/export.rs +++ b/crates/jm-server/src/export.rs @@ -484,6 +484,8 @@ pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow: } } + // After a season move the show is still listed here, but smaller. + crate::sizes::forget(state, &local_folder).await; if let Err(e) = state .jellyfin .media_updated(std::slice::from_ref(&export.jellyfin_folder)) diff --git a/crates/jm-server/src/runner.rs b/crates/jm-server/src/runner.rs index c65e60e..b2bd579 100644 --- a/crates/jm-server/src/runner.rs +++ b/crates/jm-server/src/runner.rs @@ -347,6 +347,8 @@ async fn promote(state: &Shared, job: &mut Job) -> anyhow::Result<()> { Some(season) => target_local.join(&season.folder), None => target_local.clone(), }; + // A season changes the size of a show that may already be listed here. + crate::sizes::forget(state, &target_local).await; job.note(format!("moved into {}", placed.display())); job.advance(Stage::Promoted); Ok(()) diff --git a/crates/jm-server/src/sizes.rs b/crates/jm-server/src/sizes.rs index 6f48df6..3a5d968 100644 --- a/crates/jm-server/src/sizes.rs +++ b/crates/jm-server/src/sizes.rs @@ -20,7 +20,7 @@ use std::sync::Mutex; use serde::{Deserialize, Serialize}; use time::OffsetDateTime; -use crate::state::Shared; +use crate::state::{AppState, Shared}; /// How often a cached size's signature is checked against the disk. pub const RECHECK: time::Duration = time::Duration::hours(1); @@ -151,6 +151,14 @@ async fn refresh(state: &Shared, folder: &Path) -> anyhow::Result<()> { Ok(()) } +/// Drop the cached size of a folder a move has just changed, so the next +/// listing measures it again instead of waiting for the hourly check. +pub async fn forget(state: &AppState, folder: &Path) { + if let Err(e) = state.store.delete_folder_size(&key(folder)).await { + tracing::warn!(folder = %folder.display(), error = %e, "could not forget folder size"); + } +} + fn key(p: &Path) -> String { p.to_string_lossy().into_owned() } diff --git a/crates/jm-server/tests/e2e.rs b/crates/jm-server/tests/e2e.rs index 62d5f93..40eaf62 100644 --- a/crates/jm-server/tests/e2e.rs +++ b/crates/jm-server/tests/e2e.rs @@ -589,6 +589,9 @@ async fn moves_seasons_one_at_a_time_and_trashes_the_empty_show() { assert_eq!(seasons[0]["folder"], "Season 01"); assert_eq!(seasons[1]["number"], 2); + // List cloud's shows first so their sizes are cached. + items_with_sizes(&cloud.url, "node=local&library=lib-tv-shows").await; + // Season 2 into a show home doesn't have yet: the show's NFO comes too. let s2 = cloud.fake.season_id("Severance", 2).unwrap(); assert_eq!(seasons[1]["id"], s2); @@ -612,8 +615,15 @@ async fn moves_seasons_one_at_a_time_and_trashes_the_empty_show() { let home_series = home.fake.find("Series", "Severance").unwrap(); assert!(home.fake.get_user_data(&home_series).is_none()); + // The cached size of cloud's show was dropped, so it's measured again + // without waiting for the hourly check. + let shows = items_with_sizes(&cloud.url, "node=local&library=lib-tv-shows").await; + assert_eq!(shows[0]["size"]["bytes"], tree_size(&show_cloud)); + assert_eq!(shows[0]["size"]["parts"].as_array().unwrap().len(), 1); + // Mark home's copy of the NFO so we can tell it isn't overwritten. std::fs::write(show_home.join("tvshow.nfo"), b"home's own").unwrap(); + items_with_sizes(&home.url, "node=local&library=lib-tv-shows").await; // Season 1 joins the existing show, and was the last one on cloud. let s1 = cloud.fake.season_id("Severance", 1).unwrap(); @@ -628,6 +638,10 @@ async fn moves_seasons_one_at_a_time_and_trashes_the_empty_show() { ); assert!(show_home.join("Season 01/Severance S01E02.mkv").exists()); assert_eq!(std::fs::read(show_home.join("tvshow.nfo")).unwrap(), b"home's own"); + // Home's show grew, and its size says so straight away. + let shows = items_with_sizes(&home.url, "node=local&library=lib-tv-shows").await; + assert_eq!(shows[0]["size"]["bytes"], tree_size(&show_home)); + assert_eq!(shows[0]["size"]["parts"].as_array().unwrap().len(), 2); let new_e1 = home.fake.episode_id("Severance", 1, 1).unwrap(); assert_eq!(home.fake.get_user_data(&new_e1).unwrap()["Played"], true); diff --git a/ui/src/App.svelte b/ui/src/App.svelte index ecfdc06..111025a 100644 --- a/ui/src/App.svelte +++ b/ui/src/App.svelte @@ -5,6 +5,7 @@ import Jobs from './lib/Jobs.svelte'; import StatusView from './lib/StatusView.svelte'; import Trash from './lib/Trash.svelte'; + import { watchMoves } from './lib/moves.svelte'; type Tab = 'library' | 'jobs' | 'trash' | 'status'; let tab = $state('library'); @@ -23,7 +24,11 @@ onMount(() => { loadStatus(); const t = setInterval(loadStatus, 30_000); - return () => clearInterval(t); + const stopWatching = watchMoves(); + return () => { + clearInterval(t); + stopWatching(); + }; }); const localName = $derived(status?.node.node_name ?? 'this server'); @@ -63,7 +68,7 @@ {/if} {#if tab === 'library'} - (tab = 'jobs')} /> + {:else if tab === 'jobs'} {:else if tab === 'trash'} diff --git a/ui/src/lib/Jobs.svelte b/ui/src/lib/Jobs.svelte index 3b1ed96..a321dcc 100644 --- a/ui/src/lib/Jobs.svelte +++ b/ui/src/lib/Jobs.svelte @@ -1,52 +1,24 @@ {#if error}

{error}

{/if} -{#if peerError}

Couldn't load moves running on the peer: {peerError}

{/if} +{#if moves.peerError}

Couldn't load moves running on the peer: {moves.peerError}

{/if} -{#if !sorted.length} +{#if moves.loaded && !sorted.length}

No moves yet. Pick something in Library to get started.

{/if} diff --git a/ui/src/lib/Library.svelte b/ui/src/lib/Library.svelte index 6b388b7..d3188d3 100644 --- a/ui/src/lib/Library.svelte +++ b/ui/src/lib/Library.svelte @@ -1,13 +1,13 @@ +{#snippet moveTag(mark: Mark)} + {#if mark.moving} + Moving to {mark.to}… + {:else} + Moved to {mark.to} + {/if} +{/snippet} +
- {#if item.size}{bytes(item.size.bytes)}{:else}measuring…{/if} + {#if item.size}{bytes(item.size.bytes)}{:else if !gone(item)}measuring…{/if}
- - + {#if marks[item.id]} + {@render moveTag(marks[item.id])} + {:else} + + + {/if}
{#if open[item.id]} @@ -247,7 +310,9 @@ {part ? fileCount(part.files) : ''} {part ? bytes(part.bytes) : ''} - {#if season.path} + {#if marks[season.id]} + {@render moveTag(marks[season.id])} + {:else if season.path} @@ -381,6 +446,18 @@ padding-right: 0; white-space: nowrap; } + .tag { + font-size: 0.82rem; + border: 1px solid var(--line); + border-radius: 6px; + padding: 0.2rem 0.55rem; + color: var(--muted); + white-space: nowrap; + } + .tag.moving { + color: var(--peer); + border-color: color-mix(in srgb, var(--peer) 50%, var(--line)); + } .seasons-msg { margin: 0.5rem 0 0 3.5rem; font-size: 0.88rem; diff --git a/ui/src/lib/moves.svelte.ts b/ui/src/lib/moves.svelte.ts new file mode 100644 index 0000000..3cca61a --- /dev/null +++ b/ui/src/lib/moves.svelte.ts @@ -0,0 +1,84 @@ +// Every move on either server, kept up to date for the whole app: live +// events for moves running here, and polling for moves running on the peer +// (fast while something is moving, slow otherwise). + +import { api, type Job } from './api'; + +export const moves = $state({ + jobs: {} as Record, + error: null as string | null, + peerError: null as string | null, + loaded: false, +}); + +type DoneListener = (job: Job) => void; +const listeners = new Set(); + +/** Call `fn` whenever a move (not a dry run) finishes. Returns an unsubscribe. */ +export function onMoveDone(fn: DoneListener): () => void { + listeners.add(fn); + return () => listeners.delete(fn); +} + +const isActive = (j: Job) => j.status.kind === 'Queued' || j.status.kind === 'Running'; + +/** Record a job snapshot and tell listeners if it has just finished. */ +function put(job: Job) { + const before = moves.jobs[job.id]; + moves.jobs[job.id] = job; + const finished = job.status.kind === 'Done' && !job.dry_run && before && before.status.kind !== 'Done'; + // A move we only learn about once it's done (e.g. it finished between + // polls) still counts, as long as the list had loaded before. + const unseen = job.status.kind === 'Done' && !job.dry_run && !before && moves.loaded; + if (finished || unseen) for (const fn of listeners) fn(job); +} + +export async function refreshMoves() { + try { + const view = await api.jobs(); + const all = [...view.local, ...view.peer]; + for (const j of all) put(j); + // Forget jobs that no longer exist anywhere. + const ids = new Set(all.map((j) => j.id)); + for (const id of Object.keys(moves.jobs)) if (!ids.has(id)) delete moves.jobs[id]; + moves.peerError = view.peer_error; + moves.error = null; + moves.loaded = true; + } catch (e) { + moves.error = (e as Error).message; + } +} + +let timer: ReturnType | undefined; +let running = false; + +async function tick() { + clearTimeout(timer); + await refreshMoves(); + if (!running) return; + const busy = Object.values(moves.jobs).some(isActive); + timer = setTimeout(tick, busy ? 2000 : 10_000); +} + +/** Note a move just started here, and check on it soon. */ +export function trackMove(job: Job) { + put(job); + if (running) { + clearTimeout(timer); + timer = setTimeout(tick, 1000); + } +} + +/** Start watching for the lifetime of the app. Returns a stop function. */ +export function watchMoves(): () => void { + if (running) return () => {}; + running = true; + const es = new EventSource('/api/events'); + es.addEventListener('job', (ev) => put(JSON.parse((ev as MessageEvent).data) as Job)); + tick(); + return () => { + running = false; + clearTimeout(timer); + es.close(); + }; +}