Files
silo-server/internal/metadata/nfo_merge_semantics_test.go
91e1164090 feat(metadata): local NFO metadata and sidecar artwork (builtin chain provider) (#390)
* feat(metadata): register builtin NFO provider and broaden parsing

Phases A and B of the #216 local-NFO work, implemented test-first.

Registration & hint-first identity (Phase A):
- Migration seeds a reserved kind='builtin' silo.builtin installation
  and an 'nfo' metadata capability (default_enabled=false, priority 1
  for movie/series) with a partial unique index and documented Down.
- In-process builtin provider registry (internal/metadata/builtin.go);
  buildProviders returns the registered provider for builtin rows.
- Guard rails keep the reserved row out of every plugin surface (user
  plugin-settings, installations list, image resolvers, preload,
  auto-update, store Delete, mutation handlers -> 409); silo.builtin is
  a reserved manifest id.
- Startup sync materializes legacy content_level='' chains per level,
  then appends builtin capabilities disabled via
  AppendProviderToAllChains (idempotent); resolveEnabledProvidersBy
  priority now respects default_enabled=false.
- NFO uniqueids seed the trusted-hint machinery via IdentityHintProvider
  with per-mode conflict policy (stored IDs win on scheduled refresh,
  NFO wins on manual refresh, Identify skips NFO); ID-less candidates
  are excluded from provider-priority tie-breaks and nfo never counts
  as corroboration.
- Web chain-editor empty-state gate is now server-derived so builtin
  providers are reachable on plugin-less servers.

Parser breadth & sidecar hardening (Phase B):
- Parser covers the practical Kodi/Jellyfin field set for <movie> and
  <tvshow>: original title, tagline, runtime, dates, content rating,
  genres/studios/countries/tags, multi-source ratings with scale
  normalization, cast with roles/order, director/credits. Empty
  collections stay nil so merge early-returns apply.
- findNFO parses candidates and falls through on read/parse failure or
  root-type mismatch, so a stray movie.nfo cannot shadow tvshow.nfo;
  GetMetadata gains the same ContentType guard Search has.
- New FieldReleaseDates lock gates Year/ReleaseDate/First+LastAirDate
  in merge (Go) and the edit-metadata dialog (web), closing the gap
  where a manual refresh re-applied NFO dates over admin corrections.
- Merge-contract tests pin NFO fill semantics, genres whole-list
  first-provider-wins, and NFO edits propagating on manual refresh only.
- Docs: new admin wiki page (supported fields, merge semantics,
  naming-supplies-structure contract), index bullet, sidecar wording
  revision, v1-scope feature-detection note.

Zero behavior change while the provider is disabled (default); pinned
by CI-mode and DB-gated test suites.

Part of #216

AI-use disclosure: implemented with Claude Code (Fable 5) via
spec-driven TDD and agent-assisted implementation.

* feat(metadata): ingest local sidecar artwork and read series-depth NFO

Phases C and D of the #216 local-NFO work, implemented test-first, plus
the mixed-library use-case pins. Together these deliver the headline
case: a series absent from every remote database (e.g. a fitness
library) scans into a fully presented show -> named seasons -> titled
episodes tree from NFO files and sidecar art alone.

Local sidecar artwork through the S3 image cache (Phase C):
- The NFO provider implements ImageProvider: poster/backdrop/logo
  sidecar discovery with a fixed precedence map, symlink/non-regular
  rejection, an 8 MiB cap, and file:// source URLs at rating 0. Generic
  filenames apply only via the sidecar search paths, so a shared
  folder.jpg in a flat multi-movie directory applies to none.
- file:// becomes a live local source scheme: routed into *_source_path
  (never *_path), accepted by every image enqueue gate, attributed as
  provider "local", excluded from cached-path detection.
- The image-cache processor caches local files with lexical-on-logical
  confinement to the library roots, open-handle reads with re-checks,
  the same variant widths as remote art, and stable (7-day) failure
  classification. Keys land under
  local/{contentType}/{contentID}/{hash8}/{imageType}; superseded
  prefixes are cleaned on re-cache and item deletion.
- applyIfBetter gains a local exemption so rating-0 local art can fill
  matched items without being stickily displaced; ImageRequest carries
  additive sidecar path context.

Series depth (Phase D):
- SeasonsRequest/EpisodesRequest carry additive local path context
  (series roots, per-season directories, per-episode file paths),
  derived from naming at match time and reconstructed on refresh.
- season.nfo supplies season name/plot; NFO season numbers are advisory
  (directory-derived number wins with a Warn - naming owns structure).
  <episodedetails> gains aired/runtime/ratings; <basename>.nfo titles
  episodes and <basename>-thumb.ext supplies thumbs; filename SxxEyy
  wins over NFO numbers.
- Episode NFOs work without a season.nfo (provider seasons unioned with
  on-disk seasons); SynthesizeFallbackEpisodes always runs after persist
  so NFO-less episodes keep synthesized rows. Season/episode file:// art
  rides the Phase C pipeline unchanged.
- Migration adds season:1/episode:1 to the builtin NFO capability's
  default_priority (still default_enabled=false).

Mixed sports-library use case (tests only, no product change):
- Pins the classification contract for one library holding movie-shaped
  and show-shaped content (WWE PPV events as movies next to a "WWE
  SmackDown" show, NASCAR/F1/FIFA with partial TVDB/TMDB data): naming
  decides movie-vs-series per file before any provider runs; the NFO
  supplies metadata/identity but never flips type (ContentType guard);
  the per-root Type override is the correction path.
- NFO-driven type classification at scan time is recorded as an explicit
  deferred open question.

Part of #216

AI-use disclosure: implemented with Claude Code (Fable 5) via
spec-driven TDD and agent-assisted implementation.

* docs(metadata): document local NFO metadata architecture

Add a single as-built architecture page
(docs/architecture/local-nfo-metadata.md) for the #216 local-NFO
feature: the builtin registration model, hint-first identity semantics,
the file:// -> S3 artwork pipeline and its deployment constraint, series
depth, the mixed-library classification contract, and known limitations.

This replaces the working implementation plan, the per-phase specs, and
the narrow sidecar-artwork note, which were planning drafts and are left
untracked; admin-facing behavior remains in the wiki.

Part of #216

AI-use disclosure: planned, drafted, and consolidated with Claude Code
(Fable 5) using multi-agent exploration and adversarial review.

* fix(metadata): address PR review findings on NFO builtin provider

Fold in the valid, low-risk fixes surfaced by automated review on #390:

- imagecache: extract validateCacheRequest so CacheBytes (the local
  sidecar season/episode path) enforces the same episode-requires-season
  guard as Cache, preventing distinct episodes' art from colliding under
  one S3 key.
- image_cache_processor: close the sidecar symlink-swap window by
  rejecting the opened handle unless os.SameFile matches the Lstat'd
  file, so a leaf swapped to a symlink can't pull an out-of-root target
  into the public cache.
- plugins: guard the reserved builtin installation row in the store's
  Update, matching Delete, so its version/enabled/capabilities can never
  be rewritten even if a mutation slips past the HTTP layer.
- cmd/silo: bound SyncBuiltinProviderChains with a 30s timeout so a stuck
  DB round-trip fails fast at startup instead of hanging.
- metadata: panic instead of silently no-op'ing on an invalid
  RegisterBuiltinProvider call (init-time programmer error).
- docs: correct the media-folder-and-naming NFO paragraph to state
  season/episode NFOs and sidecar artwork are actively read.

---------

Co-authored-by: Quick104 <31828688+Quick104@users.noreply.github.com>
2026-07-16 17:55:36 -04:00

189 lines
6.7 KiB
Go

package metadata
import (
"context"
"reflect"
"testing"
"github.com/Silo-Server/silo-server/internal/models"
)
// Phase-2 accumulation runs NFO (priority 1) first, then remote providers,
// always with MergeFillEmpty: the NFO wins every field it populates and the
// remote result backfills the rest.
func TestMerge_NFOFirstFillEmpty_NFOWinsRemoteBackfills(t *testing.T) {
t.Parallel()
nfoResult := &MetadataResult{
HasMetadata: true,
Title: "Curated Title",
Overview: "Curated overview.",
Genres: []string{"Documentary"},
Ratings: Ratings{IMDB: 8.1},
}
remoteResult := &MetadataResult{
HasMetadata: true,
Title: "Remote Title",
Overview: "Remote overview.",
Tagline: "Remote tagline",
Runtime: 117,
Genres: []string{"Action", "Thriller"},
Studios: []string{"Remote Studio"},
Ratings: Ratings{IMDB: 7.0, TMDB: 7.5},
People: []models.ItemPerson{{Person: models.Person{Name: "Remote Actor"}, Kind: models.PersonKindActor}},
ContentRating: "R",
}
accumulator := &MetadataResult{}
MergeMetadata(nfoResult, accumulator, nil, MergeFillEmpty)
MergeMetadata(remoteResult, accumulator, nil, MergeFillEmpty)
// NFO wins the fields it populated.
if accumulator.Title != "Curated Title" {
t.Errorf("Title = %q, want Curated Title", accumulator.Title)
}
if accumulator.Overview != "Curated overview." {
t.Errorf("Overview = %q, want the NFO overview", accumulator.Overview)
}
if accumulator.Ratings.IMDB != 8.1 {
t.Errorf("Ratings.IMDB = %v, want 8.1 (NFO wins)", accumulator.Ratings.IMDB)
}
// Genres are first-provider-wins as a whole list: no remote union.
if want := []string{"Documentary"}; !reflect.DeepEqual(accumulator.Genres, want) {
t.Errorf("Genres = %#v, want %#v (whole-list first-provider-wins)", accumulator.Genres, want)
}
// Remote backfills what the NFO left empty.
if accumulator.Tagline != "Remote tagline" || accumulator.Runtime != 117 || accumulator.ContentRating != "R" {
t.Errorf("backfill = tagline %q runtime %d rating %q", accumulator.Tagline, accumulator.Runtime, accumulator.ContentRating)
}
if accumulator.Ratings.TMDB != 7.5 {
t.Errorf("Ratings.TMDB = %v, want 7.5 (remote backfills)", accumulator.Ratings.TMDB)
}
if len(accumulator.Studios) != 1 || len(accumulator.People) != 1 {
t.Errorf("Studios = %#v People = %#v, want remote backfill", accumulator.Studios, accumulator.People)
}
}
// An NFO that declares no <genre> must leave Genres untouched so the remote
// provider's list applies (the provider emits nil, never an empty slice).
func TestMerge_NFOWithoutGenres_RemoteGenresApply(t *testing.T) {
t.Parallel()
nfoResult := &MetadataResult{HasMetadata: true, Title: "Curated Title"}
remoteResult := &MetadataResult{HasMetadata: true, Genres: []string{"Action", "Thriller"}}
accumulator := &MetadataResult{}
MergeMetadata(nfoResult, accumulator, nil, MergeFillEmpty)
MergeMetadata(remoteResult, accumulator, nil, MergeFillEmpty)
if want := []string{"Action", "Thriller"}; !reflect.DeepEqual(accumulator.Genres, want) {
t.Errorf("Genres = %#v, want %#v", accumulator.Genres, want)
}
}
// FieldReleaseDates locks Year and the release/air dates against refreshes.
func TestMerge_ReleaseDatesLockBlocksReplace(t *testing.T) {
t.Parallel()
source := &MetadataResult{
HasMetadata: true,
Year: 1982,
ReleaseDate: "1982-06-25",
FirstAirDate: "1982-06-25",
LastAirDate: "1983-01-01",
}
target := &MetadataResult{
Year: 1990,
ReleaseDate: "1990-01-01",
FirstAirDate: "1990-01-01",
LastAirDate: "1991-01-01",
}
MergeMetadata(source, target, []MetadataField{FieldReleaseDates}, MergeReplaceUnlocked)
if target.Year != 1990 || target.ReleaseDate != "1990-01-01" ||
target.FirstAirDate != "1990-01-01" || target.LastAirDate != "1991-01-01" {
t.Errorf("locked dates overwritten: %+v", target)
}
// Unlocked, replace mode applies the source values.
MergeMetadata(source, target, nil, MergeReplaceUnlocked)
if target.Year != 1982 || target.ReleaseDate != "1982-06-25" {
t.Errorf("unlocked replace did not apply: %+v", target)
}
}
// Refresh contract, scheduled side: MergeFillEmpty seeds the accumulator from
// the existing item, so an edited NFO title does NOT propagate on the 6h cycle.
func TestScheduledRefresh_DoesNotPropagateNFOEdits(t *testing.T) {
h := newTestHarness()
ctx := context.Background()
seedMovieItem(t, h, "movie:tmdb:100", "Original Title", 2018)
h.itemRepo.items["movie:tmdb:100"].TmdbID = "100"
h.itemRepo.items["movie:tmdb:100"].Overview = "Original overview."
nfo := &localHintStubProvider{
metadata: &MetadataResult{HasMetadata: true, Title: "Edited via NFO", Overview: "Edited overview."},
}
remote := &remoteStubProvider{
slug: "tmdb",
metadata: &MetadataResult{HasMetadata: true, Title: "Original Title", Year: 2018, ProviderIDs: map[string]string{"tmdb": "100"}},
}
_, err := h.service.ProcessWithProviders(ctx, ProcessRequest{
ContentID: "movie:tmdb:100",
Language: "en",
Mode: ModeScheduledRefresh,
}, []Provider{nfo, remote})
if err != nil {
t.Fatalf("ProcessWithProviders: %v", err)
}
item, err := h.itemRepo.GetByID(ctx, "movie:tmdb:100")
if err != nil {
t.Fatalf("load item: %v", err)
}
if item.Title != "Original Title" {
t.Errorf("scheduled refresh title = %q, want Original Title (NFO edits must not propagate)", item.Title)
}
if item.Overview != "Original overview." {
t.Errorf("scheduled refresh overview = %q, want the original", item.Overview)
}
}
// Refresh contract, manual side: MergeReplaceUnlocked propagates NFO edits
// ("edit the NFO, then Refresh metadata").
func TestManualRefresh_PropagatesNFOEdits(t *testing.T) {
h := newTestHarness()
ctx := context.Background()
seedMovieItem(t, h, "movie:tmdb:100", "Original Title", 2018)
h.itemRepo.items["movie:tmdb:100"].TmdbID = "100"
h.itemRepo.items["movie:tmdb:100"].Overview = "Original overview."
nfo := &localHintStubProvider{
metadata: &MetadataResult{HasMetadata: true, Title: "Edited via NFO", Overview: "Edited overview."},
}
remote := &remoteStubProvider{
slug: "tmdb",
metadata: &MetadataResult{HasMetadata: true, Title: "Original Title", Year: 2018, ProviderIDs: map[string]string{"tmdb": "100"}},
}
_, err := h.service.ProcessWithProviders(ctx, ProcessRequest{
ContentID: "movie:tmdb:100",
Language: "en",
Mode: ModeManualRefresh,
}, []Provider{nfo, remote})
if err != nil {
t.Fatalf("ProcessWithProviders: %v", err)
}
item, err := h.itemRepo.GetByID(ctx, "movie:tmdb:100")
if err != nil {
t.Fatalf("load item: %v", err)
}
if item.Title != "Edited via NFO" {
t.Errorf("manual refresh title = %q, want Edited via NFO", item.Title)
}
if item.Overview != "Edited overview." {
t.Errorf("manual refresh overview = %q, want the NFO edit", item.Overview)
}
}