Repository navigation
feat(metadata,scanner): trailers and extras for movies and series - #322
Conversation
Remote provider videos (TMDB trailers/teasers/featurettes/...) are fetched through the unified match/refresh pipeline into the new item_videos table, filtered per-library via media_folders.trailer_kinds, merged across providers with site/provider dedup, and lockable via FieldVideos. The movie scanner stops discarding supplemental directories (Trailers/, Featurettes/, Behind The Scenes/, ...) and classifies them — plus Jellyfin-style filename suffixes (-trailer, -behindthescenes, ...) and series-root supplemental dirs — into the new media_extras entity backed by ordinary media_files rows (extra_id ownership, content_id/episode_id NULL so existing version/matching queries stay structurally blind to extras). Series Extras/SxxExx season-0 mapping is unchanged. Extras are playable watch targets via a GetWatchDetail fallback tier (episodes precedent), with contentid.ForLocal minting stable ids. API: ItemDetail gains additive videos/extras arrays (single + batch parity); library settings expose trailer_kinds. jellycompat now populates RemoteTrailers, LocalTrailerCount/SpecialFeatureCount, and serves real /LocalTrailers + /SpecialFeatures items playable through PlaybackInfo. Requires silo-plugin-sdk v0.9.0 (VideoRecord) before go.mod can bump; builds locally via go.work against the SDK feat/metadata-videos branch. Part of trailers/extras capability work. Co-Authored-By: Claude Fable 5 <[email protected]>
TrailersSection (YouTube thumbnails + youtube-nocookie modal) and ExtrasSection (plays extras through the standard watch controller) on movie and series detail pages; admin library form gains a trailer-kinds allow-list synced with the server default (all provider kinds), now also honored on library create. Part of trailers/extras capability work. Co-Authored-By: Claude Fable 5 <[email protected]>
scanMediaFiles (the plural row scanner behind GetByContentID/GetByFolder/ GetByExtraID and 20+ other queries) was missing the scan destination for the new extra_id column, which would have failed every media-file read at runtime with a column/destination count mismatch. Also: extend the batch equivalence test to seed item_videos/media_extras so the new videos/extras prefetch wiring is actually proven; drop the one-off pgxRows interface for the repo-wide pgx.Rows convention; reuse formatClock instead of a third duration formatter in ExtrasSection. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds local extras scanning and playback, remote video support, and per-library trailer kind configuration. It updates shared models, migrations, scanner storage, metadata/detail plumbing, Jellyfin-compatible endpoints, admin library APIs, and item detail UI. ChangesExtras and remote trailers feature
Estimated code review effort: 4 (Complex) | ~75 minutes Sequence Diagram(s)sequenceDiagram
participant Scanner
participant ProcessExtraFiles
participant ExtraRepository
participant FileRepository
Scanner->>Scanner: classify extras and split paths
Scanner->>ProcessExtraFiles: extra candidates
ProcessExtraFiles->>ExtraRepository: upsert media_extras
ProcessExtraFiles->>FileRepository: upsert media_files and mark extra
sequenceDiagram
participant Client
participant DetailService
participant ExtraRepository
participant FileRepository
Client->>DetailService: GetWatchDetail(id)
DetailService->>DetailService: episode lookup fails
DetailService->>ExtraRepository: buildExtraWatchDetail
DetailService->>FileRepository: fetch playable files by extraID
DetailService-->>Client: watch detail with parent context
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cf68a458cd
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| } | ||
| // Surface the owning item the way episodes surface their series so | ||
| // players can show "<Extra> — <Movie>" context. | ||
| detail.SeriesID = extra.ParentID |
There was a problem hiding this comment.
Avoid marking movie extras as series items
When the parent is a movie, setting series_id to the movie's content ID gives the frontend a false episodic context: WatchPlaybackChrome treats any series_id as a series and enters the post-roll/next-episode flow instead of returning to the movie page when playback ends. This affects local extras attached to movies; only series-owned extras should populate series fields, or the owning movie context should be exposed through a separate field.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 90fb13d — SeriesID/SeriesTitle are now only populated when the parent is a series (both buildExtraWatchDetail and buildExtraItemDetail); movie extras keep title fallback + Year only.
| if existing != nil && existing.ExtraID == extraID && | ||
| existing.FileSize == info.Size() && existing.ProbeUpdatedAt != nil && | ||
| existing.MissingSince == nil { |
There was a problem hiding this comment.
Re-scan extras when mtime changes
This unchanged shortcut ignores file_modified_at, so replacing an extra in place with a different video of the same byte size leaves the old probe data (duration, streams, chapters) and title/kind association untouched because the scan skips before probing/upserting. The primary scanner already treats mtime changes as an update; extras need the same check to avoid stale playback metadata after same-size file replacements.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 90fb13d — the unchanged fast-path now also requires FileModifiedAt equality, so same-size in-place replacements re-probe.
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
internal/jellycompat/mapping.go (1)
714-738: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePrefer a typed DTO over
map[string]anyfor RemoteTrailers.Other DTOs in this file (
personDTO,mediaSourceDTO, etc.) are typed structs; using an untyped map here loses compile-time key safety and is inconsistent with the surrounding style.♻️ Suggested typed DTO
+type remoteTrailerDTO struct { + Url string `json:"Url"` + Name string `json:"Name"` +} + -func remoteTrailerDTOs(videos []catalog.ItemVideoInfo) []map[string]any { - trailers := []map[string]any{} +func remoteTrailerDTOs(videos []catalog.ItemVideoInfo) []remoteTrailerDTO { + trailers := []remoteTrailerDTO{} for _, v := range videos { if v.Kind != string(models.ExtraKindTrailer) && v.Kind != string(models.ExtraKindTeaser) { continue } var url string switch v.Site { case "youtube": url = "https://www.youtube.com/watch?v=" + v.SiteKey case "vimeo": url = "https://vimeo.com/" + v.SiteKey default: continue } - trailers = append(trailers, map[string]any{ - "Url": url, - "Name": v.Name, - }) + trailers = append(trailers, remoteTrailerDTO{Url: url, Name: v.Name}) } return trailers }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/jellycompat/mapping.go` around lines 714 - 738, The remoteTrailerDTOs helper currently returns an untyped []map[string]any for RemoteTrailers, which is inconsistent with the typed DTOs used elsewhere in mapping.go. Introduce a dedicated typed DTO for the RemoteTrailers shape (Url, Name) and update remoteTrailerDTOs to build and return that type instead of maps, keeping the existing filtering logic for ExtraKindTrailer/ExtraKindTeaser and supported sites intact.internal/jellycompat/handlers_items.go (1)
954-958: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueLog swallowed
GetItemDetailerrors for observability.Genuine internal errors (DB timeouts, etc.) are indistinguishable from "not found" here — both silently produce
200 []. Consider a debug/warn log so backend failures on this path remain visible without changing the client-facing contract.🔍 Suggested logging addition
detail, err := h.content.GetItemDetail(r.Context(), session, contentID, nil) if err != nil { + slog.Debug("local extras: item detail lookup failed", "content_id", contentID, "error", err) writeJSON(w, http.StatusOK, []baseItemDTO{}) return }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/jellycompat/handlers_items.go` around lines 954 - 958, The GetItemDetail error path in h.handleItemsGet is swallowing backend failures by always returning an empty 200 response, which makes real internal issues invisible. Add a debug or warn log in the err branch right after h.content.GetItemDetail(...) fails, including the contentID and the error value, while keeping the existing client-facing writeJSON(w, http.StatusOK, []baseItemDTO{}) response unchanged. Use the surrounding handler logic in handlers_items.go to place the log where the failure is handled.internal/metadata/service.go (1)
764-776: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueUnrecognized
Kindvalues silently rank as highest priority instead of last.
rank[ordered[i].Kind]returns Go's zero value (0) for any kind missing frommodels.AllExtraKinds, which is the same rank as the first vocabulary entry (trailer). If an un-normalizedKindever reaches this function (e.g., videos round-tripped from storage via a path not covered here), it would sort as if it were a trailer instead of falling to the end. Low risk today sincemodels.NormalizeExtraKindis applied at ingestion, but a defensive fallback would remove the ambiguity.♻️ Optional defensive fallback
rank := make(map[models.ExtraKind]int, len(models.AllExtraKinds)) for i, k := range models.AllExtraKinds { rank[k] = i } + unknownRank := len(models.AllExtraKinds) ordered := append([]RemoteVideo(nil), videos...) sort.SliceStable(ordered, func(i, j int) bool { - if ri, rj := rank[ordered[i].Kind], rank[ordered[j].Kind]; ri != rj { + ri, riOK := rank[ordered[i].Kind] + rj, rjOK := rank[ordered[j].Kind] + if !riOK { + ri = unknownRank + } + if !rjOK { + rj = unknownRank + } + if ri != rj { return ri < rj } return ordered[i].IsOfficial && !ordered[j].IsOfficial })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/metadata/service.go` around lines 764 - 776, The sorting in itemVideosFromRemote treats unknown RemoteVideo.Kind values as rank 0 because the map lookup falls back to Go’s zero value, which can incorrectly place them ahead of all known kinds. Update the rank lookup inside itemVideosFromRemote so unrecognized kinds get a lowest-priority fallback (for example, by checking the presence of the key before comparing) while preserving the existing kind and official-ordering behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/catalog/folder_repo.go`:
- Around line 285-297: Normalize and validate trailer_kinds before persisting
them in the folder save paths. In the create/update logic around the
trailerKinds handling in folder_repo.go, trim whitespace and lowercase each
input value before calling models.NormalizeExtraKind, and consider rejecting
values that still normalize to other instead of silently storing them. Apply the
same normalization/validation behavior in both create and update flows so
FolderRepo cannot persist unintended allow-list entries.
In `@internal/scanner/extras.go`:
- Around line 136-143: The fast path in the extra reconciliation logic is
returning too early in the scanner flow, so `parentID` resolution and
`media_extras` upsert never happen for some candidates. Update the `extras.go`
reconciliation path around the `existingByPath`/`extraID` check so the
“unchanged” decision happens only after ownership metadata is refreshed, and
expand the comparison beyond `FileSize` and `ProbeUpdatedAt` to also account for
modified-time and hash changes. This should keep `parent_id`, kind/title, and
probe metadata current even when the file size is unchanged.
In `@internal/scanner/file_repo.go`:
- Around line 887-890: Make the file ownership update atomic in the upsert: in
the conflict handler for the media_files file_path upsert, when
EXCLUDED.extra_id is present, do not preserve content_id or episode_id via
COALESCE. Update the upsert logic in the file_repo.go insert path so the row is
mutually exclusive immediately, clearing primary ownership in the same statement
instead of relying on MarkFileAsExtra afterward. Use the existing upsert block
around the media_files conflict update to identify the change.
In `@internal/scanner/scanner.go`:
- Around line 1661-1667: The early return in scanner.go’s extra-path handling
skips the normal library cleanup after processExtraFiles/MarkFileAsExtra changes
a previously primary file into an extra. Update the classifyExtraPath branch in
scanner.process to run the same post-processing reconciliation as the regular
scan path, specifically the syncPresentLibraryState and
reconcileLibraryMemberships cleanup, before returning success so stale
membership state is cleared immediately.
In `@migrations/sql/20260706201110_media_extras.sql`:
- Around line 29-36: The migration adds an immediate foreign key on
media_files.extra_id and a normal index in the same transaction, which can hold
heavy locks during deployment. Update the media_extras migration to add the FK
on media_files as NOT VALID and validate it in a separate step, and create
idx_media_files_extra_id with CONCURRENTLY in a goose NO TRANSACTION block. Use
the existing media_files, extra_id, and idx_media_files_extra_id statements to
place the changes without changing the schema intent.
---
Nitpick comments:
In `@internal/jellycompat/handlers_items.go`:
- Around line 954-958: The GetItemDetail error path in h.handleItemsGet is
swallowing backend failures by always returning an empty 200 response, which
makes real internal issues invisible. Add a debug or warn log in the err branch
right after h.content.GetItemDetail(...) fails, including the contentID and the
error value, while keeping the existing client-facing writeJSON(w,
http.StatusOK, []baseItemDTO{}) response unchanged. Use the surrounding handler
logic in handlers_items.go to place the log where the failure is handled.
In `@internal/jellycompat/mapping.go`:
- Around line 714-738: The remoteTrailerDTOs helper currently returns an untyped
[]map[string]any for RemoteTrailers, which is inconsistent with the typed DTOs
used elsewhere in mapping.go. Introduce a dedicated typed DTO for the
RemoteTrailers shape (Url, Name) and update remoteTrailerDTOs to build and
return that type instead of maps, keeping the existing filtering logic for
ExtraKindTrailer/ExtraKindTeaser and supported sites intact.
In `@internal/metadata/service.go`:
- Around line 764-776: The sorting in itemVideosFromRemote treats unknown
RemoteVideo.Kind values as rank 0 because the map lookup falls back to Go’s zero
value, which can incorrectly place them ahead of all known kinds. Update the
rank lookup inside itemVideosFromRemote so unrecognized kinds get a
lowest-priority fallback (for example, by checking the presence of the key
before comparing) while preserving the existing kind and official-ordering
behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: eb0ceac9-a6b7-4dee-a211-23360de83b3f
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (41)
docs/wiki/admin/media-folder-and-naming.mdgo.modinternal/api/handlers/libraries.gointernal/catalog/detail.gointernal/catalog/detail_batch_equivalence_test.gointernal/catalog/extras_repo.gointernal/catalog/folder_repo.gointernal/catalog/video_repo.gointernal/jellycompat/content_direct.gointernal/jellycompat/handlers_items.gointernal/jellycompat/mapping.gointernal/jellycompat/router.gointernal/jellycompat/upstream_types.gointernal/metadata/merge.gointernal/metadata/merge_videos_test.gointernal/metadata/plugin_provider.gointernal/metadata/service.gointernal/metadata/types.gointernal/models/extras.gointernal/models/media.gointernal/naming/extras.gointernal/naming/extras_test.gointernal/pathscope/pathscope.gointernal/scanner/extras.gointernal/scanner/extras_test.gointernal/scanner/file_repo.gointernal/scanner/root_observation_test.gointernal/scanner/scan_state.gointernal/scanner/scanner.gomigrations/sql/20260706201109_item_videos.sqlmigrations/sql/20260706201110_media_extras.sqlmigrations/sql/20260706201112_media_folder_trailer_kinds.sqlweb/src/api/types.tsweb/src/components/admin/libraries/LibraryFormSections.tsxweb/src/components/admin/libraries/useLibraryForm.tsweb/src/lib/extraKinds.tsweb/src/pages/ItemDetail/MovieContent.tsxweb/src/pages/ItemDetail/SeriesContent.tsxweb/src/pages/ItemDetail/components/ExtrasSection.tsxweb/src/pages/ItemDetail/components/TrailerModal.tsxweb/src/pages/ItemDetail/components/TrailersSection.tsx
…t linking Dev verification caught extras media_files rows (content_id NULL by design) being swept into the movie/series match queues and the root-claim bulk relink: a '-featurette' suffix extra was matched onto its parent as a version, and a Trailers/ file minted a spurious local skeleton item that shadowed the extra's watch target. Add 'extra_id IS NULL' to the queue eligibility conditions, root/group claim relinks, observed-root content assignment, and the admin unmatched-files listing. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/metadata/series_root_match_queue_repo.go (1)
82-92: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the repeated eligibility predicate into a shared constant.
The pair
mf.missing_since IS NULL AND mf.extra_id IS NULLis now hand-copied across 11 locations in this file (EnqueueSeriesRoot,SyncForFolder,SyncInScope,Claim,ClaimByFolderAndPathPrefix).movie_match_queue_repo.goalready factors its equivalent eligibility condition into amovieQueueFileEligibleCondconstant. A similar constant here would reduce risk of the predicates drifting out of sync on future changes (e.g., if another exclusion flag needs to be added later).♻️ Suggested approach
+const seriesFileLiveCond = `mf.missing_since IS NULL AND mf.extra_id IS NULL`Then reference
seriesFileLiveCondin place of the repeated literal across the five methods.Also applies to: 122-127, 174-180, 204-209, 254-260, 315-320, 358-363, 388-389, 442-443, 456-461, 487-488
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/metadata/series_root_match_queue_repo.go` around lines 82 - 92, Extract the repeated series file eligibility predicate into a shared constant in series_root_match_queue_repo.go, similar to movieQueueFileEligibleCond in the movie repo. Define seriesFileLiveCond and replace every inline occurrence of mf.missing_since IS NULL AND mf.extra_id IS NULL across EnqueueSeriesRoot, SyncForFolder, SyncInScope, Claim, and ClaimByFolderAndPathPrefix so the condition stays consistent in one place.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/metadata/series_root_match_queue_repo.go`:
- Around line 82-92: Extract the repeated series file eligibility predicate into
a shared constant in series_root_match_queue_repo.go, similar to
movieQueueFileEligibleCond in the movie repo. Define seriesFileLiveCond and
replace every inline occurrence of mf.missing_since IS NULL AND mf.extra_id IS
NULL across EnqueueSeriesRoot, SyncForFolder, SyncInScope, Claim, and
ClaimByFolderAndPathPrefix so the condition stays consistent in one place.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 927bc0f1-b5b7-4028-9f93-a9824e6937eb
📒 Files selected for processing (6)
internal/api/handlers/admin.gointernal/catalog/group_claim_repo.gointernal/catalog/root_claim_repo.gointernal/metadata/movie_match_queue_repo.gointernal/metadata/series_root_match_queue_repo.gointernal/scanner/file_repo.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/scanner/file_repo.go
Dev verification: playback/start (and the shared MediaFileAuthorizer used by markers/subtitles/ebook reader) resolved file ownership only via episode_id/content_id, so extras files (extra_id only) 404ed. Add an ExtraLookup tier that resolves media_extras and gates on the parent item's access, mirroring the episode->series pattern. Co-Authored-By: Claude Fable 5 <[email protected]>
…layback jellycompat PlaybackInfo (and any per-item consumer resolving arbitrary content ids) goes through GetItemDetail, which lacked the extras tier that GetWatchDetail has — so Jellyfin clients got zero MediaSources for extras. Add buildExtraItemDetail (minimal detail + ordinary playback surface, parent-gated access) as the fourth resolution tier, and map the extra type to Jellyfin's Video kind. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/playback.go`:
- Around line 2219-2232: The ExtraID branch in playback authorization has the
same nil-guard/configuration asymmetry as MediaFileAuthorizer.Authorize: avoid
returning a silent not-found when ExtraLookup is unset, and add a nil-check
before dereferencing extra.ParentID. Update the ExtraLookup.GetByID flow in
loadAuthorizedFile so it mirrors the safer handling used in
MediaFileAuthorizer.Authorize, returning a clear configuration error when the
lookup dependency is missing and guarding against a nil extra before calling
ItemAccess.EnsureAccessible.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d862e456-448c-4a78-a38c-92c2bc543f76
📒 Files selected for processing (3)
internal/api/handlers/media_file_auth.gointernal/api/handlers/playback.gointernal/api/router.go
Dev deployment verification (100.86.116.20, 2026-07-06)Deployed this branch + SDK v0.9.0 + the TMDB plugin Migrations — all three applied cleanly via the normal boot path ( Remote trailers (TMDB → item_videos) — refreshed Local extras (scanner) — seeded a test movie with Playback — jellycompat — item detail now reports Bugs found & fixed during verification (pushed to this branch)
Web UI screenshots to follow (needs an interactive login session). Test fixtures live in the throwaway "Extras Verify" library ( |
The frontend CSP's frame-src blocked the trailer modal's youtube-nocookie.com iframe (found on dev verification). Also add the missing sr-only DialogDescription and drop the redundant allowFullScreen attribute. Co-Authored-By: Claude Fable 5 <[email protected]>
- Extras watch/item detail no longer stamp SeriesID/SeriesTitle for movie-owned extras (players key episodic post-roll flows off series_id); series-owned extras keep them (Codex). - processExtraFiles resolves the parent and upserts media_extras before the unchanged fast-path, and the fast-path now also compares mtime, so rematched parents / reclassified kinds / same-size replacements converge (Codex + CodeRabbit). - media_files upsert clears content/episode linkage atomically when extra_id is set (ownership mutual exclusion in one statement); the now-redundant MarkFileAsExtra helper is removed (CodeRabbit). - ScanFile's extras branch runs syncPresentLibraryState + reconcileLibraryMemberships so converting a primary file to an extra cleans stale library membership immediately (CodeRabbit). - media_extras migration adds the media_files FK as NOT VALID + VALIDATE to avoid a full-scan exclusive lock on large tables (CodeRabbit). - trailer_kinds input is trimmed/lowercased/deduped and unknown values are dropped instead of silently widening the allow-list to 'other' (CodeRabbit). - Extras authorization branches match the episode branch's posture: unconfigured lookup is a config error, nil extra is a 404 (CodeRabbit). Co-Authored-By: Claude Fable 5 <[email protected]>
|
All actionable review comments addressed in 90fb13d (inline replies on each thread). Two nitpicks deliberately skipped: the typed RemoteTrailers DTO (field + empty-stub predate this PR; wire shape unchanged) and extracting the repeated queue-eligibility predicate into a shared constant (the conditions live inside 11 inline SQL strings across two repos' differing aliases — extraction churn outweighs the win right now). The shared episode/content/extra authorization helper suggestion is a good follow-up but out of scope since the duplication predates the PR. |
* fix(scanner): stop classifying "other" content folders as extras Regression from #322 (trailers and extras for movies and series), which introduced the extrasDirKinds map. The extras directory classifier mapped the generic labels "other" and "others" to ExtraKindOther. These are not part of the Jellyfin/Plex extras folder convention the map claims to mirror, and they collide with real content-scope folder names. A library organized as "movies/other/<Title (year) {ids}>/<file>" tripped the depth-2 ancestor lookup in classifyExtraPath: every title two levels under the scope folder "other" was classified as an "other"-kind extra. Such files are partitioned out of primary root/group inference and matching, then deferred in processExtraFiles because their parent cannot resolve (they are the primary titles, not children of one). The result on one deployment was ~10k movies under a folder named "other" funneled through the slow extras path every scan (parent-unresolved deferrals at ~9.5/s), stalling the scan and freezing that scope for new/changed primary content. Remove "other"/"others" from extrasDirKinds. The ExtraKindOther kind stays reachable through genuine convention labels (extra/extras/interviews/ scenes/shorts). Add regression coverage asserting titles under a scope folder named other/others stay primary. * perf(scanner): rewrite identity-only changes without re-probing A pure identity/grouping change on an already-probed file — a root_assignment_changed or group_assignment_changed reason with nothing else — used to fall into the full update branch, which unconditionally ran ffprobe (probeFile) and then upserted every column, including probe columns, from the freshly built row. When a group-key or root scheme changes across the library (see #319), this reprobed nearly every file on the next scan: an incremental scan that normally takes ~1h ran 7h+ as a full-library ffprobe storm, even though the media bytes were untouched. Add a metadata-only update path in processFile: when identityOnlyUpdateReasons reports every reason is a root/group reassignment, rewrite just the derived identity columns via the new FileRepository.UpdateIdentity and skip ffprobe, OSHash, and marker fetch entirely. UpdateIdentity issues a targeted UPDATE of the root/group/identity and edition/presentation columns only, mirroring Upsert's column handling, and leaves probe data, file bytes/mtime/hash, subtitles, chapters, markers, and content/episode/extra linkage intact. The stored group key converges to the recomputed value on the next scan, so the file takes the unchanged fast-path thereafter — without a probe storm. The shared identity-column population is extracted into populateScanIdentity so the full path and the metadata-only path stay in lockstep. Verification: unit test for the identityOnlyUpdateReasons classifier; a DB-backed test (skipped without SILO_TEST_DATABASE_URL) asserting UpdateIdentity rewrites grouping while preserving probe/linkage columns; the UPDATE statement was also exercised against the live schema inside a rolled-back transaction. * fix(scanner): harden identity fast path and extras scope classification Review follow-ups for the two scan-regression fixes on this branch, addressing both Codex review comments on PR #341 plus adversarial-review findings. Identity fast path (processFile/UpdateIdentity): - Gate the metadata-only path on existing.ExtraID == "": a row still linked as an extra reaching processFile is being reclassified as primary, and only the full upsert clears extra linkage; UpdateIdentity would have frozen it out of matching forever (match backlog filters extra_id IS NULL). - Gate on existing.FileHash != "": the full path backfills the OSHash and fetches hash-keyed S3 intro/credits markers, which no later scan reason would repair; hash-less legacy rows now take the full path once instead of silently losing that repair channel. file_hash is added to the scan-state row shape to support the gate. - Clear match_suppressed_at like every other scan write, so files with fresh identity re-enter the match backlog (suppression is documented as lasting "until retried or seen by a new scan"). - Write media_folder_id, mirroring Upsert's ON CONFLICT reassignment. - Return ErrFileNotFound when the row vanished mid-scan (concurrent delete) and fall through to the full upsert path instead of surfacing a per-file scan error. - Return only the row id instead of RETURNING all ~75 columns: the fast path fires once per file during library-wide grouping migrations, and dragging the track/chapter JSONB payloads along for a million rows dominated the cost of the path built to be cheap. - Extract identityColumnDefaults shared by Upsert and UpdateIdentity so the defaulting rules cannot drift, and drop the no-op editionConfidence indirection copied between them. - Use populateScanIdentity in the new-file insert path too; it still carried a verbatim copy of the extracted block (with a provably dead existingByPath lookup). Extras classification: - Restore "other" to extrasDirKinds: it is part of both the documented Jellyfin and Plex extras-folder conventions (the removed-label fix overshot and broke "movies/<Title>/Other/<file>" libraries, ingesting their extras as bogus primary titles). "others" stays removed - it is in neither convention. - Replace label removal with the structural guard the PR had deferred: classifyExtraPath now rejects a supplemental-named directory sitting at library-scope depth (the dir, any supplemental ancestor, or the first non-supplemental ancestor is a configured library root). This fixes the original "movies/other/<Title>" defer-storm generically, covering every convention label (shorts, scenes, extras, ...) used as a content-scope folder. - Scope extras parent binding by folder.Paths instead of the walk roots, so a subtree scan targeting a single movie folder still binds that movie's own extras instead of deferring them. Tests: eligibility-gate unit tests, scope-guard classifier cases (convention Other/ inside a title binds; scope-level other/shorts stay primary), and the DB-backed UpdateIdentity test now also covers folder moves, suppression clearing, and ErrFileNotFound. Full scanner suite ran green against a migrated scratch PostgreSQL 17 container. * refactor(scanner): simplify extras scope guard to title-folder rule Replace the ancestor-walking supplementalDirAtScopeDepth loop with the plain rule it was approximating: a convention-named directory counts as an extras dir only when it sits inside a title folder — it must not be a configured library root or directly under one. Same outcome for the layouts that matter (movies/other/<Title> stays primary, <Title>/Other classifies), less machinery. * test(scanner): assert all rewritten identity columns in UpdateIdentity test * fix(scanner): make extras scope classification structure-aware The title-folder rule from c1828d2 anchored on library roots, so it missed both directions: chained convention dirs at the root ("movies/extras/behind the scenes/clip.mkv") classified as extras with an unresolvable parent (deferred forever), and category folders nested below the root ("movies/4K/other/<Title>/") still misclassified their titles. Replace the root-distance heuristic with the structural property that actually distinguishes the two cases: a convention-named directory only counts as an extras dir when its owner (first non-supplemental ancestor) is a title folder — a directory that holds media of its own. The new extrasClassifier derives that from the scan's walked path list (no extra I/O): movie folders must hold a file directly beside the extras dir; series folders may hold episodes one level down in season folders (media hiding inside a folder's own extras dirs doesn't count). Library roots never qualify. Watch-event scans, which have no walked list, probe ownership with bounded os.ReadDir instead. This handles title folders at any depth below the root and keeps scope/category folders primary at any depth, with two known edges: a title folder holding only extras (its media file missing) stays primary until the file appears, and a mixed dir holding both loose media and a category folder degrades to deferral, never wrong linkage. resolveExtraParent's inline supplemental-chain walk is extracted into the shared firstNonSupplementalAncestor.
* feat(metadata,scanner): trailers and extras for movies and series Remote provider videos (TMDB trailers/teasers/featurettes/...) are fetched through the unified match/refresh pipeline into the new item_videos table, filtered per-library via media_folders.trailer_kinds, merged across providers with site/provider dedup, and lockable via FieldVideos. The movie scanner stops discarding supplemental directories (Trailers/, Featurettes/, Behind The Scenes/, ...) and classifies them — plus Jellyfin-style filename suffixes (-trailer, -behindthescenes, ...) and series-root supplemental dirs — into the new media_extras entity backed by ordinary media_files rows (extra_id ownership, content_id/episode_id NULL so existing version/matching queries stay structurally blind to extras). Series Extras/SxxExx season-0 mapping is unchanged. Extras are playable watch targets via a GetWatchDetail fallback tier (episodes precedent), with contentid.ForLocal minting stable ids. API: ItemDetail gains additive videos/extras arrays (single + batch parity); library settings expose trailer_kinds. jellycompat now populates RemoteTrailers, LocalTrailerCount/SpecialFeatureCount, and serves real /LocalTrailers + /SpecialFeatures items playable through PlaybackInfo. Requires silo-plugin-sdk v0.9.0 (VideoRecord) before go.mod can bump; builds locally via go.work against the SDK feat/metadata-videos branch. Part of trailers/extras capability work. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(web): trailers and extras sections, library trailer-kinds setting TrailersSection (YouTube thumbnails + youtube-nocookie modal) and ExtrasSection (plays extras through the standard watch controller) on movie and series detail pages; admin library form gains a trailer-kinds allow-list synced with the server default (all provider kinds), now also honored on library create. Part of trailers/extras capability work. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(scanner): scan extra_id in scanMediaFiles; review cleanups scanMediaFiles (the plural row scanner behind GetByContentID/GetByFolder/ GetByExtraID and 20+ other queries) was missing the scan destination for the new extra_id column, which would have failed every media-file read at runtime with a column/destination count mismatch. Also: extend the batch equivalence test to seed item_videos/media_extras so the new videos/extras prefetch wiring is actually proven; drop the one-off pgxRows interface for the repo-wide pgx.Rows convention; reuse formatClock instead of a third duration formatter in ExtrasSection. Co-Authored-By: Claude Fable 5 <[email protected]> * chore(deps): bump silo-plugin-sdk to v0.9.0 for VideoRecord Co-Authored-By: Claude Fable 5 <[email protected]> * fix(matching): exclude extras files from match queues and bulk content linking Dev verification caught extras media_files rows (content_id NULL by design) being swept into the movie/series match queues and the root-claim bulk relink: a '-featurette' suffix extra was matched onto its parent as a version, and a Trailers/ file minted a spurious local skeleton item that shadowed the extra's watch target. Add 'extra_id IS NULL' to the queue eligibility conditions, root/group claim relinks, observed-root content assignment, and the admin unmatched-files listing. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): authorize local extras files through their parent item Dev verification: playback/start (and the shared MediaFileAuthorizer used by markers/subtitles/ebook reader) resolved file ownership only via episode_id/content_id, so extras files (extra_id only) 404ed. Add an ExtraLookup tier that resolves media_extras and gates on the parent item's access, mirroring the episode->series pattern. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(catalog): resolve local extras through GetItemDetail for compat playback jellycompat PlaybackInfo (and any per-item consumer resolving arbitrary content ids) goes through GetItemDetail, which lacked the extras tier that GetWatchDetail has — so Jellyfin clients got zero MediaSources for extras. Add buildExtraItemDetail (minimal detail + ordinary playback surface, parent-gated access) as the fourth resolution tier, and map the extra type to Jellyfin's Video kind. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(web): allow youtube-nocookie embeds in CSP; trailer modal a11y The frontend CSP's frame-src blocked the trailer modal's youtube-nocookie.com iframe (found on dev verification). Also add the missing sr-only DialogDescription and drop the redundant allowFullScreen attribute. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: address PR review findings for trailers/extras - Extras watch/item detail no longer stamp SeriesID/SeriesTitle for movie-owned extras (players key episodic post-roll flows off series_id); series-owned extras keep them (Codex). - processExtraFiles resolves the parent and upserts media_extras before the unchanged fast-path, and the fast-path now also compares mtime, so rematched parents / reclassified kinds / same-size replacements converge (Codex + CodeRabbit). - media_files upsert clears content/episode linkage atomically when extra_id is set (ownership mutual exclusion in one statement); the now-redundant MarkFileAsExtra helper is removed (CodeRabbit). - ScanFile's extras branch runs syncPresentLibraryState + reconcileLibraryMemberships so converting a primary file to an extra cleans stale library membership immediately (CodeRabbit). - media_extras migration adds the media_files FK as NOT VALID + VALIDATE to avoid a full-scan exclusive lock on large tables (CodeRabbit). - trailer_kinds input is trimmed/lowercased/deduped and unknown values are dropped instead of silently widening the allow-list to 'other' (CodeRabbit). - Extras authorization branches match the episode branch's posture: unconfigured lookup is a config error, nil extra is a 404 (CodeRabbit). Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
* fix(scanner): stop classifying "other" content folders as extras Regression from #322 (trailers and extras for movies and series), which introduced the extrasDirKinds map. The extras directory classifier mapped the generic labels "other" and "others" to ExtraKindOther. These are not part of the Jellyfin/Plex extras folder convention the map claims to mirror, and they collide with real content-scope folder names. A library organized as "movies/other/<Title (year) {ids}>/<file>" tripped the depth-2 ancestor lookup in classifyExtraPath: every title two levels under the scope folder "other" was classified as an "other"-kind extra. Such files are partitioned out of primary root/group inference and matching, then deferred in processExtraFiles because their parent cannot resolve (they are the primary titles, not children of one). The result on one deployment was ~10k movies under a folder named "other" funneled through the slow extras path every scan (parent-unresolved deferrals at ~9.5/s), stalling the scan and freezing that scope for new/changed primary content. Remove "other"/"others" from extrasDirKinds. The ExtraKindOther kind stays reachable through genuine convention labels (extra/extras/interviews/ scenes/shorts). Add regression coverage asserting titles under a scope folder named other/others stay primary. * perf(scanner): rewrite identity-only changes without re-probing A pure identity/grouping change on an already-probed file — a root_assignment_changed or group_assignment_changed reason with nothing else — used to fall into the full update branch, which unconditionally ran ffprobe (probeFile) and then upserted every column, including probe columns, from the freshly built row. When a group-key or root scheme changes across the library (see #319), this reprobed nearly every file on the next scan: an incremental scan that normally takes ~1h ran 7h+ as a full-library ffprobe storm, even though the media bytes were untouched. Add a metadata-only update path in processFile: when identityOnlyUpdateReasons reports every reason is a root/group reassignment, rewrite just the derived identity columns via the new FileRepository.UpdateIdentity and skip ffprobe, OSHash, and marker fetch entirely. UpdateIdentity issues a targeted UPDATE of the root/group/identity and edition/presentation columns only, mirroring Upsert's column handling, and leaves probe data, file bytes/mtime/hash, subtitles, chapters, markers, and content/episode/extra linkage intact. The stored group key converges to the recomputed value on the next scan, so the file takes the unchanged fast-path thereafter — without a probe storm. The shared identity-column population is extracted into populateScanIdentity so the full path and the metadata-only path stay in lockstep. Verification: unit test for the identityOnlyUpdateReasons classifier; a DB-backed test (skipped without SILO_TEST_DATABASE_URL) asserting UpdateIdentity rewrites grouping while preserving probe/linkage columns; the UPDATE statement was also exercised against the live schema inside a rolled-back transaction. * fix(scanner): harden identity fast path and extras scope classification Review follow-ups for the two scan-regression fixes on this branch, addressing both Codex review comments on PR #341 plus adversarial-review findings. Identity fast path (processFile/UpdateIdentity): - Gate the metadata-only path on existing.ExtraID == "": a row still linked as an extra reaching processFile is being reclassified as primary, and only the full upsert clears extra linkage; UpdateIdentity would have frozen it out of matching forever (match backlog filters extra_id IS NULL). - Gate on existing.FileHash != "": the full path backfills the OSHash and fetches hash-keyed S3 intro/credits markers, which no later scan reason would repair; hash-less legacy rows now take the full path once instead of silently losing that repair channel. file_hash is added to the scan-state row shape to support the gate. - Clear match_suppressed_at like every other scan write, so files with fresh identity re-enter the match backlog (suppression is documented as lasting "until retried or seen by a new scan"). - Write media_folder_id, mirroring Upsert's ON CONFLICT reassignment. - Return ErrFileNotFound when the row vanished mid-scan (concurrent delete) and fall through to the full upsert path instead of surfacing a per-file scan error. - Return only the row id instead of RETURNING all ~75 columns: the fast path fires once per file during library-wide grouping migrations, and dragging the track/chapter JSONB payloads along for a million rows dominated the cost of the path built to be cheap. - Extract identityColumnDefaults shared by Upsert and UpdateIdentity so the defaulting rules cannot drift, and drop the no-op editionConfidence indirection copied between them. - Use populateScanIdentity in the new-file insert path too; it still carried a verbatim copy of the extracted block (with a provably dead existingByPath lookup). Extras classification: - Restore "other" to extrasDirKinds: it is part of both the documented Jellyfin and Plex extras-folder conventions (the removed-label fix overshot and broke "movies/<Title>/Other/<file>" libraries, ingesting their extras as bogus primary titles). "others" stays removed - it is in neither convention. - Replace label removal with the structural guard the PR had deferred: classifyExtraPath now rejects a supplemental-named directory sitting at library-scope depth (the dir, any supplemental ancestor, or the first non-supplemental ancestor is a configured library root). This fixes the original "movies/other/<Title>" defer-storm generically, covering every convention label (shorts, scenes, extras, ...) used as a content-scope folder. - Scope extras parent binding by folder.Paths instead of the walk roots, so a subtree scan targeting a single movie folder still binds that movie's own extras instead of deferring them. Tests: eligibility-gate unit tests, scope-guard classifier cases (convention Other/ inside a title binds; scope-level other/shorts stay primary), and the DB-backed UpdateIdentity test now also covers folder moves, suppression clearing, and ErrFileNotFound. Full scanner suite ran green against a migrated scratch PostgreSQL 17 container. * refactor(scanner): simplify extras scope guard to title-folder rule Replace the ancestor-walking supplementalDirAtScopeDepth loop with the plain rule it was approximating: a convention-named directory counts as an extras dir only when it sits inside a title folder — it must not be a configured library root or directly under one. Same outcome for the layouts that matter (movies/other/<Title> stays primary, <Title>/Other classifies), less machinery. * test(scanner): assert all rewritten identity columns in UpdateIdentity test * fix(scanner): make extras scope classification structure-aware The title-folder rule from 53632022 anchored on library roots, so it missed both directions: chained convention dirs at the root ("movies/extras/behind the scenes/clip.mkv") classified as extras with an unresolvable parent (deferred forever), and category folders nested below the root ("movies/4K/other/<Title>/") still misclassified their titles. Replace the root-distance heuristic with the structural property that actually distinguishes the two cases: a convention-named directory only counts as an extras dir when its owner (first non-supplemental ancestor) is a title folder — a directory that holds media of its own. The new extrasClassifier derives that from the scan's walked path list (no extra I/O): movie folders must hold a file directly beside the extras dir; series folders may hold episodes one level down in season folders (media hiding inside a folder's own extras dirs doesn't count). Library roots never qualify. Watch-event scans, which have no walked list, probe ownership with bounded os.ReadDir instead. This handles title folders at any depth below the root and keeps scope/category folders primary at any depth, with two known edges: a title folder holding only extras (its media file missing) stays primary until the file appears, and a mixed dir holding both loose media and a category folder degrades to deferral, never wrong linkage. resolveExtraParent's inline supplemental-chain walk is extracted into the shared firstNonSupplementalAncestor.
Part of #196 ("Extras displayed where present" Movies add-on; remote trailers extend the same surface).
Problem
Silo has no trailers or extras. TMDB video metadata (trailers, teasers, featurettes) is never fetched, and the movie scanner actively discards
Trailers/,Featurettes/,Behind The Scenes/,Deleted Scenes/directories before probing. jellycompat'sRemoteTrailers,LocalTrailerCount,SpecialFeatureCount,/Items/{id}/LocalTrailers, and/Items/{id}/SpecialFeaturesare all hardcoded empty.Approach
Remote videos ride the existing unified match/refresh pipeline:
MetadataItem.videos(silo-plugin-sdk v0.9.0, additive proto field) →MetadataResult.Videos→ merged across providers (dedup by provider key and site key) → replaced wholesale into the newitem_videostable (ReplacePeoplepattern). Every mode (initial match, manual/scheduled refresh, identify) gets them for free. Which kinds are stored is a per-librarymedia_folders.trailer_kindsallow-list (default: all provider kinds; empty disables), andFieldVideosjoins the lockable-field set. Fill-empty refreshes never clear on transient provider failure; replace-unlocked refreshes converge after narrowing the allow-list.Local extras follow the episodes precedent: a
media_extrasentity with its own deterministic content id (contentid.ForLocalon the file path) backed by ordinarymedia_filesrows carryingextra_idwithcontent_id/episode_idNULL — every existing version/matching/download query is structurally blind to extras with zero new filters, while probe,missing_sincelifecycle, and streaming come free. The scanner partitions extras out before root/group inference (no identity pollution), binds them to their parent by directory structure (stem-match first for suffix files, unambiguous-dir rule otherwise; library-root dirs never bind; unresolved parents defer to the next scan), and keeps the documented seriesExtras/SxxExx→ season-0 behavior byte-for-byte. Jellyfin-style filename suffixes (-trailer,-behindthescenes, ...) and series-root supplemental dirs are also classified.Playback: extras are first-class watch targets via a third
GetWatchDetailfallback tier (access gated by the parent item, like episodes gate on their series).API (additive-only):
ItemDetailgainsvideos/extrasarrays (single and batch paths, covered by the extended batch-equivalence test); library create/update/read gainstrailer_kinds. TS mirrors are field-exact.Web: Trailers carousel (YouTube thumbnails,
youtube-nocookie.commodal) + Extras section (plays through the standard watch controller) on movie/series detail; trailer-kinds picker in library settings.jellycompat:
RemoteTrailers(trailer/teaser kinds → watch URLs), realLocalTrailerCount/SpecialFeatureCount, and playable/LocalTrailers+/SpecialFeaturesitems (encoded extra content ids resolve through the same PlaybackInfo/stream path).Cross-repo
VideoRecord+MetadataItem.videos = 32. Old plugins return an empty list; old hosts drop the unknown field — no lockstep.feat/metadata-videos(branch, pending release):append_to_response=videos+include_video_language=<lang>,en,nullfallback; forwards all sites/kinds — filtering is server policy.ItemDetail.videos/extras; extras play through the existing watch flow. Will open tracking issues on the client repos.Risks / notes
Sample/Subsskips and all primary-content paths are unchanged (characterization tests updated + added). Match-candidate queries gainedAND extra_id IS NULL.-trailersuffix files are converted on rescan (MarkFileAsExtraclears content linkage).i.ytimg.com/youtube-nocookie.com); embeds can be geo/age-blocked upstream. A privacy toggle for external embeds is a possible follow-up.Verification
go build ./...and touched-package suites green withGOWORK=offagainst tagged SDK v0.9.0 (only failures: the two pre-existing flakyTestBeginWebOperation*).item_videos/media_extras(runs underSILO_TEST_DATABASE_URL).tsc -bclean, touched vitest suites pass.goose validateclean. NOT yet verified: live migration apply + end-to-end playback on dev (no local Postgres in this environment) — will verify on dev deploy and attach UI screenshots then.AI-use disclosure
Implemented by Claude Code (Claude Fable 5) end-to-end — design exploration, implementation across the three repos, and a three-lens adversarial review pass (which caught and fixed a critical scan-destination bug in
scanMediaFiles) — directed and reviewed by @Quick104.Summary by CodeRabbit
trailer_kindsconfiguration to control which remote trailer types are imported and displayed.