Files
jellytau/src/lib/services/offlineCatalog.ts
T
dtourolle 1b70926c36
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 20m34s
Publish Documentation / Build & publish docs to gitea-pages (push) Successful in 6m6s
Traceability Validation / Check Requirement Traces (push) Successful in 18s
Build & Release / Run Tests (push) Successful in 20m26s
🏗️ Build and Test JellyTau / Android Compile Check (push) Successful in 10m3s
Build & Release / Build Linux (push) Successful in 37m59s
Build & Release / Build Windows (push) Successful in 23m0s
Build & Release / Build Android (push) Successful in 40m26s
Build & Release / Create Release (push) Successful in 1m20s
feat(offline): play downloaded video, and drain the offline sync queue (0.4.6)
Bundles this session's work plus the concurrent search/offline/player changes.
Every gate passes on the combined tree: 885 frontend tests, 610 Rust tests,
clippy clean, boundary clean, trace coverage 86%.

Offline video playback — four separate defects, each of which alone stopped it:

  DR-133  A completed download's file_path is already absolute (the worker
          rewrites it on completion), but the player rooted it a second time and
          handed the webview /data/user/0/app//data/user/0/app/videos/x.mp4.
  DR-134  The asset protocol was never enabled: no protocol-asset feature and no
          assetProtocol config, so convertFileSrc produced URLs nothing answered.
          Also silently defeated the cached-thumbnail path, which fails soft to
          the server copy and hid it whenever the server was reachable.
  DR-137  Tauri's asset protocol answers a range-less request by reading the
          whole file into memory, and only advertises Accept-Ranges from inside
          its range branch, so the first request never learns ranges exist.
          Chromium gave up with PIPELINE_ERROR_READ after ~31s. Local media is
          now served by a loopback HTTP server: bounded 4 MiB chunks streamed
          from the file handle, every response length-delimited, and a range-less
          request answered with one chunk rather than the file. Confined by a
          per-session token and to the app data directory, because loopback is
          shared between apps on Android.
  DR-138  Release builds set usesCleartextTraffic=false, so Android rejected the
          request to that server before any I/O. A network-security-config
          exempts 127.0.0.1 only; a remote server must still be HTTPS.

Downloads:

  DR-135  download_item never records media_type and the reconnect resolver read
          that NULL as 'audio', so a movie queued from a media card had its URL
          resolved by get_audio_stream_url and completed as an audio-only
          transcode. The item's own type now decides.
  DR-136  Rows already downloaded that way are requeued on reconnect, since
          prevention alone leaves them reading "downloaded" and still unplayable.

Known limitation: a download taken at `original` quality is a byte copy of the
source, so it can be any container. One such file is an AVI holding XVID, which
the webview cannot play in any case — the media server serves it correctly and
Chromium refuses it. That needs either a transcoded download preset or the
native ExoPlayer surface work, and is not addressed here.

Also fixes two ID collisions between concurrent work: DR-143 defined twice
(search vs offline gate) and UT-131 defined twice (Episode Focus hero vs channel
cap). The search requirement is now DR-147 and the channel-cap test UT-141, with
their code references and matrix rows updated.
2026-08-09 16:38:07 +02:00

169 lines
6.4 KiB
TypeScript

// Offline catalog service - "browse & queue" for offline mode.
//
// Two responsibilities:
// 1. Full-catalog pre-sync: while online, walk every library and persist all
// items to the offline cache so the whole catalog is browsable (greyed out)
// offline. Backed by the `syncFullCatalog` Rust command.
// 2. Resume-on-reconnect: when the server becomes reachable again, resolve the
// stream URLs of downloads that were queued while offline and let the pump
// start them. Backed by `resumeQueuedDownloads`.
//
// It also owns the `showServerCatalog` UI flag (the offline banner toggle that
// reveals greyed-out, non-downloaded server media).
//
// TRACES: UR-002, UR-052 | DR-078
import { writable, type Writable } from "svelte/store";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
import { isConnected } from "$lib/stores/connectivity";
/**
* When true (and offline), library grids reveal greyed-out versions of media
* that exists on the server but isn't downloaded, each with a button to queue
* a download for the next reconnect. Toggled from the offline banner.
*/
export const showServerCatalog: Writable<boolean> = writable(false);
/**
* Bumped every time the backend's downloads-only gate *settles* into a new
* state. Library pages watch it and re-query.
*
* The gate lives in Rust and is only consulted when a query runs, so flipping
* it changes nothing already on screen. Without this signal the toggle merely
* greyed cards — `MediaCard.isServerOnly` is a pure frontend derivation and
* updates instantly — while the item list stayed as first loaded. That is the
* "shows everything until I filter" behaviour: the listing had never been
* re-queried under the closed gate. Going offline had the same problem, since
* nothing reloads on the online → offline transition either.
*
* It bumps *after* the command resolves, never before: a reload racing the push
* would re-query under the old gate and undo itself.
*
* TRACES: UR-052 | DR-143
*/
export const catalogFilterVersion: Writable<number> = writable(0);
// Keep the backend's offline library queries in sync with the UI toggle. The
// offline cache holds the whole synced catalog, so `get_items` would otherwise
// return every server item even offline with the toggle off. Include the
// non-downloaded catalog only when online (fast browsing reads the same cache)
// or when the "Show all server media" toggle is on.
let lastIncludeCatalog: boolean | null = null;
async function pushCatalogVisibility(connected: boolean, showCatalog: boolean): Promise<void> {
const include = connected || showCatalog;
if (include === lastIncludeCatalog) return;
lastIncludeCatalog = include;
try {
await commands.setShowServerCatalog(include);
} catch (err) {
console.warn("[OfflineCatalog] Failed to set catalog visibility:", err);
// The backend is still on the old gate, so forget that we sent this —
// otherwise the next identical transition is skipped as a no-op and the
// frontend and backend disagree about the filter for the rest of the
// session. No version bump: there is nothing new to re-query under.
lastIncludeCatalog = null;
return;
}
catalogFilterVersion.update((n) => n + 1);
}
let connectedNow = true;
let showCatalogNow = false;
// Fire-and-forget on purpose: the push handles its own failure, and subscribers
// must not block. Consumers wait on `catalogFilterVersion` instead.
isConnected.subscribe((v) => {
connectedNow = v;
void pushCatalogVisibility(connectedNow, showCatalogNow);
});
showServerCatalog.subscribe((v) => {
showCatalogNow = v;
void pushCatalogVisibility(connectedNow, showCatalogNow);
});
/** Last time a full catalog sync completed, for a UI hint. */
export const lastCatalogSync: Writable<string | null> = writable(null);
// Guard against overlapping syncs (they can be slow on large libraries).
let syncInProgress = false;
function currentHandle(): string | null {
try {
return auth.getRepository().getHandle();
} catch {
return null; // not connected yet
}
}
/**
* Force a full re-index now, ignoring freshness.
*
* Routine scheduling is the Rust indexer's job (DR-109) — this is the manual
* override, for a "re-index now" affordance. It is deliberately *not* called on
* startup or reconnect any more: doing so forced a full crawl on every launch
* regardless of how fresh the index was.
*
* The backend refuses overlapping passes, so this is safe to call at any time.
*/
export async function syncCatalog(): Promise<void> {
if (syncInProgress) return;
const handle = currentHandle();
if (!handle) return;
syncInProgress = true;
try {
const result = await commands.syncFullCatalog(handle);
console.info(
`[OfflineCatalog] Synced ${result.itemsCached} items (${result.librariesFailed} libraries failed)`
);
await refreshSyncStatus();
} catch (err) {
console.warn("[OfflineCatalog] Full catalog sync failed:", err);
} finally {
syncInProgress = false;
}
}
/**
* Resolve URLs for downloads queued while offline and pump them. Call on
* reconnect. No-ops if not connected.
*/
export async function resumeQueued(): Promise<void> {
const handle = currentHandle();
if (!handle) return;
try {
const result = await commands.resumeQueuedDownloads(handle);
if (result.resolved > 0 || result.failed > 0) {
console.info(
`[OfflineCatalog] Resumed queued downloads: ${result.resolved} resolved, ${result.failed} failed`
);
}
} catch (err) {
console.warn("[OfflineCatalog] Failed to resume queued downloads:", err);
}
}
/** Refresh the last-synced timestamp from the backend. */
export async function refreshSyncStatus(): Promise<void> {
try {
const status = await commands.catalogSyncStatus();
lastCatalogSync.set(status.lastSyncedAt ?? null);
} catch (err) {
console.debug("[OfflineCatalog] Failed to fetch sync status:", err);
}
}
/**
* Called when the server becomes reachable again: resume queued downloads first
* (fast, user-visible), then refresh the catalog in the background.
*/
export async function onReconnected(): Promise<void> {
await resumeQueued();
// Re-indexing on reconnect is the Rust indexer's job (DR-109) — it re-checks
// staleness every tick, so it picks this up without a nudge from here. Queued
// downloads still need resolving from the frontend, which is why this
// function remains.
}