* docs: design spec for manga library type (host sub-project) Forks the ebooks library type into a 'manga' type: series detected from the folder tree as a first-class type='manga' item, .cbz/.cbr chapters stay readable ebook items linked via a new manga_chapters table, browse shows series cards, enrichment targets the series item at content level 'manga'. Hands off to a follow-on plugin spec for the manga metadata source. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs: implementation plan for manga library type (host) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(scanner): manga filename index/volume parser * feat(scanner): manga series-name-from-folder detection Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs(plan): align manga DB/scanner tasks to scanner pure-planner pattern (no test-DB) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(scanner): manga parser corpus regression Add TestParseMangaIndexCorpus — 36 real-world scanlation filenames covering bare chapter, decimal chapter, v/vol-prefix volume, and c/ch-prefix chapter patterns; asserts <5% miss rate. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(db): manga_chapters link table Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(scanner): manga_chapters repository + pure chapter-write mapping Adds mangaChapterWrite (pure, unit-tested), upsertMangaChapter, and listMangaChapters following the ebook/audiobook thin-SQL pattern. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(scanner): recognize manga library type Add isMangaLibraryType helper (unexported, matching the style of isEbookLibraryType / isAudiobookLibraryType) with a corresponding TestIsMangaLibraryType unit test. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(api): manga library content level Map library type "manga" to content level ["manga"] in metadataContentLevelsForLibraryType so that seedDefaultChain seeds a manga-level metadata provider chain when a manga library is created. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(scanner): route manga libraries to a manga scan path Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(scanner): group manga chapters under a manga series item Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(scanner): give manga series item a library membership so it browses Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(catalog): browse manga libraries as series Accept "manga" as a valid media_scope so a manga library browses only its type='manga' series items; the per-chapter type='ebook' items are naturally excluded because MediaScopeItemTypes("manga") expands to {"manga"}. Add the manga default library sections (scoped to media_scope='manga') so the library feed shows series cards. Refresh the two media_scope validation error messages. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(catalog): manga series detail lists chapters For a type='manga' item, attach its chapters to the detail response via a new MangaDetailExtension. fetchMangaChapters joins manga_chapters to media_items on the chapter content ID, scopes to the series, and orders by chapter_index (NULLS LAST) then sort_title — matching the scanner's chapter ordering. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): manga detail types + library browse scoping Add MangaChapter/MangaDetailExtension TS types mirroring the host catalog structs, wire manga? onto ItemDetail, and admit "manga" as a QueryDefinition.media_scope. Scope manga libraries to media_scope=manga in browse (host expands it to type=manga series items) while reusing the ebook sort universe via getLibrarySortRelevanceScope. Add isMangaLibraryType. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): manga series detail with volume-grouped chapter list Add MangaContent detail view: a DetailHero series header plus a chapter list grouped by volume. groupMangaChapters (pure, unit-tested) buckets chapters by their volume token, orders chapters within a group by chapter_index (nulls last) and orders groups by their minimum index; loose (volume-less) chapters collapse into a trailing "Chapters" group. Each chapter links to the existing ebook reader by content_id alone (file_id is optional — the reader resolves the file server-side), reusing buildMediaPlayHref. Admit "manga" into ItemDetail.type and wire the detail switch. Continue-reading is deferred (needs per-chapter progress fan-out / a last-read timestamp not in the current payload). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): handle manga in playable-type + collection filter-scope unions Adding "manga" to the shared ItemDetail["type"] and QueryDefinition["media_scope"] unions leaked into consumers with narrower local types, breaking the production tsc build. Fixes: - mediaNavigation: admit "manga" into PlayableMediaType. Manga series are not directly playable (you open the detail page and read a chapter, itself an ebook item), so buildMediaPlayHref falls through to the item href for them, like series/season. - FilterRuleEditor: add "manga" to FilterRuleMediaScope and relabel "watched" -> "Read" for manga as well as ebook (manga is read). - CollectionGuidedRulesEditor: add "manga" to GuidedFormState.mediaScope, a "Manga" media-type option, ebook-like "Read Status" labels, and map manga -> ebook sort-relevance scope (manga has no dedicated sort scope). - CatalogFilterBar (cascading leak surfaced after the above): add a "Manga" scope option and map manga -> ebook sort-relevance scope in both scope handlers. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): offer manga as a library type in the create dialog Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(scanner): strip scene-release junk from manga series names Add cleanMangaSeriesName which repeatedly strips trailing parenthetical groups (year, year-range, Digital, release-group tags) then trims any dangling dash, so folder names like "404 Demons (Digital) (Oak)" resolve to "404 Demons". Wire it into mangaSeriesFromPath so both the series title and the mangaSeriesGroupKey identity key use the cleaned value. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): flat volume/chapter manga list; nest only multi-chapter volumes Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(scanner): parse manga index after stripping series-name prefix Numbers inside a series title (e.g. "404 Demons", "365 Days to the Wedding") were wrongly grabbed as the chapter number because parseMangaIndex matched the first bare number in the full filename. mangaIndexForFile now strips the series-name prefix before delegating to parseMangaIndex, so only the number that follows the title is used. reconcileMangaFile in manga_scan.go is updated to call mangaIndexForFile instead of parseMangaIndex directly. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(scanner): stop missing-file reconcile from deleting manga series items Manga series items are file-less virtual parents; the shared ReconcileFolderMembership swept them every scan because they have no media_file. Exclude type='manga' from file-presence membership reconciliation, and add a manga-scan step that deletes only series with zero remaining chapters. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(ebooks): exclude manga chapters from individual ebook enrichment Manga chapters are type='ebook' parts of a series; the ebook enrichment sweep was searching each one against book sources (Gutenberg/Anna's/etc.) and failing in a pointless storm. Exclude items with a manga_chapters link; series-level enrichment is handled separately. * docs: design spec for manga metadata plugin + series enrichment (sub-project 2) New silo-plugin-manga-metadata (AniList, high-confidence matching) + a host MangaEnricher for type='manga' series; default-enabled metadata source for manga libraries. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs: implementation plan for manga metadata plugin + series enrichment Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(db): manga_enrichment_state table Mirrors ebook_enrichment_state: dedicated failure counter for the manga enrichment sweep so it does not contend with media_items.refresh_failures. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(manga): series enricher (claims type='manga', resolves manga chain) * feat(manga): sync_manga_metadata task + enricher wiring * feat(catalog): expose manga chapter/volume counts in browse Add manga_chapter_count and manga_volume_count to browse cards so the frontend can render a Vols N / Ch N chip on manga series. The counts come from two index-backed correlated subqueries over manga_chapters in the browse SELECT (mangaCountColumns), scanned positionally before added_at and nilled out for non-manga rows. Threaded through models.MediaItem and exposed on the itemListResponse JSON card. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(sections): scope manga home recent sections to type=manga series A manga library mixes type='manga' series with type='ebook' chapters, so the auto-generated home 'Recently Added/Released in <Library>' rows surfaced the junk chapter filenames. Add GeneratedHomeLibraryRecentConfigScoped which emits the modern QueryDefinition shape (library_ids + media_scope) so a manga library's generated home rows filter to type='manga' only. Other library types are unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(catalog): exclude manga chapters from browse/section/search surfaces Manga CHAPTER items (type='ebook' rows linked into a type='manga' series via manga_chapters) were leaking into catalog browse, section resolution, and search as standalone items showing junk filenames. They are internal sub-units of the series and only the series should appear. There is no single shared item-listing chokepoint: browse, the query/preview executor, and search each build their own WHERE. Add a shared, index-backed anti-join predicate (manga_chapters.chapter_content_id is the PK) via mangaChapterExclusionWhere and wire it into all three builders. By-id fetch paths that legitimately resolve chapters (ebook reader, continue-reading, series detail chapter list) use separate queries and are unaffected. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(scanner): use #NN as the manga volume for Vol.YYYY #NN releases mangaVolYearIssue early-return was returning the year token (e.g. "Vol.2003") as the volume label, which the frontend couldn't prettify to "Volume N". Now returns "v<issue>" (e.g. "v04") so the existing frontend regex ^v?(\d+)$ renders it as "Volume 4" correctly. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(web): manga count chip on posters Add an optional manga_chapter_count / manga_volume_count to the browse item type and render a top-right "Vols N" / "Ch N" chip on ItemCard, strictly gated on type==='manga'. The label prefers "Vols" when the volume count dominates, "Ch" otherwise; the chip is hidden when the chapter count is missing or non-positive. No other card type renders it. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): manga reader back returns to series (no loop) The ebook reader's back action defaulted to the chapter's own item detail (/item/<chapter>), whose back returned to the reader — an infinite loop for manga chapters. The reader now honors an explicit backTo search param when present, navigating there instead. Absent for normal ebooks, so their back behavior is unchanged. Only manga chapter rows pass backTo, keeping the fix manga-only. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): manga chapter row actions (read/mark-read/download) Each manga chapter/volume row now offers Read (the existing reader link, now carrying a backTo to the series), Mark-read (the shared watched-state mutation per chapter content_id), and Download (lazily fetches the chapter's file versions on demand and opens the shared DownloadVersionPicker, gated on user.download_allowed). The volume-unit / loose-chapter / section structure from buildMangaList is unchanged. Scoped to MangaContent only; EbookContent is untouched. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): validate reader backTo param is a safe in-app relative path Prevents open-redirect / javascript:-URI XSS from a crafted ?backTo= URL. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(catalog): include per-chapter read state in manga detail Manga chapters are ebook items, so a chapter is "read" when the viewer's ebook_reader_progress row crosses the finished threshold. fetchMangaChapters now LEFT JOINs that table scoped to the AccessFilter's user_id/profile_id and exposes a per-chapter Read bool on MangaChapter, threaded through buildMangaExtension. The detail payload previously carried no read state, so the row toggle always started unread. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): manga rows reflect read state on load MangaChapter now carries an optional read flag from the detail payload, and MangaRow seeds its mark-read toggle from chapter.read instead of always starting unread. The optimistic toggle + shared watched mutation are unchanged; only the initial value is seeded. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(sections): exclude manga chapters from recently-added/released/random + other library-listing sections Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(sections): manga recently-added/released cards show the latest volume's cover * fix(manga): keep enrichment honest about no-match vs enriched, batch 50->200 - sweep stats now separate enriched / no_match / failed: a stamped no-match was counted (and logged) as an enrichment, which masked a collapse of the real match rate during the backfill - batch size 50 -> 200 (SILO_MANGA_ENRICH_BATCH overrides): with the plugin serving GetMetadata from its search cache an item costs one rate-limited AniList request, so a sweep still fits the 5-minute task interval Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(manga): size enrich batch to the 5-minute interval at AniList's real budget 140 items x ~2.1s/request fits the interval; an overlong sweep makes the task manager drop the next trigger and the effective rate falls below the AniList budget. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(catalog): manga count chip data missing from library browse manga_chapter_count/manga_volume_count were only added to BrowseRepository, but /library/{id}?tab=library flows through previewQuerySource -> QueryExecutor.PreviewPage, which selects qualifiedListItemColumns and scans with scanItems - so manga cards never carried the counts and the Vols/Ch poster chip stayed hidden. Append mangaCountColumns to the preview-page SELECT and scan them via a new scanItemsWithMangaCounts (nil for non-manga rows, mirroring scanBrowseItems). Extract listItemScanDests so the three scan variants share one destination list instead of duplicating the 48-column scan. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): manga chip reads 'X Volumes · X Chapters', menu verbs say Read - chip: show distinct-volume and loose-chapter counts side by side instead of the single 'Vols N'/'Ch N' heuristic; mangaCountColumns now counts DISTINCT volume tokens (rows sharing a volume are one volume) and only un-volumed rows as chapters - watched-state labels: type='manga' fell through to the video default, so the card dot menu and detail page said 'Mark Watched' - manga now uses the ebook reading verbs (Mark Read / Mark Unread, 'Marked as read' toast) - format MangaContent.test.tsx (pre-existing prettier miss) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(manga): backdrop enrichment - banner hero art + backdrop-only backfill - cache remote backdrops like posters (cacheRemoteImages generalizes the poster-only path; failures keep the provider URL, which still renders) - claim arm for enriched items missing a backdrop: fetched by stored provider ID (search skipped - no rate spend, no re-match risk) and only the backdrop is written; stamping after the attempt keeps banner-less series from being re-claimed every sweep - backfill = one-time SQL clearing last_refreshed for poster-set/ backdrop-empty manga Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(manga): reading-loop UX - continue CTA, next chapter, series-aware cards, file details Fixes the four high-priority findings from the manga UX review plus a file-inspector request: - H1: series hero gets a Continue / Start Reading / Read Again CTA targeting the first unread chapter (firstUnreadChapter over the ordered list), plus an overflow menu (View Details, admin Refresh Metadata) - H2: the reader resolves its owning manga series (chapter detail now carries series_id/series_title) and offers next-chapter navigation: a header next button and an end-of-book floating CTA at >=99.5% progress; back defaults to the series even without a backTo param - H3: chapter rows show a persistent read check + muted title, and the mark-read mutation carries series_id so the series detail cache invalidates (read states no longer revert on revisit) - H4: continue-reading cards for manga chapters present the series: sections payload resolves chapter->series linkage, the card heading/image link to the series, and meta lines launch the reader - View Details: manga series menus (card dot menu + detail overflow) open a file inspector showing folder paths and per-chapter file names/sizes via GET /catalog/items/{id}/manga-files; paths are stripped for viewers without file-path visibility (item-versions policy) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(manga): UX mediums - richer detail page, smarter list, manga sort scope Second batch from the manga UX review (M1-M7): - M1: multi-chapter volume sections are collapsible (fully read sections start collapsed) with sticky headers, and long series get a 'Jump to <next unread>' anchor above the list - M2: the series hero shows the author line (HeroCrewLine learns Author credits with person links; DetailHero now renders crewLine and genre chips independently) and Volumes/Chapters badges - M3: browse-card count chip abbreviates to '12 Vol - 3 Ch' so it fits narrow cards without occluding covers - M4: manga gets its own sort scope: Duration/Bitrate (meaningless for file-less series rows) disappear, reading labels (Date Read / Reads) apply, Author stays - M5: global search labels manga results 'Manga' instead of the raw type - M6: chapters carry the viewer's reading fraction; part-read rows show an inline progress bar + percent - M7: chapter rows show the extracted cover thumbnail (presigned poster_url on the chapters payload) instead of a generic icon Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(manga): UX lows - volume token dedupe, comic reader chrome, empty-state hint - buildMangaList buckets volumes by canonical numeric token so mixed release naming (v01 + 1) yields one Volume 1 instead of duplicates - cbz/cbr readers start with the side panel closed and hide prose-only chrome (reading ruler, TTS, typography/font controls, hyphenation, writing mode) while keeping comic-relevant settings (theme, brightness, margin, right-to-left, spread, flow) - manga empty state mentions chapters appear after the library scan Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(manga): publication status badge via new SDK status field - vendor the unpublished plugin SDK (adds MetadataItem.status) under internal/compat/ with a relative go.mod replace, following the zishang520-webtransport-go convention; swap to the published module before the upstream PR - map plugin status into MetadataResult.ShowStatus, persist it during manga enrichment, and show it as the hero status badge (show_status was already on the detail payload and MetadataBadges) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(manga): generalize backdrop pass to secondary fields (backdrop + status) The backdrop-only claim arm becomes a secondary-fields pass: enriched items missing a backdrop and/or publication status are claimed, fetched by stored provider ID, and only the missing secondary fields are written. Lets the new status field backfill across the already-enriched library instead of applying only to future enrichments. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(metadata): merge ShowStatus through MergeMetadata/MergeGlobalMetadata The new MetadataResult.ShowStatus never reached the accumulated result the manga enricher persists from - the field-by-field merges didn't know it, so the status backfill pass obtained nothing. Regression-tested on both paths. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(manga): keep scanner identity IDs out of the metadata flow filterMangaProviderIDs passed the scanner's manga_series identity row through, so the search-skip-when-already-matched guard saw provider IDs on every item and never searched: unmatched items went straight to a by-ID fetch with no usable ID and were stamped as terminal no-match without a single provider request (and the MangaDex fallback was never consulted). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: gitignore docker-compose.override.yml (local deployment override) The override unpublishes the bundled redis/postgres host ports (ports: !override []). It is a per-deployment, local-only file: ignoring it keeps a rebase from main and git clean -fd from disturbing it, and keeps it out of any PR. Its accidental absence once exposed Redis to the internet. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(manga): code-review fixes — no-match guard, sort comparator, volume-count consistency - enrichWithProviders: set accumulator.HasMetadata after a provider result merges (MergeMetadata doesn't propagate it). Without this, a confident match carrying only genres/authors/status/year but no cover and no overview failed the no-match check and was discarded + terminally stamped. - byChapterIndex: both un-indexed chapters yield POSITIVE_INFINITY, so the subtraction was Infinity-Infinity=NaN (Array.sort treats NaN as 0, leaving order undefined). Compare explicitly for a stable order. - MangaContent volume/chapter badges: derive counts from the rendered buildMangaList entries (which canonicalize v01 ≡ 1) instead of raw distinct volume tokens, so the badge can no longer say '2 Volumes' over one row. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(manga): clarify the enrichment claim's secondary arm is admin-reset-only The secondary arm (poster present, backdrop/status missing) requires last_refreshed IS NULL, so it is only reachable when an operator resets last_refreshed to backfill a newly-added field — not an automatic periodic re-check (which would re-fetch banner-less series every sweep). Documents the intent so it does not read as dead code. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(manga): collapse continue-reading chapters per series; batch provider-id lookup - Continue Reading now collapses multiple in-progress chapters of the same manga into one card (most recently read kept), mirroring the episode→series collapse. The reading section resolves chapter→series linkage into itemMeta (applyMangaChapterSeriesMeta) and runs the shared collapseContinueWatchingSeriesCandidates, which the reading path previously skipped. - claimBatch resolves provider IDs for the whole batch in one query via the new ProviderIDRepository.GetByContentIDs (content_id = ANY), replacing the per-item GetByContentID N+1. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): manga publication-status chip on browse cards + more legible chips - Color-coded publication status pill (Ongoing/Completed/Hiatus/Cancelled/ Upcoming) in the manga card's top-left corner, mirroring the vol/chapter count chip top-right. Strictly manga-gated; show_status was already on the browse payload. - New .glass-chip (78% surface vs glass-subtle's 40%) for the manga count + status pills so the labels stay legible over busy cover art. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * build(manga): depend on published silo-plugin-sdk v0.7.0 Replace the vendored internal/compat/silo-plugin-sdk copy with a normal dependency on the published SDK module at v0.7.0, which adds MetadataItem.status (publication/airing status) consumed by the manga status badge at internal/metadata/plugin_provider.go. - go.mod: pin v0.7.0, drop the local-path replace directive - remove the vendored internal/compat/silo-plugin-sdk tree - Dockerfile: drop the vendored-SDK COPY - strip the manga design docs/plans from docs/superpowers (internal) Requires Silo-Server/silo-plugin-sdk#4 merged and tagged v0.7.0. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(manga): exclude chapters from the matcher's unmatched-item lister Manga chapters are type='ebook' items that stay status='pending' by design - provider metadata lives on the type='manga' series item. The scan-final RetryUnmatchedItemsByFolderAndPathPrefix listed all of them and ran a rate-limited ebook-plugin search per chapter: 31,564 chapters x ~1s = 8h46m appended to a 2-minute manga library scan (observed live), every one a guaranteed no-match. Earlier runs never survived to completion, so the library's last_scanned_at stayed NULL forever. Add the same manga_chapters NOT EXISTS guard the ebook enricher's claim query already uses. Verified live: the same library now scans in 27s with retried_items=0. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(scanner): never probe-repair ebook/comic files (ebook+manga detail-page killer) NeedsCriticalProbeRepair was always true for BaseType 'ebook' files (epub, pdf, cbz, cbr — incl. manga chapters): buildEbookMediaFile leaves ProbeUpdatedAt nil and they have no audio/video, so probeEnsurer.Ensure spawned ffprobe per file on every detail/watch load and never converged (ffprobe errors on zip/rar, result never persisted). Short-circuit probe-repair for ebook base type — they're read directly and never use the transcode/playback probe pipeline. SHARED fix: benefits both the ebooks and manga library types. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * perf+fix(ebooks): parallelize detail extension + preserve finished read-state - buildEbookExtension ran its 3 related-content queries (series, also-by-author, similar) sequentially; run them concurrently like buildAudiobookExtension so ebook detail latency is the slowest query, not their sum. - PGEbookReaderProgressStore.Upsert did an unconditional SET progress=EXCLUDED; a routine autosave (e.g. reopening a finished book) could drop it below the 0.9 finished threshold and silently un-mark it read (and clear the manga chapter checkmark, which rides on the same row). Guard: once finished, progress only moves on an explicit unread (row delete); below threshold it tracks freely. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * perf(manga): batch chapter presign, index volume counts, quiet scan log - fetchMangaChapters presigned each chapter poster individually; a long-running series has hundreds of chapters. Batch them in one PresignImageURLs call, and add the missing rows.Err() check (was silently returning partial lists). - The browse manga count chip's count(DISTINCT volume) subquery wasn't covered by manga_chapters_series (series_content_id, chapter_index); add idx_manga_chapters_series_volume (series_content_id, volume) so both count subqueries are index-only. - Downgrade the per-chapter "manga scan: indexed" log from Info to Debug (one line per .cbz; the 500-file progress log already covers operator visibility). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(manga): address PR #138 code-review findings Folds PR #142 into the manga branch (already done via fast-forward) and remediates the issues surfaced in the #138 code review. Correctness: - Preserve the scanner's manga_series identity anchor through enrichment. ReplaceByContentID's DELETE was unconditional, so the first successful enrichment wiped the manga_series provider-id row the scanner relies on for idempotency, causing duplicate series + metadata loss on the next scan. excludedProviderIDs now also means "not deleted", and the DELETE preserves those rows. (internal/catalog/provider_id_repo.go) - Fall back to the series cover when the latest chapter has no poster. Poster columns default to '' (not NULL), so the manga series-card poster override blanked cards via a plain COALESCE; wrap operands in NULLIF. (internal/sections/fetcher.go) - Keep backTo a real query param on reader links when libraryId is absent. It was string-concatenated with '&', producing a malformed URL on deep-links; route it through the query helper instead. (web/src/lib/mediaNavigation.ts, EbookReader.tsx, MangaContent.tsx) Quality: - Hide manga chapters from favorites/watchlist browse, matching the exclusion enforced on every other listing surface. (internal/catalog/favorites_browse.go) - Centralize the manga chapter exclusion predicate into a single exported catalog.MangaChapterExclusionWhere, removing four duplicated copies. (catalog, sections, ebooks) - Skip the two manga count subqueries on browse scopes that cannot contain manga (non-manga type filters), substituting NULL placeholders. (internal/catalog/browse.go) - Normalize provider publication status (AniList/MangaDex/SDK variants) into a stable label set so show_status carries one manga value-domain. (internal/manga/enrichment.go) Adds unit tests for the poster NULLIF contract, browse gating, and status normalization. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore: regenerate go.sum after rebase onto main Drops stale silo-plugin-sdk v0.6.0 and other leftover hashes from the intermediate rebased states; go.mod is now on the published v0.7.0 tag. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(scanner): adapt manga scan to ebookFileShouldSkip 3-value signature main changed ebookFileShouldSkip to also return the existing content ID; the manga scan path only needs the unchanged flag, so discard the new return. Resolves a silent semantic conflict from the rebase onto main. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Silo Server Developer <warmasterx555@gmail.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1823 lines
59 KiB
Go
1823 lines
59 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"log/slog"
|
|
|
|
"github.com/Silo-Server/silo-server/internal/access"
|
|
apimw "github.com/Silo-Server/silo-server/internal/api/middleware"
|
|
"github.com/Silo-Server/silo-server/internal/auth"
|
|
"github.com/Silo-Server/silo-server/internal/catalog"
|
|
evt "github.com/Silo-Server/silo-server/internal/events"
|
|
"github.com/Silo-Server/silo-server/internal/metadata"
|
|
"github.com/Silo-Server/silo-server/internal/models"
|
|
"github.com/Silo-Server/silo-server/internal/overlays"
|
|
"github.com/Silo-Server/silo-server/internal/sections"
|
|
"github.com/Silo-Server/silo-server/internal/userstore"
|
|
"github.com/Silo-Server/silo-server/internal/watchstate"
|
|
"github.com/Silo-Server/silo-server/internal/watchsync"
|
|
)
|
|
|
|
// EpisodeFileProvider retrieves media files linked to an episode.
|
|
type EpisodeFileProvider interface {
|
|
GetByContentID(ctx context.Context, contentID string) ([]*models.MediaFile, error)
|
|
GetByEpisodeID(ctx context.Context, episodeID string) ([]*models.MediaFile, error)
|
|
ListByContentIDs(ctx context.Context, contentIDs []string) (map[string][]*models.MediaFile, error)
|
|
}
|
|
|
|
type batchEpisodeFileProvider interface {
|
|
ListByEpisodeIDs(ctx context.Context, episodeIDs []string) (map[string][]*models.MediaFile, error)
|
|
}
|
|
|
|
type MetadataRefreshRequester interface {
|
|
RequestStaleMetadataRefresh(ctx context.Context, targetType, contentID string) error
|
|
}
|
|
|
|
type LocalWatchEventDispatcher interface {
|
|
HandleLocalWatchEvent(ctx context.Context, event watchsync.LocalWatchEvent) error
|
|
}
|
|
|
|
type EbookReaderProgressLister interface {
|
|
ListByContentIDs(ctx context.Context, userID int, profileID string, contentIDs []string) (map[string]EbookReaderProgress, error)
|
|
}
|
|
|
|
// ItemsHandler handles browse, search, item detail, and series endpoints.
|
|
type ItemsHandler struct {
|
|
browseRepo *catalog.BrowseRepository
|
|
itemRepo *catalog.ItemRepository
|
|
episodeRepo *catalog.EpisodeRepository
|
|
seasonRepo *catalog.SeasonRepository
|
|
ratingsRepo ratingsRepository
|
|
catalogResolver *catalog.CatalogResolver
|
|
fileRepo EpisodeFileProvider
|
|
detailSvc *catalog.DetailService
|
|
storeProvider userstore.UserStoreProvider
|
|
watchState *watchstate.Service
|
|
profileStaler ProfileStaler
|
|
profileRefreshRequester ProfileRefreshRequester
|
|
metadataRefreshRequester MetadataRefreshRequester
|
|
localWatchDispatcher LocalWatchEventDispatcher
|
|
ebookProgressStore EbookReaderProgressLister
|
|
ebookReadStateStore EbookReadStateStore
|
|
EventsHub *evt.Hub
|
|
UserRepo *auth.UserRepository
|
|
}
|
|
|
|
// NewItemsHandler creates a new ItemsHandler.
|
|
func NewItemsHandler(
|
|
browseRepo *catalog.BrowseRepository,
|
|
itemRepo *catalog.ItemRepository,
|
|
episodeRepo *catalog.EpisodeRepository,
|
|
seasonRepo *catalog.SeasonRepository,
|
|
ratingsRepo ratingsRepository,
|
|
fileRepo EpisodeFileProvider,
|
|
storeProvider userstore.UserStoreProvider,
|
|
detailSvc *catalog.DetailService,
|
|
providerIDRepo *catalog.ProviderIDRepository,
|
|
) *ItemsHandler {
|
|
return &ItemsHandler{
|
|
browseRepo: browseRepo,
|
|
itemRepo: itemRepo,
|
|
episodeRepo: episodeRepo,
|
|
seasonRepo: seasonRepo,
|
|
ratingsRepo: ratingsRepo,
|
|
catalogResolver: catalog.NewCatalogResolver(browseRepo, itemRepo).
|
|
WithEpisodeRepository(episodeRepo).
|
|
WithUserStoreProvider(storeProvider),
|
|
fileRepo: fileRepo,
|
|
storeProvider: storeProvider,
|
|
watchState: watchstate.NewService(storeProvider).WithStableIdentityResolver(
|
|
watchstate.NewStableIdentityResolver(itemRepo, episodeRepo, providerIDRepo),
|
|
),
|
|
detailSvc: detailSvc,
|
|
}
|
|
}
|
|
|
|
// SetProfileStaler configures an optional staleness trigger for taste profiles.
|
|
func (h *ItemsHandler) SetProfileStaler(ps ProfileStaler) {
|
|
h.profileStaler = ps
|
|
}
|
|
|
|
// SetProfileRefreshRequester configures an optional background refresh queue for taste profiles.
|
|
func (h *ItemsHandler) SetProfileRefreshRequester(requester ProfileRefreshRequester) {
|
|
h.profileRefreshRequester = requester
|
|
}
|
|
|
|
func (h *ItemsHandler) SetMetadataRefreshRequester(requester MetadataRefreshRequester) {
|
|
h.metadataRefreshRequester = requester
|
|
}
|
|
|
|
func (h *ItemsHandler) SetLocalWatchEventDispatcher(dispatcher LocalWatchEventDispatcher) {
|
|
h.localWatchDispatcher = dispatcher
|
|
}
|
|
|
|
func (h *ItemsHandler) SetEbookReaderProgressStore(store EbookReaderProgressReadWriter) {
|
|
h.ebookProgressStore = store
|
|
h.ebookReadStateStore = store
|
|
}
|
|
|
|
func (h *ItemsHandler) maybeRequestStaleDetailMetadataRefresh(ctx context.Context, detail *catalog.ItemDetail) {
|
|
if h == nil || detail == nil || h.metadataRefreshRequester == nil {
|
|
return
|
|
}
|
|
switch detail.Type {
|
|
case "episode":
|
|
if h.episodeRepo == nil {
|
|
return
|
|
}
|
|
episode, err := h.episodeRepo.GetByID(ctx, detail.ContentID)
|
|
if err == nil {
|
|
h.maybeRequestStaleEpisodeMetadataRefresh(ctx, episode)
|
|
}
|
|
case "season":
|
|
if h.episodeRepo == nil {
|
|
return
|
|
}
|
|
episodes, err := h.episodeRepo.ListBySeasonID(ctx, detail.ContentID)
|
|
if err == nil {
|
|
h.maybeRequestStaleSeasonMetadataRefresh(ctx, detail.ContentID, episodes)
|
|
}
|
|
case "series":
|
|
if h.itemRepo == nil {
|
|
return
|
|
}
|
|
item, err := h.itemRepo.GetByID(ctx, detail.ContentID)
|
|
if err == nil && item != nil && item.EpisodeMetadataIncomplete {
|
|
h.requestStaleMetadataRefresh(ctx, "item", item.ContentID)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) maybeRequestStaleEpisodeMetadataRefresh(ctx context.Context, episode *models.Episode) {
|
|
if h == nil || h.metadataRefreshRequester == nil || episode == nil {
|
|
return
|
|
}
|
|
if metadata.EpisodeHasActionableMetadataDebt(episode, time.Now()) {
|
|
h.requestStaleMetadataRefresh(ctx, "episode", episode.ContentID)
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) maybeRequestStaleSeasonMetadataRefresh(ctx context.Context, seasonID string, episodes []*models.Episode) {
|
|
if h == nil || h.metadataRefreshRequester == nil || strings.TrimSpace(seasonID) == "" {
|
|
return
|
|
}
|
|
now := time.Now()
|
|
for _, episode := range episodes {
|
|
if metadata.EpisodeHasActionableMetadataDebt(episode, now) {
|
|
h.requestStaleMetadataRefresh(ctx, "season", seasonID)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) requestStaleMetadataRefresh(ctx context.Context, targetType, contentID string) {
|
|
if h == nil || h.metadataRefreshRequester == nil || strings.TrimSpace(contentID) == "" {
|
|
return
|
|
}
|
|
if err := h.metadataRefreshRequester.RequestStaleMetadataRefresh(ctx, targetType, contentID); err != nil {
|
|
slog.Warn("catalog: failed to request stale metadata refresh",
|
|
"target_type", targetType,
|
|
"content_id", contentID,
|
|
"error", err)
|
|
}
|
|
}
|
|
|
|
// --- Response types ---
|
|
|
|
// itemListResponse is the shape of a single item in browse/search list responses.
|
|
type itemListResponse struct {
|
|
ContentID string `json:"content_id"`
|
|
Type string `json:"type"`
|
|
Title string `json:"title"`
|
|
SeriesTitle string `json:"series_title,omitempty"`
|
|
SeasonNumber *int `json:"season_number,omitempty"`
|
|
EpisodeNumber *int `json:"episode_number,omitempty"`
|
|
Year int `json:"year,omitempty"`
|
|
Runtime int `json:"runtime,omitempty"`
|
|
Genres []string `json:"genres"`
|
|
Keywords []string `json:"keywords"`
|
|
Studios []string `json:"studios,omitempty"`
|
|
Networks []string `json:"networks,omitempty"`
|
|
ContentRating string `json:"content_rating,omitempty"`
|
|
Status string `json:"status"`
|
|
ShowStatus string `json:"show_status,omitempty"`
|
|
RatingIMDB *float64 `json:"rating_imdb,omitempty"`
|
|
RatingTMDB *float64 `json:"rating_tmdb,omitempty"`
|
|
RatingRTCritic *int `json:"rating_rt_critic,omitempty"`
|
|
RatingRTAudience *int `json:"rating_rt_audience,omitempty"`
|
|
OriginalLanguage string `json:"original_language,omitempty"`
|
|
Overview string `json:"overview,omitempty"`
|
|
PosterURL string `json:"poster_url,omitempty"`
|
|
PosterThumbhash string `json:"poster_thumbhash,omitempty"`
|
|
BackdropURL string `json:"backdrop_url,omitempty"`
|
|
BackdropThumbhash string `json:"backdrop_thumbhash,omitempty"`
|
|
ReleaseDate *string `json:"release_date,omitempty"`
|
|
LastAirDate *string `json:"last_air_date,omitempty"`
|
|
AddedAt *time.Time `json:"added_at,omitempty"`
|
|
MangaChapterCount *int `json:"manga_chapter_count,omitempty"`
|
|
MangaVolumeCount *int `json:"manga_volume_count,omitempty"`
|
|
OverlaySummary *models.OverlaySummary `json:"overlay_summary,omitempty"`
|
|
SortMetrics *sortMetricsResponse `json:"sort_metrics,omitempty"`
|
|
UserState *itemUserStateResponse `json:"user_state,omitempty"`
|
|
WorkID string `json:"work_id,omitempty"`
|
|
WorkTitle string `json:"work_title,omitempty"`
|
|
WorkFormats []catalog.WorkFormatSummary `json:"work_formats,omitempty"`
|
|
}
|
|
|
|
type sortMetricsResponse struct {
|
|
ReleaseDate *string `json:"release_date,omitempty"`
|
|
RuntimeMinutes *int `json:"runtime_minutes,omitempty"`
|
|
Resolution string `json:"resolution,omitempty"`
|
|
BitrateKbps *int `json:"bitrate_kbps,omitempty"`
|
|
ProgressRatio *float64 `json:"progress_ratio,omitempty"`
|
|
ViewedAt string `json:"viewed_at,omitempty"`
|
|
PlayCount *int `json:"play_count,omitempty"`
|
|
Author string `json:"author,omitempty"`
|
|
Narrator string `json:"narrator,omitempty"`
|
|
SeriesName string `json:"series_name,omitempty"`
|
|
}
|
|
|
|
// browseResponse is the paginated response for the /items endpoint.
|
|
type browseResponse struct {
|
|
Total int `json:"total"`
|
|
HasMore bool `json:"has_more"`
|
|
Items []itemListResponse `json:"items"`
|
|
}
|
|
|
|
type itemFiltersResponse struct {
|
|
Genres []string `json:"genres"`
|
|
Studios []string `json:"studios"`
|
|
Networks []string `json:"networks"`
|
|
Countries []string `json:"countries"`
|
|
ContentRatings []string `json:"content_ratings"`
|
|
}
|
|
|
|
// seasonResponse is the shape of a season in API responses.
|
|
type seasonResponse struct {
|
|
ContentID string `json:"content_id"`
|
|
SeasonNumber int `json:"season_number"`
|
|
IsSpecials bool `json:"is_specials,omitempty"`
|
|
Title string `json:"title"`
|
|
Overview string `json:"overview,omitempty"`
|
|
AirDate string `json:"air_date,omitempty"`
|
|
EpisodeCount int `json:"episode_count"`
|
|
PosterURL string `json:"poster_url,omitempty"`
|
|
PosterThumbhash string `json:"poster_thumbhash,omitempty"`
|
|
UserData *catalog.SeasonUserData `json:"user_data,omitempty"`
|
|
}
|
|
|
|
// seasonsResponse wraps the seasons list for JSON serialization.
|
|
type seasonsResponse struct {
|
|
Seasons []seasonResponse `json:"seasons"`
|
|
}
|
|
|
|
// seasonDetailResponse wraps a single season for JSON serialization.
|
|
type seasonDetailResponse struct {
|
|
Season seasonResponse `json:"season"`
|
|
}
|
|
|
|
// episodesListResponse wraps the episodes list for JSON serialization.
|
|
type episodesListResponse struct {
|
|
Episodes []episodeResponse `json:"episodes"`
|
|
}
|
|
|
|
// episodeFileResponse represents a file version available for an episode.
|
|
type episodeFileResponse struct {
|
|
FileID int `json:"file_id"`
|
|
Resolution string `json:"resolution,omitempty"`
|
|
CodecVideo string `json:"codec_video,omitempty"`
|
|
HDR bool `json:"hdr"`
|
|
AudioChannels int `json:"audio_channels,omitempty"`
|
|
Container string `json:"container,omitempty"`
|
|
FileSize int64 `json:"file_size"`
|
|
}
|
|
|
|
// episodeResponse is the shape of an episode in API responses.
|
|
type episodeResponse struct {
|
|
ContentID string `json:"content_id"`
|
|
SeasonNumber int `json:"season_number"`
|
|
EpisodeNumber int `json:"episode_number"`
|
|
Title string `json:"title"`
|
|
Overview string `json:"overview,omitempty"`
|
|
AirDate string `json:"air_date,omitempty"`
|
|
Runtime int `json:"runtime"`
|
|
ImdbID string `json:"imdb_id,omitempty"`
|
|
TmdbID string `json:"tmdb_id,omitempty"`
|
|
TvdbID string `json:"tvdb_id,omitempty"`
|
|
StillURL string `json:"still_url,omitempty"`
|
|
StillThumbhash string `json:"still_thumbhash,omitempty"`
|
|
UserData *catalog.SeasonUserData `json:"user_data,omitempty"`
|
|
Files []episodeFileResponse `json:"files,omitempty"`
|
|
}
|
|
|
|
type episodeImageFallback struct {
|
|
Path string
|
|
Thumbhash string
|
|
}
|
|
|
|
type watchedStateResponse struct {
|
|
ContentID string `json:"content_id"`
|
|
Type string `json:"type"`
|
|
AffectedCount int `json:"affected_count"`
|
|
Played bool `json:"played"`
|
|
}
|
|
|
|
// --- Handler methods ---
|
|
|
|
// HandleGetItems handles GET /items with filtering, sorting, and pagination.
|
|
func (h *ItemsHandler) HandleGetItems(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog")
|
|
if values, ok := buildLegacyItemsCatalogValues(r.URL.Query()); ok && h.catalogResolver != nil {
|
|
h.writeCatalogBrowseResponse(w, r, values)
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Catalog is not configured")
|
|
}
|
|
|
|
// HandleGetLatestItems handles GET /items/latest — shortcut for sort=created_at&order=desc.
|
|
func (h *ItemsHandler) HandleGetLatestItems(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog")
|
|
if h.catalogResolver != nil {
|
|
h.writeCatalogBrowseResponse(w, r, buildLegacyLatestCatalogValues(r.URL.Query()))
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Catalog is not configured")
|
|
}
|
|
|
|
// HandleGetItemFilters handles GET /items/filters for distinct browse values.
|
|
func (h *ItemsHandler) HandleGetItemFilters(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog/filters")
|
|
if values, ok := buildLegacyItemsCatalogValues(r.URL.Query()); ok && h.catalogResolver != nil {
|
|
h.writeCatalogFiltersResponse(w, r, values)
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Catalog is not configured")
|
|
}
|
|
|
|
// HandleGetItemDetail handles GET /items/{id}.
|
|
func (h *ItemsHandler) HandleGetItemDetail(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog/items/{id}")
|
|
h.catalogResourceHandler().HandleGetItemDetail(w, r)
|
|
}
|
|
|
|
// HandleGetWatchDetail handles GET /watch/{id}.
|
|
func (h *ItemsHandler) HandleGetWatchDetail(w http.ResponseWriter, r *http.Request) {
|
|
id := chi.URLParam(r, "id")
|
|
if id == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Watch target ID is required")
|
|
return
|
|
}
|
|
|
|
detail, err := h.detailSvc.GetWatchDetail(r.Context(), id, h.accessFilter(r))
|
|
if err != nil {
|
|
switch {
|
|
case catalog.IsWatchTargetNotPlayable(err):
|
|
writeError(w, http.StatusBadRequest, "invalid_watch_target", "Content is not directly playable")
|
|
return
|
|
case isNotFound(err):
|
|
writeError(w, http.StatusNotFound, "not_found", "Watch target not found")
|
|
return
|
|
default:
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to get watch detail")
|
|
return
|
|
}
|
|
}
|
|
|
|
if detail.Type == "movie" || detail.Type == "episode" || detail.Type == "ebook" {
|
|
detail.UserData = h.getLeafUserData(r, detail.ContentID, detail.Type)
|
|
applyEffectiveEditionPreference(detail.UserData, &detail.EffectiveVersionEditionKey)
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, detail)
|
|
}
|
|
|
|
// HandleMarkWatched handles POST /watched/{id}.
|
|
func (h *ItemsHandler) HandleMarkWatched(w http.ResponseWriter, r *http.Request) {
|
|
h.handleSetWatchedState(w, r, true)
|
|
}
|
|
|
|
// HandleMarkUnwatched handles DELETE /watched/{id}.
|
|
func (h *ItemsHandler) HandleMarkUnwatched(w http.ResponseWriter, r *http.Request) {
|
|
h.handleSetWatchedState(w, r, false)
|
|
}
|
|
|
|
func (h *ItemsHandler) dispatchLocalWatchEvent(
|
|
ctx context.Context,
|
|
kind watchsync.LocalWatchEventKind,
|
|
userID int,
|
|
profileID string,
|
|
result watchstate.ManualMarkResult,
|
|
) {
|
|
if h == nil || h.localWatchDispatcher == nil {
|
|
return
|
|
}
|
|
plays := watchsync.LocalPlaysFromHistory(result.Entries)
|
|
if len(plays) == 0 {
|
|
return
|
|
}
|
|
if err := h.localWatchDispatcher.HandleLocalWatchEvent(ctx, watchsync.LocalWatchEvent{
|
|
Kind: kind,
|
|
UserID: userID,
|
|
ProfileID: profileID,
|
|
Plays: plays,
|
|
}); err != nil {
|
|
slog.Warn("failed to queue local watch provider event", "kind", kind, "user_id", userID, "profile_id", profileID, "error", err)
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) handleSetWatchedState(w http.ResponseWriter, r *http.Request, played bool) {
|
|
userID := apimw.GetUserID(r.Context())
|
|
profileID := apimw.GetProfileID(r.Context())
|
|
id := chi.URLParam(r, "id")
|
|
|
|
if id == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Item ID is required")
|
|
return
|
|
}
|
|
if profileID == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Profile ID is required")
|
|
return
|
|
}
|
|
|
|
filter := h.accessFilter(r)
|
|
targetType, targets, err := h.resolveWatchedTargets(r.Context(), id, filter)
|
|
if err != nil {
|
|
switch {
|
|
case isNotFound(err):
|
|
writeError(w, http.StatusNotFound, "not_found", "Item not found")
|
|
default:
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to update watched state")
|
|
}
|
|
return
|
|
}
|
|
|
|
switch {
|
|
case targetType == "ebook":
|
|
// Ebook read state lives in ebook_reader_progress, not in
|
|
// user_watch_progress/user_watch_history; watch providers do not sync
|
|
// books, so no local watch event is dispatched.
|
|
err = h.setEbookReadState(r.Context(), userID, profileID, id, played, filter)
|
|
case h.watchState == nil:
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to access user store")
|
|
return
|
|
case played:
|
|
leafTargets := make([]watchstate.LeafWatchTarget, 0, len(targets))
|
|
for _, target := range targets {
|
|
leafTargets = append(leafTargets, watchstate.LeafWatchTarget{
|
|
MediaItemID: target.ContentID,
|
|
DurationSeconds: target.DurationSeconds,
|
|
})
|
|
}
|
|
updatedAt := time.Now().UTC()
|
|
var result watchstate.ManualMarkResult
|
|
result, err = h.watchState.RecordManualMarkWatchedWithResult(r.Context(), userID, profileID, leafTargets, updatedAt)
|
|
if err == nil {
|
|
h.dispatchLocalWatchEvent(r.Context(), watchsync.LocalWatchEventMarkedWatched, userID, profileID, result)
|
|
}
|
|
default:
|
|
targetIDs := make([]string, 0, len(targets))
|
|
for _, target := range targets {
|
|
targetIDs = append(targetIDs, target.ContentID)
|
|
}
|
|
var result watchstate.ManualMarkResult
|
|
result, err = h.watchState.RecordManualMarkUnwatchedWithResult(r.Context(), userID, profileID, targetIDs)
|
|
if err == nil {
|
|
h.dispatchLocalWatchEvent(r.Context(), watchsync.LocalWatchEventMarkedUnwatched, userID, profileID, result)
|
|
}
|
|
}
|
|
if err != nil {
|
|
if isNotFound(err) {
|
|
writeError(w, http.StatusNotFound, "not_found", "Item not found")
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to update watched state")
|
|
return
|
|
}
|
|
|
|
triggerProfileRefresh(r.Context(), h.profileStaler, h.profileRefreshRequester, userID, profileID)
|
|
publishUserStateEvent(r.Context(), h.EventsHub, userID, profileID, id, "", "watched", userStateEventState{
|
|
Played: boolPtr(played),
|
|
})
|
|
|
|
writeJSON(w, http.StatusOK, watchedStateResponse{
|
|
ContentID: id,
|
|
Type: targetType,
|
|
AffectedCount: len(targets),
|
|
Played: played,
|
|
})
|
|
}
|
|
|
|
// HandleGetItemVersions handles GET /items/{id}/versions.
|
|
func (h *ItemsHandler) HandleGetItemVersions(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog/items/{id}/versions")
|
|
h.catalogResourceHandler().HandleGetItemVersions(w, r)
|
|
}
|
|
|
|
// HandleGetItemEpisodes handles GET /items/{id}/episodes for season IDs.
|
|
func (h *ItemsHandler) HandleGetItemEpisodes(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog/items/{id}/episodes")
|
|
h.catalogResourceHandler().HandleGetItemEpisodes(w, r)
|
|
}
|
|
|
|
// HandleGetSeasons handles GET /series/{id}/seasons.
|
|
func (h *ItemsHandler) HandleGetSeasons(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog/series/{id}/seasons")
|
|
h.catalogResourceHandler().HandleGetSeasons(w, r)
|
|
}
|
|
|
|
// HandleGetSeason handles GET /series/{id}/seasons/{num}.
|
|
func (h *ItemsHandler) HandleGetSeason(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog/series/{id}/seasons/{num}")
|
|
h.catalogResourceHandler().HandleGetSeason(w, r)
|
|
}
|
|
|
|
// HandleGetEpisodes handles GET /series/{id}/seasons/{num}/episodes.
|
|
func (h *ItemsHandler) HandleGetEpisodes(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog/series/{id}/seasons/{num}/episodes")
|
|
h.catalogResourceHandler().HandleGetEpisodes(w, r)
|
|
}
|
|
|
|
func (h *ItemsHandler) catalogResourceHandler() *CatalogResourceHandler {
|
|
return NewCatalogResourceHandler(h)
|
|
}
|
|
|
|
func (h *ItemsHandler) catalogHandler() *CatalogHandler {
|
|
return NewCatalogHandler(h.catalogResolver, h)
|
|
}
|
|
|
|
func (h *ItemsHandler) writeCatalogBrowseResponse(w http.ResponseWriter, r *http.Request, values map[string][]string) bool {
|
|
req, err := catalog.ParseCatalogRequest(values)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return true
|
|
}
|
|
|
|
result, err := h.catalogResolver.Resolve(r.Context(), req, h.accessFilter(r))
|
|
if err != nil {
|
|
if errors.Is(err, catalog.ErrInvalidCatalogRequest) {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return true
|
|
}
|
|
if errors.Is(err, catalog.ErrCatalogSourceNotFound) {
|
|
writeError(w, http.StatusNotFound, "not_found", "Catalog source not found")
|
|
return true
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to browse items")
|
|
return true
|
|
}
|
|
|
|
overlaySummaries := h.listOverlaySummaries(r.Context(), result.Items, h.accessFilter(r))
|
|
userStates := h.listItemUserStates(r, result.Items)
|
|
items := make([]itemListResponse, 0, len(result.Items))
|
|
for _, item := range result.Items {
|
|
items = append(items, h.toItemListResponseWithOverlay(r, item, overlaySummaries[item.ContentID], userStates[item.ContentID]))
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, browseResponse{
|
|
Total: result.Total,
|
|
HasMore: result.HasMore,
|
|
Items: items,
|
|
})
|
|
return true
|
|
}
|
|
|
|
func (h *ItemsHandler) writeCatalogFiltersResponse(w http.ResponseWriter, r *http.Request, values map[string][]string) bool {
|
|
req, err := catalog.ParseCatalogRequest(values)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return true
|
|
}
|
|
|
|
filters, err := h.catalogResolver.ListFiltersWithOptions(
|
|
r.Context(),
|
|
req,
|
|
h.accessFilter(r),
|
|
catalog.CatalogFilterOptions{IncludeTechnical: false},
|
|
)
|
|
if err != nil {
|
|
if errors.Is(err, catalog.ErrInvalidCatalogRequest) {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return true
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to list item filters")
|
|
return true
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, itemFiltersResponse{
|
|
Genres: filters.Genres,
|
|
Studios: filters.Studios,
|
|
Networks: filters.Networks,
|
|
Countries: filters.Countries,
|
|
ContentRatings: filters.ContentRatings,
|
|
})
|
|
return true
|
|
}
|
|
|
|
// toItemListResponse converts a MediaItem to an itemListResponse with presigned URLs.
|
|
func (h *ItemsHandler) toItemListResponse(r *http.Request, item *models.MediaItem) itemListResponse {
|
|
return h.toItemListResponseWithOverlay(r, item, nil, nil)
|
|
}
|
|
|
|
func (h *ItemsHandler) toItemListResponseWithOverlay(r *http.Request, item *models.MediaItem, overlaySummary *models.OverlaySummary, userState *itemUserStateResponse) itemListResponse {
|
|
if h.detailSvc != nil {
|
|
if localized, err := h.detailSvc.LocalizeItemModel(r.Context(), item, h.accessFilter(r)); err == nil && localized != nil {
|
|
item = localized
|
|
}
|
|
}
|
|
resp := itemListResponse{
|
|
ContentID: item.ContentID,
|
|
Type: item.Type,
|
|
Title: item.Title,
|
|
Year: item.Year,
|
|
Runtime: item.Runtime,
|
|
Genres: item.Genres,
|
|
Keywords: item.Keywords,
|
|
Studios: item.Studios,
|
|
Networks: item.Networks,
|
|
ContentRating: item.ContentRating,
|
|
Status: item.Status,
|
|
ShowStatus: item.ShowStatus,
|
|
RatingIMDB: item.RatingIMDB,
|
|
RatingTMDB: item.RatingTMDB,
|
|
RatingRTCritic: item.RatingRTCritic,
|
|
RatingRTAudience: item.RatingRTAudience,
|
|
OriginalLanguage: item.OriginalLanguage,
|
|
Overview: item.Overview,
|
|
PosterThumbhash: item.PosterThumbhash,
|
|
BackdropThumbhash: item.BackdropThumbhash,
|
|
OverlaySummary: overlaySummary,
|
|
UserState: userState,
|
|
}
|
|
|
|
resp.AddedAt = item.AddedAt
|
|
resp.MangaChapterCount = item.MangaChapterCount
|
|
resp.MangaVolumeCount = item.MangaVolumeCount
|
|
resp.ReleaseDate = item.ReleaseDate
|
|
resp.LastAirDate = item.LastAirDate
|
|
resp.PosterURL = h.presignURL(r, cardThumbnailPath(item.PosterPath), "card")
|
|
resp.BackdropURL = h.presignURL(r, cardThumbnailPath(item.BackdropPath), "card")
|
|
if resp.Genres == nil {
|
|
resp.Genres = []string{}
|
|
}
|
|
if resp.Keywords == nil {
|
|
resp.Keywords = []string{}
|
|
}
|
|
|
|
return resp
|
|
}
|
|
|
|
func (h *ItemsHandler) listEpisodeBrowseMetadata(
|
|
ctx context.Context,
|
|
items []*models.MediaItem,
|
|
) map[string]struct {
|
|
SeriesTitle string
|
|
SeasonNumber *int
|
|
EpisodeNumber *int
|
|
} {
|
|
if h == nil || h.episodeRepo == nil {
|
|
return map[string]struct {
|
|
SeriesTitle string
|
|
SeasonNumber *int
|
|
EpisodeNumber *int
|
|
}{}
|
|
}
|
|
|
|
episodeIDs := make([]string, 0)
|
|
for _, item := range items {
|
|
if item == nil || item.Type != "episode" || strings.TrimSpace(item.ContentID) == "" {
|
|
continue
|
|
}
|
|
episodeIDs = append(episodeIDs, item.ContentID)
|
|
}
|
|
if len(episodeIDs) == 0 {
|
|
return map[string]struct {
|
|
SeriesTitle string
|
|
SeasonNumber *int
|
|
EpisodeNumber *int
|
|
}{}
|
|
}
|
|
|
|
episodes, err := h.episodeRepo.GetByIDs(ctx, episodeIDs)
|
|
if err != nil || len(episodes) == 0 {
|
|
return map[string]struct {
|
|
SeriesTitle string
|
|
SeasonNumber *int
|
|
EpisodeNumber *int
|
|
}{}
|
|
}
|
|
|
|
seriesIDs := make([]string, 0, len(episodes))
|
|
seenSeriesIDs := make(map[string]struct{}, len(episodes))
|
|
for _, episode := range episodes {
|
|
if episode == nil || strings.TrimSpace(episode.SeriesID) == "" {
|
|
continue
|
|
}
|
|
if _, ok := seenSeriesIDs[episode.SeriesID]; ok {
|
|
continue
|
|
}
|
|
seenSeriesIDs[episode.SeriesID] = struct{}{}
|
|
seriesIDs = append(seriesIDs, episode.SeriesID)
|
|
}
|
|
|
|
seriesTitles := make(map[string]string, len(seriesIDs))
|
|
if len(seriesIDs) > 0 {
|
|
if seriesItems, err := h.itemRepo.GetByIDs(ctx, seriesIDs); err == nil {
|
|
for _, seriesItem := range seriesItems {
|
|
if seriesItem == nil {
|
|
continue
|
|
}
|
|
seriesTitles[seriesItem.ContentID] = seriesItem.Title
|
|
}
|
|
}
|
|
}
|
|
|
|
result := make(map[string]struct {
|
|
SeriesTitle string
|
|
SeasonNumber *int
|
|
EpisodeNumber *int
|
|
}, len(episodes))
|
|
for _, episode := range episodes {
|
|
if episode == nil {
|
|
continue
|
|
}
|
|
seasonNumber := episode.SeasonNumber
|
|
episodeNumber := episode.EpisodeNumber
|
|
result[episode.ContentID] = struct {
|
|
SeriesTitle string
|
|
SeasonNumber *int
|
|
EpisodeNumber *int
|
|
}{
|
|
SeriesTitle: seriesTitles[episode.SeriesID],
|
|
SeasonNumber: &seasonNumber,
|
|
EpisodeNumber: &episodeNumber,
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func (h *ItemsHandler) listItemUserStates(r *http.Request, items []*models.MediaItem) map[string]*itemUserStateResponse {
|
|
store, profileID, ok := h.userStoreForRequest(r)
|
|
if !ok {
|
|
return map[string]*itemUserStateResponse{}
|
|
}
|
|
states, err := resolveItemUserStatesWithOptions(r.Context(), store, profileID, h.episodeRepo, items, itemUserStateOptions{
|
|
UserID: apimw.GetUserID(r.Context()),
|
|
EbookProgressStore: h.ebookProgressStore,
|
|
})
|
|
if err != nil {
|
|
return map[string]*itemUserStateResponse{}
|
|
}
|
|
return states
|
|
}
|
|
|
|
// toEpisodeResponse converts an Episode model to an API response.
|
|
func (h *ItemsHandler) toEpisodeResponse(r *http.Request, ep *models.Episode) episodeResponse {
|
|
return h.toEpisodeResponseWithFallback(r, ep, episodeImageFallback{})
|
|
}
|
|
|
|
func (h *ItemsHandler) toEpisodeResponseWithFallback(r *http.Request, ep *models.Episode, fallback episodeImageFallback) episodeResponse {
|
|
if h.detailSvc != nil {
|
|
if localized, err := h.detailSvc.LocalizeEpisodeModel(r.Context(), ep, h.accessFilter(r)); err == nil && localized != nil {
|
|
ep = localized
|
|
}
|
|
}
|
|
resp, stillPath := episodeResponseShell(ep, fallback)
|
|
resp.StillURL = h.presignURL(r, stillPath, "card")
|
|
return resp
|
|
}
|
|
|
|
// episodeResponseShell maps an already-localized episode onto the response
|
|
// shape, returning the card-variant still path for the caller to presign.
|
|
func episodeResponseShell(ep *models.Episode, fallback episodeImageFallback) (episodeResponse, string) {
|
|
stillPath := ep.StillPath
|
|
stillThumbhash := ep.StillThumbhash
|
|
if strings.TrimSpace(stillPath) == "" && strings.TrimSpace(fallback.Path) != "" {
|
|
stillPath = fallback.Path
|
|
stillThumbhash = fallback.Thumbhash
|
|
}
|
|
resp := episodeResponse{
|
|
ContentID: ep.ContentID,
|
|
SeasonNumber: ep.SeasonNumber,
|
|
EpisodeNumber: ep.EpisodeNumber,
|
|
Title: ep.Title,
|
|
Overview: ep.Overview,
|
|
Runtime: ep.Runtime,
|
|
ImdbID: ep.ImdbID,
|
|
TmdbID: ep.TmdbID,
|
|
TvdbID: ep.TvdbID,
|
|
StillThumbhash: stillThumbhash,
|
|
}
|
|
|
|
if ep.AirDate != nil {
|
|
resp.AirDate = ep.AirDate.Format("2006-01-02")
|
|
}
|
|
|
|
return resp, cardThumbnailPath(stillPath)
|
|
}
|
|
|
|
// buildEpisodeResponses converts episodes to API responses using batched
|
|
// lookups — localization, media files, watch progress, and image presigning
|
|
// each resolve in one round-trip for the whole list instead of per episode.
|
|
func (h *ItemsHandler) buildEpisodeResponses(r *http.Request, episodes []*models.Episode) []episodeResponse {
|
|
ctx := r.Context()
|
|
filter := h.accessFilter(r)
|
|
|
|
if h.detailSvc != nil {
|
|
if localized, err := h.detailSvc.LocalizeEpisodeModels(ctx, episodes, filter); err == nil && len(localized) == len(episodes) {
|
|
episodes = localized
|
|
}
|
|
}
|
|
|
|
fallbacks := h.episodeImageFallbacks(ctx, episodes)
|
|
|
|
episodeIDs := make([]string, 0, len(episodes))
|
|
for _, ep := range episodes {
|
|
if ep != nil && ep.ContentID != "" {
|
|
episodeIDs = append(episodeIDs, ep.ContentID)
|
|
}
|
|
}
|
|
filesByEpisode := h.listEpisodeFiles(ctx, episodeIDs)
|
|
userData := h.listLeafUserData(r, episodeIDs)
|
|
|
|
resp := make([]episodeResponse, 0, len(episodes))
|
|
stillPaths := make([]string, 0, len(episodes))
|
|
for _, ep := range episodes {
|
|
if ep == nil {
|
|
continue
|
|
}
|
|
shell, stillPath := episodeResponseShell(ep, fallbacks[ep.SeriesID])
|
|
resp = append(resp, shell)
|
|
stillPaths = append(stillPaths, stillPath)
|
|
}
|
|
|
|
stillURLs := map[string]catalog.ResolvedImageURL{}
|
|
if h.detailSvc != nil {
|
|
stillURLs = h.detailSvc.PresignURLsWithExpiry(ctx, stillPaths, "card")
|
|
}
|
|
for i := range resp {
|
|
resp[i].StillURL = stillURLs[stillPaths[i]].URL
|
|
resp[i].Files = episodeFileResponses(filesByEpisode[resp[i].ContentID], filter)
|
|
resp[i].UserData = userData[resp[i].ContentID]
|
|
}
|
|
return resp
|
|
}
|
|
|
|
// listEpisodeFiles batch-fetches media files keyed by episode ID, falling back
|
|
// to per-episode lookups when the repository lacks batch support.
|
|
func (h *ItemsHandler) listEpisodeFiles(ctx context.Context, episodeIDs []string) map[string][]*models.MediaFile {
|
|
if h.fileRepo == nil || len(episodeIDs) == 0 {
|
|
return nil
|
|
}
|
|
if batchProvider, ok := h.fileRepo.(batchEpisodeFileProvider); ok {
|
|
files, err := batchProvider.ListByEpisodeIDs(ctx, episodeIDs)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return files
|
|
}
|
|
files := make(map[string][]*models.MediaFile, len(episodeIDs))
|
|
for _, id := range episodeIDs {
|
|
if list, err := h.fileRepo.GetByEpisodeID(ctx, id); err == nil {
|
|
files[id] = list
|
|
}
|
|
}
|
|
return files
|
|
}
|
|
|
|
func episodeFileResponses(files []*models.MediaFile, filter catalog.AccessFilter) []episodeFileResponse {
|
|
var resp []episodeFileResponse
|
|
for _, f := range files {
|
|
if !catalog.FileAllowedByAccess(f, filter) {
|
|
continue
|
|
}
|
|
resp = append(resp, episodeFileResponse{
|
|
FileID: f.ID,
|
|
Resolution: f.Resolution,
|
|
CodecVideo: f.CodecVideo,
|
|
HDR: f.HDR,
|
|
AudioChannels: f.AudioChannels,
|
|
Container: f.Container,
|
|
FileSize: f.FileSize,
|
|
})
|
|
}
|
|
return resp
|
|
}
|
|
|
|
func (h *ItemsHandler) episodeImageFallbacks(ctx context.Context, episodes []*models.Episode) map[string]episodeImageFallback {
|
|
if h.itemRepo == nil || len(episodes) == 0 {
|
|
return map[string]episodeImageFallback{}
|
|
}
|
|
seriesIDs := make([]string, 0, 1)
|
|
seen := make(map[string]struct{})
|
|
for _, ep := range episodes {
|
|
if ep == nil || strings.TrimSpace(ep.SeriesID) == "" {
|
|
continue
|
|
}
|
|
if _, ok := seen[ep.SeriesID]; ok {
|
|
continue
|
|
}
|
|
seen[ep.SeriesID] = struct{}{}
|
|
seriesIDs = append(seriesIDs, ep.SeriesID)
|
|
}
|
|
if len(seriesIDs) == 0 {
|
|
return map[string]episodeImageFallback{}
|
|
}
|
|
|
|
seriesItems, err := h.itemRepo.GetByIDs(ctx, seriesIDs)
|
|
if err != nil {
|
|
return map[string]episodeImageFallback{}
|
|
}
|
|
fallbacks := make(map[string]episodeImageFallback, len(seriesItems))
|
|
for _, series := range seriesItems {
|
|
if series == nil {
|
|
continue
|
|
}
|
|
path := strings.TrimSpace(series.BackdropPath)
|
|
thumbhash := series.BackdropThumbhash
|
|
if path == "" {
|
|
path = strings.TrimSpace(series.PosterPath)
|
|
thumbhash = series.PosterThumbhash
|
|
}
|
|
if path == "" {
|
|
continue
|
|
}
|
|
fallbacks[series.ContentID] = episodeImageFallback{Path: path, Thumbhash: thumbhash}
|
|
}
|
|
return fallbacks
|
|
}
|
|
|
|
func (h *ItemsHandler) listOverlaySummaries(ctx context.Context, items []*models.MediaItem, filter catalog.AccessFilter) map[string]*models.OverlaySummary {
|
|
summaries := make(map[string]*models.OverlaySummary, len(items))
|
|
if h.fileRepo == nil || len(items) == 0 {
|
|
return summaries
|
|
}
|
|
|
|
groupedFiles := h.listBrowseItemFiles(ctx, items, filter)
|
|
for contentID, files := range groupedFiles {
|
|
if summary := overlays.BuildSummary(files); summary != nil {
|
|
summaries[contentID] = summary
|
|
}
|
|
}
|
|
return summaries
|
|
}
|
|
|
|
func (h *ItemsHandler) listSortMetrics(
|
|
ctx context.Context,
|
|
items []*models.MediaItem,
|
|
sortField string,
|
|
filter catalog.AccessFilter,
|
|
overlaySummaries map[string]*models.OverlaySummary,
|
|
store userstore.UserStore,
|
|
userID int,
|
|
profileID string,
|
|
) map[string]*sortMetricsResponse {
|
|
metrics := make(map[string]*sortMetricsResponse, len(items))
|
|
switch sortField {
|
|
case "release_date":
|
|
for _, item := range items {
|
|
if item == nil {
|
|
continue
|
|
}
|
|
releaseDate := firstNonBlankPtr(item.ReleaseDate, item.FirstAirDate)
|
|
if releaseDate != nil {
|
|
metrics[item.ContentID] = &sortMetricsResponse{ReleaseDate: releaseDate}
|
|
}
|
|
}
|
|
case "runtime":
|
|
for _, item := range items {
|
|
if item == nil || item.Runtime <= 0 {
|
|
continue
|
|
}
|
|
runtimeMinutes := item.Runtime
|
|
metrics[item.ContentID] = &sortMetricsResponse{RuntimeMinutes: &runtimeMinutes}
|
|
}
|
|
case "resolution":
|
|
for _, item := range items {
|
|
if item == nil {
|
|
continue
|
|
}
|
|
if summary := overlaySummaries[item.ContentID]; summary != nil && strings.TrimSpace(summary.Resolution) != "" {
|
|
metrics[item.ContentID] = &sortMetricsResponse{Resolution: summary.Resolution}
|
|
}
|
|
}
|
|
case "bitrate":
|
|
groupedFiles := h.listBrowseItemFiles(ctx, items, filter)
|
|
for contentID, files := range groupedFiles {
|
|
if bitrate := maxFileBitrate(files); bitrate > 0 {
|
|
value := bitrate
|
|
metrics[contentID] = &sortMetricsResponse{BitrateKbps: &value}
|
|
}
|
|
}
|
|
case "progress", "date_viewed", "plays":
|
|
h.listUserSortMetrics(ctx, items, sortField, store, userID, profileID, metrics)
|
|
case "author", "narrator", "series":
|
|
h.listAudiobookSortMetrics(ctx, items, sortField, metrics)
|
|
}
|
|
return metrics
|
|
}
|
|
|
|
func (h *ItemsHandler) listAudiobookSortMetrics(
|
|
ctx context.Context,
|
|
items []*models.MediaItem,
|
|
sortField string,
|
|
metrics map[string]*sortMetricsResponse,
|
|
) {
|
|
if h == nil || h.browseRepo == nil || h.browseRepo.Pool() == nil || len(items) == 0 {
|
|
return
|
|
}
|
|
contentIDs := uniqueItemContentIDs(items)
|
|
if len(contentIDs) == 0 {
|
|
return
|
|
}
|
|
|
|
var query string
|
|
switch sortField {
|
|
case "author":
|
|
query = audiobookPersonSortMetricQuery(int(models.PersonKindAuthor))
|
|
case "narrator":
|
|
query = audiobookPersonSortMetricQuery(int(models.PersonKindNarrator))
|
|
case "series":
|
|
query = `
|
|
SELECT target.content_id, BTRIM(s.series_name) AS value
|
|
FROM unnest($1::text[]) WITH ORDINALITY AS target(content_id, ord)
|
|
JOIN audiobook_series s ON s.content_id = target.content_id
|
|
WHERE BTRIM(s.series_name) <> ''`
|
|
default:
|
|
return
|
|
}
|
|
|
|
rows, err := h.browseRepo.Pool().Query(ctx, query, contentIDs)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
var contentID, value string
|
|
if err := rows.Scan(&contentID, &value); err != nil {
|
|
return
|
|
}
|
|
value = strings.TrimSpace(value)
|
|
if contentID == "" || value == "" {
|
|
continue
|
|
}
|
|
resp := metrics[contentID]
|
|
if resp == nil {
|
|
resp = &sortMetricsResponse{}
|
|
metrics[contentID] = resp
|
|
}
|
|
switch sortField {
|
|
case "author":
|
|
resp.Author = value
|
|
case "narrator":
|
|
resp.Narrator = value
|
|
case "series":
|
|
resp.SeriesName = value
|
|
}
|
|
}
|
|
}
|
|
|
|
func audiobookPersonSortMetricQuery(kind int) string {
|
|
return fmt.Sprintf(`
|
|
SELECT target.content_id, person.name AS value
|
|
FROM unnest($1::text[]) WITH ORDINALITY AS target(content_id, ord)
|
|
JOIN LATERAL (
|
|
SELECT BTRIM(p.name) AS name
|
|
FROM item_people ip
|
|
JOIN people p ON p.id = ip.person_id
|
|
WHERE ip.content_id = target.content_id
|
|
AND ip.kind = %d
|
|
AND p.name IS NOT NULL
|
|
AND BTRIM(p.name) <> ''
|
|
ORDER BY p.name ASC
|
|
LIMIT 1
|
|
) person ON TRUE`, kind)
|
|
}
|
|
|
|
func (h *ItemsHandler) listUserSortMetrics(
|
|
ctx context.Context,
|
|
items []*models.MediaItem,
|
|
sortField string,
|
|
store userstore.UserStore,
|
|
userID int,
|
|
profileID string,
|
|
metrics map[string]*sortMetricsResponse,
|
|
) {
|
|
if store == nil || profileID == "" || len(items) == 0 {
|
|
return
|
|
}
|
|
contentIDs := uniqueItemContentIDs(items)
|
|
if len(contentIDs) == 0 {
|
|
return
|
|
}
|
|
|
|
progressMap, err := store.ListProgressByMediaItems(ctx, profileID, contentIDs)
|
|
if err != nil {
|
|
return
|
|
}
|
|
ebookProgressMap, err := h.listEbookReaderProgressByContentIDs(ctx, userID, profileID, contentIDs)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
switch sortField {
|
|
case "progress":
|
|
for _, item := range items {
|
|
if item == nil || item.ContentID == "" {
|
|
continue
|
|
}
|
|
progress, ok := progressMap[item.ContentID]
|
|
if ok && !progress.Completed && progress.PositionSeconds > 0 && progress.DurationSeconds > 0 {
|
|
ratio := progress.PositionSeconds / progress.DurationSeconds
|
|
metrics[item.ContentID] = &sortMetricsResponse{ProgressRatio: &ratio}
|
|
continue
|
|
}
|
|
ebookProgress, ok := ebookProgressMap[item.ContentID]
|
|
if !ok || ebookProgress.Progress <= 0 || ebookProgress.Progress >= models.EbookFinishedProgressThreshold {
|
|
continue
|
|
}
|
|
ratio := ebookProgress.Progress
|
|
metrics[item.ContentID] = &sortMetricsResponse{ProgressRatio: &ratio}
|
|
}
|
|
case "date_viewed", "plays":
|
|
history, err := listCompletedHistoryForItems(ctx, store, profileID, contentIDs)
|
|
if err != nil {
|
|
return
|
|
}
|
|
historyCounts := make(map[string]int, len(contentIDs))
|
|
historyViewedAt := make(map[string]string, len(contentIDs))
|
|
for _, entry := range history {
|
|
if entry.MediaItemID == "" {
|
|
continue
|
|
}
|
|
historyCounts[entry.MediaItemID]++
|
|
if entry.WatchedAt > historyViewedAt[entry.MediaItemID] {
|
|
historyViewedAt[entry.MediaItemID] = entry.WatchedAt
|
|
}
|
|
}
|
|
for _, item := range items {
|
|
if item == nil || item.ContentID == "" {
|
|
continue
|
|
}
|
|
resp := &sortMetricsResponse{}
|
|
if sortField == "date_viewed" {
|
|
viewedAt := historyViewedAt[item.ContentID]
|
|
if progress, ok := progressMap[item.ContentID]; ok && progress.Completed && progress.UpdatedAt > viewedAt {
|
|
viewedAt = progress.UpdatedAt
|
|
}
|
|
if progress, ok := ebookProgressMap[item.ContentID]; ok && progress.Progress >= models.EbookFinishedProgressThreshold {
|
|
ebookViewedAt := progress.UpdatedAt.UTC().Format(time.RFC3339)
|
|
if ebookViewedAt > viewedAt {
|
|
viewedAt = ebookViewedAt
|
|
}
|
|
}
|
|
if viewedAt == "" {
|
|
continue
|
|
}
|
|
resp.ViewedAt = viewedAt
|
|
} else {
|
|
playCount := historyCounts[item.ContentID]
|
|
if progress, ok := progressMap[item.ContentID]; ok && progress.Completed && playCount < 1 {
|
|
playCount = 1
|
|
}
|
|
if progress, ok := ebookProgressMap[item.ContentID]; ok && progress.Progress >= models.EbookFinishedProgressThreshold && playCount < 1 {
|
|
playCount = 1
|
|
}
|
|
if playCount <= 0 {
|
|
continue
|
|
}
|
|
resp.PlayCount = &playCount
|
|
}
|
|
metrics[item.ContentID] = resp
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) listEbookReaderProgressByContentIDs(
|
|
ctx context.Context,
|
|
userID int,
|
|
profileID string,
|
|
contentIDs []string,
|
|
) (map[string]EbookReaderProgress, error) {
|
|
if h == nil || h.ebookProgressStore == nil || userID <= 0 || profileID == "" || len(contentIDs) == 0 {
|
|
return nil, nil
|
|
}
|
|
return h.ebookProgressStore.ListByContentIDs(ctx, userID, profileID, contentIDs)
|
|
}
|
|
|
|
func uniqueItemContentIDs(items []*models.MediaItem) []string {
|
|
contentIDs := make([]string, 0, len(items))
|
|
seen := make(map[string]struct{}, len(items))
|
|
for _, item := range items {
|
|
if item == nil || item.ContentID == "" {
|
|
continue
|
|
}
|
|
if _, ok := seen[item.ContentID]; ok {
|
|
continue
|
|
}
|
|
seen[item.ContentID] = struct{}{}
|
|
contentIDs = append(contentIDs, item.ContentID)
|
|
}
|
|
return contentIDs
|
|
}
|
|
|
|
func listCompletedHistoryForItems(
|
|
ctx context.Context,
|
|
store userstore.UserStore,
|
|
profileID string,
|
|
contentIDs []string,
|
|
) ([]userstore.WatchHistoryEntry, error) {
|
|
const pageSize = 500
|
|
var all []userstore.WatchHistoryEntry
|
|
for offset := 0; ; offset += pageSize {
|
|
page, err := store.ListCompletedHistory(ctx, userstore.CompletedHistoryQuery{
|
|
ProfileID: profileID,
|
|
MediaItemIDs: contentIDs,
|
|
Limit: pageSize,
|
|
Offset: offset,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
all = append(all, page...)
|
|
if len(page) < pageSize {
|
|
return all, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) listBrowseItemFiles(ctx context.Context, items []*models.MediaItem, filter catalog.AccessFilter) map[string][]*models.MediaFile {
|
|
grouped := make(map[string][]*models.MediaFile, len(items))
|
|
if h.fileRepo == nil || len(items) == 0 {
|
|
return grouped
|
|
}
|
|
|
|
contentIDs := make([]string, 0, len(items))
|
|
episodeIDs := make([]string, 0)
|
|
seen := make(map[string]struct{}, len(items))
|
|
for _, item := range items {
|
|
if item == nil || item.ContentID == "" {
|
|
continue
|
|
}
|
|
if _, ok := seen[item.ContentID]; ok {
|
|
continue
|
|
}
|
|
seen[item.ContentID] = struct{}{}
|
|
if item.Type == "episode" {
|
|
episodeIDs = append(episodeIDs, item.ContentID)
|
|
} else {
|
|
contentIDs = append(contentIDs, item.ContentID)
|
|
}
|
|
}
|
|
|
|
if len(contentIDs) > 0 {
|
|
contentFiles, err := h.fileRepo.ListByContentIDs(ctx, contentIDs)
|
|
if err == nil {
|
|
for contentID, files := range contentFiles {
|
|
grouped[contentID] = catalog.FilterMediaFilesByAccess(files, filter)
|
|
}
|
|
}
|
|
}
|
|
|
|
if len(episodeIDs) > 0 {
|
|
if batchProvider, ok := h.fileRepo.(batchEpisodeFileProvider); ok {
|
|
episodeFiles, err := batchProvider.ListByEpisodeIDs(ctx, episodeIDs)
|
|
if err == nil {
|
|
for episodeID, files := range episodeFiles {
|
|
grouped[episodeID] = catalog.FilterMediaFilesByAccess(files, filter)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return grouped
|
|
}
|
|
|
|
func firstNonBlankPtr(values ...*string) *string {
|
|
for _, value := range values {
|
|
if value == nil || strings.TrimSpace(*value) == "" {
|
|
continue
|
|
}
|
|
copyValue := *value
|
|
return ©Value
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func maxFileBitrate(files []*models.MediaFile) int {
|
|
maxBitrate := 0
|
|
for _, file := range files {
|
|
if file != nil && file.Bitrate > maxBitrate {
|
|
maxBitrate = file.Bitrate
|
|
}
|
|
}
|
|
return maxBitrate
|
|
}
|
|
|
|
// toSeasonResponse converts a Season model to an API response.
|
|
func (h *ItemsHandler) toSeasonResponse(r *http.Request, seriesID string, s *models.Season) seasonResponse {
|
|
if h.detailSvc != nil {
|
|
if localized, err := h.detailSvc.LocalizeSeasonModel(r.Context(), s, h.accessFilter(r)); err == nil && localized != nil {
|
|
s = localized
|
|
}
|
|
}
|
|
episodes, _ := h.episodeRepo.ListBySeason(r.Context(), seriesID, s.SeasonNumber)
|
|
|
|
resp := seasonResponse{
|
|
ContentID: s.ContentID,
|
|
SeasonNumber: s.SeasonNumber,
|
|
IsSpecials: s.SeasonNumber == 0,
|
|
Title: s.Title,
|
|
Overview: s.Overview,
|
|
EpisodeCount: len(episodes),
|
|
PosterThumbhash: s.PosterThumbhash,
|
|
}
|
|
if s.AirDate != nil {
|
|
resp.AirDate = s.AirDate.Format("2006-01-02")
|
|
}
|
|
resp.PosterURL = h.presignURL(r, featuredPosterPath(s.PosterPath), "featured")
|
|
resp.UserData = h.getAggregateUserData(r, episodes)
|
|
|
|
return resp
|
|
}
|
|
|
|
func (h *ItemsHandler) getLeafUserData(r *http.Request, contentID string, itemType ...string) *catalog.SeasonUserData {
|
|
if len(itemType) > 0 && itemType[0] == "ebook" {
|
|
return h.getEbookLeafUserData(r, contentID)
|
|
}
|
|
|
|
store, profileID, ok := h.userStoreForRequest(r)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
progress, err := store.GetProgress(r.Context(), profileID, contentID)
|
|
if err != nil || progress == nil {
|
|
return nil
|
|
}
|
|
|
|
return leafUserDataFromProgress(*progress)
|
|
}
|
|
|
|
// listLeafUserData batch-fetches watch progress for the given content IDs in a
|
|
// single query; the result only holds entries for items with progress rows.
|
|
func (h *ItemsHandler) listLeafUserData(r *http.Request, contentIDs []string) map[string]*catalog.SeasonUserData {
|
|
store, profileID, ok := h.userStoreForRequest(r)
|
|
if !ok || len(contentIDs) == 0 {
|
|
return nil
|
|
}
|
|
|
|
progressMap, err := store.ListProgressByMediaItems(r.Context(), profileID, contentIDs)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
result := make(map[string]*catalog.SeasonUserData, len(progressMap))
|
|
for contentID, progress := range progressMap {
|
|
result[contentID] = leafUserDataFromProgress(progress)
|
|
}
|
|
return result
|
|
}
|
|
|
|
func leafUserDataFromProgress(progress userstore.WatchProgress) *catalog.SeasonUserData {
|
|
return &catalog.SeasonUserData{
|
|
PositionSeconds: progress.PositionSeconds,
|
|
DurationSeconds: progress.DurationSeconds,
|
|
IsInProgress: progress.PositionSeconds > 0,
|
|
Played: progress.Completed,
|
|
LastFileID: progress.LastFileID,
|
|
LastResolution: progress.LastResolution,
|
|
LastHDR: progress.LastHDR,
|
|
LastCodecVideo: progress.LastCodecVideo,
|
|
LastEditionKey: progress.LastEditionKey,
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) getEbookLeafUserData(r *http.Request, contentID string) *catalog.SeasonUserData {
|
|
if h == nil || h.ebookProgressStore == nil {
|
|
return nil
|
|
}
|
|
userID := apimw.GetUserID(r.Context())
|
|
profileID := requestProfileID(r)
|
|
if userID <= 0 || profileID == "" || contentID == "" {
|
|
return nil
|
|
}
|
|
|
|
progress, err := h.ebookProgressStore.ListByContentIDs(r.Context(), userID, profileID, []string{contentID})
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
row, ok := progress[contentID]
|
|
if !ok || row.Progress <= 0 {
|
|
return nil
|
|
}
|
|
|
|
// Ebooks have no playback duration, so PositionSeconds/DurationSeconds
|
|
// encode the 0..1 reading ratio (position=ratio, duration=1). Clients can
|
|
// derive percent-complete from the pair as usual, but rendering them as
|
|
// absolute times is meaningless for ebooks. Changing the wire shape needs
|
|
// coordinated Android/Apple client updates.
|
|
return &catalog.SeasonUserData{
|
|
PositionSeconds: row.Progress,
|
|
DurationSeconds: 1,
|
|
IsInProgress: row.Progress < models.EbookFinishedProgressThreshold,
|
|
Played: row.Progress >= models.EbookFinishedProgressThreshold,
|
|
}
|
|
}
|
|
|
|
func applyEffectiveEditionPreference(userData *catalog.SeasonUserData, target **string) {
|
|
if userData == nil || userData.LastEditionKey == nil || *userData.LastEditionKey == "" {
|
|
return
|
|
}
|
|
if target != nil && *target == nil {
|
|
*target = userData.LastEditionKey
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) getAggregateUserData(r *http.Request, episodes []*models.Episode) *catalog.SeasonUserData {
|
|
if len(episodes) == 0 {
|
|
return nil
|
|
}
|
|
|
|
store, profileID, ok := h.userStoreForRequest(r)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
var watchedCount int
|
|
var inProgressCount int
|
|
for _, ep := range episodes {
|
|
progress, progressErr := store.GetProgress(r.Context(), profileID, ep.ContentID)
|
|
if progressErr != nil || progress == nil {
|
|
continue
|
|
}
|
|
if progress.Completed {
|
|
watchedCount++
|
|
continue
|
|
}
|
|
if progress.PositionSeconds > 0 {
|
|
inProgressCount++
|
|
}
|
|
}
|
|
|
|
unplayedCount := len(episodes) - watchedCount
|
|
return &catalog.SeasonUserData{
|
|
WatchedCount: watchedCount,
|
|
UnplayedCount: unplayedCount,
|
|
InProgressCount: inProgressCount,
|
|
Played: watchedCount == len(episodes),
|
|
}
|
|
}
|
|
|
|
// requestProfileID resolves the active profile for a request, falling back to
|
|
// the X-Profile-Id header when the auth context does not carry one.
|
|
func requestProfileID(r *http.Request) string {
|
|
profileID := apimw.GetProfileID(r.Context())
|
|
if profileID == "" {
|
|
profileID = r.Header.Get("X-Profile-Id")
|
|
}
|
|
return profileID
|
|
}
|
|
|
|
func (h *ItemsHandler) userStoreForRequest(r *http.Request) (userstore.UserStore, string, bool) {
|
|
if h.storeProvider == nil {
|
|
return nil, "", false
|
|
}
|
|
|
|
userID := apimw.GetUserID(r.Context())
|
|
if userID == 0 {
|
|
return nil, "", false
|
|
}
|
|
|
|
profileID := requestProfileID(r)
|
|
if profileID == "" {
|
|
return nil, "", false
|
|
}
|
|
|
|
store, err := h.storeProvider.ForUser(r.Context(), userID)
|
|
if err != nil || store == nil {
|
|
return nil, "", false
|
|
}
|
|
|
|
return store, profileID, true
|
|
}
|
|
|
|
// cardThumbnailPath converts an S3 image path from original to w300 for use in
|
|
// browse/card views (posters, backdrops, and stills at card size).
|
|
// Full URLs (TMDB/TVDB) and plugin-prefixed paths are returned as-is —
|
|
// variant selection is handled at resolution time for plugin paths.
|
|
func cardThumbnailPath(path string) string {
|
|
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
|
|
return path
|
|
}
|
|
// Plugin-prefixed paths pass through — variant handled at resolution time.
|
|
if strings.Contains(path, "://") {
|
|
return path
|
|
}
|
|
return strings.Replace(path, "/original.", "/w300.", 1)
|
|
}
|
|
|
|
// featuredPosterPath converts an S3 poster path from original to w500 for
|
|
// featured/hero contexts (displayed at ~220px CSS / 440px retina).
|
|
// Full URLs (TMDB/TVDB) and plugin-prefixed paths are returned as-is.
|
|
func featuredPosterPath(path string) string {
|
|
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
|
|
return path
|
|
}
|
|
if strings.Contains(path, "://") {
|
|
return path
|
|
}
|
|
return strings.Replace(path, "/original.", "/w500.", 1)
|
|
}
|
|
|
|
// featuredBackdropPath converts an S3 backdrop path from original to w1920 for
|
|
// featured/hero contexts (displayed at full viewport width). Episode stills
|
|
// used as backdrops lack a w1920 variant and clamp to their largest cached
|
|
// size. Full URLs (TMDB/TVDB) and plugin-prefixed paths are returned as-is.
|
|
func featuredBackdropPath(path string) string {
|
|
return catalog.BackdropVariantPath(path, "w1920")
|
|
}
|
|
|
|
// presignURL resolves an image path to a usable URL, delegating to the
|
|
// DetailService which handles plugin-prefixed paths, HTTP pass-through,
|
|
// and legacy S3 presigning.
|
|
func (h *ItemsHandler) presignURL(r *http.Request, path string, variant string) string {
|
|
if h.detailSvc != nil {
|
|
return h.detailSvc.PresignURL(r.Context(), path, variant)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// HandleFilterItems handles POST /items/filter with a full rule-group filter body.
|
|
func (h *ItemsHandler) HandleFilterItems(w http.ResponseWriter, r *http.Request) {
|
|
writeDeprecatedReadHeaders(w, "/api/v1/catalog/query")
|
|
h.catalogHandler().HandlePostCatalogQuery(w, r)
|
|
}
|
|
|
|
type filterItemsRequest struct {
|
|
sections.FilterConfig
|
|
LibraryID int `json:"library_id"`
|
|
Limit int `json:"limit"`
|
|
Offset int `json:"offset"`
|
|
}
|
|
|
|
func filterItemColumns(alias string) string {
|
|
cols := []string{
|
|
"content_id", "type", "title", "sort_title", "original_title", "year", "genres",
|
|
"content_rating", "runtime", "overview", "tagline",
|
|
"rating_imdb", "rating_tmdb", "rating_rt_critic", "rating_rt_audience",
|
|
"imdb_id", "tmdb_id", "tvdb_id",
|
|
"poster_path", "poster_thumbhash", "backdrop_path", "backdrop_thumbhash", "logo_path",
|
|
"metadata_s3_path", "metadata_etag", "season_count",
|
|
"studios", "networks", "countries", "first_air_date", "last_air_date",
|
|
"matched_at", "status", "created_at", "updated_at",
|
|
}
|
|
prefixed := make([]string, len(cols))
|
|
for i, c := range cols {
|
|
prefixed[i] = alias + "." + c
|
|
}
|
|
return strings.Join(prefixed, ", ")
|
|
}
|
|
|
|
func filterSortClause(sort, order string) string {
|
|
dir := "DESC"
|
|
if order == "asc" {
|
|
dir = "ASC"
|
|
}
|
|
switch sort {
|
|
case "rating":
|
|
return fmt.Sprintf("ORDER BY mi.rating_imdb %s NULLS LAST", dir)
|
|
case "year":
|
|
return fmt.Sprintf("ORDER BY mi.year %s", dir)
|
|
case "title":
|
|
return fmt.Sprintf("ORDER BY LOWER(COALESCE(NULLIF(BTRIM(mi.sort_title), ''), mi.title)) %s, LOWER(mi.title) %s, mi.content_id ASC", dir, dir)
|
|
default:
|
|
return fmt.Sprintf("ORDER BY mi.created_at %s", dir)
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) accessFilter(r *http.Request) catalog.AccessFilter {
|
|
selectedFileID := 0
|
|
if fileIDRaw := strings.TrimSpace(r.URL.Query().Get("fileId")); fileIDRaw != "" {
|
|
if fileID, err := strconv.Atoi(fileIDRaw); err == nil && fileID > 0 {
|
|
selectedFileID = fileID
|
|
}
|
|
}
|
|
|
|
var presentationLibraryID *int
|
|
if libraryIDRaw := strings.TrimSpace(r.URL.Query().Get("library_id")); libraryIDRaw != "" {
|
|
if libraryID, err := strconv.Atoi(libraryIDRaw); err == nil && libraryID > 0 {
|
|
presentationLibraryID = &libraryID
|
|
}
|
|
}
|
|
|
|
if scope, ok := access.GetScope(r.Context()); ok {
|
|
return catalog.AccessFilter{
|
|
AllowedLibraryIDs: scope.AllowedLibraryIDs,
|
|
DisabledLibraryIDs: scope.DisabledLibraryIDs,
|
|
MaxContentRating: scope.MaxContentRating,
|
|
MaxPlaybackQuality: scope.MaxPlaybackQuality,
|
|
PresentationLibraryID: presentationLibraryID,
|
|
ProfilePreferredLanguage: scope.PreferredMetadataLanguage,
|
|
SelectedFileID: selectedFileID,
|
|
UserID: apimw.GetUserID(r.Context()),
|
|
ProfileID: apimw.GetProfileID(r.Context()),
|
|
}
|
|
}
|
|
|
|
var libraryIDs []int
|
|
var maxPlaybackQuality string
|
|
if h.UserRepo != nil {
|
|
userID := apimw.GetUserID(r.Context())
|
|
if userID != 0 {
|
|
user, userErr := h.UserRepo.GetByID(r.Context(), userID)
|
|
if userErr != nil {
|
|
slog.Error("looking up user for library access", "error", userErr)
|
|
} else {
|
|
if user.LibraryIDs != nil {
|
|
libraryIDs = user.LibraryIDs
|
|
}
|
|
maxPlaybackQuality = access.NormalizePlaybackQuality(user.MaxPlaybackQuality)
|
|
}
|
|
}
|
|
}
|
|
|
|
return catalog.AccessFilter{
|
|
AllowedLibraryIDs: libraryIDs,
|
|
MaxPlaybackQuality: maxPlaybackQuality,
|
|
PresentationLibraryID: presentationLibraryID,
|
|
SelectedFileID: selectedFileID,
|
|
UserID: apimw.GetUserID(r.Context()),
|
|
ProfileID: apimw.GetProfileID(r.Context()),
|
|
}
|
|
}
|
|
|
|
func (h *ItemsHandler) ensurePresentationLibraryAccess(ctx context.Context, contentID string, filter catalog.AccessFilter) error {
|
|
if filter.PresentationLibraryID == nil {
|
|
return nil
|
|
}
|
|
membership, err := h.itemRepo.GetItemsInLibrary(ctx, []string{contentID}, *filter.PresentationLibraryID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !membership[contentID] {
|
|
return catalog.ErrItemNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type watchedLeafTarget struct {
|
|
ContentID string
|
|
DurationSeconds float64
|
|
}
|
|
|
|
func (h *ItemsHandler) resolveWatchedTargets(ctx context.Context, contentID string, filter catalog.AccessFilter) (string, []watchedLeafTarget, error) {
|
|
item, err := h.itemRepo.GetByID(ctx, contentID)
|
|
switch {
|
|
case err == nil:
|
|
if err := h.itemRepo.EnsureAccessible(ctx, contentID, filter); err != nil {
|
|
return "", nil, err
|
|
}
|
|
switch item.Type {
|
|
case "movie":
|
|
return "movie", []watchedLeafTarget{{
|
|
ContentID: item.ContentID,
|
|
DurationSeconds: h.contentDurationSeconds(ctx, item.ContentID, "", item.Runtime),
|
|
}}, nil
|
|
case "ebook":
|
|
// Ebooks have no playback duration; read state is keyed off
|
|
// ebook_reader_progress, so the leaf target only carries the ID.
|
|
return "ebook", []watchedLeafTarget{{ContentID: item.ContentID}}, nil
|
|
case "series":
|
|
if h.episodeRepo == nil {
|
|
return "", nil, catalog.ErrItemNotFound
|
|
}
|
|
episodes, err := h.episodeRepo.ListBySeries(ctx, item.ContentID)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
return "series", h.episodeTargets(ctx, episodes), nil
|
|
default:
|
|
return "", nil, catalog.ErrItemNotFound
|
|
}
|
|
case !errors.Is(err, catalog.ErrItemNotFound):
|
|
return "", nil, err
|
|
}
|
|
|
|
if h.seasonRepo != nil {
|
|
season, err := h.seasonRepo.GetByID(ctx, contentID)
|
|
switch {
|
|
case err == nil:
|
|
if err := h.itemRepo.EnsureAccessible(ctx, season.SeriesID, filter); err != nil {
|
|
return "", nil, err
|
|
}
|
|
if h.episodeRepo == nil {
|
|
return "", nil, catalog.ErrItemNotFound
|
|
}
|
|
episodes, err := h.episodeRepo.ListBySeasonID(ctx, season.ContentID)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
return "season", h.episodeTargets(ctx, episodes), nil
|
|
case !errors.Is(err, catalog.ErrSeasonNotFound):
|
|
return "", nil, err
|
|
}
|
|
}
|
|
|
|
if h.episodeRepo == nil {
|
|
return "", nil, catalog.ErrItemNotFound
|
|
}
|
|
|
|
episode, err := h.episodeRepo.GetByID(ctx, contentID)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
if err := h.itemRepo.EnsureAccessible(ctx, episode.SeriesID, filter); err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
return "episode", []watchedLeafTarget{{
|
|
ContentID: episode.ContentID,
|
|
DurationSeconds: h.contentDurationSeconds(ctx, "", episode.ContentID, episode.Runtime),
|
|
}}, nil
|
|
}
|
|
|
|
func (h *ItemsHandler) episodeTargets(ctx context.Context, episodes []*models.Episode) []watchedLeafTarget {
|
|
targets := make([]watchedLeafTarget, 0, len(episodes))
|
|
for _, episode := range episodes {
|
|
targets = append(targets, watchedLeafTarget{
|
|
ContentID: episode.ContentID,
|
|
DurationSeconds: h.contentDurationSeconds(ctx, "", episode.ContentID, episode.Runtime),
|
|
})
|
|
}
|
|
return targets
|
|
}
|
|
|
|
func (h *ItemsHandler) contentDurationSeconds(ctx context.Context, contentID, episodeID string, fallbackRuntimeMinutes int) float64 {
|
|
if h.fileRepo == nil {
|
|
if fallbackRuntimeMinutes > 0 {
|
|
return float64(fallbackRuntimeMinutes * 60)
|
|
}
|
|
return 0
|
|
}
|
|
|
|
var (
|
|
files []*models.MediaFile
|
|
err error
|
|
)
|
|
|
|
switch {
|
|
case episodeID != "":
|
|
files, err = h.fileRepo.GetByEpisodeID(ctx, episodeID)
|
|
case contentID != "":
|
|
files, err = h.fileRepo.GetByContentID(ctx, contentID)
|
|
}
|
|
if err == nil {
|
|
for _, file := range files {
|
|
if file != nil && file.Duration > 0 {
|
|
return float64(file.Duration)
|
|
}
|
|
}
|
|
}
|
|
|
|
if fallbackRuntimeMinutes > 0 {
|
|
return float64(fallbackRuntimeMinutes * 60)
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// isNotFound checks if an error is a "not found" sentinel.
|
|
func isNotFound(err error) bool {
|
|
return errors.Is(err, catalog.ErrItemNotFound) ||
|
|
errors.Is(err, catalog.ErrEpisodeNotFound) ||
|
|
errors.Is(err, catalog.ErrSeasonNotFound)
|
|
}
|
|
|
|
func (h *ItemsHandler) requestCanViewFilePaths(r *http.Request) bool {
|
|
claims := apimw.GetClaims(r.Context())
|
|
if claims == nil {
|
|
return false
|
|
}
|
|
if claims.Role == "admin" {
|
|
return true
|
|
}
|
|
if h == nil || h.UserRepo == nil {
|
|
return false
|
|
}
|
|
user, err := h.UserRepo.GetByID(r.Context(), claims.UserID)
|
|
if err != nil {
|
|
slog.WarnContext(r.Context(), "checking file path visibility permissions", "user_id", claims.UserID, "error", err)
|
|
return false
|
|
}
|
|
return auth.HasEffectivePermission(user, auth.PermissionMetadataCuration)
|
|
}
|