Files
jellytau/src/lib/services/downloadedCatalog.ts
T
dtourolle bb7d5dc01a fix(offline): one server-only rule for both library views
Two defects with one cause: "server only" was a private $derived inside
MediaCard.

The list view (what LibraryGrid renders when the stored view preference
is list) had no notion of it at all, so a library browsed as a list
offline showed every revealed item as an ordinary tappable row that plays
nothing, with no way to queue it.

And the rule asked the downloads store whether *this item id* was
downloaded — but only a playable leaf (Audio, Movie, Episode) ever has a
download row. An album's tracks carry them, the album does not, so a
fully downloaded album greyed itself out and offered to queue what was
already on the device.

The rule moves to the pure $lib/utils/serverOnly and both views call it.
The container half is answered by the backend rather than guessed at:
get_download_disk_usage().sizes already carries container subtotals
beside leaf sizes (DR-085), so deviceContentIds is membership in a
Rust-computed map, not a frontend list of which item types are
containers. That map was loaded only by the Downloads page, so the shell
primes it at startup and re-reads it whenever the offline gate settles.
Queueing is shared too, since the list view had no copy to diverge from.

TRACES: UR-052, UR-055 | DR-292 | UT-257, UT-258
2026-09-22 21:29:38 -04:00

134 lines
4.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Downloaded catalog service — the "Downloaded" browse surface's data source.
//
// This is the offline library, filtered to what's on the device. It reads the
// dedicated offline-only browse path on the repository (never the hybrid merge),
// so results are authoritative regardless of connectivity: an empty result means
// "nothing downloaded here", never "server unreachable". See the spec
// docs/architecture/02-svelte-frontend.md ("Downloaded Browse") and
// ux-flows §7.27.3.
//
// It also owns disk-usage: a per-item/container byte map plus the device total,
// aggregated from `downloads.file_size` by the backend.
//
// TRACES: UR-055, UR-056 | DR-082, DR-083, DR-085
import { writable, derived, get } from "svelte/store";
import type { Library, MediaItem, GetItemsOptions } from "$lib/api/types";
import type { DownloadDiskUsage } from "$lib/api/bindings";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
interface DownloadedCatalogState {
libraries: Library[];
/** item id → bytes on disk (leaf's own size, or a container subtotal). */
sizes: Record<string, number>;
/** container id → true when only partially downloaded. */
partialContainers: Record<string, boolean>;
deviceTotalBytes: number;
itemCount: number;
loading: boolean;
error: string | null;
}
const initial: DownloadedCatalogState = {
libraries: [],
sizes: {},
partialContainers: {},
deviceTotalBytes: 0,
itemCount: 0,
loading: false,
error: null,
};
function createDownloadedCatalogStore() {
const { subscribe, update, set } = writable<DownloadedCatalogState>(initial);
function repo() {
return auth.getRepository();
}
/** Load the downloaded-library list and disk-usage totals for the top bar. */
async function refresh(): Promise<void> {
update((s) => ({ ...s, loading: true, error: null }));
try {
const [libraries, usage] = await Promise.all([
repo().getDownloadedLibraries(),
repo().getDownloadDiskUsage() as Promise<DownloadDiskUsage>,
]);
// The wire type is Partial<{ [k]: number }>; normalise to a dense record.
const sizes: Record<string, number> = {};
for (const [k, v] of Object.entries(usage.sizes)) {
if (typeof v === "number") sizes[k] = v;
}
const partialContainers: Record<string, boolean> = {};
for (const [k, v] of Object.entries(usage.partialContainers)) {
if (v) partialContainers[k] = true;
}
update((s) => ({
...s,
libraries,
sizes,
partialContainers,
deviceTotalBytes: usage.deviceTotalBytes,
itemCount: usage.itemCount,
loading: false,
}));
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to load downloads";
update((s) => ({ ...s, loading: false, error: message }));
}
}
/** Downloaded-only items under a container (library, album, season, series). */
async function loadItems(parentId: string, options?: GetItemsOptions): Promise<MediaItem[]> {
const result = await repo().getDownloadedItems(parentId, options);
return result.items;
}
/** Bytes on disk for an item id (leaf's own, or a container subtotal), or 0. */
function sizeOf(itemId: string): number {
return get({ subscribe }).sizes[itemId] ?? 0;
}
/**
* Remove every completed download at or under a container/leaf, then refresh
* so the browse and totals update. Returns the number of downloads removed.
* TRACES: UR-055, UR-056 | DR-083
*/
async function remove(itemId: string): Promise<number> {
const userId = auth.getUserId();
if (!userId) throw new Error("Not signed in");
const removed = await commands.deleteDownloadsUnder(itemId, userId);
await refresh();
return removed;
}
function reset() {
set(initial);
}
return { subscribe, refresh, loadItems, sizeOf, remove, reset };
}
export const downloadedCatalog = createDownloadedCatalogStore();
/**
* Every item id the device holds bytes for — playable leaves *and* the
* containers above them, as the backend's disk-usage map reports them.
*
* This is what stops the offline browse greying out a fully downloaded album:
* only a leaf (Audio, Movie, Episode) ever has a download row of its own, so
* asking the downloads store about an album id always answered "no". Which ids
* are containers, and which children roll up into them, stays a Rust question
* (`get_download_disk_usage`); the frontend only reads membership.
*
* Refreshed with the rest of the catalog — see `downloadedCatalog.refresh()`.
*
* TRACES: UR-052, UR-056 | DR-292
*/
export const deviceContentIds = derived(downloadedCatalog, ($c) => new Set(Object.keys($c.sizes)));
export const downloadedLibraries = derived(downloadedCatalog, ($c) => $c.libraries);
export const downloadedDeviceTotal = derived(downloadedCatalog, ($c) => $c.deviceTotalBytes);
export const downloadedItemCount = derived(downloadedCatalog, ($c) => $c.itemCount);