feat(search): answer search from a local index; tier downloads by lifetime
Search's instant leg read only downloaded items, so with no downloads it returned nothing and every keystroke fell through to a full Recursive=true server query. It now reads the whole synced catalog through the same availability CTE get_items uses, gated on the same include_catalog_browse flag so search and browse cannot diverge. (UR-065, DR-108) Also fixes three defects found while confirming that: - items_fts grew by a full duplicate index every catalog pass. INSERT OR REPLACE fires no AFTER DELETE trigger without recursive_triggers, so the old index row was orphaned, and a TEXT PRIMARY KEY meant the replacement took a fresh rowid and inserted a second entry. Now a real upsert, with migration 021 rebuilding existing indexes. (DR-110) - DELETE FROM items existed nowhere, so server-side deletions never propagated. Adds a post-crawl mark-and-sweep, scoped to crawled types, skipping downloaded items, and refusing to run after a partial crawl because items.parent_id cascades. (DR-110) - The index omitted MusicArtist, Playlist and People, which search groups results by. Adds them plus people_fts (migration 022). (DR-111) Re-indexing moves from a frontend startup call to a Rust background task with a 6h TTL, so a long session no longer searches a stale catalog and a restart no longer forces a crawl regardless of freshness. (DR-109, IR-030) Downloads gain a lifetime tier. Eviction selected every completed row by age with no download_source filter, so hitting the storage limit deleted the oldest download -- typically one saved deliberately for offline -- to make room for a precached track. It now reclaims only 'auto' rows, and expired ones are reclaimed first, before live cache is evicted. (DR-126, DR-127) Downloaded video and audio-only handoffs now play from disk instead of streaming; the video path had never consulted downloads at all. No transcode is involved: MPV runs video=no and ExoPlayer has no surface for an Audio item. (DR-123 in part, DR-128) FTS queries are built as quoted phrases so apostrophes, hyphens and slashes are data rather than operator syntax, and the item-type filter is bound rather than interpolated. Specs: docs/specs/catalog-index-search.md, docs/specs/read-through-media-cache.md Includes concurrently-developed favourites browsing and background-audio stream-end handling; the two workstreams share offline.rs, lib.rs and online.rs, so no subset of files builds independently.
This commit is contained in:
+62
-3
@@ -75,7 +75,13 @@ For a narrative overview of the system design, see
|
||||
| UR-062 | Opening a TV series lands the viewer **where they are in it**, not at season 1: the series page scrolls the current season into view and highlights the current episode, and the hero button opens that episode (labelled `Resume S2E4` / `Play S1E1`). "Current" means the episode in progress, else the server's Next Up for that series, else the first unwatched episode, else the first — resolved by the backend so it also works offline. A season is **never a page of its own**: every route that names a season lands on the series with that season in view, so the episodes of all seasons are always one continuous scrollable list | High | Done |
|
||||
| UR-063 | Each video library is **one page**, not three. Browsing (hero, Continue Watching, Next Up, Recently Added, genre rows), the full title grid, and the genre browser are tabs of `/library/tv` and `/library/movies` rather than separate routes with inconsistent names (`/library/tv/shows` vs `/library/movies/all`, `/library/shows/genres` vs `/library/movies/genres`). The old routes redirect so existing links keep working | Medium | Done |
|
||||
| UR-064 | Watch history can be **erased**, per series and per season, from the series page. Clearing marks every episode inside unwatched and clears resume positions, so the show returns to "never watched" and reopens on its premiere. It asks for confirmation first (it cannot be undone) and requires a connection to the server, since history cleared only locally would be undone by the next sync | Medium | Done |
|
||||
| UR-065 | Search answers from a **locally indexed copy of the library**, so results appear as fast as the device can query rather than at the speed of a round trip to the server, and the same results are found with the server unreachable. A background job keeps the index current — refreshing on a schedule rather than only at app start, dropping media removed from the server, and covering everything the result groups can show (including artists and people). The server is still queried in the background so media added since the last index still turns up, merged in without reordering what is already on screen | High | Implemented |
|
||||
| UR-066 | The app's own chrome stays clear of the device's system chrome. On Android the bottom navigation sits above the navigation/gesture bar instead of underneath it, the header clears the status bar, and full-screen video and audio playback keep their controls inside the usable screen — clear of the gesture bar and, in landscape, of the display notch. This must hold across navigation modes (gesture and 3-button) and rotation, not only on the handsets it happened to be tested on | High | Done |
|
||||
| UR-067 | Favourited media can be **found again**. A Favourites page lists everything favourited across all libraries, scoped by tabs (All / Movies / Shows / Music); the home screen carries favourite rows for movies, shows and music, hidden when a category is empty; and each library page can be filtered to favourites in place. Without this the like button writes to a store nothing reads | Medium | Done |
|
||||
| UR-068 | Anything the app shows can be favourited where it is shown — from a movie, series, episode, album, artist or playlist page, and from any card in a grid or carousel — not only from the player while the item happens to be playing | Medium | Done |
|
||||
| UR-069 | Favourite state agrees with the server in both directions. An item favourited in another Jellyfin client shows as favourited here without being touched, and an item favourited here while the server is unreachable reaches the server once it returns — without the user going back to the screen where they marked it | Medium | Done |
|
||||
| UR-070 | Playback quality is the viewer's choice: the player offers the bitrates the server can produce for what is playing, and changing one resumes at the same point with the same audio and subtitle tracks. Because the chosen rendition can change at any moment, nothing that streams for playback is treated as a stored copy unless it happens to be byte-identical to the real file | Medium | Proposed |
|
||||
| UR-071 | Media the viewer is watching can be **kept**, by a whole-file download that runs in the background independently of playback and at its own quality, so it is unaffected by bitrate changes. Where the streamed bytes already are that file (direct play), they are kept rather than fetched twice. A completed download is then played from disk rather than streamed again | Medium | Proposed |
|
||||
|
||||
---
|
||||
|
||||
@@ -116,7 +122,9 @@ External system integrations and platform-specific implementations.
|
||||
| IR-027 | Jellyfin `/System/Info/Public` reachability probe used as an offline→online recovery detector | API | UR-043 | Done |
|
||||
| IR-028 | Jellyfin/LMS SyncGroups API client (list, create, join, unsync, dissolve sync groups) | API | UR-046 | Done |
|
||||
| IR-029 | Android `ConnectivityManager`/`NetworkCapabilities` transport probe with a `NetworkCallback` change subscription, surfaced to the frontend via the `AndroidNetworkType` JS bridge and the `jellytau-network-changed` WebView event (requires `ACCESS_NETWORK_STATE`) | Platform | UR-053 | Done (pending device verification) |
|
||||
| IR-030 | Scheduled full-catalog crawl of every library (`Recursive=true`, paged) feeding the local index, driven by a Rust background task and the `ConnectivityMonitor` reconnect signal rather than by the frontend | Storage | UR-065 | Implemented |
|
||||
| IR-031 | Android `WindowInsets` bridge: an `OnApplyWindowInsetsListener` on the decor view reports `systemBars() | displayCutout()` in CSS pixels, pushed into the WebView as `jt-inset` CSS custom properties plus a `jellytau-insets-changed` event, and pullable via the `AndroidInsets` JS bridge | Platform | UR-066 | Done (pending device verification) |
|
||||
| IR-032 | Whole-file background download of the item being played, reusing the existing resumable download worker and the Range-capable `/Videos/{id}/stream.mp4` endpoint; plus per-platform read-through caching hooks (ExoPlayer `CacheDataSource`, mpv `stream-record`) for direct-play sessions only | Storage | UR-071 | Proposed |
|
||||
|
||||
### 2.2 Jellyfin API Requirements
|
||||
|
||||
@@ -156,6 +164,8 @@ API endpoints and data contracts required for Jellyfin integration.
|
||||
| JA-030 | Get person details and filmography | Persons | UR-036 | Done |
|
||||
| JA-031 | Get items by person (actor/director filmography) | Items | UR-036 | Done |
|
||||
| JA-032 | Get audio-only stream URL for a video item (selected audio-stream index) | MediaInfo | UR-040 | Done |
|
||||
| JA-033 | Query favourite items (`Filters=IsFavorite`, recursive, scoped by item type) | Items | UR-067 | Done |
|
||||
| JA-034 | Read `UserData` (favourite, played, resume position) from item responses | UserData | UR-069 | Done |
|
||||
|
||||
### 2.3 Development Requirements
|
||||
|
||||
@@ -266,7 +276,28 @@ Internal architecture, components, and application logic.
|
||||
| DR-105 | Video library routes collapse to one per library. `/library/tv` and `/library/movies` render browse / all-titles / genres as in-page tabs driven by `?view=`, omitted for the default `browse` (the convention `searchRouteUrl` already uses for the `all` scope); `resolveLibraryView` is pure and unit-tested. The four legacy routes become redirect-only `+page.ts` loads rather than deletions, because `GenreTags` links to them and users have them in history; `resolveSearchScope` keeps its `/library/shows` branch for the same reason. The "Browse" tile grid at the bottom of both landing pages is removed — it was a second navigation affordance to the same destinations the carousels' "Show all" links already reach | UI | UR-063 | Done |
|
||||
| DR-106 | Erasing watch history goes through the repository, not the local cache: `clear_watch_history(item_id)` maps to Jellyfin's `DELETE /Users/{userId}/PlayedItems/{itemId}`, which clears the played flag *and* zeroes the resume position, and which the server applies recursively to a folder — so one call handles a whole series or season. `OfflineRepository` returns `RepoError::Offline` rather than clearing locally, because history diverged only on the device would be silently undone by the next sync; the button disables itself while the server is unreachable. `ClearHistoryButton` is shared by the series hero and each `SeasonSection` header, confirms before acting (there is no undo), and reloads the page on success so the recomputed current episode — the premiere, for a fully cleared series — is what the viewer sees | Repository | UR-064 | Done |
|
||||
| DR-107 | Seasons on the series page are collapsible, and **only the current season is expanded** on load — the one holding the episode DR-101 resolved. A show with ten seasons otherwise renders every episode of every season at once, burying the one episode the viewer came for under hundreds of rows. Expansion state is per season and pure (`initialExpandedSeasons` in `seriesNavigation.ts`): the current season, or the first season when there is no current episode, so a never-watched show still opens on season 1 rather than fully collapsed. A `?episode=` deep link expands that episode's season too. Toggling is local and not persisted — it is a reading position, not a preference | UI | UR-062 | Done |
|
||||
| DR-108 | The instant (cache) leg of `repository_search` searches the **synced catalog**, not just downloads. `OfflineRepository::search` replaces its `downloaded_items` CTE with the `available_items` CTE `get_items` already uses — the same downloads branches plus a `synced_at IS NOT NULL` branch gated on the same `include_catalog_browse()` flag — so search and browse cannot diverge on what is visible. Online (flag true) search reads the whole index and answers before any HTTP request completes; offline with "Show all server media" off (flag false) it stays downloads-only, unchanged. Requires no frontend change, since the flag is already set correctly for all three states. The `include_item_types` filter is switched from string interpolation to bound parameters, as `SearchOptions` is settable from the frontend and not only from `SearchScope` | Backend | UR-065 | Implemented |
|
||||
| DR-109 | Index freshness is a Rust-owned policy, not a frontend startup call. A tokio task ticks every 30 min and runs a full pass when a repository is active, the server is reachable, and `last_catalog_sync` (already persisted to `app_settings`, previously read only for a UI hint) is older than `CATALOG_INDEX_TTL` (6 h); the `ConnectivityMonitor` reconnect signal re-evaluates the same condition immediately. An `AtomicBool` prevents concurrent passes, replacing `offlineCatalog.ts`'s `syncInProgress` — the frontend trigger is removed rather than left alongside, since two triggers with one guard each is how double-crawls happen. `RepositoryManager` gains an active-handle slot so the task has something to run against. Progress is emitted as the kebab-case `catalog-index-event` | Backend | UR-065 | Implemented |
|
||||
| DR-110 | Index hygiene. `save_to_cache` switches from `INSERT OR REPLACE INTO items` to `ON CONFLICT(id) DO UPDATE`: REPLACE fires no `AFTER DELETE` trigger unless `recursive_triggers` is on (it is not — only `foreign_keys` and `journal_mode` are set), so `items_ad` never ran, and because `items.id` is a `TEXT PRIMARY KEY` each replacement also took a fresh rowid and appended a second `items_fts` entry — a duplicate index per sync, invisible in results but permanently degrading `MATCH`. The upsert preserves the rowid `items_fts` keys on and fires `items_au`; migration `021_rebuild_items_fts` clears orphans on existing installs. Separately, a post-crawl sweep deletes synced-but-not-downloaded rows a successful library crawl did not return, so media removed from the server stops being searchable; it skips items with completed downloads and skips any library whose crawl errored, because `items.parent_id` is `ON DELETE CASCADE` and a partial crawl would cascade away a whole series | Storage | UR-065 | Implemented |
|
||||
| DR-111 | The index covers what the result groups render: `CATALOG_ITEM_TYPES` gains `MusicArtist` and `Playlist`, and migration `022_people_fts` adds a `people_fts` virtual table over the existing `people` table (which had no FTS, and is populated incidentally by item-detail fetches) with the same trigger pattern as `items_fts`. `OfflineRepository::search` UNIONs `people_fts` matches in as `Person` items when the resolved scope admits them — i.e. `SearchScope::All`, which expands to no filter (DR-063). Without this, the Artists and People groups UR-060 mandates can only ever be filled by the server leg | Storage | UR-065, UR-060 | Implemented |
|
||||
| DR-112 | Safe-area insets come from **native**, not from `env()` alone. `env(safe-area-inset-*)` is 0px without `viewport-fit=cover` (missing from `app.html`, so every safe-area rule in the app was already a no-op), and even with it Android WebView maps only the *display cutout* — never the status bar or navigation bar. Since `enableEdgeToEdge()` plus `targetSdk 36` make edge-to-edge unconditional, the WebView always spans the system bars, so CSS could not learn about them by any route. `WindowInsetsBridge` reads the real insets and publishes `jt-inset` custom properties; `app.css` folds them with `env()` via `max()` into `--safe-*`, which is the only thing components may pad from. Ownership is exactly one element per edge: the app shell takes top/left/right, and BottomUi takes bottom wherever it renders (`shellReservesBottomInset` hands it back to the shell on routes with no bottom UI) so the padding sits inside BottomUi's surface box and the colour extends behind the gesture bar. The full-screen players inset their control layers only, leaving video and artwork edge-to-edge. The theme's `fitsSystemWindows=true` — which claimed the opposite and was overridden at runtime and ignored at this target SDK — is removed | UI | UR-066 | Done |
|
||||
| DR-113 | `MediaItem.user_data` is populated from the server instead of being hardcoded `None`. `JellyfinItem` gains a `UserData` field (`#[serde(alias = "UserData")]` → the existing `UserData` type) and `to_media_item` maps it, so every list and detail response carries favourite/played/resume state. `UserData` is named explicitly in the `Fields=` list rather than relying on Jellyfin's default. Without this no card or detail page can render a favourite it did not itself set, and the mini player's per-track `storageGetPlaybackProgress` fetch is the only way to colour one heart | Repository | UR-069 | Done |
|
||||
| DR-114 | Server favourite state is mirrored into the local `user_data` table by `OfflineRepository::save_to_cache` — the single choke point every cached server result passes through — so offline browsing and the offline Favourites page see the same favourites as the server. The upsert carries `pending_sync = 0` and is guarded by `WHERE user_data.pending_sync = 0`, which is the conflict rule: a toggle made offline is never overwritten by a stale server value before it has been pushed | Storage | UR-069 | Done |
|
||||
| DR-115 | Cross-library favourites query: a `get_favorites(scope, options)` repository method plus the `repository_get_favorites` command. Online issues `Filters=IsFavorite&Recursive=true` with `IncludeItemTypes` expanded from `SearchScope::item_types()` in Rust (the frontend sends the opaque scope, never a type list — DR-063); offline reads `items ⨝ user_data (is_favorite = 1)` under the same `include_catalog_browse()` gate as browsing; hybrid races cache against server like `get_items`, including the DR-080 rule that an empty offline result is authoritative when the gate is off. A separate method rather than `get_items` because favourites span libraries and `get_items` is `ParentId`-shaped | Repository | UR-067 | Done |
|
||||
| DR-116 | `GetItemsOptions.favorites_only` filters an existing library listing in place — online by appending `Filters=IsFavorite`, offline by joining `user_data` into the existing `available_items` CTE so the downloads-only gate still applies. This is what backs the per-library favourites toggle, and composes with the genre and item-type filters already there | Repository | UR-067 | Done |
|
||||
| DR-117 | The Favourites page (`/library/favorites`) renders favourites across libraries with All / Movies / Shows / Music scope tabs, reusing `LibraryViewTabs` + `LibraryGrid` + `MediaCard` so card shape still follows the media (§5A.1) and a mixed All tab reads as posters, squares and thumbnails side by side. Each tab sends a `SearchScope` value and nothing else. Reached from the library overview and from "See all" on the home rows | UI | UR-067 | Done |
|
||||
| DR-118 | Home carries favourite rows for movies, shows and music, loaded via `repository_get_favorites` per scope and rendered below Recently Added. A row with no items does not render at all, so a fresh install shows no empty favourite rows | UI | UR-067 | Done |
|
||||
| DR-119 | `FavoriteButton` is mounted wherever a whole item is shown — movie/series/episode detail heroes, album/artist/playlist headers, and as a `MediaCard` artwork overlay — and a `favorites` store holds in-session optimistic state so un-hearting on one surface updates every other without a refetch. Resolution order is `store override ?? item.userData?.isFavorite ?? false`. On a card the heart is its own button and stops propagation, so hearting never also opens, plays, or triggers the §5B.5 long-press; it is suppressed on server-only (greyed) cards | UI | UR-068 | Done |
|
||||
| DR-120 | Favourite toggles made while offline reach the server. A Rust drain, triggered by the `ConnectivityMonitor` offline→online transition, pushes every `user_data` row with `pending_sync = 1` and clears the flag on success, leaving failures pending for the next transition. It lives in Rust rather than the frontend because a frontend drain dies with the component that started it. Both the drain and the hybrid background refresh emit the kebab-case `favorites-changed` event (`{ itemIds }`) so open views update — without it a favourite marked on another client appears only on the *second* visit to a page, since the cache-first read returns local rows and the server refresh is invisible to the frontend. Supersedes the unused `syncService.queueFavorite`, which is deleted rather than left as a second queue | Backend | UR-069 | Done |
|
||||
| DR-121 | Player quality selector: Rust reports the bitrates available for the current media source and owns the quality→transcode-parameter mapping (the one `get_video_download_url` already holds — playback calls into it rather than restating it, or the two tables drift). Changing quality re-negotiates the stream URL and resumes at the current position with audio/subtitle selection preserved. On Linux, video re-negotiates *within* HLS: returning `stream.mp4` is the documented cause of transcoded playback never starting. The frontend renders the list and remembers the choice; it does not decide what the choice resolves to | UI | UR-070 | Proposed |
|
||||
| DR-122 | The playback path is ephemeral. Streamed bytes are never persisted unless DR-124 rules them keepable, and any in-flight capture is abandoned — partial file deleted, never promoted — the moment the viewer changes quality, because a capture spanning a rendition change is a splice of two encodings rather than a playable file | Playback | UR-070 | Proposed |
|
||||
| DR-123 | The download path is independent of playback: a whole-file fetch through the existing download manager at one canonical quality (default `original`, the direct static copy) over the Range-capable `/Videos/{id}/stream.mp4`, unaffected by bitrate changes and completing into an ordinary `downloads` row so offline browsing and `refresh_queue_local_sources` pick it up unchanged. Prerequisite: downloaded video is currently never played locally — `repository_get_video_stream_url` goes straight to the online repo and the player route calls it with no local check, so a completed video download is still streamed. Without that fix nothing in this spec is observable for video | Repository | UR-071 | In Progress |
|
||||
| DR-124 | Streamed bytes are kept only where they *are* the download artifact — a direct-play session. Android uses ExoPlayer `SimpleCache`/`CacheDataSource` keyed by item **and** media-source id so renditions cannot collide, sharing the existing smart-cache storage budget rather than opening a second one over the same disk; Linux audio uses mpv `stream-record`, abandoned on seek because it is documented as intended for linear streams and seeking breaks the recording. Transcoded Linux video is **not** captured: HLS segments are not a file, and assembling one needs ffmpeg, which is not a dependency and which CI may not install at job time — DR-123 covers that case instead | Playback | UR-071 | Proposed |
|
||||
| DR-125 | A capture is promoted to a completed `downloads` row only when it covers the whole resource; partials stay evictable cache. A new `downloads.source_rendition` column records the negotiated quality/container/codec (`NULL` for the existing paths, which are always `original`) so a captured transcode and a real download are distinguishable rows and an "upgrade to original" remains possible. A quality change never touches a file that already exists — not a permanent download, and not a completed temporary one, both of which stay valid copies of the rendition they hold. It invalidates only an **in-flight** capture or background download of cached media, which is abandoned and restarted at the newly chosen quality, because a capture spanning a rendition change is a splice of two encodings rather than a playable file | Storage | UR-071 | Proposed |
|
||||
| DR-126 | Cache eviction only reclaims the *temporary* tier. `evict_lru_async` selected every completed download ordered by `completed_at ASC` with no `download_source` filter, so hitting the 10 GB storage limit deleted the **oldest** download — typically a film saved deliberately for offline — to make room for a newly precached track. It now evicts only `COALESCE(download_source, 'user') = 'auto'` rows; `COALESCE` rather than a bare equality because rows predating migration 012 can be NULL and unknown provenance must be treated as the user's, never as disposable. Freeing less than requested is the correct outcome when only user downloads remain — the caller reports "unable to free enough space" instead of silently deleting them | Storage | UR-071 | Done |
|
||||
| DR-127 | A cache entry *is* a download with a shorter life: same `downloads` row and same file handling, distinguished by `download_source = 'auto'` plus an expiry, so there is one storage model rather than a cache and a download library that can disagree. Temporary rows are reclaimed on whichever comes first — the life limit elapsing, or eviction under space pressure (DR-126). Permanent (`'user'`) rows have no expiry. A temporary row can be promoted to permanent by the user choosing to keep it, which only clears the expiry and flips the source; the bytes never move | Storage | UR-071 | Done |
|
||||
| DR-128 | Audio-only playback of *downloaded* media reads the local file rather than fetching an audio-only stream. No transcode is involved or wanted: the Linux backend already runs MPV with `video: no`, so handing it the downloaded video file decodes the audio track and ignores the video, and ExoPlayer disables its video renderer equivalently. Transcoding to a separate audio artifact would cost CPU and battery, need an encoder the project does not ship, and produce a second file to keep in step — for no gain over simply not decoding the video | Playback | UR-071 | Done |
|
||||
| DR-129 | A stream that stops delivering is recovered, not treated as terminal. Two failure shapes, because the streams differ. (a) *Phantom end* — the background audio-only handoff uses a progressive mp3 transcode over plain HTTP, chunked and therefore length-less, so a dropped connection reaches the player as end-of-input and ExoPlayer reports `STATE_ENDED` indistinguishably from the real end. The item's runtime is the only thing that can tell them apart: an end reported more than a tolerance short of it (comparing the *absolute* position — handoff base plus the player's relative position) is a truncation. Left unhandled, playback parked in `STATE_ENDED` and the next play intent from the lockscreen, notification or a Bluetooth reconnect seeks an ended player to position 0 — the user-visible "the episode randomly restarted". (b) *Recoverable error* — music (`/Audio/{id}/stream?Static=true`) and video (`/Videos/{id}/master.m3u8`) declare their length, so the player detects the truncation itself and raises an error; the frontend's handler stopped playback outright, turning a hiccup into silence. Both resume the current item **in place** (never via `play_item`, which would replace the queue with a single item and lose the album), the error path after a per-attempt backoff. Seekable streams are re-prepared at the URL they already have and seeked; the length-less transcode, which cannot be seeked, has `StartTimeTicks` rewritten into its existing URL so the user's audio-track selection survives and recovery needs no network round-trip. Only `Remote` sources qualify — a local file cannot fail from the network. A shared budget of consecutive attempts at the same position, refilled whenever playback progresses, stops an unreachable server from looping | Playback | UR-040, UR-004 | Done |
|
||||
| DR-093 | Traceability coverage gate derives its requirement denominators from `requirements.md` at run time rather than hardcoded literals: `countDefinedRequirements` counts an ID only where it leads a markdown table row (ignoring the "Traces To" column and prose) and deduplicates IDs listed both in the definition tables and in the §3 traceability matrix; `computeCoverage` reports the *intersection* of traced and defined IDs so an ID traced in code but absent from `requirements.md` is surfaced as `orphaned` instead of inflating the ratio past 100%. UT/IT test identifiers are excluded as a separate taxonomy. CI and `bun run traces:coverage` share this computation and fail on both a sub-threshold and an impossible >100% result | Tooling | - | Done |
|
||||
|
||||
---
|
||||
@@ -280,7 +311,7 @@ Internal architecture, components, and application logic.
|
||||
| UR-001 | IR-001, IR-002 | - |
|
||||
| UR-002 | IR-013 | DR-003, DR-012, DR-013, DR-014 |
|
||||
| UR-003 | IR-003, IR-004, IR-011 | DR-002, DR-004, DR-010 |
|
||||
| UR-004 | IR-003, IR-004, IR-008, IR-011 | DR-002, DR-004, DR-006 |
|
||||
| UR-004 | IR-003, IR-004, IR-008, IR-011 | DR-002, DR-004, DR-006, DR-129 |
|
||||
| UR-005 | - | DR-001, DR-005, DR-009 |
|
||||
| UR-006 | IR-005, IR-006, IR-007, IR-008 | - |
|
||||
| UR-007 | IR-010 | DR-007, DR-008, DR-016 |
|
||||
@@ -316,7 +347,7 @@ Internal architecture, components, and application logic.
|
||||
| UR-037 | IR-010 | DR-042 |
|
||||
| UR-038 | IR-010 | DR-043 |
|
||||
| UR-039 | - | DR-045, DR-046 |
|
||||
| UR-040 | IR-025 | DR-051, DR-052 |
|
||||
| UR-040 | IR-025 | DR-051, DR-052, DR-129 |
|
||||
| UR-041 | IR-026 | DR-053 |
|
||||
| UR-042 | IR-009, IR-014 | DR-054 |
|
||||
| UR-043 | IR-027 | DR-055 |
|
||||
@@ -335,12 +366,18 @@ Internal architecture, components, and application logic.
|
||||
| UR-056 | - | DR-085 |
|
||||
| UR-057 | - | DR-086 |
|
||||
| UR-058 | - | DR-087 |
|
||||
| UR-060 | - | DR-090, DR-091 |
|
||||
| UR-060 | - | DR-090, DR-091, DR-111 |
|
||||
| UR-061 | - | DR-092 |
|
||||
| UR-062 | - | DR-101, DR-102, DR-103, DR-104, DR-107 |
|
||||
| UR-063 | - | DR-105 |
|
||||
| UR-064 | - | DR-106 |
|
||||
| UR-065 | IR-030 | DR-108, DR-109, DR-110, DR-111 |
|
||||
| UR-066 | IR-031 | DR-112 |
|
||||
| UR-067 | - | DR-115, DR-116, DR-117, DR-118 |
|
||||
| UR-068 | - | DR-119 |
|
||||
| UR-069 | - | DR-113, DR-114, DR-120 |
|
||||
| UR-070 | - | DR-121, DR-122 |
|
||||
| UR-071 | IR-032 | DR-123, DR-124, DR-125, DR-126, DR-127, DR-128 |
|
||||
|
||||
---
|
||||
|
||||
@@ -445,6 +482,28 @@ Internal architecture, components, and application logic.
|
||||
| UT-096 | `readNativeInsets` returns null with no bridge and survives a stale WebView proxy (missing or throwing `get`) instead of throwing out of layout init | IR-031, DR-112 | Done |
|
||||
| UT-097 | `initSafeArea` primes the document on start, re-applies on `jellytau-insets-changed` (rotation, nav-mode switch), unsubscribes on teardown, and writes nothing without a bridge so `env()` still wins on iOS/desktop | IR-031, DR-112 | Done |
|
||||
| UT-098 | `shellReservesBottomInset` gives the bottom inset to BottomUi wherever one renders and to the app shell only on routes without one, so the gesture bar is never ignored nor double-padded | DR-112 | Done |
|
||||
| UT-099 | A Jellyfin item payload carrying `UserData.IsFavorite` maps to `MediaItem.user_data.is_favorite` | DR-113, JA-034 | Done |
|
||||
| UT-100 | `OnlineRepository::get_favorites` builds `Filters=IsFavorite` + `Recursive=true` + the scope's `IncludeItemTypes`, and omits the type filter entirely for `SearchScope::All` | DR-115, JA-033 | Done |
|
||||
| UT-101 | `OfflineRepository::get_favorites` returns only `is_favorite = 1` rows, honours the scope type filter, and stays downloads-only when the catalog-browse gate is off | DR-115 | Done |
|
||||
| UT-102 | The `save_to_cache` favourite mirror does not overwrite a row with `pending_sync = 1` | DR-114 | Done |
|
||||
| UT-103 | The reconnect drain pushes pending favourites, clears `pending_sync`, and leaves failed rows pending | DR-120 | Done |
|
||||
| UT-104 | `get_items` with `favorites_only` filters online (endpoint) and offline (SQL) | DR-116 | Done |
|
||||
| UT-105 | `favorites` store precedence: override beats `userData.isFavorite` beats `false` | DR-119 | Done |
|
||||
| UT-106 | Un-favouriting removes an item from a favourites listing view | DR-117, DR-119 | Done |
|
||||
| UT-107 | The hybrid background refresh emits `favorites-changed` only for ids whose favourite state actually flipped | DR-120 | Done |
|
||||
| UT-109 | Search covers synced-but-not-downloaded items when catalog browse is on, and stays downloads-only when off | DR-108 | Done |
|
||||
| UT-110 | Search item-type filter is bound, not interpolated: a quote-bearing type neither errors nor widens results | DR-108 | Done |
|
||||
| UT-111 | FTS prefix queries quote each token, so apostrophes/hyphens/slashes are data; empty or punctuation-only input returns no rows rather than erroring | DR-108 | Done |
|
||||
| UT-112 | Repeated catalog passes leave one `items_fts` entry per item, not one per pass | DR-110 | Done |
|
||||
| UT-113 | The stale-catalog sweep removes vanished synced rows, keeps downloaded ones, keeps uncrawled types, and stays scoped to one server | DR-110 | Done |
|
||||
| UT-114 | Cached people are reachable from unscoped search and excluded from scoped search | DR-111 | Done |
|
||||
| UT-115 | Re-index staleness policy: never-indexed and unparseable timestamps are due, fresh ones are not, future ones are not | DR-109 | Done |
|
||||
| UT-116 | `resolve_local_media_path` returns a completed download's file, and `None` for an in-progress download, a row whose file has been deleted, or an unknown item | DR-123 | Done |
|
||||
| UT-118 | `resolveVideoSource` prefers a downloaded file, never marks a local file as needing transcoding, and falls back to streaming for a blank path | DR-123 | Done |
|
||||
| UT-119 | The audio-only handoff picks a downloaded file over the audio-only stream URL, preserving the Jellyfin id for progress sync | DR-128 | Done |
|
||||
| UT-120 | Expiry reclaim takes only expired temporary entries: derived from `completed_at`+TTL, honouring an `expires_at` override, never a user download, and disabled by a zero TTL | DR-127 | Done |
|
||||
| UT-108 | LRU eviction reclaims only `'auto'` downloads and never a user's own, even when the user's is the oldest | DR-126 | Done |
|
||||
| UT-117 | A background audio-only stream cut short resumes where it died instead of ending the episode; a real end still advances; the absolute position is compared against the runtime; retries at a stuck position give up. A recoverable error resumes music and video too, with growing backoff, leaving the rest of the queue intact and the seekable stream's URL untouched; local and DirectUrl sources are excluded | DR-129 | Done |
|
||||
|
||||
### Integration Tests
|
||||
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
# Spec: Locally-indexed search
|
||||
|
||||
**Status:** Implemented
|
||||
**Requirements:** UR-065 → DR-108, DR-109, DR-110, DR-111; IR-030
|
||||
**UX spec:** [ux-flows.md §6.1](../ux-flows.md) (search surface is unchanged)
|
||||
**Revises:** [scoped-search.md](scoped-search.md) and
|
||||
[scoped-search-boundary.md](scoped-search-boundary.md) — scope semantics are
|
||||
untouched; this changes only *which corpus* the cache leg searches.
|
||||
|
||||
## Summary
|
||||
|
||||
Search stops depending on a per-keystroke round trip to Jellyfin. The local
|
||||
SQLite catalog — which is already synced and already FTS5-indexed — becomes the
|
||||
corpus the instant leg of search reads, so results appear as fast as SQLite can
|
||||
answer, online or offline. A background indexer keeps that catalog fresh on a
|
||||
schedule instead of only at app start, prunes content deleted on the server, and
|
||||
covers the item types search groups results by. The server query stays, demoted
|
||||
to a background reconciliation that merges in late results for anything indexed
|
||||
since the last pass.
|
||||
|
||||
## Motivation
|
||||
|
||||
The pieces are already built and simply not wired together:
|
||||
|
||||
- [`sync_full_catalog`](../../src-tauri/src/commands/catalog.rs) already walks
|
||||
every library `Recursive=true` and persists items with `synced_at`.
|
||||
- `items_fts` (schema.rs migration 001) already indexes `name`, `overview`,
|
||||
`album_name`, `album_artist`, `artists`, `series_name` with keep-in-sync
|
||||
triggers.
|
||||
- `repository_search` is already two-phase — synchronous cache result, then a
|
||||
spawned server query merged in via the `search-event`.
|
||||
|
||||
What breaks the chain is that the cache leg is hard-restricted to *downloaded*
|
||||
items. `OfflineRepository::search` wraps its FTS query in a `downloaded_items`
|
||||
CTE requiring `d.status = 'completed'`:
|
||||
|
||||
```sql
|
||||
FROM items i
|
||||
JOIN items_fts fts ON fts.rowid = i.rowid
|
||||
INNER JOIN downloaded_items di ON i.id = di.id
|
||||
WHERE i.server_id = ? AND items_fts MATCH ?
|
||||
```
|
||||
|
||||
So for a user with no downloads, phase 1 returns nothing on every query, and
|
||||
every debounced keystroke falls through to a full `Recursive=true` server
|
||||
request with `Limit=10000`. The populated local index is never read.
|
||||
|
||||
`get_items` does not have this problem — it gates a third `synced_at IS NOT NULL`
|
||||
branch on `include_catalog_browse()` (offline.rs, the "Show all server media"
|
||||
toggle). The asymmetry is the bug: **offline you can already browse the whole
|
||||
catalog but cannot search it.**
|
||||
|
||||
Three further defects found while confirming the above:
|
||||
|
||||
1. **The FTS index grows without bound.** `save_to_cache` uses
|
||||
`INSERT OR REPLACE INTO items`, but `recursive_triggers` is never enabled
|
||||
(`storage/mod.rs` sets only `foreign_keys` and `journal_mode`). SQLite fires
|
||||
`AFTER DELETE` triggers on a REPLACE *only* with recursive triggers on — so
|
||||
`items_ad` never runs, the old FTS row is orphaned, and because `items.id` is
|
||||
a `TEXT PRIMARY KEY` the replacement row takes a **new rowid** and inserts a
|
||||
second FTS entry. Every sync appends a duplicate index. Results stay correct
|
||||
(the `INNER JOIN … ON fts.rowid = i.rowid` hides orphans, and no rowid is ever
|
||||
reused because nothing is deleted) but `MATCH` degrades permanently.
|
||||
2. **Server-side deletions never propagate.** There is no `DELETE FROM items`
|
||||
anywhere in the codebase. The local catalog is append-only, so media removed
|
||||
from the server would stay searchable forever — tolerable when the cache was
|
||||
only a browse accelerator, not acceptable when it is the search corpus.
|
||||
3. **The index omits types search groups by.** `CATALOG_ITEM_TYPES` is
|
||||
`MusicAlbum, Movie, Series, Season, Episode, Audio, BoxSet` — no
|
||||
`MusicArtist`, no `Playlist`, and People live in a separate `people` table
|
||||
with no FTS at all. UR-060 mandates Artists and People result groups, so today
|
||||
those can *only* come from the server.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Which corpus search reads (downloads-only vs full synced catalog) | **Rust** | Sync/availability policy over domain data. Changes if Jellyfin's API or the offline rules change, not if the UI is redesigned. Reuses the existing `include_catalog_browse()` flag so search and browse cannot diverge again. |
|
||||
| Index freshness policy — TTL, when a re-index is due, skip-while-offline | **Rust** | Explicitly named as domain policy in [SPEC-REVIEW-CHECKLIST.md](SPEC-REVIEW-CHECKLIST.md) ("reachability/sync policy"). It is currently frontend-driven in `offlineCatalog.ts`; this spec moves it. |
|
||||
| Which Jellyfin item types get indexed (`CATALOG_ITEM_TYPES`) | **Rust** | Textbook domain taxonomy — a category→item-type set. Must never appear in `src/`. |
|
||||
| Reconciling a crawl against local rows (what to prune) | **Rust** | Operates on domain data and depends on crawl completeness semantics. |
|
||||
| FTS query construction, ranking, scope→type expansion | **Rust** | Already there (`search_rank.rs`, `SearchScope::item_types()`); unchanged by this spec. |
|
||||
| Rendering a "catalog last indexed N ago" hint and any re-index button | **Frontend** | Pure presentation of a backend-supplied timestamp. |
|
||||
| Debounce interval, result group order, scope chips | **Frontend** | Input handling and view preference; changes only if the UI is redesigned. |
|
||||
|
||||
Borderline call, recorded: the **TTL value itself** (how many hours before a
|
||||
re-index is due) could be argued as a user preference and therefore frontend. It
|
||||
is placed in Rust because the frontend must not be able to decide *whether the
|
||||
cache is authoritative* — that is the same class of decision as
|
||||
`include_catalog_browse`, which already lives in Rust. If the TTL later becomes
|
||||
user-configurable it stays a Rust-owned setting the frontend edits through a
|
||||
command, not a frontend constant. Borderline defaults to Rust.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Search the full synced catalog (DR-108)
|
||||
|
||||
`OfflineRepository::search` mirrors `get_items` exactly: rename the CTE to
|
||||
`available_items` and add the same third branch, gated on the same flag.
|
||||
|
||||
```rust
|
||||
let catalog_branch = if include_catalog_browse() {
|
||||
"UNION
|
||||
|
||||
-- Synced catalog: fast online search, or the offline 'Show all
|
||||
-- server media' view. Mirrors get_items; see set_include_catalog_browse.
|
||||
SELECT DISTINCT i.id
|
||||
FROM items i
|
||||
WHERE i.synced_at IS NOT NULL"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
```
|
||||
|
||||
No new IPC surface and no frontend change: `set_include_catalog_browse` is
|
||||
already called with `true` when online or when the offline toggle is on, and
|
||||
`false` only when offline with the toggle off. Search inherits the correct
|
||||
behaviour in all three states, and the "search is restricted to downloads" case
|
||||
survives for users who deliberately asked for downloads-only.
|
||||
|
||||
Also fix, in the same function, the `type_filter` built by **string
|
||||
interpolation** of `include_item_types` rather than bound parameters. It is
|
||||
currently safe only because callers pass `SearchScope`-derived values, but
|
||||
`SearchOptions.include_item_types` is settable directly from the frontend (as
|
||||
`GenericMediaListPage` does). Bind the values.
|
||||
|
||||
Phase 2 (the server query) is unchanged and still merges via `search-event`, so
|
||||
content added to the server since the last index still surfaces — just late
|
||||
rather than first.
|
||||
|
||||
### 2. Scheduled background indexer (DR-109, IR-030)
|
||||
|
||||
A Rust-owned task replaces the frontend's startup-only trigger.
|
||||
|
||||
```rust
|
||||
/// How long a full-catalog index stays fresh before a re-index is due.
|
||||
const CATALOG_INDEX_TTL: Duration = Duration::from_secs(6 * 60 * 60);
|
||||
```
|
||||
|
||||
Behaviour:
|
||||
|
||||
- On app setup, spawn a tokio task that ticks every 30 min.
|
||||
- Each tick: if a repository is active **and** the server is reachable **and**
|
||||
`now - last_catalog_sync > CATALOG_INDEX_TTL`, run a full index pass.
|
||||
- On the existing `ConnectivityMonitor` reconnect signal, evaluate the same
|
||||
staleness condition immediately rather than waiting for the next tick.
|
||||
- Never run two passes concurrently (the existing `syncInProgress` guard moves
|
||||
into Rust as an `AtomicBool`).
|
||||
|
||||
`last_catalog_sync` is already written to `app_settings` by `sync_full_catalog`
|
||||
and is currently read only for a UI hint; this makes it load-bearing.
|
||||
|
||||
`RepositoryManager` (`commands/repository.rs`) is a `HashMap<String, …>` with no
|
||||
notion of an active handle, so the task has nothing to run against. Add:
|
||||
|
||||
```rust
|
||||
pub struct RepositoryManager {
|
||||
repositories: Arc<Mutex<HashMap<String, Arc<HybridRepository>>>>,
|
||||
active: Arc<Mutex<Option<String>>>, // set in create(), cleared in destroy()
|
||||
}
|
||||
```
|
||||
|
||||
Progress is reported with a **kebab-case** event (per the project convention):
|
||||
|
||||
```rust
|
||||
// event name: "catalog-index-event"
|
||||
#[derive(specta::Type, Serialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CatalogIndexEvent {
|
||||
pub state: CatalogIndexState, // #[serde(tag = "type")] Idle | Running | Complete | Failed
|
||||
pub libraries_done: usize,
|
||||
pub libraries_total: usize,
|
||||
pub items_indexed: usize,
|
||||
}
|
||||
```
|
||||
|
||||
`sync_full_catalog` stays a command so the UI can still force a pass; it and the
|
||||
scheduler share one internal `run_index_pass()`.
|
||||
|
||||
### 3. Index hygiene — no orphans, and deletions propagate (DR-110)
|
||||
|
||||
**Orphan growth.** Replace `INSERT OR REPLACE INTO items (…)` in `save_to_cache`
|
||||
with a true upsert:
|
||||
|
||||
```sql
|
||||
INSERT INTO items (id, server_id, …) VALUES (…)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
name = excluded.name, overview = excluded.overview, …,
|
||||
synced_at = excluded.synced_at
|
||||
```
|
||||
|
||||
This preserves the rowid (which `items_fts` keys on via `content_rowid`) and
|
||||
fires `items_au` instead of silently orphaning a row. Preferred over
|
||||
`PRAGMA recursive_triggers = ON` because it also stops the rowid churn, and the
|
||||
three FTS triggers are the only triggers in the schema so nothing else depends
|
||||
on REPLACE semantics.
|
||||
|
||||
A new migration `021_rebuild_items_fts` clears the orphans already accumulated on
|
||||
existing installs:
|
||||
|
||||
```sql
|
||||
INSERT INTO items_fts(items_fts) VALUES('rebuild');
|
||||
```
|
||||
|
||||
**Deletions.** After a library crawls *successfully and completely*, reconcile:
|
||||
delete local rows for that library whose `id` was not seen in the crawl. Two
|
||||
constraints the implementation must respect:
|
||||
|
||||
- Skip any item with a completed download — the user has the file; removing the
|
||||
row would orphan it. Prune only synced-but-not-downloaded rows.
|
||||
- Only sweep libraries whose crawl succeeded. `sync_full_catalog` is
|
||||
deliberately best-effort per library, and `items.parent_id` is
|
||||
`ON DELETE CASCADE` — sweeping on a partial crawl would cascade a whole series
|
||||
away because one request timed out.
|
||||
|
||||
### 4. Index the types search groups by (DR-111)
|
||||
|
||||
Add `MusicArtist` and `Playlist` to `CATALOG_ITEM_TYPES`.
|
||||
|
||||
People need a different mechanism: they live in `people` (`id`, `server_id`,
|
||||
`name`, `overview`, `primary_image_tag`, `synced_at`), populated incidentally by
|
||||
item-detail fetches, with no FTS table. Migration `022_people_fts` adds one
|
||||
mirroring the `items_fts` pattern:
|
||||
|
||||
```sql
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS people_fts USING fts5(
|
||||
name, overview, content='people', content_rowid='rowid'
|
||||
);
|
||||
-- plus people_ai / people_ad / people_au triggers
|
||||
```
|
||||
|
||||
`OfflineRepository::search` UNIONs `people_fts` matches into its result set as
|
||||
`Person`-typed items when the resolved scope permits them (i.e. when
|
||||
`include_item_types` is `None` — `SearchScope::All`). `search_rank.rs` already
|
||||
handles `MediaKind::Person`, so ranking needs no change.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- **Incremental indexing** (e.g. Jellyfin's `MinDateLastSaved`). A full crawl is
|
||||
what makes the deletion sweep in §3 sound — it yields the authoritative id set
|
||||
per library. An incremental pass cannot detect deletions, so it would need a
|
||||
separate reconciliation strategy. Worth revisiting if full crawls prove too
|
||||
slow on large libraries; measure first.
|
||||
- **Changing search UX** — scope chips, group order, the debounce, and the
|
||||
`/search` route are untouched.
|
||||
- **Removing the server leg.** Phase 2 stays.
|
||||
- The two dead search implementations (`storage_search_items` in
|
||||
`commands/storage/mod.rs`, `offline_search` in `commands/offline.rs`) — both
|
||||
registered in `lib.rs` and exported to `bindings.ts`, neither called from the
|
||||
frontend. Deleting them is correct but is cleanup, not this feature; file
|
||||
separately so this spec's diff stays reviewable.
|
||||
- `GenericMediaListPage` passing raw `includeItemTypes` and re-implementing the
|
||||
store's request-id/event protocol. A real boundary smell, tracked separately.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] With a synced catalog and **zero downloads**, typing a query returns
|
||||
results from the local index before any server request completes.
|
||||
- [ ] Offline with "Show all server media" **on**, search returns the full
|
||||
catalog (non-downloaded entries greyed out, matching browse).
|
||||
- [ ] Offline with the toggle **off**, search returns downloaded media only —
|
||||
the behaviour that exists today.
|
||||
- [ ] Re-running a full index pass N times does not grow `items_fts` row count
|
||||
beyond the `items` row count.
|
||||
- [ ] An item deleted server-side disappears from local search after one index
|
||||
pass; a **downloaded** item deleted server-side does not.
|
||||
- [ ] A library that fails mid-crawl prunes nothing.
|
||||
- [ ] Searching an artist or actor name returns results with the server
|
||||
unreachable.
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||
- [ ] `bun run check:boundary` passes.
|
||||
- [ ] New requirement-implementing code carries `// TRACES:` comments.
|
||||
- [ ] `bindings.ts` regenerated (new `CatalogIndexEvent` type).
|
||||
|
||||
## Testing
|
||||
|
||||
Per CLAUDE.md, each defect gets a **failing test first**.
|
||||
|
||||
Rust (`cargo test`), against an in-memory DB seeded with synced-but-not-
|
||||
downloaded items:
|
||||
|
||||
- `search` returns synced items when `include_catalog_browse()` is true, and
|
||||
only downloaded items when false. *Fails today* — the current CTE returns
|
||||
empty in the first case.
|
||||
- Upserting the same item twice leaves exactly one `items_fts` row. *Fails
|
||||
today.*
|
||||
- The sweep removes a vanished synced item, retains a vanished downloaded item,
|
||||
and no-ops for a library whose crawl errored.
|
||||
- `type_filter` binds parameters — a type string containing a quote does not
|
||||
alter the query.
|
||||
- Staleness: a `last_catalog_sync` inside the TTL does not trigger a pass; one
|
||||
outside it does; offline never does.
|
||||
- `people_fts` matches surface as `Person` items under `SearchScope::All` and
|
||||
are excluded under `Music`/`Movies`/`Tv`.
|
||||
|
||||
Frontend (`vitest`): the catalog-index event maps to the staleness hint; no
|
||||
change to the search store's request-id/stale-response handling, which stays
|
||||
covered by its existing tests.
|
||||
|
||||
## TRACES
|
||||
|
||||
| Piece | Tag |
|
||||
|---|---|
|
||||
| `OfflineRepository::search` availability CTE | `// TRACES: UR-065 \| DR-108` |
|
||||
| Background indexer task + scheduling | `// TRACES: UR-065 \| DR-109, IR-030` |
|
||||
| `save_to_cache` upsert + FTS rebuild migration | `// TRACES: UR-065 \| DR-110` |
|
||||
| Deletion reconciliation | `// TRACES: UR-065 \| DR-110` |
|
||||
| `CATALOG_ITEM_TYPES` widening + `people_fts` | `// TRACES: UR-065, UR-060 \| DR-111` |
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- **A parallel Claude session may be active in this repo.** Run `git diff`
|
||||
before "repairing" changes you did not make (CLAUDE.md gotchas).
|
||||
- The frontend's `offlineCatalog.ts` startup trigger should be **removed**, not
|
||||
left alongside the Rust scheduler — two independent triggers with one
|
||||
`syncInProgress` guard each is how double-crawls happen.
|
||||
- `downloads` has a relaxed FK to `items` (migration 005). Verify the deletion
|
||||
sweep's interaction with it before enabling the sweep, and check whether
|
||||
`parent_id`'s `ON DELETE CASCADE` reaches further than intended.
|
||||
- The existing 100 ms `cache_with_timeout` in `hybrid.rs` returns *empty* on
|
||||
timeout rather than erroring. Once the cache leg is the primary path, that
|
||||
budget may need raising — an FTS query over a large catalog on cold page cache
|
||||
can exceed it, and the failure mode is a silently empty result.
|
||||
- Keep `SearchScope` semantics as-is: `All => None` (no filter), deliberately
|
||||
not a union, so People and folders are not filtered out (DR-063).
|
||||
- Noted but deliberately not fixed here: `pushCatalogVisibility` in
|
||||
`offlineCatalog.ts` derives the flag as `connected || showCatalog` — the
|
||||
frontend computing an availability *policy*, even though the flag itself is
|
||||
Rust-stored. DR-108 depends on that derivation being correct and it is, so
|
||||
this spec leaves it alone. Once DR-109 has moved sync policy into Rust, the
|
||||
derivation belongs there too, with the frontend pushing only the raw user
|
||||
toggle. Folding it into this change would enlarge the diff for no behavioural
|
||||
gain — but do not add *new* policy on the frontend side of that line.
|
||||
@@ -0,0 +1,395 @@
|
||||
# Spec: Favourites — marking, browsing, and sync
|
||||
|
||||
**Status:** Implemented
|
||||
**Requirements:** UR-067, UR-068, UR-069 → DR-113 … DR-120; JA-033, JA-034
|
||||
(allocated in [requirements.md](../requirements.md); tests UT-099 … UT-107).
|
||||
Note: UR-066/DR-112/IR-031 were claimed by the concurrent safe-area work while
|
||||
this spec was being written, so the ids here start one higher than first drafted.
|
||||
Existing: UR-017 → DR-021, JA-017, JA-018 (the toggle itself, already built).
|
||||
**UX spec:** [ux-flows.md](../ux-flows.md) §3.2 (full-player favourite), §5.2
|
||||
(album detail favourite), §5B.3 (movie detail hero: *Play / Download / Favorite*)
|
||||
— all three already specify favourite affordances that **do not exist in the
|
||||
build**. This spec closes those, and adds a new §5C for the Favourites browse
|
||||
surface.
|
||||
**Supersedes / revises:** nothing.
|
||||
|
||||
## Summary
|
||||
|
||||
JellyTau can favourite an item but can never show you what you favourited. The
|
||||
heart is mounted in exactly one place (the mini player), no query anywhere asks
|
||||
Jellyfin or the local database for favourites, and favourites marked on any other
|
||||
client are invisible here. This spec adds the read side (a Favourites page, home
|
||||
carousels, an in-library filter), puts the heart on detail pages and media cards,
|
||||
teaches the backend to ingest server-side favourite state, and drains favourite
|
||||
toggles made while offline.
|
||||
|
||||
## Background: what exists today
|
||||
|
||||
Verified in code, 2026-08-04. The **write** path is real and mostly correct; the
|
||||
**read** path does not exist at all.
|
||||
|
||||
1. **Toggling works, from one place only.**
|
||||
[FavoriteButton.svelte](../../src/lib/components/FavoriteButton.svelte) is
|
||||
mounted solely in
|
||||
[MiniPlayer.svelte:381](../../src/lib/components/player/MiniPlayer.svelte#L381).
|
||||
Nothing else in `src/` renders it — so the only favouritable item in the app
|
||||
is the one currently playing.
|
||||
|
||||
2. **The toggle's plumbing is sound.**
|
||||
[favorites.ts](../../src/lib/services/favorites.ts) writes local first
|
||||
(`storage_toggle_favorite`,
|
||||
[storage/mod.rs:908](../../src-tauri/src/commands/storage/mod.rs#L908) — sets
|
||||
`user_data.is_favorite` + `pending_sync = 1`), then POST/DELETEs
|
||||
`/Users/{uid}/FavoriteItems/{id}`
|
||||
([online.rs:1652](../../src-tauri/src/repository/online.rs#L1652)) only when
|
||||
connected. Leave this design intact.
|
||||
|
||||
3. **`MediaItem.user_data` is always `None` from the server.**
|
||||
`JellyfinItem` has no `UserData` field, and `to_media_item` hardcodes
|
||||
[`user_data: None`](../../src-tauri/src/repository/online.rs#L656) with the
|
||||
comment *"User data not included in basic item responses"*. The only
|
||||
populated `user_data` in the app comes from
|
||||
[series_progress.rs](../../src-tauri/src/repository/series_progress.rs#L244)
|
||||
and the local read in
|
||||
[offline.rs:115](../../src-tauri/src/repository/offline.rs#L115). **Nothing
|
||||
ingests server favourite state**, which is why the mini player has to fetch
|
||||
`storageGetPlaybackProgress` per track to colour one heart
|
||||
([MiniPlayer.svelte:75-93](../../src/lib/components/player/MiniPlayer.svelte#L75-L93)).
|
||||
|
||||
4. **No favourites query exists.**
|
||||
[`GetItemsOptions`](../../src-tauri/src/repository/types.rs#L278) has no
|
||||
favourites field; `Filters=IsFavorite` appears nowhere; no SQL selects
|
||||
`is_favorite = 1`; there is no `/library/favorites` route and no favourites
|
||||
carousel in [home.ts](../../src/lib/stores/home.ts).
|
||||
|
||||
5. **Offline favourites are silently lossy.** Offline `mark_favorite` /
|
||||
`unmark_favorite` are no-ops
|
||||
([offline.rs:1620](../../src-tauri/src/repository/offline.rs#L1620)), so an
|
||||
offline toggle survives only as a local row with `pending_sync = 1` — and
|
||||
**nothing ever drains that flag**. `syncService.queueFavorite`
|
||||
([syncService.ts:91](../../src/lib/services/syncService.ts#L91)) exists with
|
||||
no callers.
|
||||
|
||||
## Motivation
|
||||
|
||||
Favouriting is a promise: the app takes the input and shows a "Added to
|
||||
favorites" toast, then discards it as far as the user can tell. Three of the UX
|
||||
flows already specify favourite buttons that were never built, and the one that
|
||||
was built (mini player) writes to a store nothing reads. Either the feature gets
|
||||
its read side or the heart should be removed — this spec takes the first option.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Favourites **scope** → set of Jellyfin item types | Rust | Domain taxonomy. Changes when Jellyfin adds/renames a type, never when the UI is redesigned. Reuses the canonical `SearchScope::item_types()` ([types.rs:324](../../src-tauri/src/repository/types.rs#L324)) — the exact leak class of [scoped-search-boundary.md](scoped-search-boundary.md). |
|
||||
| Cross-library favourites query (`Filters=IsFavorite`, `Recursive`, paging, sort field) | Rust | Query shaping against the Jellyfin API is domain logic; the endpoint's contract changes with the server, not the UI. |
|
||||
| Offline favourites SQL (join `user_data`, downloaded/catalog gating) | Rust | Storage + domain. Must obey the existing catalog-browse gate (DR-080) which the frontend cannot see. |
|
||||
| Deserialising Jellyfin `UserData` into `MediaItem.user_data` | Rust | Provider payload mapping. |
|
||||
| Mirroring server favourite state into the local `user_data` table | Rust | Cache/sync policy. |
|
||||
| Conflict rule: a local row with `pending_sync = 1` beats the server value | Rust | Business rule about which write wins; nothing to do with rendering. |
|
||||
| Draining pending favourite toggles on reconnect | Rust | Sync policy, and it must run whether or not any view is mounted — a frontend-driven drain dies with the component. Consistent with *reachability from real traffic* (DR-055). |
|
||||
| Which surfaces show favourites, tab order, row placement on home | Frontend | Pure presentation; changes only if the UI is redesigned. |
|
||||
| Heart placement, animation, toast, haptics, empty-state copy | Frontend | Presentation. |
|
||||
| In-session optimistic heart state shared across views | Frontend | View state, not persisted truth; the durable write already goes to Rust. |
|
||||
|
||||
**Borderline, and the tie-breaker used:** *which* scopes appear as tabs (All /
|
||||
Movies / Shows / Music) is a presentation choice — the frontend picks which
|
||||
`SearchScope` values to offer. What each scope *means* is Rust's. The frontend
|
||||
sends the enum value and never names an item type in connection with favourites.
|
||||
Single-type pages (`itemType: "Movie"` on the Movies list page) stay as they are;
|
||||
this rule targets category taxonomy, not every mention of a type.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Server user data reaches `MediaItem` (Rust, DR-113, JA-034)
|
||||
|
||||
Jellyfin returns `UserData` on `/Users/{uid}/Items*` responses. Add the field to
|
||||
`JellyfinItem` and map it in `to_media_item`, replacing the hardcoded `None`:
|
||||
|
||||
```rust
|
||||
// in JellyfinItem
|
||||
#[serde(alias = "UserData")]
|
||||
pub user_data: Option<JellyfinUserData>,
|
||||
```
|
||||
|
||||
`JellyfinUserData` deserialises `IsFavorite`, `Played`, `PlaybackPositionTicks`,
|
||||
`PlayCount`, `LastPlayedDate` into the existing
|
||||
[`UserData`](../../src-tauri/src/repository/types.rs#L44) type (which already
|
||||
carries `is_favorite` and already serialises camelCase, so `bindings.ts` needs no
|
||||
new type — only regeneration). Add `UserData` to the `Fields=` list in `get_items`
|
||||
/ `get_item` so the shape is explicit rather than relying on the default.
|
||||
|
||||
Wire shape, unchanged from today's `UserData`:
|
||||
|
||||
```ts
|
||||
item.userData?.isFavorite // boolean | null | undefined
|
||||
```
|
||||
|
||||
Delete the now-false `// User data not included in basic item responses` comment.
|
||||
|
||||
### 2. Local mirror of server favourites (Rust, DR-114)
|
||||
|
||||
Choke point: `save_to_cache(parent_id, &items)` in
|
||||
[offline.rs](../../src-tauri/src/repository/offline.rs) — every server result
|
||||
that gets cached (including via
|
||||
[`cache_items_from_server`](../../src-tauri/src/repository/hybrid.rs#L124) and
|
||||
the background cache refresh) passes through it.
|
||||
|
||||
For each item carrying `user_data.is_favorite`, upsert:
|
||||
|
||||
```sql
|
||||
INSERT INTO user_data (user_id, item_id, is_favorite, synced_at, pending_sync)
|
||||
VALUES (?, ?, ?, ?, 0)
|
||||
ON CONFLICT(user_id, item_id) DO UPDATE SET
|
||||
is_favorite = excluded.is_favorite,
|
||||
synced_at = excluded.synced_at
|
||||
WHERE user_data.pending_sync = 0; -- local unsynced change wins
|
||||
```
|
||||
|
||||
The `WHERE` on the conflict clause is the whole conflict rule: a toggle made
|
||||
offline is never overwritten by a stale server value before it has been pushed.
|
||||
|
||||
### 3. Favourites queries (Rust, DR-115, DR-116, JA-033)
|
||||
|
||||
**(a) In-library filter** — one new field on `GetItemsOptions`:
|
||||
|
||||
```rust
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub favorites_only: Option<bool>,
|
||||
```
|
||||
|
||||
- online `get_items`: append `&Filters=IsFavorite` when true.
|
||||
- offline `get_items`: add `INNER JOIN user_data ud ON ud.item_id = i.id AND ud.user_id = ? AND ud.is_favorite = 1`, composed with the existing `available_items` CTE so the downloads-only gate still applies.
|
||||
|
||||
Frontend sends `{ favoritesOnly: true }` (camelCase — nested struct field, needs
|
||||
the existing `#[serde(rename_all = "camelCase")]` on `GetItemsOptions`, already
|
||||
present).
|
||||
|
||||
**(b) Cross-library favourites** — a new trait method, because favourites span
|
||||
libraries and `get_items` is `ParentId`-shaped:
|
||||
|
||||
```rust
|
||||
/// TRACES: UR-067 | DR-115 | JA-033
|
||||
async fn get_favorites(
|
||||
&self,
|
||||
scope: SearchScope,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError>;
|
||||
```
|
||||
|
||||
```rust
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_get_favorites(
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
handle: String,
|
||||
scope: SearchScope,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, String>
|
||||
```
|
||||
|
||||
Frontend call (command name matches the Rust fn exactly; top-level params
|
||||
auto-camelCase; `SearchScope` is `#[serde(rename_all = "camelCase")]` so the wire
|
||||
values are `"all" | "music" | "movies" | "tv"`):
|
||||
|
||||
```ts
|
||||
await commands.repositoryGetFavorites(handle, "movies", { limit: 100 });
|
||||
```
|
||||
|
||||
- **online**: `/Users/{uid}/Items?Filters=IsFavorite&Recursive=true&SortBy=SortName&SortOrder=Ascending` + `&IncludeItemTypes=…` from `scope.item_types()` (omit entirely on `None`, per that function's contract) + the standard `Fields=`.
|
||||
- **offline**: `items ⨝ user_data (is_favorite = 1)`, type filter from the same `scope.item_types()`, honouring `include_catalog_browse()`.
|
||||
- **hybrid**: same cache-first race as `get_items`, **including the DR-080 rule** — with the catalog-browse gate off, an empty offline result is authoritative and must not fall through to the server. Getting this wrong reproduces Defect B from [offline-downloaded-only-filter.md](offline-downloaded-only-filter.md).
|
||||
|
||||
**The cache-first result arrives stale, and there is no second payload.** On a
|
||||
cache hit, `hybrid::get_items` returns the local rows and refreshes the cache in
|
||||
a background task whose result the frontend never sees — fine for a library
|
||||
listing that changes daily, wrong for favourites, where the *point* is that
|
||||
another client just changed something. Favourites is the second read path (after
|
||||
search) that needs the deferred update, so the background refresh in
|
||||
`get_favorites` must emit the same `favorites-changed` event as §4 when the
|
||||
server's favourite set differs from what was returned:
|
||||
|
||||
```
|
||||
favorites-changed → { itemIds: string[] } // union of ids whose is_favorite flipped
|
||||
```
|
||||
|
||||
Both producers (background refresh, reconnect drain) emit the identical payload,
|
||||
and the frontend has one handler that refreshes the `favorites` store. Without
|
||||
this, a favourite marked on another client appears in JellyTau only on the
|
||||
*second* visit to the page.
|
||||
|
||||
### 4. Draining offline toggles (Rust, DR-120)
|
||||
|
||||
On the offline→online transition already detected by `ConnectivityMonitor`,
|
||||
select `user_data WHERE pending_sync = 1 AND is_favorite IS NOT NULL`, POST or
|
||||
DELETE `/Users/{uid}/FavoriteItems/{id}` per row, then set `pending_sync = 0` and
|
||||
`synced_at`. Failures leave the row pending for the next transition.
|
||||
|
||||
Emit a kebab-case event when anything changed, so open views refresh without
|
||||
polling:
|
||||
|
||||
```
|
||||
favorites-changed → { itemIds: string[] }
|
||||
```
|
||||
|
||||
`syncService.queueFavorite` is dead code once this lands — delete it or point it
|
||||
at the backend drain; do not leave two competing queues.
|
||||
|
||||
### 5. Frontend surfaces (DR-117, DR-118, DR-119)
|
||||
|
||||
**Favourites page** — new route `/library/favorites`:
|
||||
- Scope tabs *All / Movies / Shows / Music* via the existing `LibraryViewTabs`; each tab sends a `SearchScope` value, nothing more.
|
||||
- Renders through `LibraryGrid` + `MediaCard` (tracklist for Music→tracks if the tab is later split; not in this pass).
|
||||
- Entry points: a card on the library overview ([library/+page.svelte](../../src/routes/library/+page.svelte)) and "See all" on the home rows.
|
||||
- Empty state per tab: "Nothing favourited yet — tap the heart on anything you like."
|
||||
|
||||
**Home carousels** — `favoriteMovies`, `favoriteShows`, `favoriteMusic` added to
|
||||
[home.ts](../../src/lib/stores/home.ts), each `repositoryGetFavorites(scope, { limit: 20 })`,
|
||||
rendered after *Recently Added* and **only when non-empty** (no empty rows on a
|
||||
fresh install).
|
||||
|
||||
**In-library filter** — a favourites toggle in the header of
|
||||
[GenericMediaListPage](../../src/lib/components/library/GenericMediaListPage.svelte)
|
||||
and the Movies/TV landing pages, passing `favoritesOnly: true` into the existing
|
||||
`repo.getItems(...)` options. Session-scoped state; not persisted (a persisted
|
||||
filter that hides most of a library is a support call waiting to happen).
|
||||
|
||||
**Hearts** — mount `FavoriteButton`:
|
||||
- Movie / series detail hero button row, beside the download buttons ([library/[id]/+page.svelte:528-553](../../src/routes/library/%5Bid%5D/+page.svelte#L528-L553)) — closes ux-flows §5B.3.
|
||||
- `EpisodeFocusView`, `ArtistDetailView`, `PlaylistDetailView`, album detail — closes ux-flows §5.2.
|
||||
- `MediaCard` artwork overlay (top-right). Suppressed on `isServerOnly` cards, and must not fight the existing long-press/scroll-guard handlers ([MediaCard.svelte:60-70](../../src/lib/components/library/MediaCard.svelte#L60-L70)) — the heart is its own button and stops propagation.
|
||||
|
||||
**Shared optimistic state** — a small `favorites` store (`Map<string, boolean>`
|
||||
overlay + `favorites.set(id, value)`), so un-hearting an item on the Favourites
|
||||
page removes it from the grid and from any home row without a refetch, and a
|
||||
heart tapped on a card is reflected on the detail page. Resolution order:
|
||||
|
||||
```
|
||||
favorites store override ?? item.userData?.isFavorite ?? false
|
||||
```
|
||||
|
||||
`toggleFavorite()` updates the store alongside its existing local + server
|
||||
writes; the `favorites-changed` event refreshes it. This removes the mini
|
||||
player's per-track `storageGetPlaybackProgress` fetch once items carry
|
||||
`userData`.
|
||||
|
||||
### 6. Offline behaviour
|
||||
|
||||
Toggling offline keeps working exactly as now (local write + `pending_sync`), and
|
||||
now actually reaches the server on reconnect (§4). The Favourites page offline
|
||||
shows favourites among downloaded/cached items, subject to the existing
|
||||
catalog-browse gate. The offline repo's no-op `mark_favorite`/`unmark_favorite`
|
||||
stay no-ops — the local write plus the drain is the offline path.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Favouriting people, genres, or collections; favourite **playlists** are included only insofar as they fall under the Music scope.
|
||||
- Sorting by "date favourited" — Jellyfin does not expose it. Favourites sort by name.
|
||||
- A dedicated bottom-nav tab for favourites (reachable from library overview + home).
|
||||
- Building a playlist or download batch from favourites.
|
||||
- Reconciling favourites for items that no longer exist on the server.
|
||||
- Splitting the Music tab into albums/artists/tracks sub-tabs.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Favouriting is possible from movie, series, episode, album, artist and playlist detail pages, and from media cards in any grid.
|
||||
- [ ] A favourite marked in another Jellyfin client shows a filled heart in JellyTau without toggling it here.
|
||||
- [ ] `/library/favorites` lists favourites across libraries, filtered by the All/Movies/Shows/Music tabs.
|
||||
- [ ] Home shows favourite rows for movies, shows and music, and shows no row when a category has none.
|
||||
- [ ] Movies/TV/Music list pages can be filtered to favourites only.
|
||||
- [ ] Un-hearting an item on one surface updates the others without a manual refresh.
|
||||
- [ ] A favourite toggled while offline reaches the server after reconnect (verified against a real server or a fake repository).
|
||||
- [ ] Offline, the Favourites page respects the "Show all server media" gate — with it off, an empty result stays empty and does not fall through to the server.
|
||||
- [ ] No item-type set appears in `src/` in connection with favourites; the frontend sends `SearchScope` only.
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||
- [ ] `bun run check:boundary` passes (necessary, not sufficient — see CLAUDE.md).
|
||||
- [ ] New requirement-implementing code carries `// TRACES:` comments.
|
||||
- [ ] `bindings.ts` regenerated from Rust, not hand-edited.
|
||||
|
||||
## Testing
|
||||
|
||||
**🔴 §4 (the pending-sync drain) is a bug fix — failing test first.** Write a
|
||||
test that toggles a favourite with the repository offline, transitions to online,
|
||||
and asserts the server call happened; watch it fail before writing the drain.
|
||||
|
||||
Rust (`cd src-tauri && cargo test`):
|
||||
|
||||
| Test | Covers |
|
||||
|------|--------|
|
||||
| UT-099 | A Jellyfin item JSON fixture with `UserData.IsFavorite: true` maps to `MediaItem.user_data.is_favorite == Some(true)` |
|
||||
| UT-100 | `online::get_favorites` builds an endpoint with `Filters=IsFavorite`, `Recursive=true`, and the scope's `IncludeItemTypes`; `SearchScope::All` omits the type filter entirely |
|
||||
| UT-101 | `offline::get_favorites` returns only `is_favorite = 1` rows, respects the scope type filter, and returns nothing extra when the catalog-browse gate is off |
|
||||
| UT-102 | `save_to_cache` mirror does **not** overwrite a row with `pending_sync = 1` |
|
||||
| UT-103 | Drain pushes pending rows, clears `pending_sync`, sets `synced_at`, and leaves failed rows pending |
|
||||
| UT-104 | `get_items` with `favorites_only: true` filters both online (endpoint) and offline (SQL) |
|
||||
| UT-107 | The background refresh in `hybrid::get_favorites` emits `favorites-changed` with the flipped ids, and emits nothing when the server set matches the cache |
|
||||
|
||||
Frontend (`bun run test`):
|
||||
|
||||
| Test | Covers |
|
||||
|------|--------|
|
||||
| UT-105 | `favorites` store override precedence: store value beats `userData.isFavorite` beats `false` |
|
||||
| UT-106 | Un-hearting removes the item from a favourites list view (pure logic extracted to a `.ts` module, per the TrackList/episodeStrip pattern) |
|
||||
| IT-0xx | `repositoryGetFavorites` param naming — add to [tauriIntegration.test.ts](../../src/lib/utils/tauriIntegration.test.ts): camelCase top-level params, scope serialised as `"movies"` etc. |
|
||||
|
||||
Any component logic worth testing gets extracted into a plain `.ts` module first
|
||||
(`favoritesView.ts`), rather than tested through the component.
|
||||
|
||||
## TRACES
|
||||
|
||||
| Piece | Tag |
|
||||
|-------|-----|
|
||||
| `JellyfinUserData` + `to_media_item` mapping | `// TRACES: UR-069 \| DR-113, JA-034 \| UT-099` |
|
||||
| `save_to_cache` user_data mirror | `// TRACES: UR-069 \| DR-114 \| UT-102` |
|
||||
| `get_favorites` (trait, online, offline, hybrid) + command | `// TRACES: UR-067 \| DR-115, JA-033 \| UT-100, UT-101` |
|
||||
| `GetItemsOptions.favorites_only` handling | `// TRACES: UR-067 \| DR-116 \| UT-104` |
|
||||
| `/library/favorites` route + tabs | `// TRACES: UR-067 \| DR-117` |
|
||||
| Home favourite carousels | `// TRACES: UR-067 \| DR-118` |
|
||||
| `FavoriteButton` mounts + `favorites` store | `// TRACES: UR-068 \| DR-119 \| UT-105, UT-106` |
|
||||
| Pending-favourite drain + `favorites-changed` | `// TRACES: UR-069 \| DR-120 \| UT-103` |
|
||||
|
||||
New requirement rows to add to [requirements.md](../requirements.md):
|
||||
|
||||
- **UR-067** — Browse favourited media across libraries (page, home rows, in-library filter).
|
||||
- **UR-068** — Mark/unmark favourites from browse and detail surfaces, not only the player.
|
||||
- **UR-069** — Favourite state stays consistent with the server in both directions.
|
||||
- **DR-113 … DR-120** — as tabled above.
|
||||
- **JA-033** — Query favourite items (`Filters=IsFavorite`).
|
||||
- **JA-034** — Read `UserData` from item responses.
|
||||
|
||||
## Implementation notes (as built)
|
||||
|
||||
Two things landed differently from the design above, both forced by where the
|
||||
`AppHandle` lives:
|
||||
|
||||
1. **The `favorites-changed` event is emitted from the command layer, not the
|
||||
repository.** `HybridRepository` has no `AppHandle` — the same reason
|
||||
`search-event` is emitted from `repository_search`. `repository_get_favorites`
|
||||
therefore does the two-phase read itself (cache leg returned, server leg
|
||||
spawned) and diffs the two id sets via `changed_favorite_ids`, which is
|
||||
extracted and unit-tested (UT-107) rather than buried in the spawn.
|
||||
2. **The drain hooks the existing `connectivity:reconnected` event** via
|
||||
`app.listen` in `commands/favorites.rs`, rather than reaching into
|
||||
`ConnectivityMonitor` (which knows nothing about repositories). It drains
|
||||
through a narrow `FavoriteSink` trait so it can be tested against a recording
|
||||
double instead of a forty-method `MediaRepository` mock.
|
||||
|
||||
Also as built: `DatabaseService` is not object-safe (generic methods), so the
|
||||
drain takes `Arc<RusqliteService>` like the rest of the storage code, and
|
||||
`get_items`' endpoint construction was extracted to `build_get_items_endpoint`
|
||||
so the `favorites_only` filter could be asserted without an HTTP server.
|
||||
|
||||
**Not built:** the full-player heart. ux-flows §3.2 lists one among the full
|
||||
player's secondary controls and it remains unbuilt — recorded as a known
|
||||
deviation in ux-flows §5C.5 rather than silently dropped.
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- A parallel Claude session may be active in this repo — `git diff` before "repairing" unexpected changes.
|
||||
- Do **not** try to reuse `get_items` with an empty `ParentId` for cross-library favourites; that endpoint is built as `?ParentId={}` ([online.rs:731](../../src-tauri/src/repository/online.rs#L731)) and an empty value is not a reliable "all libraries" request. Use `get_favorites`.
|
||||
- `SearchScope` is reused rather than a new `FavoritesScope` so there is one taxonomy expansion in the codebase, not two that can drift. If the name grates once favourites ship, rename the type across search + favourites in one commit — don't fork it.
|
||||
- `SearchScope::All` returns `None` from `item_types()` **on purpose**; callers must omit `IncludeItemTypes` entirely rather than sending a union (see the doc comment at [types.rs:316](../../src-tauri/src/repository/types.rs#L316)).
|
||||
- Ship order that keeps each step demonstrable: §1+§2 (state becomes visible) → §5 hearts (marking becomes possible) → §3+§5 browse surfaces (finding becomes possible) → §4 drain.
|
||||
- Regenerate `bindings.ts` after the Rust types change; never hand-edit it.
|
||||
@@ -0,0 +1,219 @@
|
||||
# Spec: Two-path media — selectable playback bitrate, independent whole-file download
|
||||
|
||||
**Status:** Proposed
|
||||
**Requirements:** UR-070, UR-071 → DR-121, DR-122, DR-123, DR-124, DR-125; IR-032
|
||||
**UX spec:** player quality selector — needs a `ux-flows.md` section before build
|
||||
**Related:** [catalog-index-search.md](catalog-index-search.md),
|
||||
[downloads-as-offline-library.md](downloads-as-offline-library.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Two things that are today tangled become explicitly separate:
|
||||
|
||||
- **The playback path** streams at a bitrate the viewer can change from the
|
||||
player. It is ephemeral and its rendition is volatile.
|
||||
- **The download path** fetches the whole file at one canonical quality, in the
|
||||
background, independently of whatever playback is doing.
|
||||
|
||||
Bytes fetched for playback are kept **only** when the playback rendition happens
|
||||
to be the same artifact the download path would produce — i.e. direct play.
|
||||
Otherwise playback bytes are discarded and the download path does its own fetch.
|
||||
|
||||
## Motivation
|
||||
|
||||
The appealing version of this — "stream and download at once, switch when enough
|
||||
has arrived" — breaks the moment the viewer can change bitrate. A capture taken
|
||||
while the rendition changes underneath it is a splice of two encodings: not a
|
||||
playable file, and not something that can be honestly recorded as a download.
|
||||
Once bitrate is selectable, one stream cannot serve both jobs.
|
||||
|
||||
Separating the paths also removes the thing that made the original idea
|
||||
expensive: there is no mid-playback source swap to engineer, because the download
|
||||
never has to take over the live session. It lands on disk and is used at the next
|
||||
natural boundary — next episode, or next time the item is played.
|
||||
|
||||
What exists already and is *not* this: `SmartCache` predictively downloads *other*
|
||||
items, `player_preload_upcoming` warms the next one, and
|
||||
`refresh_queue_local_sources` swaps queue entries to local at boundaries. All of
|
||||
it concerns items you are not currently playing.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Available bitrate options for an item | **Rust** | Derived from Jellyfin's media sources and playback-info negotiation; changes with the API. |
|
||||
| Mapping a chosen bitrate to transcode parameters | **Rust** | Domain vocabulary. `get_video_download_url` already owns the quality→params mapping; playback must reuse it, not restate it. |
|
||||
| Deciding whether playback bytes are keepable (direct play vs transcode) | **Rust** | Depends on the negotiated session. |
|
||||
| Canonical download quality | **Rust** | Policy over domain data. |
|
||||
| Cache eviction, storage budget, sparse-range bookkeeping | **Rust** | Storage policy. |
|
||||
| Promotion to a `downloads` row, and what invalidates a cache entry | **Rust** | Domain state. |
|
||||
| Rendering the quality selector; remembering the last choice | **Frontend** | Presentation and a view preference. The *list* comes from Rust. |
|
||||
| WiFi-only / opt-in toggles | **Frontend collects, Rust enforces** | The control is UI; the gate must hold even if the UI never calls. |
|
||||
|
||||
Borderline, recorded: the **default** playback bitrate could look like a user
|
||||
preference (frontend). It goes to Rust because it must be reconcilable with what
|
||||
the server can actually produce for a given media source — a preference the
|
||||
backend has to validate is not a preference the frontend can own alone. The
|
||||
frontend stores the user's *choice*; Rust decides what that choice resolves to.
|
||||
|
||||
## Design
|
||||
|
||||
### DR-121 — Bitrate selection in the player
|
||||
|
||||
The player exposes the qualities Rust reports for the current item. Changing it
|
||||
re-negotiates the stream URL at the new quality and resumes at the current
|
||||
position. This is a deliberate, user-initiated interruption — a brief rebuffer is
|
||||
expected and acceptable, unlike the involuntary swap the earlier design would
|
||||
have needed.
|
||||
|
||||
Constraints that must not be broken:
|
||||
|
||||
- On Linux, video playback must keep using the HLS `master.m3u8` URL. CLAUDE.md
|
||||
records that returning `stream.mp4` means transcoded playback never starts.
|
||||
A quality change re-negotiates *within* HLS.
|
||||
- The quality→transcode-parameter mapping already exists in
|
||||
`get_video_download_url` ([online.rs:1702-1717](../../src-tauri/src/repository/online.rs#L1702-L1717)).
|
||||
Playback must call into the same mapping. Two copies of that table will drift.
|
||||
- Track selection (audio/subtitle) already survives a stream re-negotiation
|
||||
elsewhere in the player; a quality change must preserve it too.
|
||||
|
||||
### DR-122 — The playback path is ephemeral
|
||||
|
||||
Playback bytes are not persisted unless DR-124 says they are keepable. No partial
|
||||
capture is ever retained across a quality change: on change, any in-flight capture
|
||||
for that session is abandoned and its partial file deleted.
|
||||
|
||||
### DR-123 — The download path is independent
|
||||
|
||||
Downloading the whole file is a separate operation through the existing download
|
||||
manager, at one canonical quality (default `original`, the direct static copy),
|
||||
using `/Videos/{id}/stream.mp4` — progressive and Range-capable, which is what
|
||||
the resumable download worker relies on. It is unaffected by what playback is
|
||||
doing, and playback is unaffected by it.
|
||||
|
||||
Once complete it becomes an ordinary download row, so everything already built on
|
||||
top of downloads — offline browsing, `refresh_queue_local_sources`, the Downloads
|
||||
page — picks it up with no further work.
|
||||
|
||||
**Prerequisite:** downloaded *video* is currently never played locally.
|
||||
`repository_get_video_stream_url` goes straight to the online repo and
|
||||
[player/[id]/+page.svelte:316](../../src/routes/player/[id]/+page.svelte#L316)
|
||||
calls it with no local check — so a completed video download is still streamed.
|
||||
This must be fixed or the whole feature is invisible for video.
|
||||
|
||||
### DR-124 — Keep playback bytes only when they *are* the download
|
||||
|
||||
Capture is enabled only where the played bytes and the canonical download artifact
|
||||
are the same thing — a **direct-play** session. Then:
|
||||
|
||||
| Path | Mechanism |
|
||||
|---|---|
|
||||
| Android / ExoPlayer | `SimpleCache` + `CacheDataSource`, keyed by item id **and** media-source id so renditions never collide. LRU evictor sharing the existing smart-cache budget — not a second budget over the same disk. |
|
||||
| Linux audio / MPV | `stream-record`, set through the existing `set_property` plumbing. |
|
||||
| Linux video (HLS transcode) | **Not captured.** Segments are not a file; assembling one needs ffmpeg, which is not a dependency and which CI is forbidden from installing at job time. The download path (DR-123) covers this case instead. |
|
||||
|
||||
Two abandonment rules, both of which must delete the partial rather than promote
|
||||
it:
|
||||
|
||||
- **Seek during an mpv capture.** `stream-record` is documented as intended for
|
||||
linear streams; seeking breaks the recording. Straight-through listening
|
||||
captures, scrubbing does not.
|
||||
- **Any quality change** (DR-122).
|
||||
|
||||
### DR-125 — Promotion, rendition, and invalidation
|
||||
|
||||
A capture is promoted to a `downloads` row (`status = 'completed'`) only when it
|
||||
covers the whole resource. Partial captures stay cache and remain evictable.
|
||||
|
||||
A new `downloads.source_rendition` column records the negotiated
|
||||
quality/container/codec of whatever produced the bytes; `NULL` for rows fetched by
|
||||
the existing paths, which are always `original`. This is what makes an "upgrade to
|
||||
original" action possible later, and what stops a 720p capture and a 4K download
|
||||
being indistinguishable rows.
|
||||
|
||||
**Invalidation.** A quality change never touches a file that already exists —
|
||||
neither a permanent download nor a completed temporary one. Both remain valid
|
||||
copies of the rendition they hold, and deleting either would throw away bytes
|
||||
already paid for.
|
||||
|
||||
What a quality change *does* invalidate is an **in-flight** capture or background
|
||||
download of cached media: it is abandoned and restarted at the newly chosen
|
||||
quality, because a capture spanning a rendition change is a splice of two
|
||||
encodings rather than a playable file (DR-122).
|
||||
|
||||
So the rule is about *ongoing* work, not stored files. Nothing in this spec
|
||||
deletes user data.
|
||||
|
||||
### Gating
|
||||
|
||||
Capture and background download obey the existing WiFi-only gate and storage
|
||||
budget, and are off unless opted in. Enforcement is in Rust.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- **Mid-playback switch onto a completing download.** Two independent paths make
|
||||
it unnecessary; the download is used from the next boundary.
|
||||
- **Backfilling the unplayed remainder of a capture.** Watch 40 minutes and you
|
||||
have 40 minutes; completing it needs sparse-range bookkeeping and a resumable
|
||||
tail fetch. The DR-123 download path already produces a complete file, which is
|
||||
the reason this can wait.
|
||||
- **Bundling ffmpeg** to make transcoded video capturable. Real option, large
|
||||
packaging decision, its own proposal.
|
||||
- **Routing Linux video playback through `stream.mp4`.** Regresses a documented,
|
||||
hard-won fix.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] The player offers the qualities Rust reports, and changing one resumes at
|
||||
the same position with audio/subtitle selection preserved.
|
||||
- [ ] A quality change abandons any in-flight capture and leaves no partial file.
|
||||
- [ ] A quality change never deletes a `downloads` row.
|
||||
- [ ] A completed background download of a video is *played from disk* on the next
|
||||
play (the DR-123 prerequisite).
|
||||
- [ ] A direct-play session played start-to-finish leaves a complete local file
|
||||
with no second fetch; replaying it fetches no media bytes.
|
||||
- [ ] Seeking during an mpv capture abandons it; no truncated file is promoted.
|
||||
- [ ] A transcoded Linux video session is never captured, and never partially
|
||||
promoted.
|
||||
- [ ] Promoted rows record their rendition; existing paths still record
|
||||
`NULL`/`original`.
|
||||
- [ ] Gates hold with the setting off *and* with the frontend never sending it.
|
||||
- [ ] Eviction cannot delete bytes backing a promoted download row.
|
||||
- [ ] `bun run check`, `bun run test`, `cargo fmt`, `cargo clippy`,
|
||||
`bun run test:rust`, `bun run check:boundary` pass; `bindings.ts`
|
||||
regenerated if Rust types changed.
|
||||
|
||||
## Testing
|
||||
|
||||
Rust, table-driven and pure where possible: quality→params resolution shared with
|
||||
the download path; keepability (direct play vs transcode vs gate off); promotion
|
||||
(complete → promoted, partial → not, seek-abandoned → not, quality-changed → not);
|
||||
invalidation (evicts cache, never a download row); rendition round-trip.
|
||||
|
||||
Android: instrumented — a played direct-play item yields cache entries, and a
|
||||
replay issues no media network request.
|
||||
|
||||
Frontend: the quality list renders from backend data with no item-type or
|
||||
codec taxonomy in `src/`; the selector's remembered choice is a view preference.
|
||||
|
||||
## TRACES
|
||||
|
||||
| Piece | Tag |
|
||||
|---|---|
|
||||
| Quality selector + re-negotiation | `// TRACES: UR-070 \| DR-121` |
|
||||
| Ephemeral playback / capture abandonment | `// TRACES: UR-070 \| DR-122` |
|
||||
| Independent whole-file download + local video playback fix | `// TRACES: UR-071 \| DR-123, IR-032` |
|
||||
| ExoPlayer cache / mpv stream-record / keepability | `// TRACES: UR-071 \| DR-124` |
|
||||
| Promotion, `source_rendition`, invalidation | `// TRACES: UR-071 \| DR-125` |
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- **A parallel Claude session is active in this repo.** `git diff` before
|
||||
"repairing" anything you did not write.
|
||||
- Do not duplicate the quality→transcode-parameter table. Call the existing one.
|
||||
- Reuse the smart-cache storage budget; two budgets over one disk is how devices
|
||||
fill up.
|
||||
- The `downloads` FK to `items` is relaxed (migration 005) — exercise promotion
|
||||
for an item that was never cached.
|
||||
- Build DR-123's local-playback fix first. Without it nothing in this spec is
|
||||
observable for video.
|
||||
+126
-2
@@ -634,7 +634,7 @@ episode strip.
|
||||
│ │ S2E4 • 48m • ★8.1 │ │
|
||||
│ │ Overview… │ │
|
||||
│ │ ▓▓▓▓▓░░░░░ 32m left │ │
|
||||
│ │ [▶ Play] │ │
|
||||
│ │ [▶ Play] [⬇] [♡] │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ More Episodes │ ← 2. EPISODE STRIP
|
||||
@@ -688,7 +688,7 @@ A movie has no continuation set, so cast follows the hero directly.
|
||||
### 5B.4 Series detail — section order
|
||||
|
||||
```
|
||||
Hero (poster, title, metadata, Resume SxEy / Download / Clear history)
|
||||
Hero (poster, title, metadata, Resume SxEy / Download / Favorite / Clear history)
|
||||
→ Crew links
|
||||
→ Genre tags
|
||||
→ Seasons (collapsible; only the current season expanded)
|
||||
@@ -757,6 +757,130 @@ opt-in. Grids and other surfaces keep tap-to-open with no long-press.
|
||||
|
||||
---
|
||||
|
||||
## 5C. Favourites
|
||||
|
||||
Favouriting is a two-sided promise: the heart takes the input, and the app must
|
||||
be able to give it back. This section covers both sides — where you can mark a
|
||||
favourite, and where marked favourites resurface.
|
||||
|
||||
See [specs/favorites-browsing.md](specs/favorites-browsing.md) for the layer
|
||||
assignment and wire shapes.
|
||||
|
||||
### 5C.1 The heart appears wherever an item does
|
||||
|
||||
A favourite is a property of an *item*, so the affordance follows the item
|
||||
rather than living on one privileged screen. Any surface that shows a whole
|
||||
item shows its heart.
|
||||
|
||||
| Surface | Heart position | Notes |
|
||||
|---------|----------------|-------|
|
||||
| Movie / Series detail hero | In the button row, after Play and Download | §5B.3, §5B.4 |
|
||||
| Episode Focus View hero | Same row as Play / Download | §5B.2 |
|
||||
| Album, Artist, Playlist detail | In the header button row | §5.2 |
|
||||
| Media card (any grid or carousel) | Top-right overlay on the artwork | Hidden on server-only (greyed) cards |
|
||||
| Mini player | Right of the track metadata | Existing behaviour, unchanged |
|
||||
| Full player | Secondary controls row | §3.2 — **not yet built**, see §5C.5 |
|
||||
|
||||
Rules:
|
||||
|
||||
- **The heart never competes with the card.** On a media card it is its own
|
||||
button and swallows the tap, so hearting an item never also opens or plays
|
||||
it, and never triggers the §5B.5 long-press.
|
||||
- **State is shown, not guessed.** A filled heart means the *server* considers
|
||||
the item a favourite (or you just tapped it). An item favourited in Jellyfin
|
||||
Web, on another device, or by another client renders filled here without
|
||||
being touched in JellyTau.
|
||||
- **Feedback is immediate.** The heart fills on tap and a toast confirms;
|
||||
neither waits for the server round-trip.
|
||||
|
||||
### 5C.2 Three ways back to what you favourited
|
||||
|
||||
Favourites are not one destination — they are a lens, and the right surface
|
||||
depends on whether the user is *browsing*, *deciding*, or *hunting*.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
User[User wants their favourites] --> How{Intent}
|
||||
|
||||
How -->|Passive: show me something| Home[Home carousels<br/>Favourite Movies / Shows / Music]
|
||||
How -->|Deliberate: my whole collection| Page[Favourites page<br/>/library/favorites]
|
||||
How -->|Narrowing: within this library| Filter[Favourites filter<br/>on a library page]
|
||||
|
||||
Home -->|See all| Page
|
||||
Page --> Detail[Item detail page]
|
||||
Filter --> Detail
|
||||
```
|
||||
|
||||
**Home carousels.** Rows for favourite movies, shows and music sit below
|
||||
*Recently Added*. A row with nothing in it **does not render** — a fresh install
|
||||
shows no empty favourite rows. Each row ends with *See all*, landing on the
|
||||
matching tab of the Favourites page.
|
||||
|
||||
**The Favourites page** (`/library/favorites`) is the complete collection,
|
||||
scoped by tabs:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ [←] Favourites │
|
||||
│ ┌─────┬────────┬───────┬───────┐ │
|
||||
│ │ All │ Movies │ Shows │ Music │ ← scope tabs │
|
||||
│ └─────┴────────┴───────┴───────┘ │
|
||||
│ │
|
||||
│ ┌────┐┌────┐┌────┐┌────┐┌────┐ │
|
||||
│ │ ♥ ││ ♥ ││ ♥ ││ ♥ ││ ♥ │ grid/list │
|
||||
│ └────┘└────┘└────┘└────┘└────┘ per §5A │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- Cards obey §5A in full — shape follows the media, so a mixed *All* tab reads
|
||||
as posters, squares and thumbnails side by side rather than one forced shape.
|
||||
- Reached from a card on the library overview (`/library`) and from *See all*
|
||||
on any home favourites row.
|
||||
- Sorted by name. Jellyfin does not record *when* an item was favourited, so
|
||||
"recently favourited" is not offerable — see §5C.5.
|
||||
- Empty state, per tab: *"Nothing favourited yet — tap the heart on anything
|
||||
you like."*
|
||||
|
||||
**The in-library filter** is for narrowing where the user already is: a
|
||||
favourites toggle in the header of the Movies, TV and Music browse pages,
|
||||
filtering the current list in place. It is **session-scoped and not persisted** —
|
||||
a sticky filter that silently hides most of a library reads as data loss on the
|
||||
next launch.
|
||||
|
||||
### 5C.3 Removing a favourite removes it everywhere, at once
|
||||
|
||||
Un-hearting an item on the Favourites page removes its card from the grid
|
||||
immediately; the same item disappears from the home rows and shows an empty
|
||||
heart on its detail page without a manual refresh. The reverse holds for
|
||||
favouriting. There is no confirmation prompt — the action is one tap to undo.
|
||||
|
||||
### 5C.4 Offline
|
||||
|
||||
- **Marking works offline.** The heart fills, the toast confirms, and the change
|
||||
is held locally.
|
||||
- **It reaches the server on reconnect**, without the user returning to the
|
||||
screen where they made it.
|
||||
- **Browsing offline shows favourites among media on the device**, subject to
|
||||
the same "Show all server media" gate as every other browse surface (§7.2) —
|
||||
with the gate off, an empty Favourites tab means *nothing favourited is
|
||||
downloaded*, and the page does not quietly fall back to the server catalog.
|
||||
|
||||
### 5C.5 Known deviations
|
||||
|
||||
- **The full player has no heart.** §3.2 and §3.3 list a Favorite button among
|
||||
the full player's secondary controls; it was never built, and this pass does
|
||||
not add it. The mini player heart above it is the only in-player affordance.
|
||||
*(UR-067)*
|
||||
- **No "recently favourited" sort.** Jellyfin's API does not expose a favourite
|
||||
timestamp, so favourites can only be ordered by name. Recording the
|
||||
timestamp locally at toggle time would order *this device's* favourites only,
|
||||
which is worse than a consistent name sort.
|
||||
- **Music is one tab, not three.** The Music scope mixes albums, artists and
|
||||
tracks in a single grid rather than offering sub-tabs. Acceptable while
|
||||
favourite counts are small; revisit if the tab becomes unscannable.
|
||||
|
||||
---
|
||||
|
||||
## 6. Search Flow
|
||||
|
||||
Search is **context-scoped**: what you are looking at when you start a search
|
||||
|
||||
@@ -173,10 +173,10 @@ describe("live requirements.md", () => {
|
||||
);
|
||||
const defined = countDefinedRequirements(md);
|
||||
|
||||
expect(defined.UR).toBe(65);
|
||||
expect(defined.IR).toBe(30);
|
||||
expect(defined.DR).toBe(105);
|
||||
expect(defined.JA).toBe(32);
|
||||
expect(defined.total).toBe(232);
|
||||
expect(defined.UR).toBe(71);
|
||||
expect(defined.IR).toBe(32);
|
||||
expect(defined.DR).toBe(126);
|
||||
expect(defined.JA).toBe(34);
|
||||
expect(defined.total).toBe(263);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,10 +14,12 @@
|
||||
//! that were queued offline (they have `stream_url IS NULL`), mirroring the
|
||||
//! heal-and-pump pattern in `player_preload_upcoming`.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use log::{info, warn};
|
||||
use tauri::State;
|
||||
use tauri::{Emitter, Manager, State};
|
||||
|
||||
use crate::commands::download::{pump_download_queue, DownloadManagerWrapper};
|
||||
use crate::commands::repository::RepositoryManagerWrapper;
|
||||
@@ -29,16 +31,79 @@ use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
||||
/// full-catalog sync.
|
||||
const LAST_CATALOG_SYNC_KEY: &str = "last_catalog_sync";
|
||||
|
||||
/// How long an index stays fresh before a re-index is due.
|
||||
///
|
||||
/// This lives in Rust rather than being a frontend constant because it decides
|
||||
/// *whether the local cache is authoritative* — the same class of decision as
|
||||
/// `include_catalog_browse`, and squarely the "sync policy" the spec review
|
||||
/// checklist keeps out of the presentation layer. If it later becomes
|
||||
/// user-configurable it stays a Rust-owned setting edited through a command.
|
||||
const CATALOG_INDEX_TTL: Duration = Duration::from_secs(6 * 60 * 60);
|
||||
|
||||
/// How often the scheduler wakes to *check* staleness. Far shorter than the TTL
|
||||
/// because a tick is nearly free — one indexed `app_settings` lookup — and it is
|
||||
/// what makes the indexer responsive to events it cannot subscribe to: signing
|
||||
/// in, and coming back online. The TTL, not the tick, decides whether a crawl
|
||||
/// actually happens.
|
||||
const CATALOG_INDEX_TICK: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
/// Delay before the first staleness check, to let sign-in complete and the
|
||||
/// repository be registered. Without it the first check runs against an empty
|
||||
/// repository manager and a fresh install would sit unindexed until the next
|
||||
/// tick.
|
||||
const CATALOG_INDEX_FIRST_CHECK: Duration = Duration::from_secs(15);
|
||||
|
||||
/// Kebab-case, per the project's event convention.
|
||||
pub const CATALOG_INDEX_EVENT: &str = "catalog-index-event";
|
||||
|
||||
/// Guards against two passes running at once. Replaces the frontend's
|
||||
/// `syncInProgress` boolean in `offlineCatalog.ts`, which could not see a pass
|
||||
/// started by the scheduler.
|
||||
static INDEX_IN_PROGRESS: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Clears [`INDEX_IN_PROGRESS`] however the pass leaves — including on the `?`
|
||||
/// early return when `get_libraries` fails, which a plain store at the end of
|
||||
/// the function would leak.
|
||||
struct IndexPassGuard;
|
||||
|
||||
impl Drop for IndexPassGuard {
|
||||
fn drop(&mut self) {
|
||||
INDEX_IN_PROGRESS.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// Progress of a background index pass, for the staleness hint in the UI.
|
||||
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CatalogIndexEvent {
|
||||
/// `started` | `finished` | `failed`
|
||||
pub state: String,
|
||||
pub items_cached: usize,
|
||||
pub items_pruned: usize,
|
||||
pub libraries_failed: usize,
|
||||
/// Present on `failed`.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Item types worth caching for offline browsing: containers the library
|
||||
/// landing pages render plus the playable leaves users queue for download.
|
||||
/// `MusicArtist` and `Playlist` are here because search groups results by them
|
||||
/// (UR-060's Artists group). Without them in the crawl, the local index can
|
||||
/// never answer an artist query and those groups can only ever be filled by the
|
||||
/// server leg. Keep this in step with what `prune_stale_catalog` is allowed to
|
||||
/// sweep — the crawl is only authoritative for the types it asks for.
|
||||
///
|
||||
/// TRACES: UR-065, UR-060 | DR-111
|
||||
const CATALOG_ITEM_TYPES: &[&str] = &[
|
||||
"MusicAlbum",
|
||||
"MusicArtist",
|
||||
"Movie",
|
||||
"Series",
|
||||
"Season",
|
||||
"Episode",
|
||||
"Audio",
|
||||
"BoxSet",
|
||||
"Playlist",
|
||||
];
|
||||
|
||||
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
@@ -48,6 +113,9 @@ pub struct CatalogSyncResult {
|
||||
pub items_cached: usize,
|
||||
/// Libraries that failed to sync (e.g. server hiccup); best-effort.
|
||||
pub libraries_failed: usize,
|
||||
/// Entries removed because the server no longer has them. Always 0 when any
|
||||
/// library failed, since a partial crawl cannot prove an item is gone.
|
||||
pub items_pruned: usize,
|
||||
}
|
||||
|
||||
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
@@ -71,8 +139,6 @@ pub async fn sync_full_catalog(
|
||||
db: State<'_, DatabaseWrapper>,
|
||||
handle: String,
|
||||
) -> Result<CatalogSyncResult, String> {
|
||||
use crate::repository::MediaRepository;
|
||||
|
||||
let repo = repository.0.get(&handle).ok_or("Repository not found")?;
|
||||
|
||||
let db_service = {
|
||||
@@ -80,6 +146,27 @@ pub async fn sync_full_catalog(
|
||||
Arc::new(database.service())
|
||||
};
|
||||
|
||||
run_index_pass(repo, db_service).await
|
||||
}
|
||||
|
||||
/// One full-catalog indexing pass, shared by the [`sync_full_catalog`] command
|
||||
/// and the background scheduler (DR-109) so there is exactly one implementation
|
||||
/// and one concurrency guard.
|
||||
///
|
||||
/// TRACES: UR-065 | DR-109, DR-110
|
||||
pub(crate) async fn run_index_pass(
|
||||
repo: Arc<crate::repository::HybridRepository>,
|
||||
db_service: Arc<crate::storage::db_service::RusqliteService>,
|
||||
) -> Result<CatalogSyncResult, String> {
|
||||
use crate::repository::MediaRepository;
|
||||
|
||||
// One pass at a time. The command and the scheduler can both land here, and
|
||||
// two concurrent crawls would double the server load and race on the sweep.
|
||||
if INDEX_IN_PROGRESS.swap(true, Ordering::SeqCst) {
|
||||
return Err("A catalog index pass is already running".to_string());
|
||||
}
|
||||
let _guard = IndexPassGuard;
|
||||
|
||||
let libraries = repo.get_libraries().await.map_err(|e| e.to_string())?;
|
||||
info!(
|
||||
"[Catalog] Full sync starting across {} libraries",
|
||||
@@ -88,6 +175,10 @@ pub async fn sync_full_catalog(
|
||||
|
||||
let include_types: Vec<String> = CATALOG_ITEM_TYPES.iter().map(|s| s.to_string()).collect();
|
||||
|
||||
// Taken before the crawl: every row the crawl writes gets a `synced_at`
|
||||
// newer than this, so anything still older afterwards is gone server-side.
|
||||
let pass_started_at = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
let mut items_cached = 0usize;
|
||||
let mut libraries_failed = 0usize;
|
||||
|
||||
@@ -118,6 +209,35 @@ pub async fn sync_full_catalog(
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate server-side deletions — but only after a *complete* crawl.
|
||||
// `sync_full_catalog` is best-effort per library, and `items.parent_id` is
|
||||
// ON DELETE CASCADE, so sweeping when a library failed to fetch could
|
||||
// cascade a whole series away because one request timed out.
|
||||
let mut items_pruned = 0usize;
|
||||
if libraries_failed == 0 && !libraries.is_empty() {
|
||||
match repo
|
||||
.prune_stale_catalog(&pass_started_at, &include_types)
|
||||
.await
|
||||
{
|
||||
Ok(removed) => {
|
||||
items_pruned = removed;
|
||||
if removed > 0 {
|
||||
info!(
|
||||
"[Catalog] Pruned {} entries no longer on the server",
|
||||
removed
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => warn!("[Catalog] Prune of stale catalog entries failed: {:?}", e),
|
||||
}
|
||||
} else if libraries_failed > 0 {
|
||||
info!(
|
||||
"[Catalog] Skipping stale-entry prune: {} librar{} failed to sync, so the crawl is not authoritative",
|
||||
libraries_failed,
|
||||
if libraries_failed == 1 { "y" } else { "ies" }
|
||||
);
|
||||
}
|
||||
|
||||
// Record the sync time so callers can skip re-syncing too eagerly.
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let upsert = Query::with_params(
|
||||
@@ -133,16 +253,169 @@ pub async fn sync_full_catalog(
|
||||
}
|
||||
|
||||
info!(
|
||||
"[Catalog] Full sync complete: {} items cached, {} libraries failed",
|
||||
items_cached, libraries_failed
|
||||
"[Catalog] Full sync complete: {} items cached, {} pruned, {} libraries failed",
|
||||
items_cached, items_pruned, libraries_failed
|
||||
);
|
||||
|
||||
Ok(CatalogSyncResult {
|
||||
items_cached,
|
||||
libraries_failed,
|
||||
items_pruned,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an index pass is due, given when one last completed.
|
||||
///
|
||||
/// Pure so the policy is unit-testable without a clock, a server, or a database.
|
||||
/// `None` (never indexed) and an unparseable stored value both mean "due" — a
|
||||
/// corrupt timestamp should trigger a re-index, not silently freeze the catalog.
|
||||
///
|
||||
/// TRACES: UR-065 | DR-109 | UT-115
|
||||
pub(crate) fn index_is_due(
|
||||
last_synced_at: Option<&str>,
|
||||
now: chrono::DateTime<chrono::Utc>,
|
||||
ttl: Duration,
|
||||
) -> bool {
|
||||
let Some(raw) = last_synced_at else {
|
||||
return true;
|
||||
};
|
||||
let Ok(last) = chrono::DateTime::parse_from_rfc3339(raw) else {
|
||||
return true;
|
||||
};
|
||||
now.signed_duration_since(last.with_timezone(&chrono::Utc))
|
||||
.to_std()
|
||||
.map(|elapsed| elapsed >= ttl)
|
||||
// Negative elapsed => the stored stamp is in the future (clock skew).
|
||||
// Not due; a future stamp will age into due-ness on its own.
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Read the last-sync timestamp straight from `app_settings`.
|
||||
async fn read_last_sync(
|
||||
db_service: &Arc<crate::storage::db_service::RusqliteService>,
|
||||
) -> Option<String> {
|
||||
db_service
|
||||
.query_optional(
|
||||
Query::with_params(
|
||||
"SELECT value FROM app_settings WHERE key = ?",
|
||||
vec![QueryParam::String(LAST_CATALOG_SYNC_KEY.to_string())],
|
||||
),
|
||||
|row| row.get(0),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Start the background catalog indexer.
|
||||
///
|
||||
/// Replaces the frontend's startup-only `syncCatalog()` call: index freshness is
|
||||
/// sync policy and belongs in Rust (see the layer assignment in
|
||||
/// docs/specs/catalog-index-search.md). Ticks every [`CATALOG_INDEX_TICK`] and
|
||||
/// runs a pass when a repository exists, the server is reachable, and the index
|
||||
/// is older than [`CATALOG_INDEX_TTL`].
|
||||
///
|
||||
/// TRACES: UR-065 | DR-109, IR-030
|
||||
pub fn spawn_catalog_indexer(app: tauri::AppHandle) {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// Check shortly after launch, then on every tick — not tick-then-check,
|
||||
// which would leave a fresh install unindexed for a full tick.
|
||||
tokio::time::sleep(CATALOG_INDEX_FIRST_CHECK).await;
|
||||
|
||||
loop {
|
||||
if let Err(e) = maybe_run_scheduled_pass(&app).await {
|
||||
// Never fatal — a failed pass leaves the existing index in place
|
||||
// and we retry on the next tick.
|
||||
warn!("[Catalog] Scheduled index pass skipped: {}", e);
|
||||
}
|
||||
|
||||
tokio::time::sleep(CATALOG_INDEX_TICK).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// One scheduler tick: check the preconditions, then index if due.
|
||||
async fn maybe_run_scheduled_pass(app: &tauri::AppHandle) -> Result<(), String> {
|
||||
if INDEX_IN_PROGRESS.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let db_service = {
|
||||
let db = app.state::<DatabaseWrapper>();
|
||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||
Arc::new(database.service())
|
||||
};
|
||||
|
||||
if !index_is_due(
|
||||
read_last_sync(&db_service).await.as_deref(),
|
||||
chrono::Utc::now(),
|
||||
CATALOG_INDEX_TTL,
|
||||
) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Offline: leave the index alone. The crawl would fail every library and,
|
||||
// more importantly, a partial crawl must never reach the deletion sweep.
|
||||
{
|
||||
let monitor = app.state::<crate::commands::connectivity::ConnectivityMonitorWrapper>();
|
||||
let monitor = monitor.0.lock().await;
|
||||
if !monitor.get_status().await.is_server_reachable {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
let repo = {
|
||||
let manager = app.state::<RepositoryManagerWrapper>();
|
||||
let handles = manager.0.handles();
|
||||
let Some(handle) = handles.first() else {
|
||||
// Not signed in yet.
|
||||
return Ok(());
|
||||
};
|
||||
manager.0.get(handle).ok_or("Repository not found")?
|
||||
};
|
||||
|
||||
info!("[Catalog] Index is stale; starting a scheduled pass");
|
||||
let _ = app.emit(
|
||||
CATALOG_INDEX_EVENT,
|
||||
CatalogIndexEvent {
|
||||
state: "started".to_string(),
|
||||
items_cached: 0,
|
||||
items_pruned: 0,
|
||||
libraries_failed: 0,
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
|
||||
match run_index_pass(repo, db_service).await {
|
||||
Ok(result) => {
|
||||
let _ = app.emit(
|
||||
CATALOG_INDEX_EVENT,
|
||||
CatalogIndexEvent {
|
||||
state: "finished".to_string(),
|
||||
items_cached: result.items_cached,
|
||||
items_pruned: result.items_pruned,
|
||||
libraries_failed: result.libraries_failed,
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = app.emit(
|
||||
CATALOG_INDEX_EVENT,
|
||||
CatalogIndexEvent {
|
||||
state: "failed".to_string(),
|
||||
items_cached: 0,
|
||||
items_pruned: 0,
|
||||
libraries_failed: 0,
|
||||
error: Some(e.clone()),
|
||||
},
|
||||
);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Report the last-synced timestamp so the UI can show a hint / decide whether
|
||||
/// to trigger a fresh sync.
|
||||
#[tauri::command]
|
||||
@@ -378,6 +651,43 @@ mod tests {
|
||||
use rusqlite::Connection;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The re-index policy. Pure, so it is testable without a clock, a server or
|
||||
/// a database — which is the reason it was factored out of the scheduler.
|
||||
///
|
||||
/// TRACES: UR-065 | DR-109 | UT-115
|
||||
#[test]
|
||||
fn test_index_is_due() {
|
||||
let ttl = Duration::from_secs(6 * 60 * 60);
|
||||
let now = chrono::DateTime::parse_from_rfc3339("2026-08-04T12:00:00+00:00")
|
||||
.unwrap()
|
||||
.with_timezone(&chrono::Utc);
|
||||
|
||||
// Never indexed => due. This is the first-run case.
|
||||
assert!(index_is_due(None, now, ttl));
|
||||
|
||||
// Indexed 7 hours ago => past the 6h TTL => due.
|
||||
assert!(index_is_due(Some("2026-08-04T05:00:00+00:00"), now, ttl));
|
||||
|
||||
// Indexed 1 hour ago => fresh => not due. This is what stops the
|
||||
// scheduler re-crawling every tick.
|
||||
assert!(!index_is_due(Some("2026-08-04T11:00:00+00:00"), now, ttl));
|
||||
|
||||
// Exactly at the TTL boundary counts as due.
|
||||
assert!(index_is_due(Some("2026-08-04T06:00:00+00:00"), now, ttl));
|
||||
|
||||
// A corrupt stored value must trigger a re-index, not freeze the
|
||||
// catalog forever behind an unparseable timestamp.
|
||||
assert!(index_is_due(Some("not-a-timestamp"), now, ttl));
|
||||
assert!(index_is_due(Some(""), now, ttl));
|
||||
|
||||
// A timestamp in the future (clock skew, or a restored backup) is not
|
||||
// due — it ages into due-ness rather than causing a crawl every tick.
|
||||
assert!(!index_is_due(Some("2026-08-05T00:00:00+00:00"), now, ttl));
|
||||
|
||||
// Offsets other than UTC are compared as instants, not as strings.
|
||||
assert!(!index_is_due(Some("2026-08-04T13:30:00+02:00"), now, ttl));
|
||||
}
|
||||
|
||||
fn test_db() -> Arc<RusqliteService> {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute_batch(
|
||||
|
||||
@@ -270,6 +270,19 @@ pub async fn download_item(
|
||||
if !can_download {
|
||||
warn!("Storage limit reached. Attempting to free space...");
|
||||
|
||||
// Reclaim expired temporary entries first: they are dead weight, so
|
||||
// freeing them may avoid evicting cache that is still within its
|
||||
// life. Best-effort — a failure here just means eviction does more.
|
||||
// TRACES: UR-071 | DR-127
|
||||
match cache_arc
|
||||
.reclaim_expired_async(&db_service, &user_id, &chrono::Utc::now().to_rfc3339())
|
||||
.await
|
||||
{
|
||||
Ok(n) if n > 0 => info!("Reclaimed {} expired cache entries", n),
|
||||
Ok(_) => {}
|
||||
Err(e) => warn!("Expired-entry reclaim failed: {}", e),
|
||||
}
|
||||
|
||||
// Try to evict LRU items to make space
|
||||
match cache_arc
|
||||
.evict_lru_async(&db_service, &user_id, size as u64)
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
//! Pushing favourite toggles made while the server was unreachable.
|
||||
//!
|
||||
//! Favouriting works offline: `storage_toggle_favorite` writes the local
|
||||
//! `user_data` row and sets `pending_sync = 1`. Until DR-120 nothing ever
|
||||
//! cleared that flag — the offline `mark_favorite`/`unmark_favorite` are no-ops
|
||||
//! and `syncService.queueFavorite` had no callers — so an offline toggle was
|
||||
//! silently lost.
|
||||
//!
|
||||
//! The drain lives in Rust, not the frontend, because it must run whether or
|
||||
//! not any view is mounted; a drain started by a component dies with it.
|
||||
//!
|
||||
//! TRACES: UR-069 | DR-120 | UT-103
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::{debug, info, warn};
|
||||
use tauri::{Emitter, Listener, Manager};
|
||||
|
||||
use crate::repository::types::RepoError;
|
||||
use crate::repository::MediaRepository;
|
||||
use crate::storage::db_service::{DatabaseService, Query, QueryParam, RusqliteService};
|
||||
|
||||
/// The subset of the repository the drain needs.
|
||||
///
|
||||
/// Narrow on purpose: a test double for `MediaRepository` would be forty
|
||||
/// unimplemented methods, which is how a drain ends up untested.
|
||||
#[async_trait]
|
||||
pub trait FavoriteSink: Send + Sync {
|
||||
async fn push_favorite(&self, item_id: &str, is_favorite: bool) -> Result<(), RepoError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: MediaRepository + ?Sized> FavoriteSink for T {
|
||||
async fn push_favorite(&self, item_id: &str, is_favorite: bool) -> Result<(), RepoError> {
|
||||
if is_favorite {
|
||||
self.mark_favorite(item_id).await
|
||||
} else {
|
||||
self.unmark_favorite(item_id).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A local favourite change still waiting to reach the server.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PendingFavorite {
|
||||
pub item_id: String,
|
||||
pub is_favorite: bool,
|
||||
}
|
||||
|
||||
/// Read every favourite change this user has pending.
|
||||
async fn read_pending(
|
||||
db: &Arc<RusqliteService>,
|
||||
user_id: &str,
|
||||
) -> Result<Vec<PendingFavorite>, String> {
|
||||
db.query_many(
|
||||
Query::with_params(
|
||||
"SELECT item_id, is_favorite FROM user_data \
|
||||
WHERE user_id = ? AND pending_sync = 1 AND is_favorite IS NOT NULL",
|
||||
vec![QueryParam::String(user_id.to_string())],
|
||||
),
|
||||
|row| {
|
||||
Ok(PendingFavorite {
|
||||
item_id: row.get::<_, String>(0)?,
|
||||
is_favorite: row.get::<_, Option<i32>>(1)?.unwrap_or(0) != 0,
|
||||
})
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Push pending favourite changes to the server and clear their flags.
|
||||
///
|
||||
/// Returns the ids that reached the server, for the `favorites-changed` event.
|
||||
/// A row whose push fails keeps `pending_sync = 1` and is retried on the next
|
||||
/// reconnect rather than being dropped.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-103
|
||||
pub async fn drain_pending_favorites(
|
||||
db: &Arc<RusqliteService>,
|
||||
sink: &dyn FavoriteSink,
|
||||
user_id: &str,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let pending = read_pending(db, user_id).await?;
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
info!(
|
||||
"[Favorites] Pushing {} favourite change(s) queued while offline",
|
||||
pending.len()
|
||||
);
|
||||
|
||||
let mut pushed = Vec::new();
|
||||
for change in pending {
|
||||
match sink
|
||||
.push_favorite(&change.item_id, change.is_favorite)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
let cleared = db
|
||||
.execute(Query::with_params(
|
||||
"UPDATE user_data SET pending_sync = 0, synced_at = ? \
|
||||
WHERE user_id = ? AND item_id = ?",
|
||||
vec![
|
||||
QueryParam::String(chrono::Utc::now().to_rfc3339()),
|
||||
QueryParam::String(user_id.to_string()),
|
||||
QueryParam::String(change.item_id.clone()),
|
||||
],
|
||||
))
|
||||
.await;
|
||||
|
||||
match cleared {
|
||||
Ok(_) => pushed.push(change.item_id),
|
||||
// The server took it; failing to clear the flag only means
|
||||
// we push it again next time, which is harmless.
|
||||
Err(e) => warn!(
|
||||
"[Favorites] Pushed {} but could not clear pending_sync: {}",
|
||||
change.item_id, e
|
||||
),
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// Still pending — retried on the next reconnect.
|
||||
debug!(
|
||||
"[Favorites] Deferring {}, server rejected the push: {:?}",
|
||||
change.item_id, e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(pushed)
|
||||
}
|
||||
|
||||
/// Drain on every offline→online transition.
|
||||
///
|
||||
/// Hooks the `connectivity:reconnected` event the `ConnectivityMonitor`
|
||||
/// already emits, rather than polling — reachability is derived from real
|
||||
/// traffic (DR-055) and this just reacts to it.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120
|
||||
pub fn spawn_favorites_drain(app: tauri::AppHandle) {
|
||||
let handle = app.clone();
|
||||
app.listen("connectivity:reconnected", move |_event| {
|
||||
let app = handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Err(e) = run_drain(&app).await {
|
||||
warn!("[Favorites] Drain skipped: {}", e);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async fn run_drain(app: &tauri::AppHandle) -> Result<(), String> {
|
||||
let db_service: Arc<RusqliteService> = {
|
||||
let db = app.state::<crate::commands::storage::DatabaseWrapper>();
|
||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||
Arc::new(database.service())
|
||||
};
|
||||
|
||||
let (repo, user_id) = {
|
||||
let manager = app.state::<crate::commands::repository::RepositoryManagerWrapper>();
|
||||
let handles = manager.0.handles();
|
||||
let Some(handle) = handles.first() else {
|
||||
// Not signed in — nothing to push on behalf of.
|
||||
return Ok(());
|
||||
};
|
||||
let repo = manager.0.get(handle).ok_or("Repository not found")?;
|
||||
let user_id = repo.user_id().to_string();
|
||||
(repo, user_id)
|
||||
};
|
||||
|
||||
let pushed = drain_pending_favorites(&db_service, repo.as_ref(), &user_id).await?;
|
||||
|
||||
if !pushed.is_empty() {
|
||||
let event = crate::commands::repository::FavoritesChangedEvent { item_ids: pushed };
|
||||
if let Err(e) = app.emit(crate::commands::repository::FAVORITES_CHANGED_EVENT, &event) {
|
||||
warn!("[Favorites] Failed to emit change event: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Records what the server was asked to do, and can be told to fail.
|
||||
struct RecordingSink {
|
||||
calls: Mutex<Vec<(String, bool)>>,
|
||||
fail_for: Option<String>,
|
||||
}
|
||||
|
||||
impl RecordingSink {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
calls: Mutex::new(Vec::new()),
|
||||
fail_for: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn failing_for(item_id: &str) -> Self {
|
||||
Self {
|
||||
calls: Mutex::new(Vec::new()),
|
||||
fail_for: Some(item_id.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn calls(&self) -> Vec<(String, bool)> {
|
||||
let mut calls = self.calls.lock().unwrap().clone();
|
||||
calls.sort();
|
||||
calls
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FavoriteSink for RecordingSink {
|
||||
async fn push_favorite(&self, item_id: &str, is_favorite: bool) -> Result<(), RepoError> {
|
||||
if self.fail_for.as_deref() == Some(item_id) {
|
||||
return Err(RepoError::Offline);
|
||||
}
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((item_id.to_string(), is_favorite));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn test_db() -> Arc<RusqliteService> {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute_batch(
|
||||
r#"
|
||||
CREATE TABLE user_data (
|
||||
user_id TEXT NOT NULL,
|
||||
item_id TEXT NOT NULL,
|
||||
is_favorite INTEGER,
|
||||
synced_at TEXT,
|
||||
pending_sync INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (user_id, item_id)
|
||||
);
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
Arc::new(RusqliteService::new(Arc::new(Mutex::new(conn))))
|
||||
}
|
||||
|
||||
async fn seed(db: &Arc<RusqliteService>, rows: &[(&str, &str, i32, i32)]) {
|
||||
for (user, item, fav, pending) in rows {
|
||||
db.execute(Query::with_params(
|
||||
"INSERT INTO user_data (user_id, item_id, is_favorite, pending_sync) \
|
||||
VALUES (?, ?, ?, ?)",
|
||||
vec![
|
||||
QueryParam::String(user.to_string()),
|
||||
QueryParam::String(item.to_string()),
|
||||
QueryParam::Int(*fav),
|
||||
QueryParam::Int(*pending),
|
||||
],
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
async fn pending_flag(db: &Arc<RusqliteService>, item_id: &str) -> Option<i32> {
|
||||
db.query_optional(
|
||||
Query::with_params(
|
||||
"SELECT pending_sync FROM user_data WHERE item_id = ?",
|
||||
vec![QueryParam::String(item_id.to_string())],
|
||||
),
|
||||
|row| row.get::<_, Option<i32>>(0),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// UT-103 — the core of the bug: a favourite toggled while offline reaches
|
||||
/// the server on reconnect, and stops being pending.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-103
|
||||
#[tokio::test]
|
||||
async fn test_drain_pushes_pending_favorites_and_clears_the_flag() {
|
||||
let db = test_db();
|
||||
seed(
|
||||
&db,
|
||||
&[
|
||||
("u1", "marked-offline", 1, 1),
|
||||
("u1", "unmarked-offline", 0, 1),
|
||||
// Already synced — must not be pushed again.
|
||||
("u1", "already-synced", 1, 0),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let sink = RecordingSink::new();
|
||||
let pushed = drain_pending_favorites(&db, &sink, "u1").await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
sink.calls(),
|
||||
vec![
|
||||
("marked-offline".to_string(), true),
|
||||
("unmarked-offline".to_string(), false),
|
||||
],
|
||||
"both pending changes push, with their direction preserved"
|
||||
);
|
||||
assert_eq!(pushed.len(), 2);
|
||||
assert_eq!(pending_flag(&db, "marked-offline").await, Some(0));
|
||||
assert_eq!(pending_flag(&db, "unmarked-offline").await, Some(0));
|
||||
}
|
||||
|
||||
/// A push that fails keeps its row pending, so the change is retried rather
|
||||
/// than dropped on the floor.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-103
|
||||
#[tokio::test]
|
||||
async fn test_drain_leaves_failed_pushes_pending() {
|
||||
let db = test_db();
|
||||
seed(&db, &[("u1", "ok", 1, 1), ("u1", "boom", 1, 1)]).await;
|
||||
|
||||
let sink = RecordingSink::failing_for("boom");
|
||||
let pushed = drain_pending_favorites(&db, &sink, "u1").await.unwrap();
|
||||
|
||||
assert_eq!(pushed, vec!["ok".to_string()]);
|
||||
assert_eq!(pending_flag(&db, "ok").await, Some(0));
|
||||
assert_eq!(
|
||||
pending_flag(&db, "boom").await,
|
||||
Some(1),
|
||||
"a failed push must stay queued for the next reconnect"
|
||||
);
|
||||
}
|
||||
|
||||
/// Another user's queued changes are not pushed with this user's token.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-103
|
||||
#[tokio::test]
|
||||
async fn test_drain_only_touches_the_given_user() {
|
||||
let db = test_db();
|
||||
seed(&db, &[("u1", "mine", 1, 1), ("u2", "theirs", 1, 1)]).await;
|
||||
|
||||
let sink = RecordingSink::new();
|
||||
let pushed = drain_pending_favorites(&db, &sink, "u1").await.unwrap();
|
||||
|
||||
assert_eq!(pushed, vec!["mine".to_string()]);
|
||||
assert_eq!(pending_flag(&db, "theirs").await, Some(1));
|
||||
}
|
||||
|
||||
/// Nothing pending means no server calls at all — a reconnect must not
|
||||
/// generate traffic just because it happened.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-103
|
||||
#[tokio::test]
|
||||
async fn test_drain_is_a_noop_when_nothing_is_pending() {
|
||||
let db = test_db();
|
||||
seed(&db, &[("u1", "synced", 1, 0)]).await;
|
||||
|
||||
let sink = RecordingSink::new();
|
||||
let pushed = drain_pending_favorites(&db, &sink, "u1").await.unwrap();
|
||||
|
||||
assert!(pushed.is_empty());
|
||||
assert!(sink.calls().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ pub mod connectivity;
|
||||
pub mod conversions;
|
||||
pub mod device;
|
||||
pub mod download;
|
||||
pub mod favorites;
|
||||
pub mod offline;
|
||||
pub mod playback_mode;
|
||||
pub mod playback_reporting;
|
||||
|
||||
@@ -379,16 +379,49 @@ pub(super) async fn create_media_item(
|
||||
})
|
||||
}
|
||||
|
||||
/// Check if an item has a completed download
|
||||
pub(super) async fn check_for_local_download(
|
||||
db: &DatabaseWrapper,
|
||||
/// Pick the source for an audio-only handoff.
|
||||
///
|
||||
/// A downloaded file wins over the audio-only stream URL. No transcode or audio
|
||||
/// extraction is involved or wanted: the native backends already play a video
|
||||
/// container without decoding its video — the Linux MPV backend is configured
|
||||
/// with `video: no`, and ExoPlayer simply has no surface to render to when the
|
||||
/// item is `MediaType::Audio`. Producing a separate audio-only file would cost
|
||||
/// CPU and battery, need an encoder the project does not ship, and leave a
|
||||
/// second artifact to keep in step with the first.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-128 | UT-119
|
||||
pub(super) fn background_audio_source(
|
||||
local_path: Option<String>,
|
||||
stream_url: String,
|
||||
item_id: &str,
|
||||
) -> MediaSource {
|
||||
match local_path {
|
||||
Some(path) => MediaSource::Local {
|
||||
file_path: PathBuf::from(path),
|
||||
jellyfin_item_id: Some(item_id.to_string()),
|
||||
},
|
||||
None => MediaSource::Remote {
|
||||
stream_url,
|
||||
jellyfin_item_id: item_id.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the on-disk file backing a completed download, if there is one.
|
||||
///
|
||||
/// A `downloads` row is not proof of a file: it can outlive the bytes (manual
|
||||
/// deletion, a cleared cache directory, a restored database). Every caller wants
|
||||
/// "can I play this from disk right now", so existence is checked here rather
|
||||
/// than trusted from the row.
|
||||
///
|
||||
/// Split out from [`check_for_local_download`] so the resolution is testable
|
||||
/// without a `DatabaseWrapper`, and reusable by the video path.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-123 | UT-116
|
||||
pub(super) async fn resolve_local_media_path<S: DatabaseService>(
|
||||
db_service: &Arc<S>,
|
||||
item_id: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
let db_service = {
|
||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||
Arc::new(database.service())
|
||||
};
|
||||
|
||||
let query = Query::with_params(
|
||||
"SELECT file_path FROM downloads WHERE item_id = ? AND status = 'completed' LIMIT 1",
|
||||
vec![QueryParam::String(item_id.to_string())],
|
||||
@@ -399,22 +432,58 @@ pub(super) async fn check_for_local_download(
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Verify the file actually exists on disk
|
||||
if let Some(ref file_path) = path {
|
||||
if std::path::Path::new(file_path).exists() {
|
||||
Ok(path)
|
||||
} else {
|
||||
match path {
|
||||
Some(ref file_path) if std::path::Path::new(file_path).exists() => Ok(path),
|
||||
Some(file_path) => {
|
||||
warn!(
|
||||
"[Player] Download entry exists in DB but file not found: {}",
|
||||
file_path
|
||||
);
|
||||
Ok(None)
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if an item has a completed download
|
||||
pub(super) async fn check_for_local_download(
|
||||
db: &DatabaseWrapper,
|
||||
item_id: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
let db_service = {
|
||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||
Arc::new(database.service())
|
||||
};
|
||||
|
||||
resolve_local_media_path(&db_service, item_id).await
|
||||
}
|
||||
|
||||
/// The on-disk path for a downloaded item, for playback surfaces that resolve
|
||||
/// their own source rather than going through the queue.
|
||||
///
|
||||
/// The video player is the reason this exists: audio has preferred local files
|
||||
/// since queue construction, but video asks the repository for a stream URL and
|
||||
/// never consults `downloads`, so a downloaded film was still streamed — costing
|
||||
/// bandwidth that had already been spent and failing outright when offline.
|
||||
///
|
||||
/// Returns `None` when nothing is downloaded *or* the file is missing, so the
|
||||
/// caller falls back to streaming.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-123 | UT-116
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn player_local_media_path(
|
||||
db: State<'_, DatabaseWrapper>,
|
||||
item_id: String,
|
||||
) -> Result<Option<String>, String> {
|
||||
let db_service = {
|
||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||
Arc::new(database.service())
|
||||
};
|
||||
|
||||
resolve_local_media_path(&db_service, &item_id).await
|
||||
}
|
||||
|
||||
/// Re-point queued streaming items at completed local downloads.
|
||||
///
|
||||
/// Sources are resolved once when the queue is built, so downloads that finish
|
||||
@@ -574,6 +643,7 @@ pub async fn player_play_item(
|
||||
pub async fn player_enter_background_audio(
|
||||
player: State<'_, PlayerStateWrapper>,
|
||||
session: State<'_, MediaSessionManagerWrapper>,
|
||||
db: State<'_, DatabaseWrapper>,
|
||||
item: PlayItemRequest,
|
||||
position_seconds: f64,
|
||||
) -> Result<PlayerStatus, String> {
|
||||
@@ -582,6 +652,19 @@ pub async fn player_enter_background_audio(
|
||||
item.title, position_seconds
|
||||
);
|
||||
|
||||
// Prefer the downloaded file over the audio-only stream URL the frontend
|
||||
// resolved. Handing the native backend a local video container yields
|
||||
// audio-only playback for free — no transcode, no second artifact.
|
||||
// TRACES: UR-071 | DR-128
|
||||
let local_path = check_for_local_download(&db, &item.id).await?;
|
||||
if local_path.is_some() {
|
||||
info!(
|
||||
"player_enter_background_audio: using downloaded file for {}",
|
||||
item.id
|
||||
);
|
||||
}
|
||||
let source = background_audio_source(local_path, item.stream_url, &item.id);
|
||||
|
||||
// Build an AUDIO media item pointing at the audio-only stream. We do not use
|
||||
// create_media_item() because that hardcodes MediaType::Video; background
|
||||
// audio must be Audio so no video decode is started.
|
||||
@@ -605,10 +688,7 @@ pub async fn player_enter_background_audio(
|
||||
duration: item.duration_seconds,
|
||||
artwork_url: None,
|
||||
media_type: MediaType::Audio,
|
||||
source: MediaSource::Remote {
|
||||
stream_url: item.stream_url,
|
||||
jellyfin_item_id: item.id.clone(),
|
||||
},
|
||||
source,
|
||||
video_codec: None,
|
||||
needs_transcoding: false,
|
||||
video_width: None,
|
||||
@@ -2379,6 +2459,128 @@ pub async fn player_disable_jellyfin(player: State<'_, PlayerStateWrapper>) -> R
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// The audio-only handoff must play a downloaded file when there is one,
|
||||
/// rather than fetching an audio-only stream for media already on disk.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-128 | UT-119
|
||||
#[test]
|
||||
fn test_background_audio_source_prefers_local_file() {
|
||||
use super::background_audio_source;
|
||||
use crate::player::MediaSource;
|
||||
use std::path::PathBuf;
|
||||
|
||||
let local = background_audio_source(
|
||||
Some("/downloads/ep1.mkv".to_string()),
|
||||
"https://server/audio-only".to_string(),
|
||||
"ep-1",
|
||||
);
|
||||
match local {
|
||||
MediaSource::Local {
|
||||
file_path,
|
||||
jellyfin_item_id,
|
||||
} => {
|
||||
assert_eq!(file_path, PathBuf::from("/downloads/ep1.mkv"));
|
||||
// The Jellyfin id must survive so progress still syncs back.
|
||||
assert_eq!(jellyfin_item_id.as_deref(), Some("ep-1"));
|
||||
}
|
||||
other => panic!("expected a local source, got {:?}", other),
|
||||
}
|
||||
|
||||
let remote = background_audio_source(None, "https://server/audio-only".to_string(), "ep-1");
|
||||
match remote {
|
||||
MediaSource::Remote {
|
||||
stream_url,
|
||||
jellyfin_item_id,
|
||||
} => {
|
||||
assert_eq!(stream_url, "https://server/audio-only");
|
||||
assert_eq!(jellyfin_item_id, "ep-1");
|
||||
}
|
||||
other => panic!("expected a remote source, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
/// A downloaded item must resolve to its file, and a `downloads` row whose
|
||||
/// file has gone must resolve to `None` so the caller falls back to
|
||||
/// streaming instead of handing the player a path that cannot be opened.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-123 | UT-116
|
||||
#[tokio::test]
|
||||
async fn test_resolve_local_media_path() {
|
||||
use super::resolve_local_media_path;
|
||||
use crate::storage::db_service::{DatabaseService, Query, RusqliteService};
|
||||
use rusqlite::Connection;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute(
|
||||
"CREATE TABLE downloads (id INTEGER PRIMARY KEY, item_id TEXT, status TEXT, file_path TEXT)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
let db_service = Arc::new(RusqliteService::new(Arc::new(Mutex::new(conn))));
|
||||
|
||||
// A real file on disk, so the existence check passes.
|
||||
let present = std::env::temp_dir().join("jellytau-resolve-local-test.mp4");
|
||||
std::fs::write(&present, b"x").unwrap();
|
||||
let present_str = present.to_string_lossy().to_string();
|
||||
|
||||
for (item, status, path) in [
|
||||
("downloaded", "completed", present_str.as_str()),
|
||||
("still-going", "downloading", present_str.as_str()),
|
||||
(
|
||||
"file-gone",
|
||||
"completed",
|
||||
"/nonexistent/jellytau/missing.mp4",
|
||||
),
|
||||
] {
|
||||
db_service
|
||||
.execute(Query::with_params(
|
||||
"INSERT INTO downloads (item_id, status, file_path) VALUES (?, ?, ?)",
|
||||
vec![
|
||||
crate::storage::db_service::QueryParam::String(item.to_string()),
|
||||
crate::storage::db_service::QueryParam::String(status.to_string()),
|
||||
crate::storage::db_service::QueryParam::String(path.to_string()),
|
||||
],
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
resolve_local_media_path(&db_service, "downloaded")
|
||||
.await
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some(present_str.as_str()),
|
||||
"a completed download with its file present must resolve"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
resolve_local_media_path(&db_service, "still-going")
|
||||
.await
|
||||
.unwrap(),
|
||||
None,
|
||||
"an in-progress download is not playable from disk"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
resolve_local_media_path(&db_service, "file-gone")
|
||||
.await
|
||||
.unwrap(),
|
||||
None,
|
||||
"a row whose file has gone must fall back to streaming, not hand over a dead path"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
resolve_local_media_path(&db_service, "never-heard-of-it")
|
||||
.await
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_file(&present);
|
||||
}
|
||||
|
||||
/// Queue items enqueued as Remote must flip to Local once a completed
|
||||
/// download exists on disk — this is what makes preloaded tracks (and
|
||||
/// offline playback after a connection drop) actually use the cache.
|
||||
|
||||
@@ -142,7 +142,7 @@ pub async fn player_play_next_episode(
|
||||
/// - Frontend when audio track ends via backend event - no itemId/repositoryHandle needed
|
||||
/// - Android JNI callback also triggers this logic directly
|
||||
///
|
||||
/// TRACES: UR-023, UR-026, UR-040 | DR-047, DR-052
|
||||
/// TRACES: UR-023, UR-026, UR-040 | DR-047, DR-052, DR-129
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn player_on_playback_ended(
|
||||
@@ -257,6 +257,23 @@ pub async fn player_on_playback_ended(
|
||||
.await;
|
||||
}
|
||||
}
|
||||
AutoplayDecision::ResumeStream { position } => {
|
||||
// The stream was cut short by the network, not by the media ending.
|
||||
// Re-open it where it died — no queue clearing, no PlaybackEnded, and
|
||||
// above all no leaving the player parked in ExoPlayer's STATE_ENDED,
|
||||
// where the next play intent restarts the item from 0:00.
|
||||
log::info!(
|
||||
"[Autoplay] Decision: Resume truncated stream at {:.1}s",
|
||||
position
|
||||
);
|
||||
let controller = controller_arc.lock().await;
|
||||
if let Err(e) = controller.resume_stream_at(position).await {
|
||||
log::error!("[Autoplay] Failed to resume truncated stream: {}", e);
|
||||
if let Some(emitter) = controller.event_emitter() {
|
||||
emitter.emit(PlayerStatusEvent::PlaybackEnded);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -41,6 +41,19 @@ impl RepositoryManager {
|
||||
repos.get(handle).cloned()
|
||||
}
|
||||
|
||||
/// Handles of every live repository.
|
||||
///
|
||||
/// The background catalog indexer (DR-109) runs outside any command, so it
|
||||
/// has no handle passed in and needs to discover one. In practice there is a
|
||||
/// single signed-in repository; returning all of them avoids inventing an
|
||||
/// "active" concept the rest of the code does not have.
|
||||
///
|
||||
/// TRACES: UR-065 | DR-109
|
||||
pub fn handles(&self) -> Vec<String> {
|
||||
let repos = self.repositories.lock_safe();
|
||||
repos.keys().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn destroy(&self, handle: &str) {
|
||||
let mut repos = self.repositories.lock_safe();
|
||||
repos.remove(handle);
|
||||
@@ -780,6 +793,108 @@ pub async fn repository_mark_favorite(
|
||||
.map_err(|e| format!("{:?}", e))
|
||||
}
|
||||
|
||||
/// Tauri event announcing that favourite state changed behind the UI's back —
|
||||
/// either because the server disagreed with the cache on a background refresh,
|
||||
/// or because pending offline toggles were pushed on reconnect.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120
|
||||
pub const FAVORITES_CHANGED_EVENT: &str = "favorites-changed";
|
||||
|
||||
/// Payload for [`FAVORITES_CHANGED_EVENT`] — the ids whose favourite state
|
||||
/// actually flipped, so the frontend refreshes those rather than everything.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-107
|
||||
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FavoritesChangedEvent {
|
||||
pub item_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// Ids whose favourite state differs between what we showed and what the server
|
||||
/// has — favourited elsewhere since the cache was written, or un-favourited
|
||||
/// elsewhere.
|
||||
///
|
||||
/// Pulled out of the command so the "emit nothing when nothing changed" rule is
|
||||
/// testable: an unchanged set must leave a quiet page quiet rather than
|
||||
/// triggering a refetch on every visit.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-107
|
||||
fn changed_favorite_ids(
|
||||
cached: &std::collections::HashSet<String>,
|
||||
server: &std::collections::HashSet<String>,
|
||||
) -> Vec<String> {
|
||||
let mut changed: Vec<String> = server.symmetric_difference(cached).cloned().collect();
|
||||
// Deterministic order so the event payload does not depend on hash seeding.
|
||||
changed.sort();
|
||||
changed
|
||||
}
|
||||
|
||||
/// Everything the viewer has favourited, across libraries, narrowed by scope.
|
||||
///
|
||||
/// Two-phase like `repository_search`: the local answer returns immediately and
|
||||
/// a background server pass emits `favorites-changed` when the server's set
|
||||
/// differs. Without the second phase a favourite marked in another client shows
|
||||
/// up only on the *second* visit to the page, since the cache-first read hands
|
||||
/// back local rows and the refresh is invisible to the frontend.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-115, DR-120, JA-033 | UT-107
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_get_favorites(
|
||||
app: AppHandle,
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
handle: String,
|
||||
scope: SearchScope,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, String> {
|
||||
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
|
||||
|
||||
let cache_result = repo
|
||||
.get_favorites_cache_only(scope, options.clone())
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
debug!("[Favorites] Cache miss/timeout: {:?}", e);
|
||||
SearchResult {
|
||||
items: Vec::new(),
|
||||
total_record_count: 0,
|
||||
}
|
||||
});
|
||||
|
||||
// With "Show all server media" off the local answer is authoritative
|
||||
// (DR-080) — don't go behind the user's back to the server.
|
||||
if !crate::repository::offline::include_catalog_browse() {
|
||||
return Ok(cache_result);
|
||||
}
|
||||
|
||||
let repo_bg = repo.clone();
|
||||
let cached_ids: std::collections::HashSet<String> =
|
||||
cache_result.items.iter().map(|i| i.id.clone()).collect();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match repo_bg.get_favorites_server_only(scope, options).await {
|
||||
Ok(server_result) => {
|
||||
let server_ids: std::collections::HashSet<String> =
|
||||
server_result.items.iter().map(|i| i.id.clone()).collect();
|
||||
let changed = changed_favorite_ids(&cached_ids, &server_ids);
|
||||
|
||||
if !changed.is_empty() {
|
||||
let event = FavoritesChangedEvent { item_ids: changed };
|
||||
if let Err(e) = app.emit(FAVORITES_CHANGED_EVENT, &event) {
|
||||
error!("[Favorites] Failed to emit change event: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"[Favorites] Server refresh failed, keeping cached favourites: {:?}",
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(cache_result)
|
||||
}
|
||||
|
||||
/// Unmark an item as favorite
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -853,6 +968,44 @@ mod tests {
|
||||
assert!(manager.get("any-handle").is_none());
|
||||
}
|
||||
|
||||
fn ids(values: &[&str]) -> std::collections::HashSet<String> {
|
||||
values.iter().map(|v| v.to_string()).collect()
|
||||
}
|
||||
|
||||
/// UT-107 — the background refresh reports only what actually changed.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-107
|
||||
#[test]
|
||||
fn test_changed_favorite_ids_reports_both_directions() {
|
||||
// Favourited in another client since we cached.
|
||||
assert_eq!(
|
||||
changed_favorite_ids(&ids(&["a"]), &ids(&["a", "b"])),
|
||||
vec!["b".to_string()]
|
||||
);
|
||||
|
||||
// Un-favourited in another client.
|
||||
assert_eq!(
|
||||
changed_favorite_ids(&ids(&["a", "b"]), &ids(&["a"])),
|
||||
vec!["b".to_string()]
|
||||
);
|
||||
|
||||
// Both at once, in a stable order.
|
||||
assert_eq!(
|
||||
changed_favorite_ids(&ids(&["a", "b"]), &ids(&["b", "c"])),
|
||||
vec!["a".to_string(), "c".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
/// An unchanged set emits nothing — otherwise every visit to the page would
|
||||
/// fire an event and trigger a pointless refetch.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120 | UT-107
|
||||
#[test]
|
||||
fn test_changed_favorite_ids_is_empty_when_nothing_moved() {
|
||||
assert!(changed_favorite_ids(&ids(&["a", "b"]), &ids(&["b", "a"])).is_empty());
|
||||
assert!(changed_favorite_ids(&ids(&[]), &ids(&[])).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_repository_manager_wrapper_structure() {
|
||||
let manager = RepositoryManager::new();
|
||||
|
||||
@@ -47,10 +47,25 @@ pub async fn storage_save_person(
|
||||
};
|
||||
|
||||
let query = Query::with_params(
|
||||
"INSERT OR REPLACE INTO people (
|
||||
// A real UPSERT, not INSERT OR REPLACE — `people` is now backed by the
|
||||
// `people_fts` index (migration 022), and REPLACE would orphan an index
|
||||
// entry on every re-cache: it fires no AFTER DELETE trigger without
|
||||
// `recursive_triggers`, and reassigns the rowid that `content_rowid`
|
||||
// refers to. Same defect as DR-110 fixed for `items`.
|
||||
//
|
||||
// TRACES: UR-065 | DR-110, DR-111
|
||||
"INSERT INTO people (
|
||||
id, server_id, name, overview, primary_image_tag,
|
||||
premiere_date, end_date, synced_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
server_id = excluded.server_id,
|
||||
name = excluded.name,
|
||||
overview = excluded.overview,
|
||||
primary_image_tag = excluded.primary_image_tag,
|
||||
premiere_date = excluded.premiere_date,
|
||||
end_date = excluded.end_date,
|
||||
synced_at = CURRENT_TIMESTAMP",
|
||||
vec![
|
||||
QueryParam::String(person.id),
|
||||
QueryParam::String(person.server_id),
|
||||
|
||||
@@ -26,6 +26,12 @@ pub struct CacheConfig {
|
||||
pub storage_limit: u64,
|
||||
/// Only cache on WiFi
|
||||
pub wifi_only: bool,
|
||||
/// How long a temporary (`download_source = 'auto'`) download lives before
|
||||
/// it is reclaimed, in hours. 0 disables expiry, leaving space pressure as
|
||||
/// the only reclaim trigger.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-127
|
||||
pub temporary_ttl_hours: u64,
|
||||
}
|
||||
|
||||
impl Default for CacheConfig {
|
||||
@@ -37,6 +43,10 @@ impl Default for CacheConfig {
|
||||
album_affinity_threshold: 3,
|
||||
storage_limit: 10 * 1024 * 1024 * 1024, // 10GB
|
||||
wifi_only: false, // Allow preloading on any connection by default
|
||||
// A week: long enough that re-watching over a weekend still hits
|
||||
// disk, short enough that a one-off play does not hold space
|
||||
// indefinitely.
|
||||
temporary_ttl_hours: 24 * 7,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -183,7 +193,92 @@ impl SmartCache {
|
||||
current_size + new_size <= storage_limit
|
||||
}
|
||||
|
||||
/// Evict least recently used items to make space (async version)
|
||||
/// Reclaim temporary downloads whose life limit has passed.
|
||||
///
|
||||
/// The time-based half of the temporary tier (DR-127); [`evict_lru_async`]
|
||||
/// is the space-pressure half. A row is reclaimed by whichever fires first.
|
||||
///
|
||||
/// Scoped to `download_source = 'auto'` for the same reason eviction is: a
|
||||
/// `'user'` row is someone's own download and has no expiry. `COALESCE`
|
||||
/// guards rows predating migration 012, whose source is NULL and whose
|
||||
/// provenance must therefore be treated as the user's.
|
||||
///
|
||||
/// Expiry is normally *derived* — `completed_at` plus the configured TTL —
|
||||
/// rather than stamped at completion. That means a TTL change applies to
|
||||
/// entries already on disk instead of only to future ones, and entries
|
||||
/// predating the column expire without a backfill. `expires_at` is honoured
|
||||
/// as a per-row override when something sets it.
|
||||
///
|
||||
/// `now` is passed in rather than read from the clock so the policy is
|
||||
/// testable without sleeping. Both sides go through SQLite's `datetime()`
|
||||
/// because `completed_at` is written as `CURRENT_TIMESTAMP`
|
||||
/// (`YYYY-MM-DD HH:MM:SS`) while callers pass RFC-3339 (`…T…+00:00`) — a raw
|
||||
/// string comparison between the two formats is wrong, since `' ' < 'T'`.
|
||||
///
|
||||
/// Returns the number of entries reclaimed.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-127 | UT-120
|
||||
pub async fn reclaim_expired_async<S: DatabaseService>(
|
||||
&self,
|
||||
db_service: &Arc<S>,
|
||||
user_id: &str,
|
||||
now: &str,
|
||||
) -> Result<usize, String> {
|
||||
let ttl_hours = {
|
||||
let config = self.config.lock().map_err(|e| e.to_string())?;
|
||||
config.temporary_ttl_hours
|
||||
};
|
||||
// 0 disables time-based reclaim; space pressure remains the only trigger.
|
||||
if ttl_hours == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let expired: Vec<(i64, String)> = db_service
|
||||
.query_many(
|
||||
Query::with_params(
|
||||
"SELECT id, file_path FROM downloads
|
||||
WHERE user_id = ?
|
||||
AND COALESCE(download_source, 'user') = 'auto'
|
||||
AND status = 'completed'
|
||||
AND datetime(
|
||||
COALESCE(expires_at, datetime(completed_at, '+' || ? || ' hours'))
|
||||
) < datetime(?)",
|
||||
vec![
|
||||
QueryParam::String(user_id.to_string()),
|
||||
QueryParam::String(ttl_hours.to_string()),
|
||||
QueryParam::String(now.to_string()),
|
||||
],
|
||||
),
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut reclaimed = 0usize;
|
||||
for (id, file_path) in expired {
|
||||
// Best-effort on the file: a missing one still needs its row gone,
|
||||
// or the sweep retries it forever.
|
||||
let _ = std::fs::remove_file(&file_path);
|
||||
db_service
|
||||
.execute(Query::with_params(
|
||||
"DELETE FROM downloads WHERE id = ?",
|
||||
vec![QueryParam::Int64(id)],
|
||||
))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
reclaimed += 1;
|
||||
}
|
||||
|
||||
if reclaimed > 0 {
|
||||
info!("[SmartCache] Reclaimed {} expired entries", reclaimed);
|
||||
}
|
||||
Ok(reclaimed)
|
||||
}
|
||||
|
||||
/// Evict least recently used items to make space (async version).
|
||||
///
|
||||
/// The space-pressure half of the temporary tier; [`reclaim_expired_async`]
|
||||
/// is the time-based half.
|
||||
pub async fn evict_lru_async<S: DatabaseService>(
|
||||
&self,
|
||||
db_service: &Arc<S>,
|
||||
@@ -207,10 +302,26 @@ impl SmartCache {
|
||||
let to_free = (current_size + space_needed) - limit;
|
||||
let mut freed: u64 = 0;
|
||||
|
||||
// Get downloads ordered by last access (oldest first)
|
||||
// Only the *temporary* tier is evictable. `download_source = 'auto'` is
|
||||
// precache — the cache put it there, the cache may reclaim it. A 'user'
|
||||
// row is a download someone explicitly asked for; deleting it to make
|
||||
// room for a predictive fetch is data loss, and because the old query
|
||||
// ordered purely by `completed_at ASC` it took the oldest — typically
|
||||
// exactly the film saved for a flight.
|
||||
//
|
||||
// COALESCE, not `= 'auto'` alone: migration 012 added the column with a
|
||||
// 'user' default, but rows predating it can be NULL, and an unknown
|
||||
// provenance must be treated as the user's, never as disposable.
|
||||
//
|
||||
// Freeing less than requested is the correct outcome when only user
|
||||
// downloads remain — the caller surfaces "unable to free enough space"
|
||||
// rather than silently deleting them.
|
||||
//
|
||||
// TRACES: UR-071 | DR-126 | UT-108
|
||||
let query = Query::with_params(
|
||||
"SELECT id, file_size, file_path FROM downloads
|
||||
WHERE user_id = ? AND status = 'completed'
|
||||
AND COALESCE(download_source, 'user') = 'auto'
|
||||
ORDER BY completed_at ASC",
|
||||
vec![QueryParam::String(user_id.to_string())],
|
||||
);
|
||||
@@ -304,6 +415,205 @@ mod tests {
|
||||
assert!(cache.should_precache_queue());
|
||||
}
|
||||
|
||||
/// Expiry reclaims only temporary entries that are actually past their life
|
||||
/// limit — never a user's download (which has no expiry), and never a
|
||||
/// temporary entry still within its life.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-127 | UT-120
|
||||
#[tokio::test]
|
||||
async fn test_reclaim_expired_only_takes_expired_temporary_entries() {
|
||||
use crate::storage::db_service::{DatabaseService, RusqliteService};
|
||||
use rusqlite::Connection;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute(
|
||||
"CREATE TABLE downloads (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id TEXT,
|
||||
status TEXT,
|
||||
file_size INTEGER,
|
||||
file_path TEXT,
|
||||
completed_at TEXT,
|
||||
download_source TEXT DEFAULT 'user',
|
||||
expires_at TEXT
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// `completed_at` is in SQLite's CURRENT_TIMESTAMP format (space, not
|
||||
// 'T'), deliberately: the query has to compare it against an RFC-3339
|
||||
// "now" and must not do so as raw strings.
|
||||
for (path, source, completed, expires) in [
|
||||
// Completed long ago, no override => derived expiry has passed.
|
||||
("/tmp/jt-expired.mp4", "auto", "2026-01-01 00:00:00", None),
|
||||
// Completed yesterday => still inside the 7-day default TTL.
|
||||
("/tmp/jt-fresh.mp4", "auto", "2026-05-31 00:00:00", None),
|
||||
// Old, but an explicit override keeps it alive.
|
||||
(
|
||||
"/tmp/jt-override.mp4",
|
||||
"auto",
|
||||
"2026-01-01 00:00:00",
|
||||
Some("2026-12-01T00:00:00+00:00"),
|
||||
),
|
||||
// A user download must never carry an expiry, but assert the sweep
|
||||
// ignores it even if one were somehow set.
|
||||
(
|
||||
"/tmp/jt-user.mp4",
|
||||
"user",
|
||||
"2026-01-01 00:00:00",
|
||||
Some("2026-01-01T00:00:00+00:00"),
|
||||
),
|
||||
(
|
||||
"/tmp/jt-user-noexp.mp4",
|
||||
"user",
|
||||
"2026-01-01 00:00:00",
|
||||
None,
|
||||
),
|
||||
] {
|
||||
conn.execute(
|
||||
"INSERT INTO downloads (user_id, status, file_size, file_path, download_source, completed_at, expires_at)
|
||||
VALUES ('user1', 'completed', 10, ?1, ?2, ?3, ?4)",
|
||||
rusqlite::params![path, source, completed, expires],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let conn_arc = Arc::new(Mutex::new(conn));
|
||||
let db_service = Arc::new(RusqliteService::new(conn_arc.clone()));
|
||||
let cache = SmartCache::new(CacheConfig::default());
|
||||
|
||||
let reclaimed = cache
|
||||
.reclaim_expired_async(&db_service, "user1", "2026-06-01T00:00:00+00:00")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
reclaimed, 1,
|
||||
"only the expired temporary entry is reclaimed"
|
||||
);
|
||||
|
||||
let surviving: Vec<String> = {
|
||||
let guard = conn_arc.lock_safe();
|
||||
let mut stmt = guard
|
||||
.prepare("SELECT file_path FROM downloads ORDER BY id")
|
||||
.unwrap();
|
||||
let rows = stmt
|
||||
.query_map([], |row| row.get::<_, String>(0))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
rows
|
||||
};
|
||||
assert_eq!(
|
||||
surviving,
|
||||
vec![
|
||||
"/tmp/jt-fresh.mp4".to_string(),
|
||||
"/tmp/jt-override.mp4".to_string(),
|
||||
"/tmp/jt-user.mp4".to_string(),
|
||||
"/tmp/jt-user-noexp.mp4".to_string(),
|
||||
],
|
||||
"entries within their life, those with a later override, and every user download must survive"
|
||||
);
|
||||
|
||||
// TTL of 0 disables time-based reclaim entirely.
|
||||
let cache_no_ttl = SmartCache::new(CacheConfig {
|
||||
temporary_ttl_hours: 0,
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(
|
||||
cache_no_ttl
|
||||
.reclaim_expired_async(&db_service, "user1", "2027-01-01T00:00:00+00:00")
|
||||
.await
|
||||
.unwrap(),
|
||||
0,
|
||||
"a zero TTL leaves space pressure as the only reclaim trigger"
|
||||
);
|
||||
}
|
||||
|
||||
/// Eviction must only reclaim *temporary* (`download_source = 'auto'`)
|
||||
/// downloads — the precache tier. A download the user explicitly asked for
|
||||
/// is their file: it may be deleted by them, never by the cache making room
|
||||
/// for a predictive fetch.
|
||||
///
|
||||
/// Before the fix, `evict_lru_async` selected every completed row ordered by
|
||||
/// `completed_at ASC` with no source filter, so hitting the storage limit
|
||||
/// deleted the *oldest* download — typically the film someone downloaded for
|
||||
/// a flight — in favour of a newer auto-precached track.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-126 | UT-108
|
||||
#[tokio::test]
|
||||
async fn test_evict_lru_never_deletes_user_downloads() {
|
||||
use crate::storage::db_service::RusqliteService;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute(
|
||||
"CREATE TABLE downloads (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id TEXT,
|
||||
status TEXT,
|
||||
file_size INTEGER,
|
||||
file_path TEXT,
|
||||
completed_at TEXT,
|
||||
download_source TEXT DEFAULT 'user'
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// The user's own download is the OLDEST, so a purely time-ordered
|
||||
// eviction would take it first.
|
||||
conn.execute(
|
||||
"INSERT INTO downloads (user_id, status, file_size, file_path, completed_at, download_source)
|
||||
VALUES ('user1', 'completed', 600, '/tmp/jellytau-test-user.mp4', '2026-01-01', 'user')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
// A newer, auto-precached item.
|
||||
conn.execute(
|
||||
"INSERT INTO downloads (user_id, status, file_size, file_path, completed_at, download_source)
|
||||
VALUES ('user1', 'completed', 600, '/tmp/jellytau-test-auto.mp4', '2026-06-01', 'auto')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let conn_arc = Arc::new(Mutex::new(conn));
|
||||
let db_service = Arc::new(RusqliteService::new(conn_arc.clone()));
|
||||
|
||||
let cache = SmartCache::new(CacheConfig {
|
||||
storage_limit: 1000,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// 1200 bytes held against a 1000 limit: eviction must free something.
|
||||
let freed = cache
|
||||
.evict_lru_async(&db_service, "user1", 0)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(freed > 0, "eviction should have reclaimed the auto entry");
|
||||
|
||||
let surviving: Vec<String> = {
|
||||
let guard = conn_arc.lock_safe();
|
||||
let mut stmt = guard
|
||||
.prepare("SELECT download_source FROM downloads ORDER BY id")
|
||||
.unwrap();
|
||||
let rows = stmt
|
||||
.query_map([], |row| row.get::<_, String>(0))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
rows
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
surviving,
|
||||
vec!["user".to_string()],
|
||||
"the user's own download must survive; only the 'auto' entry is evictable"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_storage_limit_check() {
|
||||
use crate::storage::db_service::RusqliteService;
|
||||
|
||||
+20
-1
@@ -128,6 +128,8 @@ use commands::{
|
||||
player_get_sleep_timer,
|
||||
player_get_status,
|
||||
player_get_video_settings,
|
||||
// Preload commands
|
||||
player_local_media_path,
|
||||
player_move_in_queue,
|
||||
player_next,
|
||||
player_on_playback_ended,
|
||||
@@ -138,7 +140,6 @@ use commands::{
|
||||
player_play_next_episode,
|
||||
player_play_queue,
|
||||
player_play_tracks,
|
||||
// Preload commands
|
||||
player_preload_upcoming,
|
||||
player_previous,
|
||||
player_remove_from_queue,
|
||||
@@ -187,6 +188,7 @@ use commands::{
|
||||
repository_get_download_disk_usage,
|
||||
repository_get_downloaded_items,
|
||||
repository_get_downloaded_libraries,
|
||||
repository_get_favorites,
|
||||
repository_get_genres,
|
||||
repository_get_image_url,
|
||||
repository_get_item,
|
||||
@@ -700,6 +702,7 @@ fn specta_builder() -> Builder<tauri::Wry> {
|
||||
player_report_position,
|
||||
player_report_media_loaded,
|
||||
// Preload commands
|
||||
player_local_media_path,
|
||||
player_preload_upcoming,
|
||||
player_set_cache_config,
|
||||
player_get_cache_config,
|
||||
@@ -893,6 +896,7 @@ fn specta_builder() -> Builder<tauri::Wry> {
|
||||
repository_get_image_url,
|
||||
repository_mark_favorite,
|
||||
repository_unmark_favorite,
|
||||
repository_get_favorites,
|
||||
repository_get_person,
|
||||
repository_get_items_by_person,
|
||||
repository_get_similar_items,
|
||||
@@ -1288,6 +1292,21 @@ pub fn run() {
|
||||
let playback_reporter_wrapper = PlaybackReporterWrapper(playback_reporter.clone());
|
||||
app.manage(playback_reporter_wrapper);
|
||||
|
||||
// Keep the local search index fresh. Ownership of *when* to re-index
|
||||
// sits here rather than in the frontend: it is sync policy over
|
||||
// domain data, and a startup-only trigger left a long session
|
||||
// searching a stale catalog.
|
||||
// TRACES: UR-065 | DR-109, IR-030
|
||||
info!("[INIT] Starting background catalog indexer...");
|
||||
commands::catalog::spawn_catalog_indexer(app.handle().clone());
|
||||
|
||||
// Push favourite toggles made while the server was unreachable, on
|
||||
// every reconnect. In Rust rather than the frontend so it runs
|
||||
// whether or not the screen that made the change is still mounted.
|
||||
// TRACES: UR-069 | DR-120
|
||||
info!("[INIT] Starting favourites drain...");
|
||||
commands::favorites::spawn_favorites_drain(app.handle().clone());
|
||||
|
||||
info!("[INIT] Application setup completed successfully");
|
||||
Ok(())
|
||||
})
|
||||
|
||||
@@ -930,6 +930,25 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Ok(AutoplayDecision::ResumeStream { position }) => {
|
||||
// ExoPlayer reported ENDED because the progressive transcode's
|
||||
// connection dropped, not because the episode finished. This
|
||||
// is the arm that matters while backgrounded: it needs no
|
||||
// frontend echo, so the stream re-opens even with the webview
|
||||
// suspended — and playback never parks in STATE_ENDED, where
|
||||
// the next lockscreen/Bluetooth play restarts the item at 0:00.
|
||||
log::info!(
|
||||
"[Autoplay] Decision: Resume truncated stream at {:.1}s",
|
||||
position
|
||||
);
|
||||
let ctrl = controller.lock().await;
|
||||
if let Err(e) = ctrl.resume_stream_at(position).await {
|
||||
log::error!("[Autoplay] Failed to resume truncated stream: {}", e);
|
||||
if let Some(emitter) = EVENT_EMITTER.get() {
|
||||
emitter.emit(PlayerStatusEvent::PlaybackEnded);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("[Autoplay] Decision failed: {}", e);
|
||||
// Emit PlaybackEnded event on error
|
||||
@@ -974,11 +993,58 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
|
||||
.get_string(&message)
|
||||
.map(|s| s.into())
|
||||
.unwrap_or_else(|_| "Unknown error".to_string());
|
||||
let recoverable = recoverable != 0;
|
||||
|
||||
// A background audio-only handoff is an mp3 the device was already decoding,
|
||||
// so a recoverable failure part-way through is the network. Surfacing it as a
|
||||
// player error stops playback for good (the frontend's handler calls
|
||||
// player_stop); re-opening the stream where it died is the "buffer and
|
||||
// resume" this actually is. Everything else keeps reporting the error.
|
||||
if recoverable {
|
||||
if let Some(controller) = PLAYER_CONTROLLER.get() {
|
||||
let controller = controller.clone();
|
||||
let message_str = message_str.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let resume = controller.lock().await.recoverable_error_resume();
|
||||
let Some((position, delay_secs)) = resume else {
|
||||
if let Some(emitter) = EVENT_EMITTER.get() {
|
||||
emitter.emit(PlayerStatusEvent::Error {
|
||||
message: message_str,
|
||||
recoverable: true,
|
||||
});
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
log::warn!(
|
||||
"[ExoPlayer] Recoverable stream error ({}) — re-opening at {:.1}s in {}s",
|
||||
message_str,
|
||||
position,
|
||||
delay_secs
|
||||
);
|
||||
// Give a brief outage time to clear before asking the server for
|
||||
// the stream again; retrying instantly just burns the budget.
|
||||
tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;
|
||||
|
||||
let ctrl = controller.lock().await;
|
||||
if let Err(e) = ctrl.resume_stream_at(position).await {
|
||||
log::error!("[ExoPlayer] Failed to resume after error: {}", e);
|
||||
if let Some(emitter) = EVENT_EMITTER.get() {
|
||||
emitter.emit(PlayerStatusEvent::Error {
|
||||
message: message_str,
|
||||
recoverable: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(emitter) = EVENT_EMITTER.get() {
|
||||
emitter.emit(PlayerStatusEvent::Error {
|
||||
message: message_str,
|
||||
recoverable: recoverable != 0,
|
||||
recoverable,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,10 @@ pub enum AutoplayDecision {
|
||||
Stop,
|
||||
/// Advance to next track in queue (for audio/movies)
|
||||
AdvanceToNext,
|
||||
/// The stream ended well short of the item's runtime — the connection
|
||||
/// dropped, not the media. Re-open the same stream at `position` instead of
|
||||
/// running any end-of-item logic (UR-040).
|
||||
ResumeStream { position: f64 },
|
||||
/// Show next episode popup with countdown
|
||||
ShowNextEpisodePopup {
|
||||
current_episode: MediaItem,
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod seek;
|
||||
pub mod session;
|
||||
pub mod sleep_timer;
|
||||
pub mod state;
|
||||
pub mod stream_end;
|
||||
|
||||
#[cfg(test)]
|
||||
mod mpv_backend_test;
|
||||
@@ -54,6 +55,16 @@ pub use android::{
|
||||
set_remote_volume_handler, MediaCommandHandler, RemoteVolumeHandler,
|
||||
};
|
||||
|
||||
/// Seconds added per attempt before retrying a stream that failed with an error.
|
||||
///
|
||||
/// Attempt 1 waits this long, attempt 2 twice as long, and so on — a spread that
|
||||
/// covers roughly a quarter-minute of outage across the retry budget without
|
||||
/// leaving the user staring at a dead notification when the network is truly gone.
|
||||
/// Only *read* by the Android error callback (`#[cfg(android)]`), but compiled
|
||||
/// and unit-tested on the host, hence `allow(dead_code)` off-Android.
|
||||
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
|
||||
const RESUME_BACKOFF_STEP_SECS: u64 = 2;
|
||||
|
||||
/// Metadata for the lockscreen / media notification.
|
||||
///
|
||||
/// Used to drive the Android MediaSession from Rust in remote (cast) mode, where
|
||||
@@ -168,6 +179,15 @@ pub struct PlayerController {
|
||||
// TRACES: UR-040 | DR-052
|
||||
background_audio_base: Arc<Mutex<f64>>,
|
||||
|
||||
// Budget for re-opening a stream that ended short of the item's runtime.
|
||||
//
|
||||
// A resume re-requests the same URL, so a server that is genuinely gone would
|
||||
// otherwise end → resume → end without limit. The tracker only bounds retries
|
||||
// that make no progress; a resume that plays on refills it.
|
||||
//
|
||||
// TRACES: UR-040 | DR-129
|
||||
stream_resume: Arc<Mutex<stream_end::ResumeTracker>>,
|
||||
|
||||
// Last state reported by a webview-rendered HTML5 <video>/<audio> element.
|
||||
//
|
||||
// Webview-rendered media is played by an element the native backend cannot
|
||||
@@ -201,6 +221,7 @@ impl PlayerController {
|
||||
end_reason: Arc::new(Mutex::new(None)),
|
||||
autoplay_episode_count: Arc::new(Mutex::new(0)),
|
||||
background_audio_base: Arc::new(Mutex::new(0.0)),
|
||||
stream_resume: Arc::new(Mutex::new(stream_end::ResumeTracker::default())),
|
||||
html5_playing: Arc::new(Mutex::new(None)),
|
||||
};
|
||||
|
||||
@@ -271,6 +292,16 @@ impl PlayerController {
|
||||
self.end_reason.lock_safe().take()
|
||||
}
|
||||
|
||||
/// Read the end reason WITHOUT consuming it.
|
||||
///
|
||||
/// `take_end_reason` has an owner: on Android the JNI ended-callback consumes
|
||||
/// the `NewTrackLoaded` every load sets, and the frontend's echoed call is the
|
||||
/// one that sees `None` and decides. The truncated-stream check runs in both
|
||||
/// calls and must not disturb that hand-off, so it peeks.
|
||||
fn peek_end_reason(&self) -> Option<EndReason> {
|
||||
*self.end_reason.lock_safe()
|
||||
}
|
||||
|
||||
/// Record that playback is being stopped by an expiring sleep timer.
|
||||
///
|
||||
/// Stopping the backend makes it fire its ended callback (ExoPlayer does on
|
||||
@@ -1034,6 +1065,15 @@ impl PlayerController {
|
||||
/// Only triggers autoplay if the track finished naturally (EndReason::Finished or None).
|
||||
/// If EndReason is NewTrackLoaded, UserStop, UserSkip, or Error, returns Stop without autoplay.
|
||||
pub async fn on_playback_ended(&self) -> Result<AutoplayDecision, String> {
|
||||
// A truncated stream is not an end at all, so this is decided BEFORE the
|
||||
// end-reason gate below — which returns early for the `NewTrackLoaded`
|
||||
// that every load sets, and would therefore swallow the whole question on
|
||||
// Android's JNI callback: the one call guaranteed to run while the app is
|
||||
// backgrounded and the webview cannot echo anything back.
|
||||
if let Some(position) = self.truncated_stream_resume_position() {
|
||||
return Ok(AutoplayDecision::ResumeStream { position });
|
||||
}
|
||||
|
||||
// Check why playback ended
|
||||
let end_reason = self.take_end_reason();
|
||||
|
||||
@@ -1248,6 +1288,194 @@ impl PlayerController {
|
||||
self.start_autoplay_countdown(next_episode, countdown_seconds);
|
||||
}
|
||||
|
||||
/// A video item played through the native *audio* path — i.e. the background
|
||||
/// audio-only handoff, the only place a length-less progressive transcode is
|
||||
/// used. Jellyfin's item-type taxonomy stays in Rust (CLAUDE.md).
|
||||
fn is_audio_only_video(item: &MediaItem) -> bool {
|
||||
item.media_type == MediaType::Audio
|
||||
&& matches!(item.item_type.as_deref(), Some("Episode") | Some("Movie"))
|
||||
}
|
||||
|
||||
/// Claim a resume attempt for the current stream, returning the absolute
|
||||
/// position to re-open at and the 1-based attempt number. `None` when the
|
||||
/// current item cannot meaningfully be re-requested, or when retrying at this
|
||||
/// position has stopped helping.
|
||||
///
|
||||
/// Only `Remote` sources qualify. A downloaded file cannot fail because of
|
||||
/// the network, so re-opening one would paper over a real read error; a
|
||||
/// `DirectUrl` is a plugin's endpoint with no Jellyfin item behind it.
|
||||
///
|
||||
/// The player's position is relative to the stream's own zero (the handoff
|
||||
/// URL's `StartTimeTicks`), so the base is added back to get an absolute one.
|
||||
/// It is zero for everything else, where positions are already absolute.
|
||||
///
|
||||
/// TRACES: UR-040, UR-004 | DR-129 | UT-117
|
||||
fn claim_stream_resume(&self) -> Option<(f64, u32)> {
|
||||
let current = {
|
||||
let queue = self.queue.lock_safe();
|
||||
queue.current().cloned()
|
||||
}?;
|
||||
if !matches!(current.source, MediaSource::Remote { .. }) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let base = *self.background_audio_base.lock_safe();
|
||||
let absolute = (base + self.position()).max(0.0);
|
||||
|
||||
match self.stream_resume.lock_safe().allow_attempt(absolute) {
|
||||
Some(attempt) => Some((absolute, attempt)),
|
||||
None => {
|
||||
warn!(
|
||||
"[PlayerController] Stream for {} keeps failing at {:.1}s — giving up on resuming",
|
||||
current.id, absolute
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The absolute position to re-open the current stream at, when the reported
|
||||
/// end was really a dropped connection — `None` when the end looks genuine,
|
||||
/// when this is not an audio-only handoff, or when retrying has stopped
|
||||
/// helping.
|
||||
///
|
||||
/// TRACES: UR-040 | DR-129 | UT-117
|
||||
fn truncated_stream_resume_position(&self) -> Option<f64> {
|
||||
// An explicit user intent already explains the end; never resume over it.
|
||||
if matches!(
|
||||
self.peek_end_reason(),
|
||||
Some(EndReason::UserStop) | Some(EndReason::UserSkip) | Some(EndReason::Error)
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// One lock at a time — `position()` reaches into the backend, and nesting
|
||||
// that inside the queue lock would invent a lock order nothing else here
|
||||
// takes.
|
||||
let item_duration = {
|
||||
let queue = self.queue.lock_safe();
|
||||
let current = queue.current()?;
|
||||
if !Self::is_audio_only_video(current) {
|
||||
return None;
|
||||
}
|
||||
current.duration
|
||||
};
|
||||
let base = *self.background_audio_base.lock_safe();
|
||||
let absolute = (base + self.position()).max(0.0);
|
||||
|
||||
// Only spend a resume attempt once the runtime says this really was cut
|
||||
// short — a genuine end must stay a genuine end.
|
||||
if !stream_end::is_truncated_end(
|
||||
absolute,
|
||||
item_duration,
|
||||
stream_end::TRUNCATED_STREAM_TOLERANCE_SECS,
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.claim_stream_resume().map(|(position, _)| position)
|
||||
}
|
||||
|
||||
/// Where to re-open the current stream after a *recoverable* playback error,
|
||||
/// plus how many seconds to wait first.
|
||||
///
|
||||
/// The media was decoding fine a moment ago, so a mid-playback failure on a
|
||||
/// server stream is the network — and stopping the player (the previous
|
||||
/// behaviour, via the frontend's error handler) turns a hiccup into "playback
|
||||
/// just died". Applies to every streamed item, not only the audio-only
|
||||
/// handoff: music and video reach here instead of the truncation path because
|
||||
/// their streams declare a length, so a cut connection surfaces as an error
|
||||
/// rather than a phantom end.
|
||||
///
|
||||
/// The wait grows with the attempt number so a short outage has time to
|
||||
/// clear, and the shared budget stops the retries when it doesn't.
|
||||
///
|
||||
/// Only *called* from the Android error callback (`#[cfg(android)]`), but
|
||||
/// compiled and unit-tested on the host, hence `allow(dead_code)` off-Android.
|
||||
///
|
||||
/// TRACES: UR-040, UR-004 | DR-129 | UT-117
|
||||
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
|
||||
pub fn recoverable_error_resume(&self) -> Option<(f64, u64)> {
|
||||
self.claim_stream_resume()
|
||||
.map(|(position, attempt)| (position, attempt as u64 * RESUME_BACKOFF_STEP_SECS))
|
||||
}
|
||||
|
||||
/// Re-open the current stream at `position` after the network cut it short.
|
||||
///
|
||||
/// Single place every dispatcher agrees on, for the same reason
|
||||
/// `auto_advance_to_next_episode` is: the Android JNI callbacks and the
|
||||
/// frontend-invoked command must not disagree about what a failed stream
|
||||
/// means. None of them emits `PlaybackEnded` for this, so nothing downstream
|
||||
/// clears the queue or tears the session down — from the outside this is a
|
||||
/// buffering hiccup, which is what it actually was.
|
||||
///
|
||||
/// Reloads the item **in place** rather than through `play_item`, which
|
||||
/// replaces the queue with a single item: recovering a track that way would
|
||||
/// throw away the rest of the album, turning a network blip into lost state.
|
||||
///
|
||||
/// Two shapes of stream, two ways back to `position`:
|
||||
///
|
||||
/// - The audio-only handoff's `/Audio/{id}/universal` transcode is chunked
|
||||
/// with no length, so it cannot be seeked. Its URL is rewritten to start at
|
||||
/// the position instead — edited, not rebuilt from the repository, since it
|
||||
/// already carries the user's audio track and media source and recovering
|
||||
/// from a network failure must not itself need a network round-trip.
|
||||
/// - Everything else (a static file with byte ranges, an HLS playlist)
|
||||
/// declares its whole timeline, so re-preparing the URL it already has and
|
||||
/// seeking lands in the right place — and leaves any transcode session
|
||||
/// behind it alone.
|
||||
///
|
||||
/// TRACES: UR-040, UR-004 | DR-129 | UT-117
|
||||
pub async fn resume_stream_at(&self, position: f64) -> Result<(), String> {
|
||||
let current = {
|
||||
let queue = self.queue.lock_safe();
|
||||
queue.current().cloned()
|
||||
}
|
||||
.ok_or_else(|| "No current item to resume".to_string())?;
|
||||
|
||||
let MediaSource::Remote { stream_url, .. } = ¤t.source else {
|
||||
return Err(format!(
|
||||
"Cannot resume a non-remote source for {}",
|
||||
current.id
|
||||
));
|
||||
};
|
||||
|
||||
info!(
|
||||
"[PlayerController] Stream for {} failed — re-opening at {:.1}s",
|
||||
current.id, position
|
||||
);
|
||||
|
||||
if !Self::is_audio_only_video(¤t) {
|
||||
self.load_and_play(¤t).map_err(|e| e.to_string())?;
|
||||
if position > 0.5 {
|
||||
self.seek(position).map_err(|e| e.to_string())?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let restarted_url = stream_end::with_start_time(stream_url, position);
|
||||
{
|
||||
let queue_arc = self.queue.clone();
|
||||
let mut queue = queue_arc.lock_safe();
|
||||
if !queue.update_current_stream_url(restarted_url) {
|
||||
return Err(format!("Failed to update stream URL for {}", current.id));
|
||||
}
|
||||
}
|
||||
let resumed = {
|
||||
let queue = self.queue.lock_safe();
|
||||
queue.current().cloned()
|
||||
}
|
||||
.ok_or_else(|| "Current item vanished mid-resume".to_string())?;
|
||||
|
||||
// The re-opened stream's timeline starts at `position` (StartTimeTicks),
|
||||
// so that is its zero: the exit-to-foreground maths and the lockscreen
|
||||
// scrubber both read absolute positions off this base.
|
||||
self.set_background_audio_base(position);
|
||||
let _ = set_lockscreen_position_offset(position.max(0.0));
|
||||
|
||||
self.load_and_play(&resumed).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Advance to the next episode while playing audio-only in the background.
|
||||
///
|
||||
/// The normal autoplay-next path navigates the frontend to `/player/<id>`,
|
||||
@@ -1322,6 +1550,9 @@ impl PlayerController {
|
||||
// back to the foreground) and the lockscreen scrubber's matching shift.
|
||||
self.set_background_audio_base(0.0);
|
||||
let _ = set_lockscreen_position_offset(0.0);
|
||||
// Different stream entirely: whatever was stuck about the last one is not
|
||||
// this one's problem.
|
||||
self.stream_resume.lock_safe().reset();
|
||||
|
||||
self.play_item(media_item).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -2862,6 +3093,13 @@ mod tests {
|
||||
async fn unmark_favorite(&self, _: &str) -> Result<(), repo_types::RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn get_favorites(
|
||||
&self,
|
||||
_: repo_types::SearchScope,
|
||||
_: Option<repo_types::GetItemsOptions>,
|
||||
) -> Result<repo_types::SearchResult, repo_types::RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn clear_watch_history(&self, _: &str) -> Result<(), repo_types::RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -3018,6 +3256,7 @@ mod tests {
|
||||
item_type: Some("Episode".to_string()),
|
||||
media_type: MediaType::Audio, // audio-only handoff, not Video
|
||||
series_id: Some("series1".to_string()),
|
||||
duration: Some(180.0),
|
||||
source: MediaSource::Remote {
|
||||
stream_url: "http://example.com/ep2-audio.m3u8".to_string(),
|
||||
jellyfin_item_id: "ep2".to_string(),
|
||||
@@ -3026,6 +3265,8 @@ mod tests {
|
||||
};
|
||||
controller.play_queue(vec![episode], 0).unwrap();
|
||||
|
||||
// Played through to the end — a natural finish, not a stream cut short.
|
||||
controller.seek(180.0).unwrap();
|
||||
// Clear the NewTrackLoaded reason to simulate natural track end.
|
||||
controller.take_end_reason();
|
||||
|
||||
@@ -3158,6 +3399,328 @@ mod tests {
|
||||
assert!(controller.current_is_audio_episode());
|
||||
}
|
||||
|
||||
/// Build the audio-only episode the background handoff loads: a video item
|
||||
/// played through the native audio path, with a known runtime and a stream
|
||||
/// URL carrying the handoff position.
|
||||
fn audio_only_episode(runtime_seconds: f64) -> MediaItem {
|
||||
MediaItem {
|
||||
id: "ep2".to_string(),
|
||||
item_type: Some("Episode".to_string()),
|
||||
media_type: MediaType::Audio,
|
||||
series_id: Some("series1".to_string()),
|
||||
duration: Some(runtime_seconds),
|
||||
source: MediaSource::Remote {
|
||||
stream_url:
|
||||
"http://s/Audio/ep2/universal?api_key=k&AudioStreamIndex=2&StartTimeTicks=0"
|
||||
.to_string(),
|
||||
jellyfin_item_id: "ep2".to_string(),
|
||||
},
|
||||
..create_test_items(1).remove(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A flaky connection truncates the progressive mp3 transcode that carries
|
||||
/// background audio-only playback. ExoPlayer sees end-of-input on a stream
|
||||
/// with no reliable length, so it reports STATE_ENDED ten minutes into a
|
||||
/// twenty-five minute episode — indistinguishable, to the player, from the
|
||||
/// real end.
|
||||
///
|
||||
/// Treating that as "the episode finished" is what the user experiences as
|
||||
/// the episode randomly restarting: playback parks in STATE_ENDED and the
|
||||
/// next play intent (lockscreen, notification, Bluetooth reconnect) seeks an
|
||||
/// ended player to position 0 before playing. The runtime we already know
|
||||
/// says the stream died early, so the decision must be to resume it.
|
||||
#[tokio::test]
|
||||
async fn test_truncated_background_audio_stream_resumes_instead_of_ending() {
|
||||
let controller = PlayerController::default();
|
||||
controller.set_repository(Arc::new(MockEpisodeRepo::season(3)));
|
||||
|
||||
controller
|
||||
.play_queue(vec![audio_only_episode(1500.0)], 0)
|
||||
.unwrap();
|
||||
// The connection dropped 10 minutes into a 25-minute episode.
|
||||
controller.seek(600.0).unwrap();
|
||||
controller.take_end_reason();
|
||||
|
||||
let decision = controller.on_playback_ended().await.unwrap();
|
||||
|
||||
match decision {
|
||||
AutoplayDecision::ResumeStream { position } => {
|
||||
assert_eq!(position, 600.0, "must resume where the stream died");
|
||||
}
|
||||
other => panic!(
|
||||
"a stream that ended 15 minutes short of the runtime must resume, \
|
||||
not run end-of-episode logic; got {:?}",
|
||||
other
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The handoff stream's timeline starts at the handoff position, so the
|
||||
/// player reports a *relative* position. The runtime it is compared against
|
||||
/// is absolute — the base has to be added back, or every handoff looks like a
|
||||
/// truncation.
|
||||
#[tokio::test]
|
||||
async fn test_truncated_check_uses_the_absolute_position() {
|
||||
let controller = PlayerController::default();
|
||||
controller.set_repository(Arc::new(MockEpisodeRepo::season(3)));
|
||||
|
||||
controller
|
||||
.play_queue(vec![audio_only_episode(1500.0)], 0)
|
||||
.unwrap();
|
||||
// Handed off at 24:00; the stream then played its last 56 seconds out.
|
||||
controller.set_background_audio_base(1440.0);
|
||||
controller.seek(56.0).unwrap();
|
||||
controller.take_end_reason();
|
||||
|
||||
let decision = controller.on_playback_ended().await.unwrap();
|
||||
|
||||
assert!(
|
||||
matches!(decision, AutoplayDecision::ShowNextEpisodePopup { .. }),
|
||||
"24:56 of a 25:00 episode is the real end, not a truncation; got {:?}",
|
||||
decision
|
||||
);
|
||||
}
|
||||
|
||||
/// The resume re-opens the same URL, so a server that is actually gone would
|
||||
/// otherwise end → resume → end forever. After the budget runs out the
|
||||
/// decision falls back to normal end-of-item handling.
|
||||
#[tokio::test]
|
||||
async fn test_repeated_truncation_at_the_same_position_gives_up() {
|
||||
let controller = PlayerController::default();
|
||||
controller.set_repository(Arc::new(MockEpisodeRepo::season(3)));
|
||||
|
||||
controller
|
||||
.play_queue(vec![audio_only_episode(1500.0)], 0)
|
||||
.unwrap();
|
||||
controller.seek(600.0).unwrap();
|
||||
|
||||
for attempt in 1..=stream_end::MAX_STALLED_RESUME_ATTEMPTS {
|
||||
controller.take_end_reason();
|
||||
let decision = controller.on_playback_ended().await.unwrap();
|
||||
assert!(
|
||||
matches!(decision, AutoplayDecision::ResumeStream { .. }),
|
||||
"attempt {} should still resume, got {:?}",
|
||||
attempt,
|
||||
decision
|
||||
);
|
||||
}
|
||||
|
||||
controller.take_end_reason();
|
||||
let decision = controller.on_playback_ended().await.unwrap();
|
||||
assert!(
|
||||
!matches!(decision, AutoplayDecision::ResumeStream { .. }),
|
||||
"a stream stuck at the same position must stop retrying, got {:?}",
|
||||
decision
|
||||
);
|
||||
}
|
||||
|
||||
/// Ordinary music is not covered: its streams are not the length-less
|
||||
/// progressive transcode this guards, and a short track legitimately ends
|
||||
/// well before a stale duration would suggest.
|
||||
#[tokio::test]
|
||||
async fn test_truncation_check_does_not_touch_plain_audio_tracks() {
|
||||
let controller = PlayerController::default();
|
||||
|
||||
let mut items = create_test_items(2);
|
||||
items[0].duration = Some(1500.0);
|
||||
controller.play_queue(items, 0).unwrap();
|
||||
controller.seek(60.0).unwrap();
|
||||
controller.take_end_reason();
|
||||
|
||||
let decision = controller.on_playback_ended().await.unwrap();
|
||||
assert!(
|
||||
matches!(decision, AutoplayDecision::AdvanceToNext),
|
||||
"plain queue audio must keep advancing, got {:?}",
|
||||
decision
|
||||
);
|
||||
}
|
||||
|
||||
/// Music and video stream from URLs that declare their own length (a static
|
||||
/// file with byte ranges, an HLS playlist), so a truncation reaches the
|
||||
/// player as an *error* rather than a phantom end. It is the same network
|
||||
/// failure, and the same recovery applies — the previous behaviour turned it
|
||||
/// into `playerStop()` and silence.
|
||||
#[tokio::test]
|
||||
async fn test_recoverable_error_resumes_a_music_track() {
|
||||
let controller = PlayerController::default();
|
||||
|
||||
let mut items = create_test_items(3);
|
||||
for item in &mut items {
|
||||
item.source = MediaSource::Remote {
|
||||
stream_url: format!("http://s/Audio/{}/stream?Static=true", item.id),
|
||||
jellyfin_item_id: item.id.clone(),
|
||||
};
|
||||
}
|
||||
controller.play_queue(items, 1).unwrap();
|
||||
controller.seek(45.0).unwrap();
|
||||
|
||||
let (position, _) = controller
|
||||
.recoverable_error_resume()
|
||||
.expect("a streamed music track must be resumable after a network error");
|
||||
assert_eq!(position, 45.0);
|
||||
}
|
||||
|
||||
/// The resume must reload the failed track IN PLACE. `play_item` replaces the
|
||||
/// whole queue with a single item, so recovering a track that way would throw
|
||||
/// away the rest of the album — turning a network blip into lost state.
|
||||
#[tokio::test]
|
||||
async fn test_resume_keeps_the_rest_of_the_queue() {
|
||||
let controller = PlayerController::default();
|
||||
|
||||
let mut items = create_test_items(3);
|
||||
for item in &mut items {
|
||||
item.source = MediaSource::Remote {
|
||||
stream_url: format!("http://s/Audio/{}/stream?Static=true", item.id),
|
||||
jellyfin_item_id: item.id.clone(),
|
||||
};
|
||||
}
|
||||
controller.play_queue(items, 1).unwrap();
|
||||
|
||||
controller
|
||||
.resume_stream_at(45.0)
|
||||
.await
|
||||
.expect("resume should succeed");
|
||||
|
||||
let queue = controller.queue.lock_safe();
|
||||
assert_eq!(queue.items().len(), 3, "the queue must survive a resume");
|
||||
assert_eq!(queue.current_index(), Some(1), "still on the same track");
|
||||
assert_eq!(queue.current().unwrap().id, "item_1");
|
||||
}
|
||||
|
||||
/// A seekable stream is re-opened by re-preparing the URL it already has and
|
||||
/// seeking — its timeline is intact, and rewriting the URL would restart a
|
||||
/// transcode session for no reason.
|
||||
#[tokio::test]
|
||||
async fn test_resume_seeks_a_seekable_stream_rather_than_rewriting_its_url() {
|
||||
let controller = PlayerController::default();
|
||||
|
||||
let mut items = create_test_items(1);
|
||||
items[0].source = MediaSource::Remote {
|
||||
stream_url: "http://s/Audio/item_0/stream?Static=true".to_string(),
|
||||
jellyfin_item_id: "item_0".to_string(),
|
||||
};
|
||||
controller.play_queue(items, 0).unwrap();
|
||||
|
||||
controller.resume_stream_at(45.0).await.unwrap();
|
||||
|
||||
match &controller.queue.lock_safe().current().unwrap().source {
|
||||
MediaSource::Remote { stream_url, .. } => {
|
||||
assert_eq!(
|
||||
stream_url, "http://s/Audio/item_0/stream?Static=true",
|
||||
"a seekable stream's URL must be left alone"
|
||||
);
|
||||
}
|
||||
other => panic!("expected Remote source, got {:?}", other),
|
||||
}
|
||||
assert_eq!(
|
||||
controller.position(),
|
||||
45.0,
|
||||
"and it must land at the position"
|
||||
);
|
||||
}
|
||||
|
||||
/// Downloaded media cannot fail from the network, and re-opening a local file
|
||||
/// would paper over a real read error.
|
||||
#[tokio::test]
|
||||
async fn test_recoverable_error_ignores_local_media() {
|
||||
let controller = PlayerController::default();
|
||||
|
||||
let mut items = create_test_items(1);
|
||||
items[0].source = MediaSource::Local {
|
||||
file_path: "/music/track.flac".into(),
|
||||
jellyfin_item_id: Some("item_0".to_string()),
|
||||
};
|
||||
controller.play_queue(items, 0).unwrap();
|
||||
controller.seek(45.0).unwrap();
|
||||
|
||||
assert!(controller.recoverable_error_resume().is_none());
|
||||
}
|
||||
|
||||
/// A recoverable error during background audio-only playback is the network,
|
||||
/// not the media — the previous behaviour (surface it, frontend stops the
|
||||
/// player) turned a hiccup into silence. Retrying must also back off, or the
|
||||
/// three attempts are spent inside a second and the outage outlives them.
|
||||
#[tokio::test]
|
||||
async fn test_recoverable_error_during_audio_only_resumes_with_backoff() {
|
||||
let controller = PlayerController::default();
|
||||
|
||||
controller
|
||||
.play_queue(vec![audio_only_episode(1500.0)], 0)
|
||||
.unwrap();
|
||||
controller.seek(600.0).unwrap();
|
||||
|
||||
let mut waits = Vec::new();
|
||||
for attempt in 1..=stream_end::MAX_STALLED_RESUME_ATTEMPTS {
|
||||
let (position, delay) = controller
|
||||
.recoverable_error_resume()
|
||||
.unwrap_or_else(|| panic!("attempt {} should still retry", attempt));
|
||||
assert_eq!(position, 600.0);
|
||||
waits.push(delay);
|
||||
}
|
||||
assert_eq!(waits, vec![2, 4, 6], "the wait must grow between attempts");
|
||||
assert!(
|
||||
controller.recoverable_error_resume().is_none(),
|
||||
"a stream that keeps failing at the same spot must surface the error"
|
||||
);
|
||||
}
|
||||
|
||||
/// Plugin/channel `DirectUrl` sources are somebody else's endpoint with no
|
||||
/// Jellyfin item behind them, so the resume has nothing to re-request.
|
||||
#[tokio::test]
|
||||
async fn test_recoverable_error_ignores_direct_url_playback() {
|
||||
let controller = PlayerController::default();
|
||||
controller.play_queue(create_test_items(2), 0).unwrap();
|
||||
|
||||
assert!(controller.recoverable_error_resume().is_none());
|
||||
}
|
||||
|
||||
/// Re-opening the stream must land where it died and keep playing, with the
|
||||
/// handoff base moved to the new stream's zero so returning to the
|
||||
/// foreground still resolves an absolute position.
|
||||
#[tokio::test]
|
||||
async fn test_resume_truncated_stream_reloads_at_position() {
|
||||
let controller = PlayerController::default();
|
||||
|
||||
controller
|
||||
.play_queue(vec![audio_only_episode(1500.0)], 0)
|
||||
.unwrap();
|
||||
controller.set_background_audio_base(0.0);
|
||||
|
||||
controller
|
||||
.resume_stream_at(600.0)
|
||||
.await
|
||||
.expect("resume should succeed");
|
||||
|
||||
let current = controller
|
||||
.queue
|
||||
.lock_safe()
|
||||
.current()
|
||||
.cloned()
|
||||
.expect("the same item should still be loaded");
|
||||
assert_eq!(current.id, "ep2", "resume must not change the item");
|
||||
match ¤t.source {
|
||||
MediaSource::Remote { stream_url, .. } => {
|
||||
assert!(
|
||||
stream_url.contains("StartTimeTicks=6000000000"),
|
||||
"stream must re-open at 600s, got {}",
|
||||
stream_url
|
||||
);
|
||||
assert!(
|
||||
stream_url.contains("AudioStreamIndex=2"),
|
||||
"the selected audio track must survive the resume, got {}",
|
||||
stream_url
|
||||
);
|
||||
}
|
||||
other => panic!("expected Remote source, got {:?}", other),
|
||||
}
|
||||
assert_eq!(
|
||||
controller.take_background_audio_base(),
|
||||
600.0,
|
||||
"the re-opened stream's zero is the resume position"
|
||||
);
|
||||
}
|
||||
|
||||
/// Foreground video playback keeps the countdown-driven advance: the frontend
|
||||
/// owns the navigation there, so the backend must NOT load the next episode
|
||||
/// itself (that would race the page transition and double-start playback).
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//! Telling a *finished* stream apart from a *truncated* one.
|
||||
//!
|
||||
//! TRACES: UR-040 | DR-129 | UT-117
|
||||
//!
|
||||
//! Background audio-only playback of a video item streams a **progressive mp3
|
||||
//! transcode over plain HTTP** (see
|
||||
//! `OnlineRepository::build_audio_only_stream_url_for_video`). That response has
|
||||
//! no reliable length — a live transcode is chunked — so when the connection
|
||||
//! drops mid-episode the data source simply sees end-of-input. ExoPlayer cannot
|
||||
//! distinguish that from the real end of the media and reports
|
||||
//! `Player.STATE_ENDED`, which the app then treats as "the episode finished".
|
||||
//!
|
||||
//! The user-visible damage is not the missed advance itself. Playback parks in
|
||||
//! ExoPlayer's `STATE_ENDED`, and the next play intent from the lockscreen,
|
||||
//! notification or a Bluetooth reconnect goes through media3's
|
||||
//! `Util.handlePlayButtonAction`, which seeks an ENDED player to its default
|
||||
//! position before playing — so **the episode starts over from 0:00**. On a
|
||||
//! flaky connection that reads as "it randomly restarts the episode".
|
||||
//!
|
||||
//! The player itself has no way to know; the *duration* does. Jellyfin gives us
|
||||
//! the item's real runtime, so an end reported well short of it is a truncation,
|
||||
//! not a finish — and the right response is to re-open the stream where it died,
|
||||
//! which is the "buffer and resume" the user expects.
|
||||
|
||||
/// How far short of the item's runtime a stream may end and still count as a
|
||||
/// natural finish.
|
||||
///
|
||||
/// Sized to swallow the two sources of slack in the comparison — the position
|
||||
/// poll is up to 250 ms stale, and Jellyfin's reported runtime can disagree with
|
||||
/// the transcoded output by a second or two — while staying far below the
|
||||
/// minutes-long gap a dropped connection leaves. Erring long is the safe
|
||||
/// direction: a false "finished" is the bug we are fixing, whereas a false
|
||||
/// "truncated" only re-opens the stream for its last few seconds and then ends
|
||||
/// again normally.
|
||||
pub const TRUNCATED_STREAM_TOLERANCE_SECS: f64 = 10.0;
|
||||
|
||||
/// Consecutive resume attempts allowed at the same position before giving up.
|
||||
///
|
||||
/// A resume re-opens the same URL, so a server that is genuinely gone would
|
||||
/// otherwise end → resume → end forever. Progress past the last attempt resets
|
||||
/// the budget (see [`ResumeTracker`]), so this only bounds *stuck* retries.
|
||||
pub const MAX_STALLED_RESUME_ATTEMPTS: u32 = 3;
|
||||
|
||||
/// Position change that counts as "this is a different playback context" —
|
||||
/// either the resume made progress, or a different item is loaded.
|
||||
const RESUME_PROGRESS_EPSILON_SECS: f64 = 1.0;
|
||||
|
||||
/// Did this end-of-stream happen far enough short of the item's runtime to be a
|
||||
/// truncation rather than a finish?
|
||||
///
|
||||
/// `position` and `duration` must be on the same timeline — for a handoff stream
|
||||
/// built with `StartTimeTicks`, that means the *absolute* position (handoff base
|
||||
/// + the player's relative position) against the item's full runtime.
|
||||
///
|
||||
/// An unknown or non-positive `duration` answers `false`: with nothing to
|
||||
/// compare against, the reported end is taken at face value (previous behaviour).
|
||||
pub fn is_truncated_end(position: f64, duration: Option<f64>, tolerance: f64) -> bool {
|
||||
let Some(duration) = duration else {
|
||||
return false;
|
||||
};
|
||||
if duration <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
position.max(0.0) + tolerance < duration
|
||||
}
|
||||
|
||||
/// Rewrite an audio-only stream URL to start at `position_seconds`.
|
||||
///
|
||||
/// Resuming re-opens *the stream we were already playing*, so the URL is edited
|
||||
/// in place rather than rebuilt from the repository: every other parameter —
|
||||
/// `AudioStreamIndex` (the track the user picked in the video player),
|
||||
/// `MediaSourceId`, `api_key` — is carried over untouched, and no network call
|
||||
/// is needed to recover from a network failure.
|
||||
pub fn with_start_time(url: &str, position_seconds: f64) -> String {
|
||||
let ticks = (position_seconds.max(0.0) * 10_000_000.0) as i64;
|
||||
let param = format!("StartTimeTicks={}", ticks);
|
||||
|
||||
let (base, query) = match url.split_once('?') {
|
||||
Some((base, query)) => (base, query),
|
||||
// No query string at all: the URL was not built by us, but appending the
|
||||
// parameter is still the correct request to make.
|
||||
None => return format!("{}?{}", url, param),
|
||||
};
|
||||
|
||||
let mut replaced = false;
|
||||
let mut parts: Vec<String> = query
|
||||
.split('&')
|
||||
.map(|part| {
|
||||
if part.split('=').next() == Some("StartTimeTicks") {
|
||||
replaced = true;
|
||||
param.clone()
|
||||
} else {
|
||||
part.to_string()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
if !replaced {
|
||||
parts.push(param);
|
||||
}
|
||||
|
||||
format!("{}?{}", base, parts.join("&"))
|
||||
}
|
||||
|
||||
/// Budget for consecutive resume attempts that make no progress.
|
||||
///
|
||||
/// Held by the player controller across ends of the *same* stream. Any position
|
||||
/// change larger than [`RESUME_PROGRESS_EPSILON_SECS`] — the resume played on,
|
||||
/// or a different item was loaded — is a fresh context and refills the budget.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ResumeTracker {
|
||||
last_position: Option<f64>,
|
||||
attempts: u32,
|
||||
}
|
||||
|
||||
impl ResumeTracker {
|
||||
/// Record an attempt at `position`, returning its 1-based number — or `None`
|
||||
/// once the budget is spent. Callers use the number to back off: a stream
|
||||
/// that failed twice at the same spot is waiting on something slower than an
|
||||
/// immediate retry can outrun.
|
||||
pub fn allow_attempt(&mut self, position: f64) -> Option<u32> {
|
||||
let progressed = match self.last_position {
|
||||
Some(last) => (position - last).abs() > RESUME_PROGRESS_EPSILON_SECS,
|
||||
None => true,
|
||||
};
|
||||
if progressed {
|
||||
self.attempts = 0;
|
||||
}
|
||||
self.last_position = Some(position);
|
||||
self.attempts += 1;
|
||||
(self.attempts <= MAX_STALLED_RESUME_ATTEMPTS).then_some(self.attempts)
|
||||
}
|
||||
|
||||
/// Forget the budget — a new item is playing, so nothing is stuck.
|
||||
pub fn reset(&mut self) {
|
||||
self.last_position = None;
|
||||
self.attempts = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_end_near_duration_is_a_natural_finish() {
|
||||
// Episode runtime 25:00, stream ended at 24:56 — that is the end.
|
||||
assert!(!is_truncated_end(
|
||||
1496.0,
|
||||
Some(1500.0),
|
||||
TRUNCATED_STREAM_TOLERANCE_SECS
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_end_far_short_of_duration_is_truncated() {
|
||||
// Episode runtime 25:00, stream died at 10:00 — the connection dropped.
|
||||
assert!(is_truncated_end(
|
||||
600.0,
|
||||
Some(1500.0),
|
||||
TRUNCATED_STREAM_TOLERANCE_SECS
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_duration_is_taken_at_face_value() {
|
||||
// Nothing to compare against: keep the previous end-of-track behaviour
|
||||
// rather than resuming a stream that may really have finished.
|
||||
assert!(!is_truncated_end(
|
||||
600.0,
|
||||
None,
|
||||
TRUNCATED_STREAM_TOLERANCE_SECS
|
||||
));
|
||||
assert!(!is_truncated_end(
|
||||
600.0,
|
||||
Some(0.0),
|
||||
TRUNCATED_STREAM_TOLERANCE_SECS
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tolerance_boundary() {
|
||||
// Exactly one tolerance short still counts as finished, so poll staleness
|
||||
// and runtime rounding never fabricate a truncation.
|
||||
assert!(!is_truncated_end(1490.0, Some(1500.0), 10.0));
|
||||
assert!(is_truncated_end(1489.0, Some(1500.0), 10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_start_time_replaces_existing_ticks() {
|
||||
let url = "http://s/Audio/ep2/universal?api_key=k&AudioStreamIndex=2&StartTimeTicks=1200000000&Container=mp3";
|
||||
let out = with_start_time(url, 600.0);
|
||||
assert_eq!(
|
||||
out,
|
||||
"http://s/Audio/ep2/universal?api_key=k&AudioStreamIndex=2&StartTimeTicks=6000000000&Container=mp3"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_start_time_appends_when_absent() {
|
||||
// The next-episode stream is built without StartTimeTicks.
|
||||
let url = "http://s/Audio/ep3/universal?api_key=k&AudioStreamIndex=0";
|
||||
let out = with_start_time(url, 90.0);
|
||||
assert_eq!(
|
||||
out,
|
||||
"http://s/Audio/ep3/universal?api_key=k&AudioStreamIndex=0&StartTimeTicks=900000000"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_start_time_preserves_selected_audio_track() {
|
||||
// The whole point of editing the URL instead of rebuilding it: the track
|
||||
// the user chose in the video player survives the resume.
|
||||
let url = "http://s/Audio/ep2/universal?AudioStreamIndex=3&MediaSourceId=src-1";
|
||||
let out = with_start_time(url, 10.0);
|
||||
assert!(out.contains("AudioStreamIndex=3"));
|
||||
assert!(out.contains("MediaSourceId=src-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_start_time_without_query() {
|
||||
assert_eq!(
|
||||
with_start_time("http://s/Audio/ep2/universal", 1.0),
|
||||
"http://s/Audio/ep2/universal?StartTimeTicks=10000000"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resume_tracker_bounds_stalled_retries() {
|
||||
let mut tracker = ResumeTracker::default();
|
||||
// Same position over and over: the stream is not recovering.
|
||||
for n in 1..=MAX_STALLED_RESUME_ATTEMPTS {
|
||||
assert_eq!(
|
||||
tracker.allow_attempt(600.0),
|
||||
Some(n),
|
||||
"attempts are numbered so callers can back off"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
tracker.allow_attempt(600.0),
|
||||
None,
|
||||
"a stream that ends at the same position every time must stop retrying"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resume_tracker_refills_after_progress() {
|
||||
let mut tracker = ResumeTracker::default();
|
||||
for _ in 0..MAX_STALLED_RESUME_ATTEMPTS {
|
||||
tracker.allow_attempt(600.0);
|
||||
}
|
||||
assert_eq!(tracker.allow_attempt(600.0), None);
|
||||
// The next drop happened further in — the resumes are working, so the
|
||||
// budget must not be exhausted by earlier trouble.
|
||||
assert_eq!(tracker.allow_attempt(900.0), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resume_tracker_reset() {
|
||||
let mut tracker = ResumeTracker::default();
|
||||
for _ in 0..=MAX_STALLED_RESUME_ATTEMPTS {
|
||||
tracker.allow_attempt(600.0);
|
||||
}
|
||||
tracker.reset();
|
||||
assert_eq!(tracker.allow_attempt(600.0), Some(1));
|
||||
}
|
||||
}
|
||||
@@ -41,12 +41,34 @@ impl HybridRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// The signed-in user this repository acts for.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-120
|
||||
pub fn user_id(&self) -> &str {
|
||||
self.online.user_id()
|
||||
}
|
||||
|
||||
/// Download raw bytes from a URL using the shared authenticated HTTP client.
|
||||
/// Delegates to online repository for connection reuse and proper auth.
|
||||
pub async fn download_bytes(&self, url: &str) -> Result<Vec<u8>, String> {
|
||||
self.online.download_bytes(url).await
|
||||
}
|
||||
|
||||
/// Remove catalog entries the server no longer has. Cache-only, so it goes
|
||||
/// straight to the offline repository. Callers must only invoke this after a
|
||||
/// crawl in which every library succeeded — see
|
||||
/// `OfflineRepository::prune_stale_catalog` for why a partial crawl must not
|
||||
/// sweep.
|
||||
///
|
||||
/// TRACES: UR-065 | DR-110
|
||||
pub async fn prune_stale_catalog(
|
||||
&self,
|
||||
cutoff: &str,
|
||||
item_types: &[String],
|
||||
) -> Result<usize, RepoError> {
|
||||
self.offline.prune_stale_catalog(cutoff, item_types).await
|
||||
}
|
||||
|
||||
/// Query the JRay plugin for actors on screen at time `t`. Online-only
|
||||
/// (the plugin lives on the Jellyfin server); empty when JRay isn't present.
|
||||
pub async fn get_jray_actors(
|
||||
@@ -113,6 +135,41 @@ impl HybridRepository {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Favourites held locally, without touching the server. Backs the instant
|
||||
/// leg of the two-phase favourites read in the command layer.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-115
|
||||
pub async fn get_favorites_cache_only(
|
||||
&self,
|
||||
scope: SearchScope,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError> {
|
||||
let offline = Arc::clone(&self.offline);
|
||||
self.cache_with_timeout(async move { offline.get_favorites(scope, options).await })
|
||||
.await
|
||||
}
|
||||
|
||||
/// Favourites straight from the server, persisted to the cache on the way
|
||||
/// through — which is also what mirrors their favourite flags into
|
||||
/// `user_data` (DR-114), so the next offline read agrees with the server.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-115
|
||||
pub async fn get_favorites_server_only(
|
||||
&self,
|
||||
scope: SearchScope,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError> {
|
||||
let result = self.online.get_favorites(scope, options).await?;
|
||||
if !result.items.is_empty() {
|
||||
// Favourites span libraries, so there is no single parent to file
|
||||
// them under; the parent id is only used for stub rows.
|
||||
if let Err(e) = self.offline.save_to_cache("favorites", &result.items).await {
|
||||
debug!("[HybridRepo] Failed to cache favourites: {:?}", e);
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Fetch a folder's items from the live server and persist them to the
|
||||
/// offline cache synchronously (unlike `get_items`, which saves in a
|
||||
/// fire-and-forget background task after a 100ms cache race).
|
||||
@@ -790,6 +847,42 @@ impl MediaRepository for HybridRepository {
|
||||
self.parallel_race(cache_future, server_future).await
|
||||
}
|
||||
|
||||
/// TRACES: UR-067 | DR-115
|
||||
async fn get_favorites(
|
||||
&self,
|
||||
scope: SearchScope,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError> {
|
||||
let offline = Arc::clone(&self.offline);
|
||||
let online = Arc::clone(&self.online);
|
||||
let opts_clone = options.clone();
|
||||
|
||||
let cache_result = self
|
||||
.cache_with_timeout(async move { offline.get_favorites(scope, opts_clone).await })
|
||||
.await;
|
||||
|
||||
// Downloads-only gate: with "Show all server media" off, an empty local
|
||||
// result means "nothing favourited is on this device" and is
|
||||
// authoritative. Falling through to the server here would re-pad the
|
||||
// page with the full favourited catalog and defeat the filter (DR-080).
|
||||
if !crate::repository::offline::include_catalog_browse() {
|
||||
if let Ok(data) = &cache_result {
|
||||
return Ok(data.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(data) = &cache_result {
|
||||
if data.has_content() {
|
||||
return Ok(data.clone());
|
||||
}
|
||||
}
|
||||
|
||||
match online.get_favorites(scope, options).await {
|
||||
Ok(data) => Ok(data),
|
||||
Err(e) => cache_result.or(Err(e)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_similar_items(
|
||||
&self,
|
||||
item_id: &str,
|
||||
@@ -1133,6 +1226,14 @@ mod tests {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_favorites(
|
||||
&self,
|
||||
_scope: SearchScope,
|
||||
_options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn clear_watch_history(&self, _item_id: &str) -> Result<(), RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -1395,6 +1496,14 @@ mod tests {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_favorites(
|
||||
&self,
|
||||
_scope: SearchScope,
|
||||
_options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn clear_watch_history(&self, _item_id: &str) -> Result<(), RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
@@ -212,6 +212,20 @@ pub trait MediaRepository: Send + Sync {
|
||||
/// Unmark item as favorite
|
||||
async fn unmark_favorite(&self, item_id: &str) -> Result<(), RepoError>;
|
||||
|
||||
/// Everything the viewer has favourited, across every library.
|
||||
///
|
||||
/// Separate from `get_items` because favourites span libraries and
|
||||
/// `get_items` is `ParentId`-shaped. `scope` is the opaque enum the
|
||||
/// frontend sends; this layer expands it to item types (DR-063) so no
|
||||
/// Jellyfin taxonomy is needed on the other side of the IPC boundary.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-115, JA-033 | UT-100, UT-101
|
||||
async fn get_favorites(
|
||||
&self,
|
||||
scope: SearchScope,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError>;
|
||||
|
||||
/// Erase the viewer's watch history for an item: clear its played flag and
|
||||
/// its resume position. On a container (series, season) this applies to
|
||||
/// everything inside it, so a series is returned to "never watched" and
|
||||
|
||||
+1150
-44
File diff suppressed because it is too large
Load Diff
@@ -48,6 +48,12 @@ pub struct OnlineRepository {
|
||||
}
|
||||
|
||||
impl OnlineRepository {
|
||||
/// The signed-in user these requests are made as. Needed by the favourites
|
||||
/// drain, which reads this user's queued rows. TRACES: UR-069 | DR-120
|
||||
pub fn user_id(&self) -> &str {
|
||||
&self.user_id
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
http_client: Arc<HttpClient>,
|
||||
server_url: String,
|
||||
@@ -560,6 +566,138 @@ struct JellyfinItem {
|
||||
media_streams: Option<Vec<JellyfinMediaStream>>,
|
||||
media_sources: Option<Vec<JellyfinMediaSource>>,
|
||||
people: Option<Vec<crate::repository::types::Person>>,
|
||||
user_data: Option<JellyfinUserData>,
|
||||
}
|
||||
|
||||
/// Per-user state Jellyfin attaches to an item (favourite, played, resume).
|
||||
///
|
||||
/// Returned on every `/Users/{uid}/Items*` response; we additionally name
|
||||
/// `UserData` in the `Fields=` list so the shape is explicit rather than
|
||||
/// dependent on the server's default field set.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-113, JA-034 | UT-099
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct JellyfinUserData {
|
||||
playback_position_ticks: Option<i64>,
|
||||
#[serde(rename = "Played")]
|
||||
is_played: Option<bool>,
|
||||
is_favorite: Option<bool>,
|
||||
play_count: Option<i32>,
|
||||
last_played_date: Option<String>,
|
||||
}
|
||||
|
||||
impl From<JellyfinUserData> for UserData {
|
||||
fn from(jf: JellyfinUserData) -> Self {
|
||||
UserData {
|
||||
playback_position_ticks: jf.playback_position_ticks,
|
||||
playback_position_ms: jf.playback_position_ticks.map(crate::domain::ticks_to_ms),
|
||||
is_played: jf.is_played,
|
||||
is_favorite: jf.is_favorite,
|
||||
play_count: jf.play_count,
|
||||
last_played_date: jf.last_played_date,
|
||||
playback_context_type: None,
|
||||
playback_context_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the Jellyfin endpoint for a folder listing.
|
||||
///
|
||||
/// Extracted from `get_items` so the query it produces — in particular the
|
||||
/// favourites filter — can be asserted without standing up an HTTP server.
|
||||
///
|
||||
/// TRACES: UR-007, UR-067 | DR-116 | UT-104
|
||||
fn build_get_items_endpoint(
|
||||
user_id: &str,
|
||||
parent_id: &str,
|
||||
options: Option<&GetItemsOptions>,
|
||||
) -> String {
|
||||
let mut endpoint = format!("/Users/{}/Items?ParentId={}", user_id, parent_id);
|
||||
|
||||
if let Some(opts) = options {
|
||||
if let Some(limit) = opts.limit {
|
||||
endpoint.push_str(&format!("&Limit={}", limit));
|
||||
}
|
||||
if let Some(start_index) = opts.start_index {
|
||||
endpoint.push_str(&format!("&StartIndex={}", start_index));
|
||||
}
|
||||
if let Some(types) = &opts.include_item_types {
|
||||
endpoint.push_str(&format!("&IncludeItemTypes={}", types.join(",")));
|
||||
}
|
||||
if let Some(sort_by) = &opts.sort_by {
|
||||
endpoint.push_str(&format!("&SortBy={}", sort_by));
|
||||
}
|
||||
if let Some(sort_order) = &opts.sort_order {
|
||||
endpoint.push_str(&format!("&SortOrder={}", sort_order));
|
||||
}
|
||||
if let Some(recursive) = opts.recursive {
|
||||
endpoint.push_str(&format!("&Recursive={}", recursive));
|
||||
}
|
||||
if let Some(genres) = &opts.genres {
|
||||
if !genres.is_empty() {
|
||||
// Genre names may contain spaces/ampersands, so percent-encode each.
|
||||
let encoded: Vec<String> = genres
|
||||
.iter()
|
||||
.map(|g| urlencoding::encode(g).into_owned())
|
||||
.collect();
|
||||
endpoint.push_str(&format!("&Genres={}", encoded.join("|")));
|
||||
}
|
||||
}
|
||||
// TRACES: UR-067 | DR-116 | UT-104
|
||||
if opts.favorites_only == Some(true) {
|
||||
endpoint.push_str("&Filters=IsFavorite");
|
||||
}
|
||||
}
|
||||
|
||||
// Request image fields for list views (People only needed in get_item
|
||||
// detail view). Genres is needed so cached items carry their genres,
|
||||
// which lets the offline store derive genre lists + per-genre counts.
|
||||
endpoint
|
||||
.push_str("&Fields=BackdropImageTags,ParentBackdropImageTags,Genres,PremiereDate,UserData");
|
||||
endpoint
|
||||
}
|
||||
|
||||
/// Build the Jellyfin endpoint for a favourites listing.
|
||||
///
|
||||
/// Pulled out of `get_favorites` so the query can be asserted without an HTTP
|
||||
/// server. `scope` is expanded here — `SearchScope::All` yields `None`, and the
|
||||
/// `IncludeItemTypes` filter is then **omitted entirely** rather than sent as a
|
||||
/// union, which would silently drop every type nobody enumerated (see
|
||||
/// `SearchScope::item_types`).
|
||||
///
|
||||
/// TRACES: UR-067 | DR-115, JA-033 | UT-100
|
||||
fn build_favorites_endpoint(
|
||||
user_id: &str,
|
||||
scope: SearchScope,
|
||||
options: Option<&GetItemsOptions>,
|
||||
) -> String {
|
||||
let mut endpoint = format!("/Users/{}/Items?Filters=IsFavorite&Recursive=true", user_id);
|
||||
|
||||
if let Some(types) = scope.item_types() {
|
||||
endpoint.push_str(&format!("&IncludeItemTypes={}", types.join(",")));
|
||||
}
|
||||
|
||||
// Jellyfin has no "date favourited", so name order is the only stable sort
|
||||
// available; callers may still override it.
|
||||
let sort_by = options
|
||||
.and_then(|o| o.sort_by.as_deref())
|
||||
.unwrap_or("SortName");
|
||||
let sort_order = options
|
||||
.and_then(|o| o.sort_order.as_deref())
|
||||
.unwrap_or("Ascending");
|
||||
endpoint.push_str(&format!("&SortBy={}&SortOrder={}", sort_by, sort_order));
|
||||
|
||||
if let Some(limit) = options.and_then(|o| o.limit) {
|
||||
endpoint.push_str(&format!("&Limit={}", limit));
|
||||
}
|
||||
if let Some(start_index) = options.and_then(|o| o.start_index) {
|
||||
endpoint.push_str(&format!("&StartIndex={}", start_index));
|
||||
}
|
||||
|
||||
endpoint
|
||||
.push_str("&Fields=BackdropImageTags,ParentBackdropImageTags,Genres,PremiereDate,UserData");
|
||||
endpoint
|
||||
}
|
||||
|
||||
// ImageTags from Jellyfin API - can be a HashMap with various image type keys
|
||||
@@ -653,7 +791,9 @@ impl JellyfinItem {
|
||||
series_name: self.series_name,
|
||||
season_id: self.season_id,
|
||||
season_name: self.season_name,
|
||||
user_data: None, // User data not included in basic item responses
|
||||
// Favourite/played/resume state as the server sees it. TRACES:
|
||||
// UR-069 | DR-113, JA-034
|
||||
user_data: self.user_data.map(UserData::from),
|
||||
media_streams: self.media_streams.map(|streams| {
|
||||
streams
|
||||
.into_iter()
|
||||
@@ -728,43 +868,7 @@ impl MediaRepository for OnlineRepository {
|
||||
parent_id: &str,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError> {
|
||||
let mut endpoint = format!("/Users/{}/Items?ParentId={}", self.user_id, parent_id);
|
||||
|
||||
if let Some(opts) = options {
|
||||
if let Some(limit) = opts.limit {
|
||||
endpoint.push_str(&format!("&Limit={}", limit));
|
||||
}
|
||||
if let Some(start_index) = opts.start_index {
|
||||
endpoint.push_str(&format!("&StartIndex={}", start_index));
|
||||
}
|
||||
if let Some(types) = opts.include_item_types {
|
||||
endpoint.push_str(&format!("&IncludeItemTypes={}", types.join(",")));
|
||||
}
|
||||
if let Some(sort_by) = opts.sort_by {
|
||||
endpoint.push_str(&format!("&SortBy={}", sort_by));
|
||||
}
|
||||
if let Some(sort_order) = opts.sort_order {
|
||||
endpoint.push_str(&format!("&SortOrder={}", sort_order));
|
||||
}
|
||||
if let Some(recursive) = opts.recursive {
|
||||
endpoint.push_str(&format!("&Recursive={}", recursive));
|
||||
}
|
||||
if let Some(genres) = opts.genres {
|
||||
if !genres.is_empty() {
|
||||
// Genre names may contain spaces/ampersands, so percent-encode each.
|
||||
let encoded: Vec<String> = genres
|
||||
.iter()
|
||||
.map(|g| urlencoding::encode(g).into_owned())
|
||||
.collect();
|
||||
endpoint.push_str(&format!("&Genres={}", encoded.join("|")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Request image fields for list views (People only needed in get_item
|
||||
// detail view). Genres is needed so cached items carry their genres,
|
||||
// which lets the offline store derive genre lists + per-genre counts.
|
||||
endpoint.push_str("&Fields=BackdropImageTags,ParentBackdropImageTags,Genres,PremiereDate");
|
||||
let endpoint = build_get_items_endpoint(&self.user_id, parent_id, options.as_ref());
|
||||
|
||||
let response: ItemsResponse = self.get_json(&endpoint).await?;
|
||||
|
||||
@@ -779,7 +883,7 @@ impl MediaRepository for OnlineRepository {
|
||||
}
|
||||
|
||||
async fn get_item(&self, item_id: &str) -> Result<MediaItem, RepoError> {
|
||||
let endpoint = format!("/Users/{}/Items/{}?Fields=BackdropImageTags,ParentBackdropImageTags,People,MediaStreams,MediaSources,PremiereDate", self.user_id, item_id);
|
||||
let endpoint = format!("/Users/{}/Items/{}?Fields=BackdropImageTags,ParentBackdropImageTags,People,MediaStreams,MediaSources,PremiereDate,UserData", self.user_id, item_id);
|
||||
|
||||
let item: JellyfinItem = self.get_json(&endpoint).await?;
|
||||
let media_item = item.to_media_item(self.user_id.clone());
|
||||
@@ -794,7 +898,7 @@ impl MediaRepository for OnlineRepository {
|
||||
) -> Result<Vec<MediaItem>, RepoError> {
|
||||
let limit_str = limit.unwrap_or(16);
|
||||
let endpoint = format!(
|
||||
"/Users/{}/Items/Latest?ParentId={}&Limit={}&Fields=BackdropImageTags,ParentBackdropImageTags",
|
||||
"/Users/{}/Items/Latest?ParentId={}&Limit={}&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
self.user_id, parent_id, limit_str
|
||||
);
|
||||
|
||||
@@ -812,7 +916,7 @@ impl MediaRepository for OnlineRepository {
|
||||
) -> Result<Vec<MediaItem>, RepoError> {
|
||||
let limit_str = limit.unwrap_or(16);
|
||||
let mut endpoint = format!(
|
||||
"/Users/{}/Items/Resume?Limit={}&MediaTypes=Video&Fields=BackdropImageTags,ParentBackdropImageTags",
|
||||
"/Users/{}/Items/Resume?Limit={}&MediaTypes=Video&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
self.user_id, limit_str
|
||||
);
|
||||
|
||||
@@ -835,7 +939,7 @@ impl MediaRepository for OnlineRepository {
|
||||
) -> Result<Vec<MediaItem>, RepoError> {
|
||||
let limit_str = limit.unwrap_or(16);
|
||||
let mut endpoint = format!(
|
||||
"/Shows/NextUp?UserId={}&Limit={}&Fields=BackdropImageTags,ParentBackdropImageTags",
|
||||
"/Shows/NextUp?UserId={}&Limit={}&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
self.user_id, limit_str
|
||||
);
|
||||
|
||||
@@ -859,7 +963,7 @@ impl MediaRepository for OnlineRepository {
|
||||
// Fetch more items to account for grouping reducing the count
|
||||
let fetch_limit = limit_val * 3;
|
||||
let endpoint = format!(
|
||||
"/Users/{}/Items?SortBy=DatePlayed&SortOrder=Descending&IncludeItemTypes=Audio&Limit={}&Recursive=true&Filters=IsPlayed&Fields=BackdropImageTags,ParentBackdropImageTags",
|
||||
"/Users/{}/Items?SortBy=DatePlayed&SortOrder=Descending&IncludeItemTypes=Audio&Limit={}&Recursive=true&Filters=IsPlayed&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
self.user_id, fetch_limit
|
||||
);
|
||||
|
||||
@@ -993,7 +1097,7 @@ impl MediaRepository for OnlineRepository {
|
||||
// Filters=IsPlayed keeps only albums the user has actually listened to,
|
||||
// and SortBy=DatePlayed ascending surfaces the ones they've neglected.
|
||||
let mut endpoint = format!(
|
||||
"/Users/{}/Items?SortBy=DatePlayed&SortOrder=Ascending&IncludeItemTypes=MusicAlbum&Limit={}&Recursive=true&Filters=IsPlayed&Fields=BackdropImageTags,ParentBackdropImageTags",
|
||||
"/Users/{}/Items?SortBy=DatePlayed&SortOrder=Ascending&IncludeItemTypes=MusicAlbum&Limit={}&Recursive=true&Filters=IsPlayed&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
self.user_id, limit_val
|
||||
);
|
||||
|
||||
@@ -1012,7 +1116,7 @@ impl MediaRepository for OnlineRepository {
|
||||
async fn get_resume_movies(&self, limit: Option<usize>) -> Result<Vec<MediaItem>, RepoError> {
|
||||
let limit_str = limit.unwrap_or(16);
|
||||
let endpoint = format!(
|
||||
"/Users/{}/Items/Resume?Limit={}&MediaTypes=Video&IncludeItemTypes=Movie&Fields=BackdropImageTags,ParentBackdropImageTags",
|
||||
"/Users/{}/Items/Resume?Limit={}&MediaTypes=Video&IncludeItemTypes=Movie&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
self.user_id, limit_str
|
||||
);
|
||||
|
||||
@@ -1113,7 +1217,9 @@ impl MediaRepository for OnlineRepository {
|
||||
|
||||
// Request image fields for list views (plus Genres so cached items
|
||||
// carry genres for offline genre lists/counts).
|
||||
endpoint.push_str("&Fields=BackdropImageTags,ParentBackdropImageTags,Genres,PremiereDate");
|
||||
endpoint.push_str(
|
||||
"&Fields=BackdropImageTags,ParentBackdropImageTags,Genres,PremiereDate,UserData",
|
||||
);
|
||||
|
||||
let response: ItemsResponse = self.get_json(&endpoint).await?;
|
||||
Ok(SearchResult {
|
||||
@@ -1654,6 +1760,25 @@ impl MediaRepository for OnlineRepository {
|
||||
self.post_json(&endpoint, &serde_json::json!({})).await
|
||||
}
|
||||
|
||||
/// TRACES: UR-067 | DR-115, JA-033 | UT-100
|
||||
async fn get_favorites(
|
||||
&self,
|
||||
scope: SearchScope,
|
||||
options: Option<GetItemsOptions>,
|
||||
) -> Result<SearchResult, RepoError> {
|
||||
let endpoint = build_favorites_endpoint(&self.user_id, scope, options.as_ref());
|
||||
let response: ItemsResponse = self.get_json(&endpoint).await?;
|
||||
|
||||
Ok(SearchResult {
|
||||
items: response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.collect(),
|
||||
total_record_count: response.total_record_count,
|
||||
})
|
||||
}
|
||||
|
||||
async fn unmark_favorite(&self, item_id: &str) -> Result<(), RepoError> {
|
||||
let endpoint = format!("/Users/{}/FavoriteItems/{}", self.user_id, item_id);
|
||||
let url = format!("{}{}", self.server_url, endpoint);
|
||||
@@ -1747,7 +1872,7 @@ impl MediaRepository for OnlineRepository {
|
||||
let limit = options.as_ref().and_then(|o| o.limit).unwrap_or(100);
|
||||
|
||||
let mut endpoint = format!(
|
||||
"/Users/{}/Items?PersonIds={}&Limit={}&Recursive=true&Fields=BackdropImageTags,ParentBackdropImageTags",
|
||||
"/Users/{}/Items?PersonIds={}&Limit={}&Recursive=true&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
self.user_id, person_id, limit
|
||||
);
|
||||
|
||||
@@ -1781,7 +1906,7 @@ impl MediaRepository for OnlineRepository {
|
||||
|
||||
// Try the /Similar endpoint which works for most items
|
||||
let endpoint = format!(
|
||||
"/Items/{}/Similar?UserId={}&Limit={}&Fields=BackdropImageTags,ParentBackdropImageTags",
|
||||
"/Items/{}/Similar?UserId={}&Limit={}&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
item_id, self.user_id, limit_str
|
||||
);
|
||||
|
||||
@@ -2369,6 +2494,140 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// UT-100 — the favourites endpoint asks the server for favourites, scoped.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-115, JA-033 | UT-100
|
||||
#[test]
|
||||
fn test_build_favorites_endpoint_scopes_and_filters() {
|
||||
let movies = build_favorites_endpoint("u1", SearchScope::Movies, None);
|
||||
assert!(movies.starts_with("/Users/u1/Items?Filters=IsFavorite&Recursive=true"));
|
||||
assert!(movies.contains("&IncludeItemTypes=Movie"));
|
||||
// Jellyfin has no favourite timestamp, so name order is the default.
|
||||
assert!(movies.contains("&SortBy=SortName&SortOrder=Ascending"));
|
||||
// Hearts must render on the returned cards.
|
||||
assert!(movies.contains("UserData"));
|
||||
|
||||
// Tv covers both the show and any individually favourited episode.
|
||||
let tv = build_favorites_endpoint("u1", SearchScope::Tv, None);
|
||||
assert!(tv.contains("&IncludeItemTypes=Series,Episode"));
|
||||
|
||||
let music = build_favorites_endpoint("u1", SearchScope::Music, None);
|
||||
assert!(music.contains("&IncludeItemTypes=MusicAlbum,MusicArtist,Audio,Playlist"));
|
||||
}
|
||||
|
||||
/// `All` must omit the type filter entirely rather than send a union, which
|
||||
/// would silently drop every type nobody enumerated.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-115 | UT-100
|
||||
#[test]
|
||||
fn test_build_favorites_endpoint_all_scope_omits_type_filter() {
|
||||
let all = build_favorites_endpoint("u1", SearchScope::All, None);
|
||||
assert!(!all.contains("IncludeItemTypes"));
|
||||
}
|
||||
|
||||
/// Paging and an explicit sort still reach the server.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-115 | UT-100
|
||||
#[test]
|
||||
fn test_build_favorites_endpoint_honours_paging_and_sort() {
|
||||
let endpoint = build_favorites_endpoint(
|
||||
"u1",
|
||||
SearchScope::All,
|
||||
Some(&GetItemsOptions {
|
||||
limit: Some(20),
|
||||
start_index: Some(40),
|
||||
sort_by: Some("Random".to_string()),
|
||||
sort_order: Some("Descending".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
assert!(endpoint.contains("&Limit=20"));
|
||||
assert!(endpoint.contains("&StartIndex=40"));
|
||||
assert!(endpoint.contains("&SortBy=Random&SortOrder=Descending"));
|
||||
}
|
||||
|
||||
/// UT-104 — the in-library favourites toggle reaches the server as
|
||||
/// `Filters=IsFavorite`, and is absent unless asked for.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-116 | UT-104
|
||||
#[test]
|
||||
fn test_get_items_endpoint_applies_favorites_only() {
|
||||
let plain = build_get_items_endpoint("u1", "lib-1", None);
|
||||
assert!(!plain.contains("Filters=IsFavorite"));
|
||||
|
||||
let filtered = build_get_items_endpoint(
|
||||
"u1",
|
||||
"lib-1",
|
||||
Some(&GetItemsOptions {
|
||||
favorites_only: Some(true),
|
||||
include_item_types: Some(vec!["Movie".to_string()]),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
assert!(filtered.contains("&Filters=IsFavorite"));
|
||||
// Composes with the filters already there rather than replacing them.
|
||||
assert!(filtered.contains("&IncludeItemTypes=Movie"));
|
||||
assert!(filtered.contains("ParentId=lib-1"));
|
||||
|
||||
// Explicitly false is not a request to filter.
|
||||
let off = build_get_items_endpoint(
|
||||
"u1",
|
||||
"lib-1",
|
||||
Some(&GetItemsOptions {
|
||||
favorites_only: Some(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
assert!(!off.contains("Filters=IsFavorite"));
|
||||
}
|
||||
|
||||
/// UT-099 — a Jellyfin item's `UserData` reaches `MediaItem.user_data`.
|
||||
///
|
||||
/// Before DR-113 this mapping was hardcoded to `None`, so nothing outside
|
||||
/// the mini player could know an item was favourited.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-113, JA-034 | UT-099
|
||||
#[test]
|
||||
fn test_jellyfin_item_maps_user_data_favorite() {
|
||||
let json = r#"{
|
||||
"Id": "movie123",
|
||||
"Name": "Test Movie",
|
||||
"Type": "Movie",
|
||||
"UserData": {
|
||||
"PlaybackPositionTicks": 6000000000,
|
||||
"Played": false,
|
||||
"IsFavorite": true,
|
||||
"PlayCount": 2,
|
||||
"LastPlayedDate": "2026-08-01T12:00:00Z"
|
||||
}
|
||||
}"#;
|
||||
|
||||
let item: JellyfinItem = serde_json::from_str(json).expect("item should deserialize");
|
||||
let media = item.to_media_item("server1".to_string());
|
||||
|
||||
let user_data = media.user_data.expect("user data should be mapped");
|
||||
assert_eq!(user_data.is_favorite, Some(true));
|
||||
assert_eq!(user_data.is_played, Some(false));
|
||||
assert_eq!(user_data.play_count, Some(2));
|
||||
assert_eq!(user_data.playback_position_ticks, Some(6_000_000_000));
|
||||
// Ticks are converted for the frontend, which never divides them itself.
|
||||
assert_eq!(user_data.playback_position_ms, Some(600_000));
|
||||
}
|
||||
|
||||
/// An item without `UserData` still maps — the field is optional, and every
|
||||
/// non-user-scoped endpoint omits it.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-113 | UT-099
|
||||
#[test]
|
||||
fn test_jellyfin_item_without_user_data_maps_to_none() {
|
||||
let json = r#"{"Id": "x", "Name": "No User Data", "Type": "Movie"}"#;
|
||||
|
||||
let item: JellyfinItem = serde_json::from_str(json).expect("item should deserialize");
|
||||
let media = item.to_media_item("server1".to_string());
|
||||
|
||||
assert!(media.user_data.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_jellyfin_item_deserialize_with_artist_items() {
|
||||
// Test that ArtistItems with PascalCase fields deserialize correctly
|
||||
|
||||
@@ -292,6 +292,12 @@ pub struct GetItemsOptions {
|
||||
pub fields: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub genres: Option<Vec<String>>,
|
||||
/// Restrict the listing to favourited items. Backs the per-library
|
||||
/// favourites toggle; composes with every other filter here.
|
||||
///
|
||||
/// TRACES: UR-067 | DR-116 | UT-104
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub favorites_only: Option<bool>,
|
||||
}
|
||||
|
||||
/// An opaque search scope the frontend selects; Rust owns what it *means*.
|
||||
|
||||
@@ -25,6 +25,9 @@ pub const MIGRATIONS: &[(&str, &str)] = &[
|
||||
("018_items_is_folder", MIGRATION_018),
|
||||
("019_genres_cache", MIGRATION_019),
|
||||
("020_items_season_index", MIGRATION_020),
|
||||
("021_rebuild_items_fts", MIGRATION_021),
|
||||
("022_people_fts", MIGRATION_022),
|
||||
("023_downloads_expiry", MIGRATION_023),
|
||||
];
|
||||
|
||||
/// Initial schema migration
|
||||
@@ -728,3 +731,91 @@ CREATE INDEX IF NOT EXISTS idx_genres_scope ON genres(server_id, library_id);
|
||||
const MIGRATION_020: &str = r#"
|
||||
CREATE INDEX IF NOT EXISTS idx_items_season ON items(season_id);
|
||||
"#;
|
||||
|
||||
/// Discard and rebuild the FTS index from the `items` table.
|
||||
///
|
||||
/// Until DR-110, `save_to_cache` used `INSERT OR REPLACE INTO items`. REPLACE
|
||||
/// deletes the conflicting row and inserts a new one, but SQLite only fires
|
||||
/// `AFTER DELETE` triggers on that implicit delete when `recursive_triggers` is
|
||||
/// enabled — it is not (storage/mod.rs sets only `foreign_keys` and
|
||||
/// `journal_mode`), so `items_ad` never ran and the old index row was orphaned.
|
||||
/// Worse, `items.id` is a `TEXT PRIMARY KEY`, so the replacement row also took a
|
||||
/// *fresh rowid* and `items_ai` appended a second entry. Every catalog pass
|
||||
/// therefore left another duplicate behind, and existing installs carry one
|
||||
/// stale entry per item per sync since the database was created.
|
||||
///
|
||||
/// This was invisible in results — the `JOIN items_fts fts ON fts.rowid =
|
||||
/// i.rowid` drops rowids that no longer exist — but it degrades `MATCH`
|
||||
/// permanently, and it becomes a *correctness* problem the moment rowids are
|
||||
/// freed and reused: a new item landing on a freed rowid inherits the orphan's
|
||||
/// index entry and matches queries for the deleted item's title. The DR-110
|
||||
/// deletion sweep frees rowids, so this rebuild must run before it.
|
||||
///
|
||||
/// `'rebuild'` is the FTS5 command for exactly this: it truncates the index and
|
||||
/// repopulates it from the external content table.
|
||||
///
|
||||
/// TRACES: UR-065 | DR-110
|
||||
const MIGRATION_021: &str = r#"
|
||||
INSERT INTO items_fts(items_fts) VALUES('rebuild');
|
||||
"#;
|
||||
|
||||
/// Full-text index over `people`, mirroring `items_fts`.
|
||||
///
|
||||
/// People live in their own table (migration 009) rather than in `items`, and
|
||||
/// had no FTS index at all — so the People group UR-060 requires could only ever
|
||||
/// be filled by the server leg of search. With the local index now answering
|
||||
/// first, an actor's name has to be findable offline too.
|
||||
///
|
||||
/// TRACES: UR-065, UR-060 | DR-111
|
||||
const MIGRATION_022: &str = r#"
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS people_fts USING fts5(
|
||||
name,
|
||||
overview,
|
||||
content='people',
|
||||
content_rowid='rowid'
|
||||
);
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS people_ai AFTER INSERT ON people BEGIN
|
||||
INSERT INTO people_fts(rowid, name, overview)
|
||||
VALUES (new.rowid, new.name, new.overview);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS people_ad AFTER DELETE ON people BEGIN
|
||||
INSERT INTO people_fts(people_fts, rowid, name, overview)
|
||||
VALUES('delete', old.rowid, old.name, old.overview);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS people_au AFTER UPDATE ON people BEGIN
|
||||
INSERT INTO people_fts(people_fts, rowid, name, overview)
|
||||
VALUES('delete', old.rowid, old.name, old.overview);
|
||||
INSERT INTO people_fts(rowid, name, overview)
|
||||
VALUES (new.rowid, new.name, new.overview);
|
||||
END;
|
||||
|
||||
-- Backfill for rows cached before this index existed.
|
||||
INSERT INTO people_fts(people_fts) VALUES('rebuild');
|
||||
"#;
|
||||
|
||||
/// Give temporary downloads a life limit.
|
||||
///
|
||||
/// A cache entry is not a different kind of object from a download — it is a
|
||||
/// download with a shorter life. Modelling it as one `downloads` row with an
|
||||
/// expiry (rather than a parallel cache store) means there is a single storage
|
||||
/// accounting, a single eviction path, and no way for a cache and a download
|
||||
/// library to disagree about what is on disk.
|
||||
///
|
||||
/// `expires_at` is NULL for permanent rows, which is every row that exists
|
||||
/// today: `download_source` defaults to `'user'`, and a user's own download
|
||||
/// never expires. Only `'auto'` rows get a timestamp, and they are reclaimed by
|
||||
/// whichever comes first — the expiry passing, or LRU eviction under space
|
||||
/// pressure (DR-126).
|
||||
///
|
||||
/// TRACES: UR-071 | DR-127
|
||||
const MIGRATION_023: &str = r#"
|
||||
ALTER TABLE downloads ADD COLUMN expires_at TEXT;
|
||||
|
||||
-- Reclaim scans filter on expiry among 'auto' rows; index both so the sweep
|
||||
-- stays cheap as the cache tier grows.
|
||||
CREATE INDEX IF NOT EXISTS idx_downloads_expiry
|
||||
ON downloads(download_source, expires_at);
|
||||
"#;
|
||||
|
||||
+55
-4
@@ -238,7 +238,7 @@ async playerPlayNextEpisode(item: PlayItemRequest) : Promise<PlayerStatus> {
|
||||
* - Frontend when audio track ends via backend event - no itemId/repositoryHandle needed
|
||||
* - Android JNI callback also triggers this logic directly
|
||||
*
|
||||
* TRACES: UR-023, UR-026, UR-040 | DR-047, DR-052
|
||||
* TRACES: UR-023, UR-026, UR-040 | DR-047, DR-052, DR-129
|
||||
*/
|
||||
async playerOnPlaybackEnded(itemId: string | null, repositoryHandle: string | null) : Promise<null> {
|
||||
return await TAURI_INVOKE("player_on_playback_ended", { itemId, repositoryHandle });
|
||||
@@ -262,6 +262,23 @@ async playerReportPosition(position: number, duration: number) : Promise<null> {
|
||||
async playerReportMediaLoaded(duration: number) : Promise<null> {
|
||||
return await TAURI_INVOKE("player_report_media_loaded", { duration });
|
||||
},
|
||||
/**
|
||||
* The on-disk path for a downloaded item, for playback surfaces that resolve
|
||||
* their own source rather than going through the queue.
|
||||
*
|
||||
* The video player is the reason this exists: audio has preferred local files
|
||||
* since queue construction, but video asks the repository for a stream URL and
|
||||
* never consults `downloads`, so a downloaded film was still streamed — costing
|
||||
* bandwidth that had already been spent and failing outright when offline.
|
||||
*
|
||||
* Returns `None` when nothing is downloaded *or* the file is missing, so the
|
||||
* caller falls back to streaming.
|
||||
*
|
||||
* TRACES: UR-071 | DR-123 | UT-116
|
||||
*/
|
||||
async playerLocalMediaPath(itemId: string) : Promise<string | null> {
|
||||
return await TAURI_INVOKE("player_local_media_path", { itemId });
|
||||
},
|
||||
/**
|
||||
* Preload upcoming tracks from the queue
|
||||
* This queues background downloads for the next N tracks that aren't already downloaded
|
||||
@@ -1422,6 +1439,20 @@ async repositoryMarkFavorite(handle: string, itemId: string) : Promise<null> {
|
||||
async repositoryUnmarkFavorite(handle: string, itemId: string) : Promise<null> {
|
||||
return await TAURI_INVOKE("repository_unmark_favorite", { handle, itemId });
|
||||
},
|
||||
/**
|
||||
* Everything the viewer has favourited, across libraries, narrowed by scope.
|
||||
*
|
||||
* Two-phase like `repository_search`: the local answer returns immediately and
|
||||
* a background server pass emits `favorites-changed` when the server's set
|
||||
* differs. Without the second phase a favourite marked in another client shows
|
||||
* up only on the *second* visit to the page, since the cache-first read hands
|
||||
* back local rows and the refresh is invisible to the frontend.
|
||||
*
|
||||
* TRACES: UR-067 | DR-115, DR-120, JA-033 | UT-107
|
||||
*/
|
||||
async repositoryGetFavorites(handle: string, scope: SearchScope, options: GetItemsOptions | null) : Promise<SearchResult> {
|
||||
return await TAURI_INVOKE("repository_get_favorites", { handle, scope, options });
|
||||
},
|
||||
/**
|
||||
* Get person details
|
||||
*/
|
||||
@@ -1704,7 +1735,15 @@ storageLimit: number;
|
||||
/**
|
||||
* Only cache on WiFi
|
||||
*/
|
||||
wifiOnly: boolean }
|
||||
wifiOnly: boolean;
|
||||
/**
|
||||
* How long a temporary (`download_source = 'auto'`) download lives before
|
||||
* it is reclaimed, in hours. 0 disables expiry, leaving space pressure as
|
||||
* the only reclaim trigger.
|
||||
*
|
||||
* TRACES: UR-071 | DR-127
|
||||
*/
|
||||
temporaryTtlHours: number }
|
||||
/**
|
||||
* Cached media item returned to frontend
|
||||
*/
|
||||
@@ -1729,7 +1768,12 @@ itemsCached: number;
|
||||
/**
|
||||
* Libraries that failed to sync (e.g. server hiccup); best-effort.
|
||||
*/
|
||||
librariesFailed: number }
|
||||
librariesFailed: number;
|
||||
/**
|
||||
* Entries removed because the server no longer has them. Always 0 when any
|
||||
* library failed, since a partial crawl cannot prove an item is gone.
|
||||
*/
|
||||
itemsPruned: number }
|
||||
export type CatalogSyncStatus = {
|
||||
/**
|
||||
* RFC-3339 timestamp of the last successful sync, if any.
|
||||
@@ -1837,7 +1881,14 @@ export type GetImageRequest = { itemId: string; imageType: string; maxWidth?: nu
|
||||
/**
|
||||
* Options for querying items
|
||||
*/
|
||||
export type GetItemsOptions = { startIndex?: number | null; limit?: number | null; sortBy?: string | null; sortOrder?: string | null; includeItemTypes?: string[] | null; recursive?: boolean | null; fields?: string[] | null; genres?: string[] | null }
|
||||
export type GetItemsOptions = { startIndex?: number | null; limit?: number | null; sortBy?: string | null; sortOrder?: string | null; includeItemTypes?: string[] | null; recursive?: boolean | null; fields?: string[] | null; genres?: string[] | null;
|
||||
/**
|
||||
* Restrict the listing to favourited items. Backs the per-library
|
||||
* favourites toggle; composes with every other filter here.
|
||||
*
|
||||
* TRACES: UR-067 | DR-116 | UT-104
|
||||
*/
|
||||
favoritesOnly?: boolean | null }
|
||||
/**
|
||||
* Image options
|
||||
*/
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// NO direct HTTP calls - everything routes through Rust backend
|
||||
|
||||
import { commands } from "./bindings";
|
||||
import type { JRayActor, DownloadDiskUsage } from "./bindings";
|
||||
import type { JRayActor, DownloadDiskUsage, SearchScope } from "./bindings";
|
||||
import type { QualityPreset } from "./quality-presets";
|
||||
import type {
|
||||
Library,
|
||||
@@ -311,6 +311,20 @@ export class RepositoryClient {
|
||||
await commands.repositoryUnmarkFavorite(this.ensureHandle(), itemId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything favourited, across libraries, narrowed by an opaque scope the
|
||||
* backend expands into item types. The frontend never names a Jellyfin type
|
||||
* here — see docs/specs/scoped-search-boundary.md.
|
||||
*
|
||||
* Resolves with the local answer; a later `favorites-changed` event reports
|
||||
* ids the server disagreed with.
|
||||
*
|
||||
* TRACES: UR-067 | DR-115
|
||||
*/
|
||||
async getFavorites(scope: SearchScope, options?: GetItemsOptions): Promise<SearchResult> {
|
||||
return commands.repositoryGetFavorites(this.ensureHandle(), scope, options ?? null);
|
||||
}
|
||||
|
||||
// ===== Person Methods (via Rust) =====
|
||||
|
||||
async getPerson(personId: string): Promise<MediaItem> {
|
||||
|
||||
@@ -1,27 +1,60 @@
|
||||
<!-- TRACES: UR-017, UR-068 | DR-021, DR-119 -->
|
||||
<script lang="ts">
|
||||
import { toggleFavorite } from "$lib/services/favorites";
|
||||
import { haptics } from "$lib/utils/haptics";
|
||||
import { toast } from "$lib/stores/toast";
|
||||
import { favoriteOverrides } from "$lib/stores/favorites";
|
||||
|
||||
interface Props {
|
||||
itemId: string;
|
||||
isFavorite?: boolean;
|
||||
size?: "sm" | "md" | "lg";
|
||||
className?: string;
|
||||
/**
|
||||
* "button" (default) is the standalone control used in header/hero rows;
|
||||
* "overlay" is the artwork corner variant used on cards, which needs its
|
||||
* own scrim to stay legible over any poster.
|
||||
*/
|
||||
variant?: "button" | "overlay";
|
||||
/** Stop the click reaching a parent card/row that would navigate or play. */
|
||||
stopPropagation?: boolean;
|
||||
}
|
||||
|
||||
let { itemId, isFavorite = $bindable(false), size = "md", className = "" }: Props = $props();
|
||||
let {
|
||||
itemId,
|
||||
isFavorite = $bindable(false),
|
||||
size = "md",
|
||||
className = "",
|
||||
variant = "button",
|
||||
stopPropagation = false,
|
||||
}: Props = $props();
|
||||
|
||||
let isLoading = $state(false);
|
||||
let isAnimating = $state(false);
|
||||
|
||||
// A toggle from any other surface (or the backend's `favorites-changed`
|
||||
// refresh) wins over the prop we were mounted with — otherwise a heart tapped
|
||||
// on a card would still read empty on the detail page behind it.
|
||||
$effect(() => {
|
||||
const override = $favoriteOverrides.get(itemId);
|
||||
if (override !== undefined && override !== isFavorite) {
|
||||
isFavorite = override;
|
||||
}
|
||||
});
|
||||
|
||||
const sizeClasses = {
|
||||
sm: "w-4 h-4",
|
||||
md: "w-5 h-5",
|
||||
lg: "w-6 h-6",
|
||||
};
|
||||
|
||||
async function handleToggle() {
|
||||
async function handleToggle(event: MouseEvent) {
|
||||
// On a card the heart sits inside a clickable tile; without this, hearting
|
||||
// an item would also open (or play) it.
|
||||
if (stopPropagation) {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
}
|
||||
if (isLoading) return;
|
||||
|
||||
isLoading = true;
|
||||
@@ -55,8 +88,15 @@
|
||||
|
||||
// Compute button classes
|
||||
const buttonClass = $derived.by(() => {
|
||||
const baseClasses = "p-2 rounded-full transition-all";
|
||||
const colorClasses = isFavorite ? "text-red-500 hover:text-red-400" : "text-gray-400 hover:text-white";
|
||||
const baseClasses =
|
||||
variant === "overlay"
|
||||
? "p-1.5 rounded-full transition-all bg-black/50 backdrop-blur-sm hover:bg-black/70"
|
||||
: "p-2 rounded-full transition-all";
|
||||
const colorClasses = isFavorite
|
||||
? "text-red-500 hover:text-red-400"
|
||||
: variant === "overlay"
|
||||
? "text-white/80 hover:text-white"
|
||||
: "text-gray-400 hover:text-white";
|
||||
const loadingClasses = isLoading ? "opacity-50 cursor-wait" : "";
|
||||
return `${baseClasses} ${colorClasses} ${loadingClasses} ${className}`.trim();
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
import LibraryGrid from "./LibraryGrid.svelte";
|
||||
import TrackList from "./TrackList.svelte";
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import FavoriteButton from "$lib/components/FavoriteButton.svelte";
|
||||
import { favoriteOverrides, resolveIsFavorite } from "$lib/stores/favorites";
|
||||
|
||||
interface Props {
|
||||
artist: MediaItem;
|
||||
@@ -126,7 +128,15 @@
|
||||
{/if}
|
||||
|
||||
<!-- Artist Name -->
|
||||
<h1 class="text-4xl font-bold text-white mb-4">{artist.name}</h1>
|
||||
<div class="flex items-center gap-2 mb-4">
|
||||
<h1 class="text-4xl font-bold text-white">{artist.name}</h1>
|
||||
<!-- TRACES: UR-068 | DR-119 -->
|
||||
<FavoriteButton
|
||||
itemId={artist.id}
|
||||
isFavorite={resolveIsFavorite(artist, $favoriteOverrides)}
|
||||
size="lg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Bio -->
|
||||
{#if artist.overview}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
import { truncateMiddle } from "$lib/utils/truncateMiddle";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import FavoriteButton from "$lib/components/FavoriteButton.svelte";
|
||||
import { favoriteOverrides, resolveIsFavorite } from "$lib/stores/favorites";
|
||||
import {
|
||||
isCurrentEpisode as isSameEpisode,
|
||||
adjacentEpisodes as computeAdjacent,
|
||||
@@ -166,8 +168,8 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Play button -->
|
||||
<div class="pt-2">
|
||||
<!-- Play button + favourite. TRACES: UR-068 | DR-119 -->
|
||||
<div class="pt-2 flex items-center gap-3">
|
||||
<button
|
||||
onclick={handlePlay}
|
||||
class="px-8 py-3 bg-white text-black hover:bg-white/90 rounded-lg font-semibold text-lg flex items-center gap-2 transition-colors"
|
||||
@@ -177,6 +179,11 @@
|
||||
</svg>
|
||||
{progress > 0 && progress < 95 ? "Resume" : "Play"}
|
||||
</button>
|
||||
<FavoriteButton
|
||||
itemId={episode.id}
|
||||
isFavorite={resolveIsFavorite(episode, $favoriteOverrides)}
|
||||
size="lg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- TRACES: UR-007, UR-029, UR-030 | DR-007, DR-032, DR-033 -->
|
||||
<!-- TRACES: UR-007, UR-029, UR-030, UR-067 | DR-007, DR-032, DR-033, DR-116 -->
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
@@ -56,6 +56,7 @@
|
||||
let gridWrapper = $state<HTMLDivElement | null>(null);
|
||||
let searchQuery = $state("");
|
||||
let debouncedSearchQuery = $state("");
|
||||
let favoritesOnly = $state(false);
|
||||
let sortBy = $state<string>("");
|
||||
let sortOrder = $state<"Ascending" | "Descending">("Ascending");
|
||||
let searchTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -140,6 +141,9 @@
|
||||
sortOrder,
|
||||
recursive: true,
|
||||
limit: 10000,
|
||||
// Narrows the listing in place; the backend owns what "favourite"
|
||||
// resolves to online vs offline. TRACES: UR-067 | DR-116
|
||||
favoritesOnly: favoritesOnly ? true : undefined,
|
||||
});
|
||||
items = excludePodcasts(result.items);
|
||||
}
|
||||
@@ -154,6 +158,12 @@
|
||||
searchQuery = query;
|
||||
}
|
||||
|
||||
/// TRACES: UR-067 | DR-116
|
||||
function toggleFavoritesOnly() {
|
||||
favoritesOnly = !favoritesOnly;
|
||||
loadItems();
|
||||
}
|
||||
|
||||
// Debounce search input (300ms delay) - skip initial mount to avoid duplicate load
|
||||
$effect(() => {
|
||||
const _query = searchQuery; // track for reactivity
|
||||
@@ -266,6 +276,33 @@
|
||||
<SearchBar value={searchQuery} placeholder={searchPlaceholder} onInput={handleSearch} />
|
||||
</div>
|
||||
|
||||
<!-- Favourites filter. Session-scoped on purpose: a persisted filter that
|
||||
hides most of a library reads as data loss on the next launch
|
||||
(ux-flows §5C.2). Hidden while searching, which has no favourites
|
||||
filter of its own. TRACES: UR-067 | DR-116 -->
|
||||
{#if !debouncedSearchQuery.trim()}
|
||||
<button
|
||||
onclick={toggleFavoritesOnly}
|
||||
aria-pressed={favoritesOnly}
|
||||
class="px-3 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-colors
|
||||
{favoritesOnly
|
||||
? 'bg-[var(--color-jellyfin)] text-white'
|
||||
: 'bg-[var(--color-surface)] text-gray-400 hover:text-white'}"
|
||||
title={favoritesOnly ? "Showing favourites only" : "Show favourites only"}
|
||||
>
|
||||
<svg
|
||||
class="w-4 h-4"
|
||||
fill={favoritesOnly ? "currentColor" : "none"}
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
|
||||
</svg>
|
||||
Favourites
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<!-- Sort (only show if there are sort options) -->
|
||||
{#if config.sortOptions.length > 0}
|
||||
<SortButtonGroup options={config.sortOptions} selected={sortBy} onSelect={handleSort} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- TRACES: UR-051, UR-052 | DR-068, DR-078 -->
|
||||
<!-- TRACES: UR-051, UR-052, UR-068 | DR-068, DR-078, DR-119 -->
|
||||
<script lang="ts">
|
||||
import type { MediaItem, Library } from "$lib/api/types";
|
||||
import { truncateMiddle } from "$lib/utils/truncateMiddle";
|
||||
@@ -7,6 +7,8 @@
|
||||
import { showServerCatalog } from "$lib/services/offlineCatalog";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import FavoriteButton from "$lib/components/FavoriteButton.svelte";
|
||||
import { favoriteOverrides, resolveIsFavorite } from "$lib/stores/favorites";
|
||||
|
||||
interface Props {
|
||||
item: MediaItem | Library;
|
||||
@@ -37,9 +39,15 @@
|
||||
* TRACES: UR-058 | DR-087
|
||||
*/
|
||||
onLongPress?: () => void;
|
||||
/**
|
||||
* Show the favourite heart on the artwork. On by default for media items;
|
||||
* surfaces that are not about the item itself can opt out.
|
||||
* TRACES: UR-068 | DR-119
|
||||
*/
|
||||
showFavorite?: boolean;
|
||||
}
|
||||
|
||||
let { item, size = "medium", showProgress = false, showDownloadStatus = true, sizeLabel, downloadedBadge, onRemove, onclick, onLongPress }: Props = $props();
|
||||
let { item, size = "medium", showProgress = false, showDownloadStatus = true, sizeLabel, downloadedBadge, onRemove, onclick, onLongPress, showFavorite = true }: Props = $props();
|
||||
|
||||
// Long-press detection. We arm a timer on pointerdown; if it fires before the
|
||||
// pointer is released (or moves too far), we treat it as a long press and set a
|
||||
@@ -120,6 +128,13 @@
|
||||
isMediaItem && !$isConnected && $showServerCatalog && !isDownloaded && !isActivelyDownloading
|
||||
);
|
||||
|
||||
// The heart is about an item, so libraries never get one, and a greyed
|
||||
// server-only card has nothing actionable to offer. TRACES: UR-068 | DR-119
|
||||
const showHeart = $derived(showFavorite && isMediaItem && !isServerOnly);
|
||||
const isFavorited = $derived(
|
||||
isMediaItem ? resolveIsFavorite(item as MediaItem, $favoriteOverrides) : false
|
||||
);
|
||||
|
||||
let queueError = $state<string | null>(null);
|
||||
|
||||
// Queue this item for download on next reconnect. Offline, this just persists
|
||||
@@ -250,12 +265,34 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Played indicator -->
|
||||
{#if "userData" in item && item.userData?.isPlayed}
|
||||
<div class="absolute top-2 right-2">
|
||||
<svg class="w-5 h-5 text-[var(--color-jellyfin)]" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
|
||||
</svg>
|
||||
<!-- Top-right status stack: played tick, then the favourite heart. Grouped
|
||||
so the two never land on the same pixels when both apply. -->
|
||||
{#if ("userData" in item && item.userData?.isPlayed) || showHeart}
|
||||
<div class="absolute top-2 right-2 flex flex-col items-end gap-1">
|
||||
{#if "userData" in item && item.userData?.isPlayed}
|
||||
<svg class="w-5 h-5 text-[var(--color-jellyfin)]" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
|
||||
</svg>
|
||||
{/if}
|
||||
{#if showHeart}
|
||||
<!-- Always visible on touch (no hover to reveal it); on pointer
|
||||
devices an unfavourited heart stays out of the way until the card
|
||||
is hovered or focused. A favourited one is always shown — it is
|
||||
state, not an affordance. TRACES: UR-068 | DR-119 -->
|
||||
<div
|
||||
class="transition-opacity {isFavorited
|
||||
? ''
|
||||
: 'opacity-100 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/card:opacity-100 [@media(hover:hover)]:group-focus-within/card:opacity-100'}"
|
||||
>
|
||||
<FavoriteButton
|
||||
itemId={item.id}
|
||||
isFavorite={isFavorited}
|
||||
size="sm"
|
||||
variant="overlay"
|
||||
stopPropagation
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
import { toast } from "$lib/stores/toast";
|
||||
import TrackList from "./TrackList.svelte";
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import FavoriteButton from "$lib/components/FavoriteButton.svelte";
|
||||
import { favoriteOverrides } from "$lib/stores/favorites";
|
||||
import { formatDuration } from "$lib/utils/duration";
|
||||
|
||||
interface Props {
|
||||
@@ -214,6 +216,13 @@
|
||||
</svg>
|
||||
Shuffle
|
||||
</button>
|
||||
<!-- TRACES: UR-068 | DR-119 -->
|
||||
<FavoriteButton
|
||||
itemId={playlist.id}
|
||||
isFavorite={$favoriteOverrides.get(playlist.id) ?? false}
|
||||
size="lg"
|
||||
className="self-center"
|
||||
/>
|
||||
<button
|
||||
onclick={() => showDeleteConfirm = true}
|
||||
class="px-4 py-2 bg-[var(--color-surface)] hover:bg-red-900/50 text-red-400 hover:text-red-300 rounded-lg font-medium flex items-center gap-2 transition-colors"
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { resolveVideoSource } from "./localSource";
|
||||
|
||||
// A stand-in for Tauri's convertFileSrc, so the module stays pure.
|
||||
const toAssetUrl = (p: string) => `asset://localhost/${encodeURIComponent(p)}`;
|
||||
|
||||
describe("resolveVideoSource", () => {
|
||||
it("plays the downloaded file when one exists", () => {
|
||||
const decision = resolveVideoSource({
|
||||
localPath: "/home/u/.local/share/jellytau/movie.mp4",
|
||||
remoteUrl: "https://server/Videos/abc/master.m3u8",
|
||||
remoteNeedsTranscoding: true,
|
||||
toAssetUrl,
|
||||
});
|
||||
|
||||
expect(decision.isLocal).toBe(true);
|
||||
expect(decision.url).toBe(toAssetUrl("/home/u/.local/share/jellytau/movie.mp4"));
|
||||
});
|
||||
|
||||
it("never marks a local file as needing transcoding, even when the remote did", () => {
|
||||
// The transcoded path re-requests a whole new stream URL on every seek.
|
||||
// A local file seeks natively; sending it down that route would ask the
|
||||
// server for a stream we deliberately avoided.
|
||||
const decision = resolveVideoSource({
|
||||
localPath: "/downloads/film.mkv",
|
||||
remoteUrl: "https://server/Videos/abc/master.m3u8",
|
||||
remoteNeedsTranscoding: true,
|
||||
toAssetUrl,
|
||||
});
|
||||
|
||||
expect(decision.needsTranscoding).toBe(false);
|
||||
});
|
||||
|
||||
it("streams when nothing is downloaded, preserving the transcoding flag", () => {
|
||||
const decision = resolveVideoSource({
|
||||
localPath: null,
|
||||
remoteUrl: "https://server/Videos/abc/master.m3u8",
|
||||
remoteNeedsTranscoding: true,
|
||||
toAssetUrl,
|
||||
});
|
||||
|
||||
expect(decision).toEqual({
|
||||
url: "https://server/Videos/abc/master.m3u8",
|
||||
needsTranscoding: true,
|
||||
isLocal: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("streams a direct-play remote without claiming it transcodes", () => {
|
||||
const decision = resolveVideoSource({
|
||||
localPath: null,
|
||||
remoteUrl: "https://server/Videos/abc/stream.mp4",
|
||||
remoteNeedsTranscoding: false,
|
||||
toAssetUrl,
|
||||
});
|
||||
|
||||
expect(decision.needsTranscoding).toBe(false);
|
||||
expect(decision.isLocal).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to streaming for a blank path rather than building a dead asset URL", () => {
|
||||
for (const localPath of ["", " "]) {
|
||||
const decision = resolveVideoSource({
|
||||
localPath,
|
||||
remoteUrl: "https://server/stream",
|
||||
remoteNeedsTranscoding: false,
|
||||
toAssetUrl,
|
||||
});
|
||||
expect(decision.isLocal).toBe(false);
|
||||
expect(decision.url).toBe("https://server/stream");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Choosing between a downloaded file and a server stream for video playback.
|
||||
*
|
||||
* Audio has preferred local files since the queue is built (the Rust queue
|
||||
* resolves `MediaSource::Local`), but video asks the repository for a stream URL
|
||||
* and never consults `downloads` — so a downloaded film was streamed anyway,
|
||||
* spending bandwidth that had already been spent and failing outright offline.
|
||||
*
|
||||
* Pure so it can be unit-tested: the component only supplies the two inputs and
|
||||
* the asset-URL converter.
|
||||
*
|
||||
* TRACES: UR-071 | DR-123 | UT-118
|
||||
*/
|
||||
|
||||
export interface VideoSourceInputs {
|
||||
/** Absolute on-disk path of a completed download, or null to stream. */
|
||||
localPath: string | null;
|
||||
/** Stream URL the repository resolved (already transcoded if it had to be). */
|
||||
remoteUrl: string;
|
||||
/** Whether the *remote* stream is a transcode. */
|
||||
remoteNeedsTranscoding: boolean;
|
||||
/** Usually Tauri's `convertFileSrc`; injected so this module stays pure. */
|
||||
toAssetUrl: (path: string) => string;
|
||||
}
|
||||
|
||||
export interface VideoSourceDecision {
|
||||
/** What to hand the `<video>` element. */
|
||||
url: string;
|
||||
/**
|
||||
* Local files are never transcodes, so this is always false for them. It
|
||||
* matters because the transcoded path re-requests a whole new stream URL on
|
||||
* every seek; a local file seeks natively and must not go down that route.
|
||||
*/
|
||||
needsTranscoding: boolean;
|
||||
/** True when playing from disk — for logging and the offline badge. */
|
||||
isLocal: boolean;
|
||||
}
|
||||
|
||||
export function resolveVideoSource(inputs: VideoSourceInputs): VideoSourceDecision {
|
||||
const { localPath, remoteUrl, remoteNeedsTranscoding, toAssetUrl } = inputs;
|
||||
|
||||
// Treat blank/whitespace paths as absent — a malformed `downloads` row must
|
||||
// not produce an asset URL pointing at nothing.
|
||||
if (localPath && localPath.trim() !== "") {
|
||||
return { url: toAssetUrl(localPath), needsTranscoding: false, isLocal: true };
|
||||
}
|
||||
|
||||
return { url: remoteUrl, needsTranscoding: remoteNeedsTranscoding, isLocal: false };
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
// Favorites service - Handles toggling favorite status with optimistic updates
|
||||
// TRACES: UR-017 | DR-021
|
||||
// TRACES: UR-017, UR-068 | DR-021, DR-119
|
||||
|
||||
import { get } from "svelte/store";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { isConnected } from "$lib/stores/connectivity";
|
||||
import { setFavorite } from "$lib/stores/favorites";
|
||||
|
||||
/**
|
||||
* Toggle the favorite status of an item.
|
||||
@@ -33,6 +34,10 @@ export async function toggleFavorite(
|
||||
// 1. Update local database first (optimistic update)
|
||||
await commands.storageToggleFavorite(userId, itemId, newIsFavorite);
|
||||
|
||||
// Publish to every mounted view at once, so the heart on a card, the detail
|
||||
// page and the Favourites grid never disagree. TRACES: UR-068 | DR-119
|
||||
setFavorite(itemId, newIsFavorite);
|
||||
|
||||
// 2. Sync to Jellyfin server.
|
||||
//
|
||||
// Only attempt this when we're actually connected. When offline, the server
|
||||
|
||||
@@ -66,9 +66,14 @@ function currentHandle(): string | null {
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk every library and cache the full catalog. Best-effort and non-blocking:
|
||||
* safe to call on startup (while online) and on reconnect. No-ops if not
|
||||
* connected or a sync is already running.
|
||||
* 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;
|
||||
@@ -124,6 +129,8 @@ export async function refreshSyncStatus(): Promise<void> {
|
||||
*/
|
||||
export async function onReconnected(): Promise<void> {
|
||||
await resumeQueued();
|
||||
// Fire-and-forget: don't block reconnection handling on a potentially long walk.
|
||||
void syncCatalog();
|
||||
// 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.
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ function makeConfig(overrides: Partial<CacheConfig> = {}): CacheConfig {
|
||||
albumAffinityThreshold: 0.75,
|
||||
storageLimit: 2 * 1024 * 1024 * 1024,
|
||||
wifiOnly: false,
|
||||
temporaryTtlHours: 24 * 7,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -177,14 +178,7 @@ describe("preload service", () => {
|
||||
});
|
||||
|
||||
it("should support all config options", async () => {
|
||||
const config = {
|
||||
queuePrecacheEnabled: true,
|
||||
queuePrecacheCount: 5,
|
||||
albumAffinityEnabled: false,
|
||||
albumAffinityThreshold: 0.75,
|
||||
storageLimit: 2 * 1024 * 1024 * 1024,
|
||||
wifiOnly: true,
|
||||
};
|
||||
const config = makeConfig({ wifiOnly: true, albumAffinityEnabled: false });
|
||||
|
||||
await expect(updateCacheConfig(config)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -84,19 +84,10 @@ class SyncService {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a favorite toggle
|
||||
* Also updates local state immediately
|
||||
*/
|
||||
async queueFavorite(itemId: string, isFavorite: boolean): Promise<number> {
|
||||
// Update local state first
|
||||
await commands.storageToggleFavorite(auth.getUserId() ?? "", itemId, isFavorite);
|
||||
|
||||
return this.queueMutation(
|
||||
isFavorite ? "mark_favorite" : "unmark_favorite",
|
||||
itemId
|
||||
);
|
||||
}
|
||||
// NOTE: `queueFavorite` is gone. Favourites are drained by Rust on the
|
||||
// `connectivity:reconnected` signal (DR-120) — the local write already sets
|
||||
// `pending_sync`, and a second queue here would push the same change twice.
|
||||
// See src-tauri/src/commands/favorites.rs.
|
||||
|
||||
/**
|
||||
* Queue playback progress update
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// TRACES: UR-067, UR-068 | DR-117, DR-119 | UT-105, UT-106
|
||||
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { get } from "svelte/store";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import {
|
||||
favoriteOverrides,
|
||||
setFavorite,
|
||||
clearFavorite,
|
||||
clearAllFavorites,
|
||||
resolveIsFavorite,
|
||||
isFavoriteNow,
|
||||
retainFavorites,
|
||||
} from "./favorites";
|
||||
|
||||
function item(id: string, isFavorite?: boolean): MediaItem {
|
||||
return {
|
||||
id,
|
||||
name: `Item ${id}`,
|
||||
type: "Movie",
|
||||
kind: "movie",
|
||||
isFolder: false,
|
||||
serverId: "s1",
|
||||
userData: isFavorite === undefined ? undefined : { isFavorite },
|
||||
} as unknown as MediaItem;
|
||||
}
|
||||
|
||||
describe("favorites store", () => {
|
||||
beforeEach(() => clearAllFavorites());
|
||||
|
||||
describe("resolveIsFavorite (UT-105)", () => {
|
||||
it("falls back to the server's userData when nothing was toggled here", () => {
|
||||
expect(resolveIsFavorite(item("a", true), new Map())).toBe(true);
|
||||
expect(resolveIsFavorite(item("a", false), new Map())).toBe(false);
|
||||
});
|
||||
|
||||
it("treats an item with no userData as not favourited", () => {
|
||||
expect(resolveIsFavorite(item("a"), new Map())).toBe(false);
|
||||
});
|
||||
|
||||
it("lets a session override win over userData", () => {
|
||||
// The whole point: after tapping the heart on a card, the item object
|
||||
// still carries the server's stale value until the next fetch.
|
||||
expect(resolveIsFavorite(item("a", false), new Map([["a", true]]))).toBe(true);
|
||||
expect(resolveIsFavorite(item("a", true), new Map([["a", false]]))).toBe(false);
|
||||
});
|
||||
|
||||
it("is false for a missing item rather than throwing", () => {
|
||||
expect(resolveIsFavorite(null, new Map())).toBe(false);
|
||||
expect(resolveIsFavorite(undefined, new Map())).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("overrides", () => {
|
||||
it("publishes a toggle to subscribers", () => {
|
||||
setFavorite("a", true);
|
||||
expect(get(favoriteOverrides).get("a")).toBe(true);
|
||||
expect(isFavoriteNow(item("a", false))).toBe(true);
|
||||
|
||||
setFavorite("a", false);
|
||||
expect(isFavoriteNow(item("a", true))).toBe(false);
|
||||
});
|
||||
|
||||
it("clearing an override hands authority back to the item's userData", () => {
|
||||
setFavorite("a", false);
|
||||
expect(isFavoriteNow(item("a", true))).toBe(false);
|
||||
|
||||
clearFavorite("a");
|
||||
expect(isFavoriteNow(item("a", true))).toBe(true);
|
||||
});
|
||||
|
||||
it("replaces the map so Svelte sees a new reference", () => {
|
||||
const before = get(favoriteOverrides);
|
||||
setFavorite("a", true);
|
||||
expect(get(favoriteOverrides)).not.toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe("retainFavorites (UT-106)", () => {
|
||||
it("drops an item un-favourited during this session", () => {
|
||||
const items = [item("a", true), item("b", true)];
|
||||
const kept = retainFavorites(items, new Map([["a", false]]));
|
||||
expect(kept.map((i) => i.id)).toEqual(["b"]);
|
||||
});
|
||||
|
||||
it("keeps everything when nothing was toggled", () => {
|
||||
const items = [item("a", true), item("b", true)];
|
||||
expect(retainFavorites(items, new Map())).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("keeps an item favourited during this session even if the server said otherwise", () => {
|
||||
const items = [item("a", false)];
|
||||
expect(retainFavorites(items, new Map([["a", true]]))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("drops items the server never marked as favourites", () => {
|
||||
// A listing fetched with a stale scope should not keep non-favourites.
|
||||
expect(retainFavorites([item("a")], new Map())).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
// Favourites overlay — in-session heart state shared across every surface.
|
||||
//
|
||||
// The durable record lives in Rust (local `user_data` + the Jellyfin server).
|
||||
// This store holds only what the *current session* has changed, so a heart
|
||||
// tapped on a card is reflected on the detail page and the item vanishes from
|
||||
// the Favourites grid without anyone refetching. It is view state, not truth.
|
||||
//
|
||||
// TRACES: UR-068 | DR-119 | UT-105
|
||||
|
||||
import { derived, get, writable } from "svelte/store";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
|
||||
/** Item id → favourite state set during this session. */
|
||||
const overrides = writable<Map<string, boolean>>(new Map());
|
||||
|
||||
export const favoriteOverrides = { subscribe: overrides.subscribe };
|
||||
|
||||
/**
|
||||
* Record a favourite state locally so every mounted view agrees immediately.
|
||||
* Called by the toggle service after the optimistic local write.
|
||||
*/
|
||||
export function setFavorite(itemId: string, isFavorite: boolean): void {
|
||||
overrides.update((map) => {
|
||||
const next = new Map(map);
|
||||
next.set(itemId, isFavorite);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget a session override, so the item's own `userData` is authoritative
|
||||
* again. Used when the backend reports the server's state changed underneath
|
||||
* us (`favorites-changed`) — the fresh fetch that follows carries the truth.
|
||||
*/
|
||||
export function clearFavorite(itemId: string): void {
|
||||
overrides.update((map) => {
|
||||
if (!map.has(itemId)) return map;
|
||||
const next = new Map(map);
|
||||
next.delete(itemId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
export function clearAllFavorites(): void {
|
||||
overrides.set(new Map());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolution order: a session override wins, then the item's own server-sent
|
||||
* `userData`, then "not favourited".
|
||||
*
|
||||
* The override has to win, or tapping the heart on a card would flip back the
|
||||
* moment the (unchanged) item object re-rendered.
|
||||
*
|
||||
* TRACES: UR-068 | DR-119 | UT-105
|
||||
*/
|
||||
export function resolveIsFavorite(
|
||||
item: Pick<MediaItem, "id" | "userData"> | null | undefined,
|
||||
overrideMap: Map<string, boolean>
|
||||
): boolean {
|
||||
if (!item) return false;
|
||||
const override = overrideMap.get(item.id);
|
||||
if (override !== undefined) return override;
|
||||
return item.userData?.isFavorite ?? false;
|
||||
}
|
||||
|
||||
/** Non-reactive read, for call sites outside a component. */
|
||||
export function isFavoriteNow(item: Pick<MediaItem, "id" | "userData">): boolean {
|
||||
return resolveIsFavorite(item, get(overrides));
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the items a listing should no longer show once un-favourited.
|
||||
*
|
||||
* Pure so it can be unit-tested without mounting the page: un-hearting on the
|
||||
* Favourites grid must remove the card, while a *newly* favourited item is
|
||||
* left alone (it belongs to whatever scope the caller fetched).
|
||||
*
|
||||
* TRACES: UR-067 | DR-117, DR-119 | UT-106
|
||||
*/
|
||||
export function retainFavorites<T extends Pick<MediaItem, "id" | "userData">>(
|
||||
items: T[],
|
||||
overrideMap: Map<string, boolean>
|
||||
): T[] {
|
||||
return items.filter((item) => resolveIsFavorite(item, overrideMap));
|
||||
}
|
||||
|
||||
/** Count of items still favourited, for "hide the row when empty" decisions. */
|
||||
export const hasOverrides = derived(overrides, ($o) => $o.size > 0);
|
||||
+23
-1
@@ -1,5 +1,5 @@
|
||||
// Home screen data store - featured items, continue watching, recently added
|
||||
// TRACES: UR-023, UR-024, UR-034, UR-059 | DR-026, DR-027, DR-038, DR-039, DR-089
|
||||
// TRACES: UR-023, UR-024, UR-034, UR-059, UR-067 | DR-026, DR-027, DR-038, DR-039, DR-089, DR-118
|
||||
import { writable, derived } from "svelte/store";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { auth } from "./auth";
|
||||
@@ -12,6 +12,10 @@ interface HomeState {
|
||||
latestItems: MediaItem[];
|
||||
recentlyPlayedAudio: MediaItem[];
|
||||
resumeMovies: MediaItem[];
|
||||
/** Favourites per scope. Empty rows are not rendered. TRACES: UR-067 | DR-118 */
|
||||
favoriteMovies: MediaItem[];
|
||||
favoriteShows: MediaItem[];
|
||||
favoriteMusic: MediaItem[];
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
@@ -24,6 +28,9 @@ function createHomeStore() {
|
||||
latestItems: [],
|
||||
recentlyPlayedAudio: [],
|
||||
resumeMovies: [],
|
||||
favoriteMovies: [],
|
||||
favoriteShows: [],
|
||||
favoriteMusic: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
};
|
||||
@@ -46,6 +53,11 @@ function createHomeStore() {
|
||||
repo.getLatestItems("", 16),
|
||||
repo.getRecentlyPlayedAudio(12), // Backend now handles intelligent grouping
|
||||
repo.getResumeMovies(12),
|
||||
// Favourites, one request per row. The scope is opaque — Rust decides
|
||||
// which item types it covers. TRACES: UR-067 | DR-118
|
||||
repo.getFavorites("movies", { limit: 20 }),
|
||||
repo.getFavorites("tv", { limit: 20 }),
|
||||
repo.getFavorites("music", { limit: 20 }),
|
||||
]);
|
||||
|
||||
const valueOr = <T>(i: number, fallback: T): T =>
|
||||
@@ -60,6 +72,10 @@ function createHomeStore() {
|
||||
const latest = valueOr(2, [] as typeof initialState.latestItems);
|
||||
const recentAudio = valueOr(3, [] as typeof initialState.recentlyPlayedAudio);
|
||||
const resumeMovies = valueOr(4, [] as typeof initialState.resumeMovies);
|
||||
const emptyResult = { items: [] as MediaItem[], totalRecordCount: 0 };
|
||||
const favoriteMovies = valueOr(5, emptyResult).items;
|
||||
const favoriteShows = valueOr(6, emptyResult).items;
|
||||
const favoriteMusic = valueOr(7, emptyResult).items;
|
||||
|
||||
// Use resume items or latest as hero items
|
||||
const hero = resume.length >= 3 ? resume.slice(0, 5) : latest.slice(0, 5);
|
||||
@@ -72,6 +88,9 @@ function createHomeStore() {
|
||||
latestItems: latest,
|
||||
recentlyPlayedAudio: recentAudio,
|
||||
resumeMovies: resumeMovies,
|
||||
favoriteMovies,
|
||||
favoriteShows,
|
||||
favoriteMusic,
|
||||
isLoading: false,
|
||||
}));
|
||||
} catch (error) {
|
||||
@@ -101,4 +120,7 @@ export const nextUpItems = derived(home, $home => $home.nextUpItems);
|
||||
export const latestItems = derived(home, $home => $home.latestItems);
|
||||
export const recentlyPlayedAudio = derived(home, $home => $home.recentlyPlayedAudio);
|
||||
export const resumeMovies = derived(home, $home => $home.resumeMovies);
|
||||
export const favoriteMovies = derived(home, $home => $home.favoriteMovies);
|
||||
export const favoriteShows = derived(home, $home => $home.favoriteShows);
|
||||
export const favoriteMusic = derived(home, $home => $home.favoriteMusic);
|
||||
export const isHomeLoading = derived(home, $home => $home.isLoading);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// TRACES: UR-067 | DR-117
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
FAVORITE_SCOPES,
|
||||
FAVORITE_SCOPE_LABELS,
|
||||
resolveFavoritesScope,
|
||||
favoritesRouteUrl,
|
||||
emptyStateMessage,
|
||||
} from "./favoritesView";
|
||||
|
||||
describe("favoritesView", () => {
|
||||
describe("resolveFavoritesScope", () => {
|
||||
it("round-trips every offered tab", () => {
|
||||
for (const scope of FAVORITE_SCOPES) {
|
||||
expect(resolveFavoritesScope(scope)).toBe(scope);
|
||||
}
|
||||
});
|
||||
|
||||
it("defaults to All for a missing param", () => {
|
||||
expect(resolveFavoritesScope(null)).toBe("all");
|
||||
expect(resolveFavoritesScope(undefined)).toBe("all");
|
||||
expect(resolveFavoritesScope("")).toBe("all");
|
||||
});
|
||||
|
||||
it("defaults to All for a stale or hand-edited param rather than blanking the page", () => {
|
||||
expect(resolveFavoritesScope("books")).toBe("all");
|
||||
expect(resolveFavoritesScope("MOVIES")).toBe("all");
|
||||
});
|
||||
});
|
||||
|
||||
describe("favoritesRouteUrl", () => {
|
||||
it("omits the default scope so the base URL stays clean", () => {
|
||||
expect(favoritesRouteUrl("all")).toBe("/library/favorites");
|
||||
});
|
||||
|
||||
it("addresses every other tab explicitly, and round-trips through resolve", () => {
|
||||
for (const scope of FAVORITE_SCOPES) {
|
||||
const url = favoritesRouteUrl(scope);
|
||||
const param = new URL(url, "http://x").searchParams.get("scope");
|
||||
expect(resolveFavoritesScope(param)).toBe(scope);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("labels every scope, using the app's vocabulary rather than Jellyfin's", () => {
|
||||
for (const scope of FAVORITE_SCOPES) {
|
||||
expect(FAVORITE_SCOPE_LABELS[scope]).toBeTruthy();
|
||||
}
|
||||
// "tv" is the backend's scope name; users see "Shows".
|
||||
expect(FAVORITE_SCOPE_LABELS.tv).toBe("Shows");
|
||||
});
|
||||
|
||||
it("gives each tab its own empty state, telling the user what to do next", () => {
|
||||
for (const scope of FAVORITE_SCOPES) {
|
||||
expect(emptyStateMessage(scope)).toContain("heart");
|
||||
}
|
||||
expect(emptyStateMessage("movies")).toContain("movies");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
// Favourites page presentation helpers — which scopes are offered as tabs, what
|
||||
// they are called, and how a tab is addressed in the URL.
|
||||
//
|
||||
// The *labels and tab order* are presentation and live here. What each scope
|
||||
// MEANS in Jellyfin item types is domain vocabulary and lives in Rust
|
||||
// (`SearchScope::item_types`); this file must never enumerate item types.
|
||||
//
|
||||
// TRACES: UR-067 | DR-117
|
||||
|
||||
import type { SearchScope } from "$lib/api/bindings";
|
||||
|
||||
/**
|
||||
* Scopes offered as tabs, in display order. A subset of `SearchScope` chosen
|
||||
* for presentation — the backend accepts more than a page needs to show.
|
||||
*/
|
||||
export const FAVORITE_SCOPES = ["all", "movies", "tv", "music"] as const;
|
||||
|
||||
export type FavoritesScope = (typeof FAVORITE_SCOPES)[number];
|
||||
|
||||
export const FAVORITE_SCOPE_LABELS: Record<FavoritesScope, string> = {
|
||||
all: "All",
|
||||
movies: "Movies",
|
||||
tv: "Shows",
|
||||
music: "Music",
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve the `?scope=` param to a tab, defaulting to All for anything
|
||||
* missing or unrecognised (a hand-edited or stale URL must not blank the page).
|
||||
*/
|
||||
export function resolveFavoritesScope(raw: string | null | undefined): FavoritesScope {
|
||||
if (!raw) return "all";
|
||||
return (FAVORITE_SCOPES as readonly string[]).includes(raw) ? (raw as FavoritesScope) : "all";
|
||||
}
|
||||
|
||||
/** URL for a tab. The default scope is omitted, keeping the base URL clean. */
|
||||
export function favoritesRouteUrl(scope: FavoritesScope): string {
|
||||
return scope === "all" ? "/library/favorites" : `/library/favorites?scope=${scope}`;
|
||||
}
|
||||
|
||||
/** Per-tab empty state copy (ux-flows §5C.2). */
|
||||
export function emptyStateMessage(scope: FavoritesScope): string {
|
||||
const what: Record<FavoritesScope, string> = {
|
||||
all: "Nothing favourited yet",
|
||||
movies: "No favourite movies yet",
|
||||
tv: "No favourite shows yet",
|
||||
music: "No favourite music yet",
|
||||
};
|
||||
return `${what[scope]} — tap the heart on anything you like.`;
|
||||
}
|
||||
|
||||
/** Compile-time guard that every tab is a scope the backend accepts. */
|
||||
const _scopesAreSearchScopes: readonly SearchScope[] = FAVORITE_SCOPES;
|
||||
void _scopesAreSearchScopes;
|
||||
@@ -3,6 +3,7 @@
|
||||
import { get } from "svelte/store";
|
||||
import { page } from "$app/stores";
|
||||
import { platform } from "@tauri-apps/plugin-os";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import "../app.css";
|
||||
import { auth, needsReauth, isAuthenticated } from "$lib/stores/auth";
|
||||
import { connectivity, isConnected } from "$lib/stores/connectivity";
|
||||
@@ -10,7 +11,8 @@
|
||||
import { initWebviewAudio, cleanupWebviewAudio } from "$lib/services/webviewAudio";
|
||||
import { downloads, initDownloadEvents, cleanupDownloadEvents } from "$lib/stores/downloads";
|
||||
import { syncService } from "$lib/services/syncService";
|
||||
import { onReconnected as onCatalogReconnected, syncCatalog, refreshSyncStatus, showServerCatalog, lastCatalogSync } from "$lib/services/offlineCatalog";
|
||||
import { clearFavorite } from "$lib/stores/favorites";
|
||||
import { onReconnected as onCatalogReconnected, refreshSyncStatus, showServerCatalog, lastCatalogSync } from "$lib/services/offlineCatalog";
|
||||
import { playbackMode } from "$lib/stores/playbackMode";
|
||||
import { sessions } from "$lib/stores/sessions";
|
||||
import ReauthModal from "$lib/components/auth/ReauthModal.svelte";
|
||||
@@ -34,6 +36,7 @@
|
||||
|
||||
/** Teardown for the network-transport reporter (WiFi-only gate). */
|
||||
let stopNetworkReporting: (() => void) | null = null;
|
||||
let stopFavoritesListener: UnlistenFn | null = null;
|
||||
|
||||
/** Teardown for the native window-inset subscription (safe areas). */
|
||||
let stopSafeArea: (() => void) | null = null;
|
||||
@@ -115,6 +118,18 @@
|
||||
// Initialize download event listener
|
||||
await initDownloadEvents();
|
||||
|
||||
// Favourite state can change behind the UI: another Jellyfin client marks
|
||||
// something, or the Rust drain pushes toggles queued while offline. Drop
|
||||
// the session overrides for those ids so the next render reads the freshly
|
||||
// cached server value rather than a stale local guess.
|
||||
// TRACES: UR-069 | DR-120
|
||||
stopFavoritesListener = await listen<{ itemIds: string[] }>(
|
||||
"favorites-changed",
|
||||
(event) => {
|
||||
for (const id of event.payload?.itemIds ?? []) clearFavorite(id);
|
||||
}
|
||||
);
|
||||
|
||||
// Report the network transport to the backend and keep it current, so the
|
||||
// WiFi-only download gate has real data to act on (UR-053). No-op on
|
||||
// desktop, where the backend defaults to unmetered.
|
||||
@@ -134,10 +149,10 @@
|
||||
// Start sync service for offline mutation queue
|
||||
syncService.start();
|
||||
|
||||
// Kick off a best-effort full-catalog pre-sync so the whole server catalog
|
||||
// is browsable (greyed out) offline, and load the last-sync hint for the
|
||||
// offline banner. Non-blocking — no-ops when not connected.
|
||||
void syncCatalog();
|
||||
// Load the last-sync hint for the offline banner. The catalog *index* is no
|
||||
// longer kicked off from here: the Rust background indexer (DR-109) owns
|
||||
// when to re-index, so a long session no longer searches a stale catalog and
|
||||
// a restart no longer forces a full crawl regardless of freshness.
|
||||
void refreshSyncStatus();
|
||||
|
||||
// Initialize playback mode and session monitoring
|
||||
@@ -147,6 +162,8 @@
|
||||
|
||||
onDestroy(() => {
|
||||
stopNetworkReporting?.();
|
||||
stopFavoritesListener?.();
|
||||
stopFavoritesListener = null;
|
||||
stopSafeArea?.();
|
||||
cleanupPlayerEvents();
|
||||
cleanupWebviewAudio();
|
||||
|
||||
@@ -133,6 +133,11 @@
|
||||
const nextUpItems = $derived($home.nextUpItems);
|
||||
const latestItems = $derived($home.latestItems);
|
||||
const recentlyPlayedAudio = $derived($home.recentlyPlayedAudio);
|
||||
// Favourite rows. Each is hidden when empty, so a fresh install shows none.
|
||||
// TRACES: UR-067 | DR-118
|
||||
const favoriteMovies = $derived($home.favoriteMovies);
|
||||
const favoriteShows = $derived($home.favoriteShows);
|
||||
const favoriteMusic = $derived($home.favoriteMusic);
|
||||
const resumeMovies = $derived($home.resumeMovies);
|
||||
const isLoading = $derived($home.isLoading);
|
||||
</script>
|
||||
@@ -218,6 +223,39 @@
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<!-- Favourites. Hidden entirely when a category has nothing in it —
|
||||
empty rows on a fresh install read as broken. ux-flows §5C.2.
|
||||
TRACES: UR-067 | DR-118 -->
|
||||
{#if favoriteMovies.length > 0}
|
||||
<Carousel
|
||||
title="Favourite Movies"
|
||||
items={favoriteMovies}
|
||||
onItemClick={handleItemClick}
|
||||
onItemLongPress={handleItemLongPress}
|
||||
showAll={() => goto("/library/favorites?scope=movies")}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if favoriteShows.length > 0}
|
||||
<Carousel
|
||||
title="Favourite Shows"
|
||||
items={favoriteShows}
|
||||
onItemClick={handleItemClick}
|
||||
onItemLongPress={handleItemLongPress}
|
||||
showAll={() => goto("/library/favorites?scope=tv")}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if favoriteMusic.length > 0}
|
||||
<Carousel
|
||||
title="Favourite Music"
|
||||
items={favoriteMusic}
|
||||
onItemClick={handleItemClick}
|
||||
onItemLongPress={handleItemLongPress}
|
||||
showAll={() => goto("/library/favorites?scope=music")}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<!-- Quick Access -->
|
||||
<div class="pt-4 px-4">
|
||||
<button
|
||||
|
||||
@@ -201,6 +201,20 @@
|
||||
<div>
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<h1 class="text-2xl font-bold text-white">Your Libraries</h1>
|
||||
<div class="flex items-center gap-1">
|
||||
<!-- Favourites cut across libraries, so they live beside the library
|
||||
list rather than inside one. ux-flows §5C.2.
|
||||
TRACES: UR-067 | DR-117 -->
|
||||
<button
|
||||
onclick={() => goto('/library/favorites')}
|
||||
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
|
||||
title="Favourites"
|
||||
aria-label="Favourites"
|
||||
>
|
||||
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onclick={() => goto('/settings')}
|
||||
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
|
||||
@@ -211,6 +225,7 @@
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if $isLibraryLoading}
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
import SeriesDownloadButton from "$lib/components/library/SeriesDownloadButton.svelte";
|
||||
import ClearHistoryButton from "$lib/components/library/ClearHistoryButton.svelte";
|
||||
import VideoDownloadButton from "$lib/components/library/VideoDownloadButton.svelte";
|
||||
import FavoriteButton from "$lib/components/FavoriteButton.svelte";
|
||||
import { favoriteOverrides, resolveIsFavorite } from "$lib/stores/favorites";
|
||||
import CastSection from "$lib/components/library/CastSection.svelte";
|
||||
import PersonDetailView from "$lib/components/library/PersonDetailView.svelte";
|
||||
import RelatedItemsSection from "$lib/components/library/RelatedItemsSection.svelte";
|
||||
@@ -557,6 +559,14 @@
|
||||
size="lg"
|
||||
/>
|
||||
{/if}
|
||||
<!-- Favourite. Sits with Play/Download rather than in the header,
|
||||
per ux-flows §5B.3/§5B.4. TRACES: UR-068 | DR-119 -->
|
||||
<FavoriteButton
|
||||
itemId={item.id}
|
||||
isFavorite={resolveIsFavorite(item, $favoriteOverrides)}
|
||||
size="lg"
|
||||
className="self-center"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Overview -->
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
<!--
|
||||
Favourites — everything the viewer has hearted, across every library.
|
||||
|
||||
Scope tabs are `?scope=`, so a tab is linkable and survives a back press (the
|
||||
same convention as the video library `?view=` tabs). Each tab sends an opaque
|
||||
`SearchScope`; what it *means* in Jellyfin item types is expanded in Rust
|
||||
(`SearchScope::item_types`), never here — see docs/specs/scoped-search-boundary.md.
|
||||
|
||||
ux-flows §5C.2. TRACES: UR-067 | DR-117
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import { page } from "$app/stores";
|
||||
import { goto } from "$app/navigation";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { isServerReachable } from "$lib/stores/connectivity";
|
||||
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
||||
import { navigateBack } from "$lib/utils/navigation";
|
||||
import { favoriteOverrides, retainFavorites } from "$lib/stores/favorites";
|
||||
import LibraryGrid from "$lib/components/library/LibraryGrid.svelte";
|
||||
import BackButton from "$lib/components/common/BackButton.svelte";
|
||||
import type { MediaItem, Library } from "$lib/api/types";
|
||||
import {
|
||||
FAVORITE_SCOPES,
|
||||
FAVORITE_SCOPE_LABELS,
|
||||
resolveFavoritesScope,
|
||||
favoritesRouteUrl,
|
||||
emptyStateMessage,
|
||||
} from "$lib/utils/favoritesView";
|
||||
|
||||
const scope = $derived(resolveFavoritesScope($page.url.searchParams.get("scope")));
|
||||
|
||||
let items = $state<MediaItem[]>([]);
|
||||
let loading = $state(true);
|
||||
let loadError = $state<string | null>(null);
|
||||
let unlistenFavorites: UnlistenFn | null = null;
|
||||
|
||||
// Un-hearting here must remove the card immediately rather than wait for a
|
||||
// refetch; a newly hearted item stays put. TRACES: UR-067 | DR-117 | UT-106
|
||||
const visibleItems = $derived(retainFavorites(items, $favoriteOverrides));
|
||||
|
||||
async function load(currentScope = scope) {
|
||||
loading = true;
|
||||
loadError = null;
|
||||
try {
|
||||
const repo = auth.getRepository();
|
||||
const result = await repo.getFavorites(currentScope, { limit: 500 });
|
||||
items = result.items;
|
||||
} catch (error) {
|
||||
console.error("Failed to load favorites:", error);
|
||||
loadError = "Could not load your favourites.";
|
||||
items = [];
|
||||
} finally {
|
||||
loading = false;
|
||||
markLoaded();
|
||||
}
|
||||
}
|
||||
|
||||
// Reload when the tab changes.
|
||||
let loadedScope = "";
|
||||
$effect(() => {
|
||||
if (scope === loadedScope) return;
|
||||
loadedScope = scope;
|
||||
load(scope);
|
||||
});
|
||||
|
||||
onMount(async () => {
|
||||
// The backend reports ids whose favourite state changed behind our back —
|
||||
// a favourite marked in another client, or pending toggles pushed on
|
||||
// reconnect. Refetch rather than patch: the scope decides what belongs.
|
||||
// TRACES: UR-069 | DR-120
|
||||
unlistenFavorites = await listen("favorites-changed", () => {
|
||||
load(scope);
|
||||
});
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
unlistenFavorites?.();
|
||||
unlistenFavorites = null;
|
||||
});
|
||||
|
||||
const { markLoaded } = useServerReachabilityReload(() => load(scope));
|
||||
|
||||
function selectScope(next: (typeof FAVORITE_SCOPES)[number]) {
|
||||
if (next === scope) return;
|
||||
// replaceState: switching tabs is not a back-press-worthy navigation step.
|
||||
goto(favoritesRouteUrl(next), { replaceState: true, noScroll: true });
|
||||
}
|
||||
|
||||
function handleItemClick(item: MediaItem | Library) {
|
||||
goto(`/library/${item.id}`);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="flex items-center gap-3 px-4 pt-4">
|
||||
<BackButton onClick={() => navigateBack("/library")} />
|
||||
<h1 class="text-2xl font-bold text-white">Favourites</h1>
|
||||
</div>
|
||||
|
||||
<nav class="flex items-center gap-1 px-4" aria-label="Favourite categories">
|
||||
{#each FAVORITE_SCOPES as tab (tab)}
|
||||
<button
|
||||
onclick={() => selectScope(tab)}
|
||||
aria-current={tab === scope ? "page" : undefined}
|
||||
class="px-4 py-2 rounded-lg text-sm font-medium transition-colors
|
||||
{tab === scope
|
||||
? 'bg-[var(--color-jellyfin)] text-white'
|
||||
: 'text-gray-400 hover:text-white hover:bg-white/10'}"
|
||||
>
|
||||
{FAVORITE_SCOPE_LABELS[tab]}
|
||||
</button>
|
||||
{/each}
|
||||
</nav>
|
||||
|
||||
<div class="px-4 pb-8">
|
||||
{#if loading}
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
|
||||
{#each Array(12) as _}
|
||||
<div class="animate-pulse">
|
||||
<div class="aspect-square bg-[var(--color-surface)] rounded-lg mb-2"></div>
|
||||
<div class="h-4 bg-[var(--color-surface)] rounded w-3/4"></div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else if loadError}
|
||||
<p class="text-gray-400 py-12 text-center">{loadError}</p>
|
||||
{:else if visibleItems.length === 0}
|
||||
<div class="py-16 text-center space-y-2">
|
||||
<p class="text-gray-300">{emptyStateMessage(scope)}</p>
|
||||
{#if !$isServerReachable}
|
||||
<p class="text-sm text-gray-500">
|
||||
Offline — showing favourites available on this device.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Card shape follows the media, not the page (§5A.1), so a mixed All
|
||||
tab reads as posters, squares and thumbnails side by side. -->
|
||||
<LibraryGrid items={visibleItems} onItemClick={handleItemClick} />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -4,6 +4,7 @@
|
||||
import { goto } from "$app/navigation";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { resolveVideoSource } from "$lib/player/localSource";
|
||||
import type { PlayQueueRequest } from "$lib/api/bindings";
|
||||
import type { MediaItem, MediaKind } from "$lib/api/types";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
@@ -299,11 +300,28 @@
|
||||
// Playback API now detects HEVC/10-bit and returns transcoded URL when needed
|
||||
console.log("loadAndPlay: Using video stream, directPlay:", playbackInfo.directPlay, "needsTranscoding:", playbackInfo.needsTranscoding);
|
||||
mediaSourceId = playbackInfo.mediaSourceId;
|
||||
videoNeedsTranscoding = playbackInfo.needsTranscoding;
|
||||
|
||||
// Use the stream URL from playback info (already transcoded if needed)
|
||||
streamUrl = playbackInfo.streamUrl;
|
||||
console.log("loadAndPlay: Using stream URL:", streamUrl);
|
||||
// Prefer a completed download over streaming. Audio has done this
|
||||
// since the queue is built; video previously always streamed, so a
|
||||
// downloaded film re-spent bandwidth already spent and would not play
|
||||
// at all offline. Rust returns null when nothing is downloaded or the
|
||||
// file has gone, so this falls back to the server on its own.
|
||||
// TRACES: UR-071 | DR-123
|
||||
const localPath = await commands.playerLocalMediaPath(id);
|
||||
const source = resolveVideoSource({
|
||||
localPath,
|
||||
remoteUrl: playbackInfo.streamUrl,
|
||||
remoteNeedsTranscoding: playbackInfo.needsTranscoding,
|
||||
toAssetUrl: convertFileSrc,
|
||||
});
|
||||
|
||||
streamUrl = source.url;
|
||||
videoNeedsTranscoding = source.needsTranscoding;
|
||||
console.log(
|
||||
source.isLocal
|
||||
? "loadAndPlay: Playing downloaded file from disk"
|
||||
: `loadAndPlay: Using stream URL: ${streamUrl}`
|
||||
);
|
||||
|
||||
// Set initial position for video player to seek to after load
|
||||
// Use explicit startPosition, or fall back to retrieved progress from database
|
||||
|
||||
@@ -69,6 +69,10 @@
|
||||
albumAffinityThreshold: 3,
|
||||
storageLimit: 10 * 1024 * 1024 * 1024,
|
||||
wifiOnly: false,
|
||||
// Placeholder only — replaced by the backend's value on load. How long a
|
||||
// temporary (auto-cached) download lives before it is reclaimed; the policy
|
||||
// itself is Rust's (DR-127).
|
||||
temporaryTtlHours: 24 * 7,
|
||||
});
|
||||
|
||||
// Whether the platform can actually detect the network type. On desktop it
|
||||
|
||||
Reference in New Issue
Block a user