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.
This commit is contained in:
1 parent
484ac50508
commit
2bd4489b1a
9 files changed
+230
-55
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
+7
-2
@@ -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<Tab>('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'}
|
||||
<Library {localName} {peerName} onmoved={() => (tab = 'jobs')} />
|
||||
<Library {localName} {peerName} />
|
||||
{:else if tab === 'jobs'}
|
||||
<Jobs {localName} />
|
||||
{:else if tab === 'trash'}
|
||||
|
||||
+9
-37
@@ -1,52 +1,24 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { api, bytes, STAGE_LABEL, STAGES, type Job } from './api';
|
||||
import { moves, trackMove } from './moves.svelte';
|
||||
|
||||
interface Props {
|
||||
localName: string;
|
||||
}
|
||||
let { localName }: Props = $props();
|
||||
|
||||
let jobs = $state<Record<string, Job>>({});
|
||||
let peerError = $state<string | null>(null);
|
||||
let error = $state<string | null>(null);
|
||||
let retryError = $state<string | null>(null);
|
||||
let open = $state<Record<string, boolean>>({});
|
||||
|
||||
const sorted = $derived(Object.values(jobs).sort((a, b) => b.created.localeCompare(a.created)));
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const view = await api.jobs();
|
||||
const next: Record<string, Job> = {};
|
||||
for (const j of [...view.local, ...view.peer]) next[j.id] = j;
|
||||
jobs = next;
|
||||
peerError = view.peer_error;
|
||||
error = null;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
load();
|
||||
// Live progress for jobs running here; poll for jobs running on the peer.
|
||||
const es = new EventSource('/api/events');
|
||||
es.addEventListener('job', (ev) => {
|
||||
const j = JSON.parse((ev as MessageEvent).data) as Job;
|
||||
jobs[j.id] = j;
|
||||
});
|
||||
const t = setInterval(load, 2000);
|
||||
return () => {
|
||||
es.close();
|
||||
clearInterval(t);
|
||||
};
|
||||
});
|
||||
const sorted = $derived(Object.values(moves.jobs).sort((a, b) => b.created.localeCompare(a.created)));
|
||||
const error = $derived(retryError ?? moves.error);
|
||||
|
||||
async function retry(id: string) {
|
||||
try {
|
||||
jobs[id] = await api.retry(id);
|
||||
trackMove(await api.retry(id));
|
||||
retryError = null;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
retryError = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,9 +47,9 @@
|
||||
</script>
|
||||
|
||||
{#if error}<p class="panel msg error">{error}</p>{/if}
|
||||
{#if peerError}<p class="panel msg muted">Couldn't load moves running on the peer: {peerError}</p>{/if}
|
||||
{#if moves.peerError}<p class="panel msg muted">Couldn't load moves running on the peer: {moves.peerError}</p>{/if}
|
||||
|
||||
{#if !sorted.length}
|
||||
{#if moves.loaded && !sorted.length}
|
||||
<p class="panel empty muted">No moves yet. Pick something in Library to get started.</p>
|
||||
{/if}
|
||||
|
||||
|
||||
+92
-15
@@ -1,13 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { api, bytes, type Library, type LibraryItem, type Movable, type SeasonItem, type Side } from './api';
|
||||
import { moves, onMoveDone, trackMove } from './moves.svelte';
|
||||
|
||||
interface Props {
|
||||
localName: string;
|
||||
peerName: string;
|
||||
onmoved: () => void;
|
||||
}
|
||||
let { localName, peerName, onmoved }: Props = $props();
|
||||
let { localName, peerName }: Props = $props();
|
||||
|
||||
let side = $state<Side>('local');
|
||||
let libraries = $state<Library[]>([]);
|
||||
@@ -28,22 +28,57 @@
|
||||
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.
|
||||
// Items with a move under way, or one that finished recently but that the
|
||||
// source's Jellyfin still lists (it drops them after its own rescan).
|
||||
const RECENT_MS = 15 * 60_000;
|
||||
type Mark = { moving: boolean; to: string };
|
||||
const marks = $derived.by(() => {
|
||||
const out: Record<string, Mark> = {};
|
||||
const now = Date.now();
|
||||
for (const j of Object.values(moves.jobs)) {
|
||||
if (j.dry_run || j.source_node !== sourceName) continue;
|
||||
const active = j.status.kind === 'Queued' || j.status.kind === 'Running';
|
||||
if (active) {
|
||||
out[j.source_item_id] = { moving: true, to: j.target_node };
|
||||
} else if (j.status.kind === 'Done' && now - Date.parse(j.updated) < RECENT_MS) {
|
||||
out[j.source_item_id] ??= { moving: false, to: j.target_node };
|
||||
}
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
let poll: ReturnType<typeof setTimeout> | undefined;
|
||||
let recheck: ReturnType<typeof setTimeout> | undefined;
|
||||
let rechecks = 0;
|
||||
let generation = 0;
|
||||
|
||||
function stopPolling() {
|
||||
clearTimeout(poll);
|
||||
clearTimeout(recheck);
|
||||
poll = undefined;
|
||||
recheck = undefined;
|
||||
}
|
||||
|
||||
/** While a moved item is still listed, look again every 20 s for a few minutes. */
|
||||
function recheckMoved(gen: number) {
|
||||
if (rechecks >= 12 || !items.some(gone)) return;
|
||||
rechecks++;
|
||||
recheck = setTimeout(() => {
|
||||
if (gen === generation) loadItems();
|
||||
}, 20_000);
|
||||
}
|
||||
|
||||
/** An item that has moved away: its folder is gone, so it has no size to wait for. */
|
||||
const gone = (i: LibraryItem) => !!marks[i.id] && !marks[i.id].moving;
|
||||
const measuring = $derived(items.filter((i) => !i.size && !gone(i)).length);
|
||||
|
||||
function pollSizes(gen: number, attempt = 0) {
|
||||
stopPolling();
|
||||
if (!items.some((i) => !i.size) || attempt >= 150) return;
|
||||
clearTimeout(poll);
|
||||
if (!items.some((i) => !i.size && !gone(i)) || attempt >= 150) return;
|
||||
poll = setTimeout(async () => {
|
||||
try {
|
||||
const fresh = await api.items(side, libraryId, search.trim());
|
||||
@@ -62,10 +97,15 @@
|
||||
const have = seasons[item.id];
|
||||
if (!open[item.id] || (have && 'list' in have)) return;
|
||||
seasons[item.id] = { loading: true };
|
||||
await loadSeasons(item.id);
|
||||
}
|
||||
|
||||
async function loadSeasons(id: string) {
|
||||
try {
|
||||
seasons[item.id] = { list: await api.seasons(side, item.id) };
|
||||
const list = await api.seasons(side, id);
|
||||
if (open[id]) seasons[id] = { list };
|
||||
} catch (e) {
|
||||
seasons[item.id] = { error: (e as Error).message };
|
||||
if (open[id]) seasons[id] = { error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +133,10 @@
|
||||
libraries = [];
|
||||
try {
|
||||
libraries = await api.libraries(s);
|
||||
const prev = libraryId;
|
||||
libraryId = libraries[0]?.id ?? '';
|
||||
// Same library ID on the other server: the effect won't fire, so load here.
|
||||
if (libraryId === prev) loadItems();
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
@@ -110,6 +153,7 @@
|
||||
if (gen !== generation) return;
|
||||
items = got;
|
||||
pollSizes(gen);
|
||||
recheckMoved(gen);
|
||||
} catch (e) {
|
||||
if (gen !== generation) return;
|
||||
error = (e as Error).message;
|
||||
@@ -129,7 +173,16 @@
|
||||
|
||||
onMount(() => {
|
||||
loadLibraries(side);
|
||||
// When a move to or from the server being browsed finishes, show the
|
||||
// result: the item leaves the source and appears on the destination.
|
||||
const unsubscribe = onMoveDone((job) => {
|
||||
if (job.source_node !== sourceName && job.target_node !== sourceName) return;
|
||||
rechecks = 0;
|
||||
loadItems();
|
||||
for (const id of Object.keys(open)) if (open[id]) loadSeasons(id);
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
generation++;
|
||||
stopPolling();
|
||||
};
|
||||
@@ -148,12 +201,10 @@
|
||||
notice = null;
|
||||
error = null;
|
||||
try {
|
||||
await api.move(side, item, dryRun);
|
||||
if (dryRun) {
|
||||
notice = `Planning a dry run for “${item.name}”. Check Moves for the plan.`;
|
||||
} else {
|
||||
onmoved();
|
||||
}
|
||||
trackMove(await api.move(side, item, dryRun));
|
||||
notice = dryRun
|
||||
? `Planning a dry run for “${item.name}”. Check Moves for the plan.`
|
||||
: `Moving “${item.name}” to ${destName}. Follow its progress in Moves.`;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
@@ -162,6 +213,14 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet moveTag(mark: Mark)}
|
||||
{#if mark.moving}
|
||||
<span class="tag moving">Moving to {mark.to}…</span>
|
||||
{:else}
|
||||
<span class="tag" title="{sourceName}'s Jellyfin will drop it from this list after its next scan">Moved to {mark.to}</span>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<section class="toolbar">
|
||||
<div class="sides" role="radiogroup" aria-label="Browse which server">
|
||||
<button role="radio" aria-checked={side === 'local'} class="local" class:on={side === 'local'} onclick={() => choose('local')}>
|
||||
@@ -219,15 +278,19 @@
|
||||
{/if}
|
||||
</div>
|
||||
<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}
|
||||
{#if item.size}{bytes(item.size.bytes)}{:else if !gone(item)}<span class="muted">measuring…</span>{/if}
|
||||
</span>
|
||||
<div class="actions">
|
||||
{#if marks[item.id]}
|
||||
{@render moveTag(marks[item.id])}
|
||||
{:else}
|
||||
<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>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if open[item.id]}
|
||||
@@ -247,7 +310,9 @@
|
||||
<td class="muted">{part ? fileCount(part.files) : ''}</td>
|
||||
<td class="num">{part ? bytes(part.bytes) : ''}</td>
|
||||
<td class="acts">
|
||||
{#if season.path}
|
||||
{#if marks[season.id]}
|
||||
{@render moveTag(marks[season.id])}
|
||||
{:else if season.path}
|
||||
<button class="small" disabled={busy === season.id} onclick={() => move(what, true)} title="Check and plan without copying anything">
|
||||
Dry run
|
||||
</button>
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string, Job>,
|
||||
error: null as string | null,
|
||||
peerError: null as string | null,
|
||||
loaded: false,
|
||||
});
|
||||
|
||||
type DoneListener = (job: Job) => void;
|
||||
const listeners = new Set<DoneListener>();
|
||||
|
||||
/** 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<typeof setTimeout> | 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();
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user