Skip to content

feat(metadata,scanner): trailers and extras for movies and series - #322

Merged
Quick104 merged 9 commits into
mainfrom
feat/trailers-extras
Jul 6, 2026
Merged

Quick104 merged 9 commits into
mainfrom
feat/trailers-extras

Conversation

@Quick104

@Quick104 Quick104 commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

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's RemoteTrailers, LocalTrailerCount, SpecialFeatureCount, /Items/{id}/LocalTrailers, and /Items/{id}/SpecialFeatures are 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 new item_videos table (ReplacePeople pattern). Every mode (initial match, manual/scheduled refresh, identify) gets them for free. Which kinds are stored is a per-library media_folders.trailer_kinds allow-list (default: all provider kinds; empty disables), and FieldVideos joins 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_extras entity with its own deterministic content id (contentid.ForLocal on the file path) backed by ordinary media_files rows carrying extra_id with content_id/episode_id NULL — every existing version/matching/download query is structurally blind to extras with zero new filters, while probe, missing_since lifecycle, 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 series Extras/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 GetWatchDetail fallback tier (access gated by the parent item, like episodes gate on their series).

API (additive-only): ItemDetail gains videos/extras arrays (single and batch paths, covered by the extended batch-equivalence test); library create/update/read gains trailer_kinds. TS mirrors are field-exact.

Web: Trailers carousel (YouTube thumbnails, youtube-nocookie.com modal) + 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), real LocalTrailerCount/SpecialFeatureCount, and playable /LocalTrailers + /SpecialFeatures items (encoded extra content ids resolve through the same PlaybackInfo/stream path).

Cross-repo

  • silo-plugin-sdk v0.9.0 (merged + tagged): VideoRecord + MetadataItem.videos = 32. Old plugins return an empty list; old hosts drop the unknown field — no lockstep.
  • silo-plugin-tmdb feat/metadata-videos (branch, pending release): append_to_response=videos + include_video_language=<lang>,en,null fallback; forwards all sites/kinds — filtering is server policy.
  • Android/Apple follow-up: clients can adopt ItemDetail.videos/extras; extras play through the existing watch flow. Will open tracking issues on the client repos.

Risks / notes

  • Scanner behavior change is confined to supplemental-dir handling; Sample/Subs skips and all primary-content paths are unchanged (characterization tests updated + added). Match-candidate queries gained AND extra_id IS NULL.
  • Existing libraries pick up extras on their next scheduled/manual rescan — no backfill job (release-notes callout suggested).
  • Previously-primary -trailer suffix files are converted on rescan (MarkFileAsExtra clears content linkage).
  • Trailer thumbnails/embeds load from YouTube (i.ytimg.com / youtube-nocookie.com); embeds can be geo/age-blocked upstream. A privacy toggle for external embeds is a possible follow-up.
  • jellycompat media-segments owner lookup doesn't yet resolve extras files (graceful degrade); follow-up candidate.

Verification

  • go build ./... and touched-package suites green with GOWORK=off against tagged SDK v0.9.0 (only failures: the two pre-existing flaky TestBeginWebOperation*).
  • New unit tests: suffix parsing, extras classification (SxxExx guard, depth bound, partition), video merge/dedup/lock, kind filtering, ordering; batch-equivalence test extended to seed item_videos/media_extras (runs under SILO_TEST_DATABASE_URL).
  • Web: eslint 0 errors, Prettier clean, tsc -b clean, touched vitest suites pass.
  • goose validate clean. 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

  • New Features
    • Movie and series item pages now include Trailers (carousel with privacy YouTube modal) and Extras (playable cards).
    • Added per-library trailer_kinds configuration to control which remote trailer types are imported and displayed.
    • Jelly-compat now serves LocalTrailers and SpecialFeatures from locally scanned extras.
  • Bug Fixes
    • Improved supplemental scanning so extras are classified/attached reliably and don’t surface as primary or unmatched items.
    • Playback and authorization now correctly support files linked to local extras.
  • Documentation
    • Expanded wiki rules for supplemental files/directories classification (extras vs noise).

Quick104 and others added 4 commits July 6, 2026 16:43
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]>
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This 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.

Changes

Extras and remote trailers feature

Layer / File(s) Summary
Data models, naming, and schema
internal/models/extras.go, internal/models/media.go, internal/naming/extras.go, docs/wiki/admin/media-folder-and-naming.md, migrations/sql/..., go.mod, web/src/lib/extraKinds.ts
Adds extra kinds, item video/extra models, filename suffix parsing, updated supplemental-content docs, schema for item_videos/media_extras/extra_id/trailer_kinds, a shared web vocabulary, and a plugin SDK version bump.
Scanner classification and persistence
internal/scanner/extras.go, internal/scanner/scanner.go, internal/scanner/file_repo.go, internal/scanner/scan_state.go, internal/scanner/extras_test.go, internal/scanner/root_observation_test.go, internal/api/handlers/admin.go, internal/catalog/*claim_repo.go, internal/metadata/*match_queue_repo.go
Separates extras from primary scan paths, stores extra ownership, tracks extra_id, and excludes extra-owned files from unmatched, claim, and queue queries.
Catalog repositories and item detail
internal/catalog/extras_repo.go, internal/catalog/video_repo.go, internal/catalog/folder_repo.go, internal/catalog/detail.go, internal/catalog/detail_batch_equivalence_test.go
Adds repositories for extras/videos, persists per-library trailer kinds, batches item-detail enrichment, and resolves watch detail for local extras.
Metadata pipeline for remote videos
internal/metadata/types.go, internal/metadata/merge.go, internal/metadata/merge_videos_test.go, internal/metadata/plugin_provider.go, internal/metadata/service.go
Carries remote videos through merge, plugin conversion, and persistence with deduping and trailer-kind filtering.
Authorization and Jellyfin compatibility
internal/api/handlers/media_file_auth.go, internal/api/handlers/playback.go, internal/api/router.go, internal/jellycompat/*
Wires extra lookup into playback authorization and exposes trailers/extras through Jellyfin-compatible routes and DTOs.
Admin and web UI for trailer kinds
internal/api/handlers/libraries.go, web/src/api/types.ts, web/src/components/admin/libraries/*, web/src/pages/ItemDetail/*, internal/server/frontend.go
Adds library trailer-kind fields to APIs and admin forms, renders trailer/extra sections on item detail pages, and allows trailer embeds in the frontend CSP.

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
Loading
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
Loading

Possibly related PRs

  • Silo-Server/silo-server#247: Shares the internal/catalog/detail.go batch detail path and Jellyfin-compat consumption of batched item details.
  • Silo-Server/silo-server#10: Touches shared media-file authorization flow reused here for extra-backed playback authorization.

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding trailers and extras support for movies and series, with metadata and scanner involvement.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/trailers-extras

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 6, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread internal/catalog/detail.go Outdated
}
// Surface the owning item the way episodes surface their series so
// players can show "<Extra> — <Movie>" context.
detail.SeriesID = extra.ParentID

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/scanner/extras.go Outdated
Comment on lines +138 to +140
if existing != nil && existing.ExtraID == extraID &&
existing.FileSize == info.Size() && existing.ProbeUpdatedAt != nil &&
existing.MissingSince == nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 90fb13d — the unchanged fast-path now also requires FileModifiedAt equality, so same-size in-place replacements re-probe.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (3)
internal/jellycompat/mapping.go (1)

714-738: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer a typed DTO over map[string]any for 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 value

Log swallowed GetItemDetail errors 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 value

Unrecognized Kind values silently rank as highest priority instead of last.

rank[ordered[i].Kind] returns Go's zero value (0) for any kind missing from models.AllExtraKinds, which is the same rank as the first vocabulary entry (trailer). If an un-normalized Kind ever 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 since models.NormalizeExtraKind is 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

📥 Commits

Reviewing files that changed from the base of the PR and between f5329e1 and cf68a45.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (41)
  • docs/wiki/admin/media-folder-and-naming.md
  • go.mod
  • internal/api/handlers/libraries.go
  • internal/catalog/detail.go
  • internal/catalog/detail_batch_equivalence_test.go
  • internal/catalog/extras_repo.go
  • internal/catalog/folder_repo.go
  • internal/catalog/video_repo.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/mapping.go
  • internal/jellycompat/router.go
  • internal/jellycompat/upstream_types.go
  • internal/metadata/merge.go
  • internal/metadata/merge_videos_test.go
  • internal/metadata/plugin_provider.go
  • internal/metadata/service.go
  • internal/metadata/types.go
  • internal/models/extras.go
  • internal/models/media.go
  • internal/naming/extras.go
  • internal/naming/extras_test.go
  • internal/pathscope/pathscope.go
  • internal/scanner/extras.go
  • internal/scanner/extras_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/root_observation_test.go
  • internal/scanner/scan_state.go
  • internal/scanner/scanner.go
  • migrations/sql/20260706201109_item_videos.sql
  • migrations/sql/20260706201110_media_extras.sql
  • migrations/sql/20260706201112_media_folder_trailer_kinds.sql
  • web/src/api/types.ts
  • web/src/components/admin/libraries/LibraryFormSections.tsx
  • web/src/components/admin/libraries/useLibraryForm.ts
  • web/src/lib/extraKinds.ts
  • web/src/pages/ItemDetail/MovieContent.tsx
  • web/src/pages/ItemDetail/SeriesContent.tsx
  • web/src/pages/ItemDetail/components/ExtrasSection.tsx
  • web/src/pages/ItemDetail/components/TrailerModal.tsx
  • web/src/pages/ItemDetail/components/TrailersSection.tsx

Comment thread internal/catalog/folder_repo.go Resolved
Comment thread internal/scanner/extras.go Resolved
Comment thread internal/scanner/file_repo.go Resolved
Comment thread internal/scanner/scanner.go Resolved
…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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/metadata/series_root_match_queue_repo.go (1)

82-92: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider extracting the repeated eligibility predicate into a shared constant.

The pair mf.missing_since IS NULL AND mf.extra_id IS NULL is now hand-copied across 11 locations in this file (EnqueueSeriesRoot, SyncForFolder, SyncInScope, Claim, ClaimByFolderAndPathPrefix). movie_match_queue_repo.go already factors its equivalent eligibility condition into a movieQueueFileEligibleCond constant. 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 seriesFileLiveCond in 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

📥 Commits

Reviewing files that changed from the base of the PR and between cf68a45 and d73779a.

📒 Files selected for processing (6)
  • internal/api/handlers/admin.go
  • internal/catalog/group_claim_repo.go
  • internal/catalog/root_claim_repo.go
  • internal/metadata/movie_match_queue_repo.go
  • internal/metadata/series_root_match_queue_repo.go
  • internal/scanner/file_repo.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/scanner/file_repo.go

Quick104 and others added 2 commits July 6, 2026 18:06
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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d73779a and eb4c541.

📒 Files selected for processing (3)
  • internal/api/handlers/media_file_auth.go
  • internal/api/handlers/playback.go
  • internal/api/router.go

Comment thread internal/api/handlers/playback.go Resolved
@Quick104

Quick104 commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Dev deployment verification (100.86.116.20, 2026-07-06)

Deployed this branch + SDK v0.9.0 + the TMDB plugin feat/metadata-videos build to the dev stack. Results:

Migrations — all three applied cleanly via the normal boot path (20260706201109/…10/…12); every existing media_folders row got the full default trailer_kinds array.

Remote trailers (TMDB → item_videos) — refreshed movie-tmdb-127544 (009 Re:Cyborg) and movie-tmdb-10378 (Big Buck Bunny): real trailer rows persisted (youtube/mPQ1ZlGpWlA, youtube/yUQM7H4Swgw) and surfaced in ItemDetail.videos. Note: the installed plugin process must be respawned after a plugin binary swap, and the installed manifest checksum must match the binary (LoadWithChecksum stamps the running binary's sha256).

Local extras (scanner) — seeded a test movie with Trailers/Making Of Reel.mkv + Big Buck Bunny (2008)-featurette.mkv. First scan matched the movie and correctly deferred the extras (parent unmatched during walk); second scan bound both: dir-classified trailer + suffix-classified featurette, media_files rows with extra_id set and content_id NULL, excluded from versions, listed in ItemDetail.extras with correct durations/file ids.

Playback — POST /playback/start on the extra returned a direct-play session; stream fetch returned 206/video/x-matroska with valid EBML magic bytes.

jellycompat — item detail now reports RemoteTrailers (real YouTube URL), LocalTrailerCount: 1, SpecialFeatureCount: 1; /Items/{id}/LocalTrailers returns a playable Trailer item and /SpecialFeatures a Video item; PlaybackInfo on the extra returns a direct-streamable MediaSource (mkv, h264/aac).

Bugs found & fixed during verification (pushed to this branch)

  1. d73779ab — extras files were swept into the movie/series match queues and root-claim bulk relink (movieQueueFileEligibleCond and seven sibling conditions lacked the extra_id IS NULL guard): a suffix extra got matched onto its parent as a version and a Trailers/ file minted a spurious local skeleton item. All candidate/bulk-link queries now guarded.
  2. eb4c541a — playback/start and the shared MediaFileAuthorizer 404ed on extras files (ownership switch only knew episode/content); added the ExtraLookup tier (parent-gated, mirrors episode→series).
  3. dd2e4603 — jellycompat PlaybackInfo returned zero MediaSources for extras because GetItemDetail lacked the extras tier GetWatchDetail has; added buildExtraItemDetail.

Web UI screenshots to follow (needs an interactive login session). Test fixtures live in the throwaway "Extras Verify" library (/tmp/silo-transcode/test-extras on dev) for eyeballing; delete the library + /opt/silo/transcode/test-extras to clean up.

@coderabbitai coderabbitai Bot removed the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 6, 2026
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]>
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 6, 2026
- 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]>
@Quick104

Quick104 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

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.

@Quick104
Quick104 merged commit bb8586d into main Jul 6, 2026
29 checks passed
@Quick104
Quick104 deleted the feat/trailers-extras branch July 6, 2026 22:52
Quick104 pushed a commit that referenced this pull request Jul 8, 2026
* 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.
Quick104 added a commit that referenced this pull request Jul 10, 2026
* 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]>
Quick104 pushed a commit that referenced this pull request Jul 10, 2026
* 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant