diff --git a/.silo-translations b/.silo-translations index 35886856ee6..ae8620ace8e 100644 --- a/.silo-translations +++ b/.silo-translations @@ -1,3 +1,3 @@ platform=web -version=2026.12.05-95a7440 -sha256=23d4c6836d55d337939d391d9e07fd667e7a7294117f95d2cfd7fce2df11ad9d +version=local-456ecc51d446 +sha256=- diff --git a/contracts/api/v2/fixtures/get_admin_collection_capabilities_ok.json b/contracts/api/v2/fixtures/get_admin_collection_capabilities_ok.json index 5760533cea8..125c249fbce 100644 --- a/contracts/api/v2/fixtures/get_admin_collection_capabilities_ok.json +++ b/contracts/api/v2/fixtures/get_admin_collection_capabilities_ok.json @@ -1,5 +1,5 @@ { - "revision": "f546a01d7936a53eaf9f8e9cfcee85544726b7ce593dbc711ad6a44fa5084e70", + "revision": "ee4fef4069fb7fa39a6b1f5c2be57a01e9a778b40f457ceeef6cb5cf3433be27", "state": "available", "allowed": true, "groups": true, @@ -13,6 +13,7 @@ "item_reorder": true, "template_summaries": true, "mdblist_search": true, + "mdblist_link_check": false, "mdblist_account_lists": false, "schedule_time_zone": { "utc_offset": "-05:00", diff --git a/contracts/api/v2/fixtures/index.json b/contracts/api/v2/fixtures/index.json index 381a88ec4ec..6ffaf6830df 100644 --- a/contracts/api/v2/fixtures/index.json +++ b/contracts/api/v2/fixtures/index.json @@ -6698,7 +6698,7 @@ "response_headers": { "Cache-Control": "private, no-cache", "Content-Type": "application/json", - "ETag": "\"1a53e61b4c2f6dac9f73962dd3d6a0cd1692be25ca0656446cbc0c6312cd6d0f\"" + "ETag": "\"9c3a0bf850b85f3c5e3ebc6e8ffa334d0ac607c447add0f71d04baddf1725cd0\"" }, "response_media_type": "application/json", "schema": "#/components/schemas/AdminCollectionCapabilityOutputBody", diff --git a/contracts/api/v2/openapi.json b/contracts/api/v2/openapi.json index 633933bf86c..28e71aee87f 100644 --- a/contracts/api/v2/openapi.json +++ b/contracts/api/v2/openapi.json @@ -6926,6 +6926,13 @@ "last_sync_message": { "type": "string" }, + "last_sync_reason": { + "description": "Why the last sync read nothing, for clients to say in their own words; absent when it gives none. mdblist_api_key_required: the list syncs only with an MDBList API key the server lacks (a private list, or a list of episodes or seasons)", + "enum": [ + "mdblist_api_key_required" + ], + "type": "string" + }, "last_sync_status": { "type": "string" }, @@ -7123,6 +7130,13 @@ ], "type": "boolean" }, + "mdblist_link_check": { + "description": "checkAdminMDBListLink reports whether an MDBList link syncs only with an MDBList API key the server lacks", + "examples": [ + true + ], + "type": "boolean" + }, "mdblist_search": { "description": "searchMDBListLists and listTopMDBListLists return lists; false when the server has no MDBList API key", "examples": [ @@ -7170,6 +7184,7 @@ "item_reorder", "template_summaries", "mdblist_search", + "mdblist_link_check", "mdblist_account_lists", "schedule_time_zone", "section_references", @@ -7690,6 +7705,13 @@ "message": { "type": "string" }, + "reason": { + "description": "Why the sync read nothing, as last_sync_reason on the collection; absent when it gives none", + "enum": [ + "mdblist_api_key_required" + ], + "type": "string" + }, "started_at": { "description": "RFC 3339 instant in UTC with millisecond precision", "format": "date-time", @@ -18172,6 +18194,22 @@ ], "type": "object" }, + "AdminMDBListLinkOutputBody": { + "additionalProperties": false, + "properties": { + "needs_api_key": { + "description": "A server collection following the link syncs only with an MDBList API key the server lacks: MDBList's public feed refuses the list (a private list) or lists nothing (a list of episodes or seasons). False whenever the server has a key", + "examples": [ + true + ], + "type": "boolean" + } + }, + "required": [ + "needs_api_key" + ], + "type": "object" + }, "AdminMarkerCapabilities": { "additionalProperties": false, "properties": { @@ -86404,6 +86442,164 @@ "x-silo-service-backed": true } }, + "/api/v2/admin/collections/mdblist/link": { + "get": { + "operationId": "checkAdminMDBListLink", + "parameters": [ + { + "description": "Optional. When present, it must name the authenticated account's primary profile; an absent header is accepted.", + "in": "header", + "name": "X-Profile-Id", + "schema": { + "examples": [ + "1" + ], + "type": "string" + } + }, + { + "description": "Verification proof for a PIN-locked profile, issued by POST /api/v2/profiles/{id}/verify-pin; required only when the declared profile is locked", + "in": "header", + "name": "X-Profile-Token", + "schema": { + "examples": [ + "pvt_5f3a9c1e7b2d4e8fa0c6" + ], + "type": "string" + } + }, + { + "description": "The MDBList list link an administrator pasted", + "explode": false, + "in": "query", + "name": "url", + "required": true, + "schema": { + "description": "The MDBList list link an administrator pasted", + "examples": [ + "https://mdblist.com/lists/alice/holiday-episodes" + ], + "format": "uri", + "maxLength": 2048, + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdminMDBListLinkOutputBody" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "406": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Acceptable" + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests" + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Report whether a server collection following an MDBList link syncs only with an MDBList API key the server lacks. Reads the list's public feed once when the server has no key.", + "tags": [ + "admin-collections" + ], + "x-silo-class": "acting_admin", + "x-silo-service-backed": true + } + }, "/api/v2/admin/collections/mdblist/lists": { "get": { "operationId": "listAdminMDBListLists", diff --git a/docs/architecture/api-contract.md b/docs/architecture/api-contract.md index c776ed327a8..edf08b521a0 100644 --- a/docs/architecture/api-contract.md +++ b/docs/architecture/api-contract.md @@ -1642,7 +1642,7 @@ answered empty (see catalog-home); `getLibrarySectionItems` answers the section wrapper, and `getLibraryCollections` has one shape whether or not collection groups are configured. -`getLibraryCollectionItems` pages manual membership by `(position, media_item_id)` and +`getLibraryCollectionItems` pages manual membership by `(position, member_id)` and smart results by the executor's complete SQL sort tuple. Collection-specific durable revisions reject continuation after definition, membership, or collection-access changes. Membership and its revision are read in one database snapshot; authorization and catalog hydration are fenced diff --git a/docs/architecture/collection-members.md b/docs/architecture/collection-members.md new file mode 100644 index 00000000000..f8fd3908648 --- /dev/null +++ b/docs/architecture/collection-members.md @@ -0,0 +1,117 @@ +# Episode and season members of library collections + +A library collection holds titles (movies and series). A synced MDBList +collection can also hold episodes and seasons, because an MDBList list can +name them (a list of Christmas episodes, say). This note records how that +works; the client contract is in +[catalog-api.md](../catalog-api.md#episode-and-season-members). + +## Storage + +- `library_collection_items` has one column per member kind: `media_item_id` + for a title, `episode_id` for an episode, `season_id` for a season. Exactly + one is set, and the generated `member_id` is that one. The primary key and + the order and continuation indexes use `member_id`. A partial index on + `collection_id` where `media_item_id IS NULL` finds a collection's episode + and season members, so readers of a titles-only collection skip them cheaply. +- Each column has its own foreign key with `ON UPDATE CASCADE ON DELETE + CASCADE`, so a content-ID rekey or a delete of the episode, season, or title + moves or removes the member. The provider-ID merge conflicts on + `(collection_id, member_id)`; `reattribute` moves title and episode members + per column (`media_item_id`, `episode_id`). +- A unique index on `(collection_id, media_item_id)` stays beside the primary + key for servers of the previous release during a rolling upgrade: their + title writes use `ON CONFLICT (collection_id, media_item_id)`, which needs + it. Episode and season rows leave `media_item_id` NULL and never collide + there. Those servers still cannot read a collection that holds episodes or + seasons, but only an upgraded server's sync creates one. + `TestPreviousReleaseCollectionWritesStillWorkDB` runs their writes verbatim. +- Those servers also replace a collection's members by deleting every row + whose `media_item_id` their list leaves out, which would empty an episode + collection they sync. The trigger `library_collection_items_guard_member_delete` + refuses a direct delete of an episode or season member unless the + transaction set `silo.collection_member_writes`, so their sync fails and the + members stay until an upgraded server syncs it. Deletes cascading from an + episode, season or collection run nested in another trigger and go through. + Every statement in this release that can directly delete an episode or + season member (`ReplaceItems`, `RemoveManualItem`, and the episode-merge + dedupe in `reattribute`) calls `AllowCollectionMemberDeletes` first; a new + one that doesn't fails on those members. `TestPreviousReleaseReplaceKeepsEpisodeAndSeasonMembersDB` runs the + old replace against them. A later release can drop the trigger once + upgrades from the release before episode members are no longer supported. + With two unique indexes on a title, an `ON CONFLICT` that names one still + fails on the other when a concurrent transaction inserts the same title, so + the current release's skip-if-present inserts use `ON CONFLICT DO NOTHING` + with no target. The provider-ID merge is an upsert, needs a target, and takes + no collection lock, so it keeps that narrow race: a merge that moves a title + into a collection while a sync or add inserts the same title there can fail + once, on either side. A failed sync is redone by the next sync; a failed + merge returns its error to the metadata refresh or repair task that ran it, + and runs again only when one of those finds the duplicate again. +- In Go a member's kind is `""` (title), `CollectionMemberEpisode`, or + `CollectionMemberSeason`. +- The migration's Down removes every episode and season member, since the + table it restores holds titles only. + +## Sync + +- MDBList's public `/json` feed leaves episodes and seasons out, so a list of + them reads empty there. An empty feed answer is read again through the + MDBList API (`/lists/{id}/items`) with the server's key, which returns + `episodes` and `seasons`, each with its own TMDB ID (`id`), its show's TMDB + ID and TMDB's numbers. The API answer comes in MDBList's rank order and + is cut by rank to the read limit the collection's item limit sets. The + link's `sort` (such as `sort=usort`, Custom Order), which the feed + follows, doesn't reach it, so a public list of episodes or seasons comes + in rank order, as a private list does. Each sync of an empty list spends + API reads from + the key's daily quota: one per page of items, plus one to resolve an + owner-and-slug URL. Without a server key the sync ends in a warning and + keeps the members it had, since an empty feed says nothing about the list; + an import still creates the collection. The v2 admin API reports it as + `last_sync_reason` `mdblist_api_key_required`, and `checkAdminMDBListLink` + warns before the collection is created (see + [catalog-api.md](../catalog-api.md#mdblist-lists-that-need-a-key)). +- A list that also holds movies or shows has a non-empty feed, so it syncs + from the feed and its episodes and seasons are left out. +- A personal collection reads through the profile's watch-provider + connection, which returns no episodes either, so personal collections hold + titles only. +- Within the series matched by the show's TMDB ID, an episode matches by its + TMDB ID first, which holds however the library numbers the series, then by + its provider numbers (`provider_season_number`, `provider_episode_number`), + falling back to the shown numbers for a row without provider numbers, the + same probes as `GetBySeriesAndProviderNumber`. A season matches the same + way, though seasons rarely carry a TMDB ID, so in practice by number. A + number probe skips a row whose TMDB ID differs from the entry's, and + unlisted episodes never match. Episodes from a provider that writes no TMDB + IDs (the TVDB plugin) match by number only, so a series the library numbers + differently from TMDB can match the wrong episode. + +## Reading members + +- A viewer sees an episode or season member when they can see its series: + library access is checked on the series, and maturity and excluded types + apply to the series row. An episode also needs an `episode_libraries` row + in the collection's libraries and one in a library the viewer may open, so + a series spanning libraries never lists an episode they can't play; a + season needs an episode on disk, in such a library for a restricted viewer. The + relations live in `internal/catalog/collection_members.go`, and every + surface uses them: the card count, the collage, the collection page and + catalog cursor, home rows, shuffle, and the jellycompat BoxSet. +- A media scope on a collection page treats an episode or season member as + standing in for its series: a library's Series category, which Roku and + Android TV pass, keeps them, and its Movies category leaves them out. +- The catalog cursor only switches to the mixed member relation when a + collection holds an episode or season member, so a titles-only collection + keeps its plain title query. +- Cards name their series and numbers (`S30E10`, or the season number). + jellycompat lists an episode member as an `Episode` and a season member as + a `Season`; Play all plays an episode member as itself and a season member + as its visible episodes, each episode once. Catalog browse reads titles + only, so a BoxSet request with a sort keeps curated order for a collection + that holds episodes or seasons, and one with an item-type or member filter + lists its titles only. +- A selective restore finds a collection's members among titles, episodes and + seasons, and adds the missing ones in any of the three columns. +- The collection page's filter options come from title members only. diff --git a/docs/catalog-api.md b/docs/catalog-api.md index 3cdb900f864..cc042110887 100644 --- a/docs/catalog-api.md +++ b/docs/catalog-api.md @@ -394,6 +394,26 @@ accepts `sync_schedule`; see [Personal sync schedules](#personal-sync-schedules) `listAdminCollectionSections` is available and `listAdminCollections` items carry row counts; see [Rows that show a server collection](#rows-that-show-a-server-collection). +## MDBList lists that need a key + +A private list, and a list of episodes or seasons, sync only with the server's MDBList API key: +MDBList's public feed refuses the first and lists nothing for the second. The API read keeps +MDBList's rank order and caps the list by rank. It ignores the `sort` on the link, which only +the public feed follows. + +- **Before creating.** `checkAdminMDBListLink` (`GET /api/v2/admin/collections/mdblist/link?url=`) + answers `needs_api_key: true` when a server collection following the link would sync only + with a key the server lacks. With a key it answers `false` without a request; without one it + reads one entry of the list's public feed. A link that is not an MDBList list page is + `malformed_request`; a feed that can't be read is `dependency_unavailable`. + `mdblist_link_check` in `getAdminCollectionCapabilities` reports the operation. +- **After a sync.** An admin collection's `last_sync_reason` is `mdblist_api_key_required` + when its last sync read nothing for want of that key. For an empty feed the sync answers a + `warning` run whose `reason` carries the same code, and keeps the members a key synced + before. For a refused feed the sync answers an error and records a `failed` run, so the code + shows only in `last_sync_reason`. Clients show the reason in their own words; + `last_sync_message` stays generic. + ## Private MDBList lists A server collection can follow a private MDBList list that the server's MDBList API key can @@ -1445,6 +1465,19 @@ titles through the existing viewer access filter; admin pages require acting administrator access. Membership identity, ordering and cursor revision checks are unchanged. +## Episode and season members + +A synced MDBList collection can hold episodes and seasons as well as titles. Its pages (the +catalog `library_collection` source and the library collection items page), home rows and Jellyfin +BoxSet children return them as items of type `episode` and `season`, in member order unless a sort +is set, with their series and numbers set as on any other episode or season card, and +`item_count` counts them. Shuffle and Play all play a season member as its episodes. A BoxSet +request with a sort keeps such a collection's curated order, and one with an item-type or member +filter lists its titles only. A viewer sees one when they can see its series and it has a file +in a library they may open. Clients that render a collection should +handle both types and open an episode or season the way they open one elsewhere. See +[collection members](architecture/collection-members.md). + ## Server smart collection libraries A server smart collection keeps two library lists. Its `library_ids` are where it shows: the diff --git a/internal/api/handlers/admin_collection_editors_service.go b/internal/api/handlers/admin_collection_editors_service.go index 74059e9ea4f..87e3dce259b 100644 --- a/internal/api/handlers/admin_collection_editors_service.go +++ b/internal/api/handlers/admin_collection_editors_service.go @@ -234,6 +234,17 @@ func (h *LibraryCollectionHandler) AdminCollectionItemsOrder(ctx context.Context func (h *LibraryCollectionHandler) AdminCollectionFeatures(context.Context) userstore.CollectionFeatures { return userstore.CollectionFeatures{Groups: h.GroupRepo != nil, Imports: h.service != nil, Artwork: h.ArtworkStore != nil, ItemReorder: h.repo != nil} } + +var errCollectionImportsUnconfigured = errors.New("collection imports are not configured") + +// CheckAdminMDBListLink reports whether a server collection following link +// syncs only with an MDBList API key the server lacks. +func (h *LibraryCollectionHandler) CheckAdminMDBListLink(ctx context.Context, link string) (bool, error) { + if h.service == nil { + return false, errCollectionImportsUnconfigured + } + return h.service.MDBListLinkNeedsKey(ctx, link) +} func (h *LibraryCollectionHandler) AdminCollectionTemplateCatalog(context.Context) templates.Catalog { return h.templateRegistry().Catalog() } diff --git a/internal/api/handlers/catalog.go b/internal/api/handlers/catalog.go index 072c6034dfd..e674481537a 100644 --- a/internal/api/handlers/catalog.go +++ b/internal/api/handlers/catalog.go @@ -133,6 +133,11 @@ func (h *CatalogHandler) catalogItemResponses(ctx context.Context, v ItemViewer, defer enrichWG.Done() playTargets = h.itemsH.listPlayableTargets(ctx, v, resultItems, libraryIDs, accessFilter) }() + // A collection can hold seasons, whose cards name their series. + var seasons map[string]catalog.SeasonCardContext + if h.itemsH != nil { + enrichWG.Go(func() { seasons = listSeasonCardContexts(ctx, h.itemsH.seasonRepo, resultItems) }) + } // Series cards are known here, so their seasons are counted alongside the // other lookups rather than after the cards are assembled. var countedSeries []string @@ -186,6 +191,9 @@ func (h *CatalogHandler) catalogItemResponses(ctx context.Context, v ItemViewer, resp.ParentArtwork = episodeParentArtworkView(meta.ParentArtwork, imageURLs[item.ContentID].parents) } } + if season, ok := seasons[item.ContentID]; ok { + setSeasonCardIdentity(&resp, season) + } resp.PosterURL = imageURLs[item.ContentID].posterURL resp.BackdropURL = imageURLs[item.ContentID].backdropURL resp.LogoURL = imageURLs[item.ContentID].logoURL @@ -225,6 +233,12 @@ func setEpisodeCardIdentity(resp *itemListResponse, meta episodeBrowseMetadata) resp.EpisodeNumber = meta.EpisodeNumber } +// setSeasonCardIdentity names a season card's series and its number. +func setSeasonCardIdentity(resp *itemListResponse, season catalog.SeasonCardContext) { + number := season.SeasonNumber + resp.SeriesID, resp.SeriesTitle, resp.SeasonNumber = season.SeriesID, season.SeriesTitle, &number +} + type groupedCatalogEntry struct { item *models.MediaItem summary *catalog.WorkSummary diff --git a/internal/api/handlers/collections_paging_service.go b/internal/api/handlers/collections_paging_service.go index 8cf8218bd3d..f8c2f07dd9b 100644 --- a/internal/api/handlers/collections_paging_service.go +++ b/internal/api/handlers/collections_paging_service.go @@ -279,7 +279,7 @@ func (h *LibraryCollectionHandler) LibraryCollectionItemsPage(ctx context.Contex page, items, last, err := pageShownMembers(ctx, opts, func(o userstore.CollectionItemsPageOptions) (userstore.CollectionItemsPage, error) { return h.repo.ListItemsPage(ctx, id, o) }, func(ids []string) ([]*models.MediaItem, error) { - return h.itemRepo.GetListedByIDsWithAccess(ctx, ids, access) + return h.itemRepo.GetListedMembersByIDsWithAccess(ctx, ids, access) }) if err != nil { return out, collectionPageError(err) diff --git a/internal/api/handlers/library_collection_episode_members_db_test.go b/internal/api/handlers/library_collection_episode_members_db_test.go new file mode 100644 index 00000000000..393783797e0 --- /dev/null +++ b/internal/api/handlers/library_collection_episode_members_db_test.go @@ -0,0 +1,159 @@ +package handlers + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Silo-Server/silo-server/internal/catalog" + "github.com/Silo-Server/silo-server/internal/models" + "github.com/Silo-Server/silo-server/internal/userstore" +) + +// episodeMembersFixture is a synced collection in library tv holding, in +// order, an episode of a series in a second library, an episode of the +// series in tv, and a season of that series. +type episodeMembersFixture struct { + pool *pgxpool.Pool + repo *catalog.LibraryCollectionRepository + collectionID string + series, season, episode string + tv int +} + +func seedEpisodeMembersFixture(t *testing.T) episodeMembersFixture { + t.Helper() + dsn := os.Getenv("SILO_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("SILO_TEST_DATABASE_URL is not set") + } + ctx := t.Context() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + + prefix := fmt.Sprintf("collection-episode-members-%d", time.Now().UnixNano()) + f := episodeMembersFixture{pool: pool, series: prefix + "-series", season: prefix + "-s1", episode: prefix + "-s1e2"} + hiddenSeries, hiddenEpisode := prefix+"-hidden", prefix+"-hidden-s1e1" + var hidden int + for name, id := range map[string]*int{prefix: &f.tv, prefix + "-hidden": &hidden} { + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, true) RETURNING id`, name).Scan(id); err != nil { + t.Fatal(err) + } + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM library_collections WHERE slug = $1`, prefix) + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = ANY($1)`, []string{f.series, hiddenSeries}) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = ANY($1)`, []int{f.tv, hidden}) + }) + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title, status, genres) VALUES ($1, 'series', 'The Series', 'matched', '{}'::text[]), ($2, 'series', 'Hidden Series', 'matched', '{}'::text[])`, []any{f.series, hiddenSeries}}, + {`INSERT INTO media_item_libraries (content_id, media_folder_id) VALUES ($1, $2), ($3, $4)`, []any{f.series, f.tv, hiddenSeries, hidden}}, + {`INSERT INTO seasons (content_id, series_id, season_number, title) VALUES ($1, $2, 1, 'Season 1')`, []any{f.season, f.series}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title) VALUES ($1, $2, $3, 1, 2, 'Two')`, []any{f.episode, f.series, f.season}}, + {`INSERT INTO episodes (content_id, series_id, season_number, episode_number, title) VALUES ($1, $2, 1, 1, 'Hidden One')`, []any{hiddenEpisode, hiddenSeries}}, + {`INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $2), ($3, $4)`, []any{f.episode, f.tv, hiddenEpisode, hidden}}, + } { + if _, err := pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + + f.repo = catalog.NewLibraryCollectionRepository(pool) + c, err := f.repo.Create(ctx, catalog.CreateLibraryCollectionInput{LibraryID: f.tv, LibraryIDs: []int{f.tv, hidden}, + Slug: prefix, Title: "Holiday", CollectionType: "mdblist", Visibility: "visible"}) + if err != nil { + t.Fatal(err) + } + if err := f.repo.ReplaceItems(ctx, c.ID, []catalog.LibraryCollectionItemInput{ + {MediaItemID: hiddenEpisode, Kind: catalog.CollectionMemberEpisode}, + {MediaItemID: f.episode, Kind: catalog.CollectionMemberEpisode}, + {MediaItemID: f.season, Kind: catalog.CollectionMemberSeason}, + }); err != nil { + t.Fatal(err) + } + f.collectionID = c.ID + return f +} + +// TestLibraryCollectionPageShowsEpisodeAndSeasonMembersDB pins that a synced +// collection's episode and season members are cards on its page, in member +// order, each naming its series and numbers, on the collection's page and in +// the catalog alike, and that an episode of a series the viewer can't open is +// left out like a title would be. +func TestLibraryCollectionPageShowsEpisodeAndSeasonMembersDB(t *testing.T) { + f := seedEpisodeMembersFixture(t) + ctx := t.Context() + viewer := catalog.AccessFilter{AllowedLibraryIDs: []int{f.tv}} + + h := NewLibraryCollectionHandler(f.repo, nil, catalog.NewItemRepository(f.pool), nil) + h.FolderRepo = catalog.NewFolderRepository(f.pool) + h.EpisodeRepo = catalog.NewEpisodeRepository(f.pool) + h.SeasonRepo = catalog.NewSeasonRepository(f.pool) + page, err := h.LibraryCollectionItemsPage(ctx, f.tv, f.collectionID, viewer, userstore.CollectionItemsPageOptions{Limit: 10}, nil) + if err != nil { + t.Fatal(err) + } + type card struct { + id, kind, series string + season, episode int + } + cards := func(items []itemListResponse) []card { + got := make([]card, 0, len(items)) + for _, i := range items { + c := card{id: i.ContentID, kind: i.Type, series: i.SeriesID} + if i.SeasonNumber != nil { + c.season = *i.SeasonNumber + } + if i.EpisodeNumber != nil { + c.episode = *i.EpisodeNumber + } + got = append(got, c) + } + return got + } + want := []card{ + {id: f.episode, kind: "episode", series: f.series, season: 1, episode: 2}, + {id: f.season, kind: "season", series: f.series, season: 1}, + } + if got := cards(page.Items); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("cards = %+v, want %+v", got, want) + } + + // The catalog, which the web collection page reads, gives the same cards. + items := catalog.NewItemRepository(f.pool) + browse := NewCatalogHandler(catalog.NewCatalogResolver(catalog.NewBrowseRepository(f.pool), items), &ItemsHandler{ + itemRepo: items, episodeRepo: catalog.NewEpisodeRepository(f.pool), seasonRepo: catalog.NewSeasonRepository(f.pool), + }) + view, err := browse.Browse(ctx, ItemViewer{Access: viewer}, catalog.CatalogRequest{ + Source: catalog.CatalogSourceLibraryCollection, CollectionID: f.collectionID, CursorPaging: true, UseSourceOrder: true, Limit: 10, + }, false) + if err != nil { + t.Fatal(err) + } + if got := cards(view.Items); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("catalog cards = %+v, want %+v", got, want) + } +} + +// TestSectionSeasonCardNamesItsSeriesDB pins that a home row's season card, +// which a row showing a collection can hold, names its series and number. +func TestSectionSeasonCardNamesItsSeriesDB(t *testing.T) { + f := seedEpisodeMembersFixture(t) + rows := &SectionHandler{SeasonRepo: catalog.NewSeasonRepository(f.pool)} + meta := rows.listSectionSeasonItemMeta(t.Context(), []*models.MediaItem{{ContentID: f.season, Type: "season"}, {ContentID: f.series, Type: "series"}}) + got, ok := meta[f.season] + if len(meta) != 1 || !ok || got.SeriesID == nil || *got.SeriesID != f.series || got.SeriesTitle != "The Series" || got.SeasonNumber == nil || *got.SeasonNumber != 1 { + t.Fatalf("season row meta = %+v", meta) + } +} diff --git a/internal/api/handlers/library_collections.go b/internal/api/handlers/library_collections.go index 0640c87be6c..e72a8d5cafe 100644 --- a/internal/api/handlers/library_collections.go +++ b/internal/api/handlers/library_collections.go @@ -75,6 +75,9 @@ type LibraryCollectionHandler struct { // EpisodeRepo gives episode cards their series and numbers; nil leaves // them out. EpisodeRepo *catalog.EpisodeRepository + // SeasonRepo gives season cards their series and number; nil leaves + // them bare. + SeasonRepo *catalog.SeasonRepository } var errLibraryCollectionInUse = catalog.ErrLibraryCollectionInUse @@ -2169,15 +2172,20 @@ func validateTMDBDiscoverRequest(req importTMDBDiscoverRequest) error { } // itemListResponsesOf renders the cards of items in order, looking up the -// series and numbers of the episodes among them in one query. +// series and numbers of the episodes, and of the seasons, among them in one +// query each. func (h *LibraryCollectionHandler) itemListResponsesOf(ctx context.Context, items []*models.MediaItem) []itemListResponse { episodes := listEpisodeCardMetadata(ctx, h.EpisodeRepo, items) + seasons := listSeasonCardContexts(ctx, h.SeasonRepo, items) out := make([]itemListResponse, 0, len(items)) for _, item := range items { resp := h.itemListResponseOf(ctx, item) if meta, ok := episodes[item.ContentID]; ok { setEpisodeCardIdentity(&resp, meta) } + if season, ok := seasons[item.ContentID]; ok { + setSeasonCardIdentity(&resp, season) + } out = append(out, resp) } return out @@ -2717,3 +2725,25 @@ func pointerStringValue(value *string) string { } return *value } + +// listSeasonCardContexts looks up the series and number of the seasons among +// items; a failed lookup leaves their cards bare rather than failing the page. +func listSeasonCardContexts(ctx context.Context, repo *catalog.SeasonRepository, items []*models.MediaItem) map[string]catalog.SeasonCardContext { + if repo == nil { + return nil + } + var ids []string + for _, item := range items { + if item != nil && item.Type == itemTypeSeason { + ids = append(ids, item.ContentID) + } + } + if len(ids) == 0 { + return nil + } + contexts, err := repo.ListCardContexts(ctx, ids) + if err != nil { + return nil + } + return contexts +} diff --git a/internal/api/handlers/sections.go b/internal/api/handlers/sections.go index c9e3f00f768..f4021ba0212 100644 --- a/internal/api/handlers/sections.go +++ b/internal/api/handlers/sections.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "log/slog" + "maps" "net/http" "reflect" "runtime/debug" @@ -37,13 +38,16 @@ type SectionHandler struct { sectionReader interface { GetByID(context.Context, string) (*sections.PageSection, error) } - sectionLister sectionScopeLister - fetcher *sections.Fetcher - previewFetcher sectionPreviewFetcher // set to fetcher at construction; separate for test injection - episodeFetcher sectionEpisodeFetcher - playableTargets sectionPlayableTargetResolver // set to fetcher at construction; separate for test injection - FolderRepo *catalog.FolderRepository - EpisodeRepo *catalog.EpisodeRepository + sectionLister sectionScopeLister + fetcher *sections.Fetcher + previewFetcher sectionPreviewFetcher // set to fetcher at construction; separate for test injection + episodeFetcher sectionEpisodeFetcher + playableTargets sectionPlayableTargetResolver // set to fetcher at construction; separate for test injection + FolderRepo *catalog.FolderRepository + EpisodeRepo *catalog.EpisodeRepository + // SeasonRepo names the series and number on the season cards of a row + // showing a collection that holds seasons. + SeasonRepo *catalog.SeasonRepository StoreProvider userstore.UserStoreProvider UserRepo *auth.UserRepository AccessGroups access.GroupPolicyProvider // optional; resolves inherited library access when no scope is in context @@ -1277,7 +1281,10 @@ func (h *SectionHandler) buildSectionsWithUserStates(ctx context.Context, withIt localizedItems, pendingTranslations = h.localizeSectionItems(ctx, allItems, localizationAccess) }) goSectionLookup(ctx, &wg, sectionLookupImageURLs, timings, func() { imageURLs = h.resolveSectionItemImageURLs(ctx, withItems, art) }) - goSectionLookup(ctx, &wg, sectionLookupEpisodeMeta, timings, func() { episodeMeta = h.listSectionEpisodeItemMeta(ctx, withItems, viewerAccess) }) + goSectionLookup(ctx, &wg, sectionLookupEpisodeMeta, timings, func() { + episodeMeta = h.listSectionEpisodeItemMeta(ctx, withItems, viewerAccess) + maps.Copy(episodeMeta, h.listSectionSeasonItemMeta(ctx, allItems)) + }) goSectionLookup(ctx, &wg, sectionLookupMangaChapterMeta, timings, func() { mangaChapterMeta = h.listSectionMangaChapterItemMeta(ctx, allItems) }) availability := h.startSectionAvailability(ctx, &wg, timings, includeAvailability, viewerAccess, allItems) @@ -1526,6 +1533,17 @@ func (h *SectionHandler) listSectionMangaChapterItemMeta(ctx context.Context, it return meta } +// listSectionSeasonItemMeta names the series and number of the seasons +// among the section items, which a row showing a collection can hold. +func (h *SectionHandler) listSectionSeasonItemMeta(ctx context.Context, items []*models.MediaItem) map[string]sections.SectionItemMeta { + contexts := listSeasonCardContexts(ctx, h.SeasonRepo, items) + meta := make(map[string]sections.SectionItemMeta, len(contexts)) + for id, season := range contexts { + meta[id] = sections.SectionItemMeta{SeriesID: new(season.SeriesID), SeriesTitle: season.SeriesTitle, SeasonNumber: new(season.SeasonNumber)} + } + return meta +} + func (h *SectionHandler) listSectionEpisodeItemMeta(ctx context.Context, withItems []sections.SectionWithItems, filter catalog.AccessFilter) map[string]sections.SectionItemMeta { if h == nil || h.episodeFetcher == nil { return map[string]sections.SectionItemMeta{} diff --git a/internal/api/router.go b/internal/api/router.go index fde9d575932..bdc27fd48ab 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -2359,6 +2359,7 @@ func newChiRouter(deps Dependencies) chi.Router { sectionHandler.StoreProvider = deps.UserStoreProvider } sectionHandler.EpisodeRepo = episodeRepo + sectionHandler.SeasonRepo = seasonRepo sectionHandler.DetailSvc = detailSvc if ebookProgressStore != nil { sectionHandler.EbookProgress = ebookProgressStore @@ -2438,6 +2439,7 @@ func newChiRouter(deps Dependencies) chi.Router { libraryCollectionHandler.FrontendFS = deps.FrontendFS libraryCollectionHandler.Executor = &catalog.QueryExecutor{Pool: deps.DB} libraryCollectionHandler.EpisodeRepo = episodeRepo + libraryCollectionHandler.SeasonRepo = seasonRepo libraryCollectionHandler.SectionRepo = sectionRepo libraryCollectionHandler.UserCollectionPool = deps.DB libraryCollectionHandler.CollectionOwners = collectionOwners diff --git a/internal/api/testdata/media_routes.txt b/internal/api/testdata/media_routes.txt index 5bcf62d4ca8..62863a06dad 100644 --- a/internal/api/testdata/media_routes.txt +++ b/internal/api/testdata/media_routes.txt @@ -176,6 +176,7 @@ GET /api/v2/admin/collections/capabilities non-media POST /api/v2/admin/collections/import/mdblist non-media POST /api/v2/admin/collections/import/tmdb non-media POST /api/v2/admin/collections/import/tmdb-list non-media +GET /api/v2/admin/collections/mdblist/link non-media GET /api/v2/admin/collections/mdblist/lists non-media GET /api/v2/admin/collections/order non-media PUT /api/v2/admin/collections/order non-media @@ -1367,6 +1368,7 @@ GET /api/v2/admin/collections/capabilities non-media POST /api/v2/admin/collections/import/mdblist non-media POST /api/v2/admin/collections/import/tmdb non-media POST /api/v2/admin/collections/import/tmdb-list non-media +GET /api/v2/admin/collections/mdblist/link non-media GET /api/v2/admin/collections/mdblist/lists non-media GET /api/v2/admin/collections/order non-media PUT /api/v2/admin/collections/order non-media diff --git a/internal/apiv2/admin_collection_mdblist_key_test.go b/internal/apiv2/admin_collection_mdblist_key_test.go new file mode 100644 index 00000000000..2c7e7eb3abf --- /dev/null +++ b/internal/apiv2/admin_collection_mdblist_key_test.go @@ -0,0 +1,94 @@ +package apiv2 + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "testing" + + catalogsvc "github.com/Silo-Server/silo-server/internal/catalog" + "github.com/Silo-Server/silo-server/internal/models" +) + +// What a keyless sync stores for a private list (a failed run) and for a +// list whose public feed is empty (a warning run). +const ( + keylessPrivateMessage = "mdblist: This List is Private. To sync a private list, add an MDBList API key from the account that owns it in Settings › Providers" + keylessEmptyMessage = "MDBList's public feed lists nothing for this list. A list of episodes or seasons syncs only with an MDBList API key; add one in Settings › Providers" +) + +type keylessAdminCollections struct { + *fakeAdminCollections + checked []string +} + +func (f *keylessAdminCollections) CheckAdminMDBListLink(_ context.Context, link string) (bool, error) { + f.checked = append(f.checked, link) + if link == "https://example.com/x" { + return false, fmt.Errorf("%w: wrong host", catalogsvc.ErrMDBListLinkInvalid) + } + return link == "https://mdblist.com/lists/alice/holiday-episodes", nil +} + +func (f *keylessAdminCollections) SyncAdminCollection(context.Context, string) (*models.LibraryCollectionSyncRun, error) { + return &models.LibraryCollectionSyncRun{ID: "run", CollectionID: "c1", Status: "warning", Message: keylessEmptyMessage, CreatedAt: fixedTime()}, nil +} + +// An admin pasting an MDBList link learns whether the list syncs only with +// an MDBList API key, and a collection whose sync read nothing for want of +// that key says so as a reason code clients show in their own words. +func TestAdminCollectionsNameTheMissingMDBListKey(t *testing.T) { + f := &keylessAdminCollections{fakeAdminCollections: newFakeAdminCollections()} + f.view.LastSyncStatus = "failed" + f.view.LastSyncMessage = keylessPrivateMessage + deps, _ := libraryDeps(t) + deps.AdminCollections = f + h := newTestHandler(t, deps) + + var caps struct { + MDBListLinkCheck bool `json:"mdblist_link_check"` + } + rec := do(t, h, http.MethodGet, "/api/v2/admin/collections/capabilities", "", bearer(adminToken)) + if err := json.Unmarshal(rec.Body.Bytes(), &caps); err != nil || !caps.MDBListLinkCheck { + t.Fatalf("capabilities %d %s: want mdblist_link_check", rec.Code, rec.Body) + } + + check := func(link string) (int, bool) { + rec := do(t, h, http.MethodGet, "/api/v2/admin/collections/mdblist/link?url="+url.QueryEscape(link), "", bearer(adminToken)) + var body struct { + NeedsAPIKey bool `json:"needs_api_key"` + } + _ = json.Unmarshal(rec.Body.Bytes(), &body) + return rec.Code, body.NeedsAPIKey + } + if code, needs := check("https://mdblist.com/lists/alice/holiday-episodes"); code != 200 || !needs { + t.Errorf("episode list = %d needs %v, want 200 needs true", code, needs) + } + if code, needs := check("https://mdblist.com/lists/alice/movies"); code != 200 || needs { + t.Errorf("title list = %d needs %v, want 200 needs false", code, needs) + } + if code, _ := check("https://example.com/x"); code != http.StatusBadRequest { + t.Errorf("other link = %d, want 400", code) + } + if rec := do(t, h, http.MethodGet, "/api/v2/admin/collections/mdblist/link?url="+url.QueryEscape("https://mdblist.com/lists/alice/movies"), "", bearer(memberToken)); rec.Code != http.StatusForbidden { + t.Errorf("non-admin check = %d, want 403", rec.Code) + } + + var collection struct { + LastSyncReason string `json:"last_sync_reason"` + LastSyncMessage string `json:"last_sync_message"` + } + rec = do(t, h, http.MethodGet, "/api/v2/admin/collections/c1", "", bearer(adminToken)) + if err := json.Unmarshal(rec.Body.Bytes(), &collection); err != nil || collection.LastSyncReason != catalogsvc.SyncReasonMDBListAPIKeyRequired { + t.Errorf("collection %d %s: want last_sync_reason %s", rec.Code, rec.Body, catalogsvc.SyncReasonMDBListAPIKeyRequired) + } + var run struct { + Reason string `json:"reason"` + } + rec = do(t, h, http.MethodPost, "/api/v2/admin/collections/c1/sync", "", bearer(adminToken)) + if err := json.Unmarshal(rec.Body.Bytes(), &run); err != nil || run.Reason != catalogsvc.SyncReasonMDBListAPIKeyRequired { + t.Errorf("sync %d %s: want reason %s", rec.Code, rec.Body, catalogsvc.SyncReasonMDBListAPIKeyRequired) + } +} diff --git a/internal/apiv2/admin_collection_types.go b/internal/apiv2/admin_collection_types.go index dc2086e369f..a0f841723c4 100644 --- a/internal/apiv2/admin_collection_types.go +++ b/internal/apiv2/admin_collection_types.go @@ -6,6 +6,7 @@ import ( "time" "github.com/Silo-Server/silo-server/internal/api/handlers" + catalogsvc "github.com/Silo-Server/silo-server/internal/catalog" "github.com/Silo-Server/silo-server/internal/models" ) @@ -42,6 +43,7 @@ type AdminCollection struct { ManagementKey string `json:"management_key"` LastSyncStatus string `json:"last_sync_status"` LastSyncMessage string `json:"last_sync_message"` + LastSyncReason string `json:"last_sync_reason,omitempty" enum:"mdblist_api_key_required" doc:"Why the last sync read nothing, for clients to say in their own words; absent when it gives none. mdblist_api_key_required: the list syncs only with an MDBList API key the server lacks (a private list, or a list of episodes or seasons)"` LastSyncAt *Instant `json:"last_sync_at,omitempty" nullable:"false"` SyncSchedule string `json:"sync_schedule,omitempty"` NextSyncAt *Instant `json:"next_sync_at,omitempty" nullable:"false"` @@ -400,6 +402,7 @@ type AdminCollectionSyncRun struct { CollectionID ID `json:"collection_id"` Status string `json:"status"` Message string `json:"message"` + Reason string `json:"reason,omitempty" enum:"mdblist_api_key_required" doc:"Why the sync read nothing, as last_sync_reason on the collection; absent when it gives none"` ItemsAdded int `json:"items_added"` ItemsRemoved int `json:"items_removed"` ItemsMatched int `json:"items_matched"` @@ -427,7 +430,7 @@ func adminCollectionSyncRunOf(v *models.LibraryCollectionSyncRun) *AdminCollecti if v.Status == adminCollectionSyncFailed || v.Status == adminCollectionSyncError { message = "Collection sync failed." } - return &AdminCollectionSyncRun{ID: ID(v.ID), CollectionID: ID(v.CollectionID), Status: v.Status, Message: message, ItemsAdded: v.ItemsAdded, ItemsRemoved: v.ItemsRemoved, ItemsMatched: v.ItemsMatched, ItemsUnmatched: v.ItemsUnmatched, StartedAt: adminSyncInstant(v.StartedAt), CompletedAt: adminSyncInstant(v.CompletedAt), CreatedAt: NewInstant(v.CreatedAt)} + return &AdminCollectionSyncRun{ID: ID(v.ID), CollectionID: ID(v.CollectionID), Status: v.Status, Message: message, Reason: catalogsvc.SyncMessageReason(v.Message), ItemsAdded: v.ItemsAdded, ItemsRemoved: v.ItemsRemoved, ItemsMatched: v.ItemsMatched, ItemsUnmatched: v.ItemsUnmatched, StartedAt: adminSyncInstant(v.StartedAt), CompletedAt: adminSyncInstant(v.CompletedAt), CreatedAt: NewInstant(v.CreatedAt)} } func adminCollectionImportResultOf(v handlers.AdminCollectionImportResult) AdminCollectionImportResult { return AdminCollectionImportResult{Collection: adminCollectionOf(v.Collection), SyncRun: adminCollectionSyncRunOf(v.SyncRun)} @@ -459,6 +462,7 @@ func adminCollectionOf(v handlers.AdminCollection) AdminCollection { ManagementKey: v.ManagementKey, LastSyncStatus: v.LastSyncStatus, LastSyncMessage: "", + LastSyncReason: catalogsvc.SyncMessageReason(v.LastSyncMessage), LastSyncAt: instantOfStamp(v.LastSyncAt), SyncSchedule: v.SyncSchedule, NextSyncAt: instantOfStamp(v.NextSyncAt), diff --git a/internal/apiv2/admin_collections.go b/internal/apiv2/admin_collections.go index a4a3194bb95..e9d11638cd2 100644 --- a/internal/apiv2/admin_collections.go +++ b/internal/apiv2/admin_collections.go @@ -132,6 +132,7 @@ type AdminCollectionCapabilityOutputBody struct { ItemReorder bool `json:"item_reorder"` TemplateSummaries bool `json:"template_summaries" doc:"listAdminCollectionTemplateBundles returns each bundle's templates" example:"true"` MDBListSearch bool `json:"mdblist_search" doc:"searchMDBListLists and listTopMDBListLists return lists; false when the server has no MDBList API key" example:"true"` + MDBListLinkCheck bool `json:"mdblist_link_check" doc:"checkAdminMDBListLink reports whether an MDBList link syncs only with an MDBList API key the server lacks" example:"true"` MDBListAccountLists bool `json:"mdblist_account_lists" doc:"listAdminMDBListLists returns the lists of the account that owns the server's MDBList API key, and server collections sync that account's private lists; false when the server has no MDBList API key" example:"true"` ScheduleTimeZone CollectionScheduleTimeZone `json:"schedule_time_zone"` SectionReferences bool `json:"section_references" doc:"listAdminCollectionSections lists the rows that show a collection, and listAdminCollections items carry home_row_count and row_count" example:"true"` @@ -178,6 +179,7 @@ func registerAdminCollections(reg *Registry) { out := &AdminCollectionCapabilityOutput{} out.Body.MDBListSearch = reg.mdblistSearch() out.Body.MDBListAccountLists = reg.serverMDBListAccountLists() != nil + out.Body.MDBListLinkCheck = reg.adminMDBListLinkChecker() != nil out.Body.ScheduleTimeZone = reg.scheduleTimeZone() out.Body.SectionReferences = reg.adminCollectionSections() != nil if !ok { @@ -193,6 +195,9 @@ func registerAdminCollections(reg *Registry) { out.Body.TemplateSummaries = true return out, nil }) + check := adminCollectionOperation(http.MethodGet, "/admin/collections/mdblist/link", "checkAdminMDBListLink", "Report whether a server collection following an MDBList link syncs only with an MDBList API key the server lacks. Reads the list's public feed once when the server has no key.", false) + check.Errors = append(check.Errors, http.StatusServiceUnavailable) + Register(reg, check, reg.checkAdminMDBListLink) Register(reg, adminCollectionOperation(http.MethodGet, "/admin/collections/mdblist/lists", "listAdminMDBListLists", "List the lists of the MDBList account that owns the server's MDBList API key, private ones included, to sync as server collections.", false), reg.listAdminMDBListLists) registerAdminCollectionGroups(reg) registerAdminCollectionExtras(reg) @@ -460,6 +465,47 @@ func (reg *Registry) serverMDBListAccountLists() interface { return svc } +// adminMDBListLinkChecker returns the service that checks an MDBList link +// for a server collection, or nil when none is wired. +func (reg *Registry) adminMDBListLinkChecker() interface { + CheckAdminMDBListLink(context.Context, string) (bool, error) +} { + svc, ok := reg.deps.AdminCollections.(interface { + CheckAdminMDBListLink(context.Context, string) (bool, error) + }) + if !ok { + return nil + } + return svc +} + +type AdminMDBListLinkInput struct { + URL string `query:"url" required:"true" maxLength:"2048" format:"uri" doc:"The MDBList list link an administrator pasted" example:"https://mdblist.com/lists/alice/holiday-episodes"` +} + +type AdminMDBListLinkOutput struct { + Body struct { + NeedsAPIKey bool `json:"needs_api_key" doc:"A server collection following the link syncs only with an MDBList API key the server lacks: MDBList's public feed refuses the list (a private list) or lists nothing (a list of episodes or seasons). False whenever the server has a key" example:"true"` + } +} + +func (reg *Registry) checkAdminMDBListLink(ctx context.Context, in *AdminMDBListLinkInput) (*AdminMDBListLinkOutput, error) { + svc := reg.adminMDBListLinkChecker() + if svc == nil { + return nil, unavailable("admin collections") + } + needs, err := svc.CheckAdminMDBListLink(ctx, in.URL) + if errors.Is(err, catalogsvc.ErrMDBListLinkInvalid) { + return nil, NewProblem(TypeMalformedRequest, "url is not an MDBList list link.") + } + if err != nil { + return nil, NewProblem(TypeDependencyUnavailable, "Reading the MDBList list failed.").WithRetryAfter(30) + } + out := &AdminMDBListLinkOutput{} + out.Body.NeedsAPIKey = needs + return out, nil +} + func (reg *Registry) listAdminMDBListLists(ctx context.Context, _ *struct{}) (*MDBListAccountListCollectionOutput, error) { svc := reg.serverMDBListAccountLists() if svc == nil { diff --git a/internal/backup/restoreset_write.go b/internal/backup/restoreset_write.go index 6218bdc9310..cf236ad1920 100644 --- a/internal/backup/restoreset_write.go +++ b/internal/backup/restoreset_write.go @@ -487,10 +487,10 @@ func readCollections(ctx context.Context, tx pgx.Tx) ([]collectionRow, error) { return nil, err } rows, err = tx.Query(ctx, ` - SELECT i.collection_id, i.media_item_id FROM library_collection_items i + SELECT i.collection_id, i.member_id FROM library_collection_items i JOIN library_collections c ON c.id = i.collection_id WHERE c.management_mode <> 'template_bundle' - ORDER BY i.collection_id, i.position, i.media_item_id`) + ORDER BY i.collection_id, i.position, i.member_id`) if err != nil { return nil, err } diff --git a/internal/backup/selective_collection_members_postgres_test.go b/internal/backup/selective_collection_members_postgres_test.go new file mode 100644 index 00000000000..e76a88ea0a1 --- /dev/null +++ b/internal/backup/selective_collection_members_postgres_test.go @@ -0,0 +1,39 @@ +package backup + +import ( + "context" + "testing" +) + +// A collection's episode and season members are as restorable as its +// titles: the plan finds them on this server, so a restore adds them rather +// than counting them unknown. +func TestCollectionPlanFindsEpisodeAndSeasonMembersDB(t *testing.T) { + pool, _ := testDB(t) + ctx := t.Context() + prefix := "bk-members-" + randomHex(t, 4) + series, season, episode := prefix+"-series", prefix+"-s1", prefix+"-s1e1" + t.Cleanup(func() { + _, _ = pool.Exec(context.Background(), `DELETE FROM media_items WHERE content_id = $1`, series) + }) + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title) VALUES ($1, 'series', 'Show')`, []any{series}}, + {`INSERT INTO seasons (content_id, series_id, season_number) VALUES ($1, $2, 1)`, []any{season, series}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title) VALUES ($1, $2, $3, 1, 1, 'One')`, []any{episode, series, season}}, + } { + if _, err := pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + + known, err := existingCollectionMembers(ctx, pool, []string{series, season, episode, prefix + "-gone"}) + if err != nil { + t.Fatal(err) + } + if len(known) != 3 || !known[series] || !known[season] || !known[episode] { + t.Fatalf("known members = %v, want the series, season and episode", known) + } +} diff --git a/internal/backup/selective_plan.go b/internal/backup/selective_plan.go index 2f6a95085d5..9116be2b243 100644 --- a/internal/backup/selective_plan.go +++ b/internal/backup/selective_plan.go @@ -521,7 +521,7 @@ func (p *planner) planCollection(ctx context.Context, c CollectionEntry, libMap return plan, nil } plan.item.Collection.LibraryIDs = plan.scope - known, err := existingItems(ctx, p.q, c.Items) + known, err := existingCollectionMembers(ctx, p.q, c.Items) if err != nil { return plan, err } @@ -621,6 +621,23 @@ func existingItems(ctx context.Context, q queryer, ids []string) (map[string]boo return out, rows.Err() } +// existingCollectionMembers reports which of ids name a title, episode or +// season on this server, the members a library collection can hold. +func existingCollectionMembers(ctx context.Context, q queryer, ids []string) (map[string]bool, error) { + out := map[string]bool{} + if len(ids) == 0 { + return out, nil + } + found, err := collectStringsArgs(ctx, q, ` + SELECT content_id FROM media_items WHERE content_id = ANY($1) + UNION ALL SELECT content_id FROM episodes WHERE content_id = ANY($1) + UNION ALL SELECT content_id FROM seasons WHERE content_id = ANY($1)`, ids) + for _, id := range found { + out[id] = true + } + return out, err +} + func collectionsNamed(ctx context.Context, q queryer, libraryID int, title string) ([]string, error) { return collectStringsArgs(ctx, q, ` SELECT c.id FROM library_collections c @@ -629,7 +646,7 @@ func collectionsNamed(ctx context.Context, q queryer, libraryID int, title strin } func collectionItems(ctx context.Context, q queryer, collectionID string) (map[string]bool, error) { - ids, err := collectStringsArgs(ctx, q, `SELECT media_item_id FROM library_collection_items WHERE collection_id = $1`, collectionID) + ids, err := collectStringsArgs(ctx, q, `SELECT member_id FROM library_collection_items WHERE collection_id = $1`, collectionID) out := map[string]bool{} for _, id := range ids { out[id] = true diff --git a/internal/catalog/browse.go b/internal/catalog/browse.go index 8730415dbe5..7776d544dcd 100644 --- a/internal/catalog/browse.go +++ b/internal/catalog/browse.go @@ -701,7 +701,7 @@ func (r *BrowseRepository) buildBrowsePlan(filters BrowseFilters) (browseQueryPl // library collection. The membership is joined in SQL rather than passed as a // ContentIDs allowlist, so a large collection costs one page, not every ID. func (f *BrowseFilters) RestrictToLibraryCollection(collectionID string) { - f.contentSourceSQL = "SELECT media_item_id FROM library_collection_items WHERE collection_id = $1" + f.contentSourceSQL = "SELECT member_id FROM library_collection_items WHERE collection_id = $1" f.contentSourceArgs = []any{collectionID} } diff --git a/internal/catalog/catalog_collection_cursor.go b/internal/catalog/catalog_collection_cursor.go index 809f0ac9436..a96d7a27e2b 100644 --- a/internal/catalog/catalog_collection_cursor.go +++ b/internal/catalog/catalog_collection_cursor.go @@ -327,11 +327,15 @@ func (r *CatalogResolver) resolveLibraryMembershipQueryCursor(ctx context.Contex executor := r.queryExecutorForScope(req.Query.MediaScope, req.SnapshotAt) executor.SourceArgs = []any{req.CollectionID} if req.Query.Sort.Field == "" { - applyCollectionPositionOrder(executor, libraryMembershipOrderJoin) + applyCollectionPositionOrder(executor, libraryMembershipOrderJoin, "member_id") } else { - executor.SourceWhere = "EXISTS (SELECT 1 FROM library_collection_items cursor_membership WHERE cursor_membership.collection_id=$1 AND cursor_membership.media_item_id=mi.content_id)" + executor.SourceWhere = libraryMembershipSourceWhere } - return resolveCollectionExecutorCursor(ctx, executor, req, req.Query, access) + def, access, err := readLibraryCollectionMembers(ctx, r.itemRepo.pool, executor, req.CollectionID, req.Query, access) + if err != nil { + return nil, err + } + return resolveCollectionExecutorCursor(ctx, executor, req, def, access) } func resolveCollectionExecutorCursor(ctx context.Context, executor *QueryExecutor, req CatalogRequest, def QueryDefinition, access AccessFilter) (*CatalogResult, error) { @@ -438,7 +442,7 @@ func (r *CatalogResolver) resolvePersonalMembershipQueryCursor(ctx context.Conte executor := r.queryExecutorForScope(req.Query.MediaScope, req.SnapshotAt) executor.SourceArgs = []any{access.UserID, req.CollectionID} if req.Query.Sort.Field == "" { - applyCollectionPositionOrder(executor, personalMembershipOrderJoin) + applyCollectionPositionOrder(executor, personalMembershipOrderJoin, "media_item_id") } else { executor.SourceWhere = personalMembershipSourceWhere } @@ -452,27 +456,30 @@ func (r *CatalogResolver) resolvePersonalMembershipQueryCursor(ctx context.Conte // matching membership EXISTS: the collection ID for a library collection, and // the account ID and collection ID for a personal one. const ( - libraryMembershipOrderJoin = "JOIN library_collection_items cursor_membership ON cursor_membership.collection_id=$1 AND cursor_membership.media_item_id=mi.content_id" - personalMembershipOrderJoin = "JOIN user_personal_collection_items cursor_membership ON cursor_membership.user_id=$1 AND cursor_membership.collection_id=$2 AND cursor_membership.sub_item_id='' AND cursor_membership.media_item_id=mi.content_id" + // libraryMembershipSourceWhere is a stored library collection's + // membership test for a sort that isn't its curated order. + libraryMembershipSourceWhere = "EXISTS (SELECT 1 FROM library_collection_items cursor_membership WHERE cursor_membership.collection_id=$1 AND cursor_membership.member_id=mi.content_id)" + libraryMembershipOrderJoin = "JOIN library_collection_items cursor_membership ON cursor_membership.collection_id=$1 AND cursor_membership.member_id=mi.content_id" + personalMembershipOrderJoin = "JOIN user_personal_collection_items cursor_membership ON cursor_membership.user_id=$1 AND cursor_membership.collection_id=$2 AND cursor_membership.sub_item_id='' AND cursor_membership.media_item_id=mi.content_id" ) // applyCollectionPositionOrder pages a membership source in curated order. It // joins each member's row, one per member by the table's primary key, instead // of testing membership with EXISTS, and orders by that row's -// (COALESCE(position,0), media_item_id). That matches the table's continuation -// index, so PostgreSQL reads a page in index order and stops, and a -// continuation starts its index range at the cursor, which is why the position -// binds as integer. Ordering by a correlated +// (COALESCE(position,0), idColumn), idColumn being the member's ID column. +// That matches the table's continuation index, so PostgreSQL reads a page in +// index order and stops, and a continuation starts its index range at the +// cursor, which is why the position binds as integer. Ordering by a correlated // position subquery evaluated and sorted every member for each page. The tie // breaker equals mi.content_id through the join, so the order and the cursor // keys are unchanged. -func applyCollectionPositionOrder(executor *QueryExecutor, membershipJoin string) { +func applyCollectionPositionOrder(executor *QueryExecutor, membershipJoin, idColumn string) { // TRUE keeps the display filter and collection search able to AND onto the // source predicate. executor.SourceWhere = cursorTruePredicate executor.SourceJoin = membershipJoin executor.SourceOrder = []queryCursorTerm{ {expression: "COALESCE(cursor_membership.position,0)", kind: cursorKindNumber, nullsLast: true, notNull: true, sqlType: "integer"}, - {expression: "cursor_membership.media_item_id", kind: cursorKindText, nullsLast: true, notNull: true}, + {expression: "cursor_membership." + idColumn, kind: cursorKindText, nullsLast: true, notNull: true}, } } diff --git a/internal/catalog/catalog_resolver.go b/internal/catalog/catalog_resolver.go index 45f78cb4bd2..c31a5b4369e 100644 --- a/internal/catalog/catalog_resolver.go +++ b/internal/catalog/catalog_resolver.go @@ -2424,10 +2424,20 @@ func (r *CatalogResolver) loadCollectionSource(ctx context.Context, req CatalogR return "", nil, err } contentIDs := make([]string, 0, len(collectionItems)) + holdsEpisodes := false for _, item := range collectionItems { contentIDs = append(contentIDs, item.MediaItemID) + holdsEpisodes = holdsEpisodes || item.Kind != "" + } + base := catalogBaseCollectionRequest(req) + if holdsEpisodes { + // Episodes and seasons are no media items, which + // fetchAccessibleItemsByID reads. + items, _, err := PreviewLibraryCollectionMembers(ctx, r.itemRepo.pool, collection.ID, + QueryDefinition{LibraryIDs: base.Query.LibraryIDs}, access, len(contentIDs), false) + return collection.Title, items, err } - items, err := r.fetchAccessibleItemsByID(ctx, contentIDs, catalogBaseCollectionRequest(req), access) + items, err := r.fetchAccessibleItemsByID(ctx, contentIDs, base, access) return collection.Title, items, err case CatalogSourceUserCollection: store, err := r.catalogStoreForAccess(ctx, access) diff --git a/internal/catalog/collection_members.go b/internal/catalog/collection_members.go new file mode 100644 index 00000000000..65c7bf760f0 --- /dev/null +++ b/internal/catalog/collection_members.go @@ -0,0 +1,325 @@ +package catalog + +import ( + "context" + "fmt" + "slices" + "strings" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Silo-Server/silo-server/internal/models" +) + +// AllowCollectionMemberDeletes lets tx delete episode and season members of a +// library collection. The schema refuses a direct delete of one otherwise, so +// that a server of the release before them, which would delete them while +// syncing a list, fails instead (see docs/architecture/collection-members.md). +// Every statement that can directly delete an episode or season member, +// rather than through a cascade, calls it first in the same transaction. +func AllowCollectionMemberDeletes(ctx context.Context, tx pgx.Tx) error { + if _, err := tx.Exec(ctx, `SELECT set_config('silo.collection_member_writes', 'on', true)`); err != nil { + return fmt.Errorf("allowing collection member deletes: %w", err) + } + return nil +} + +// seasonCatalogColumnOverrides are the season relation's own values for the +// item columns; every other column carries the season's series' value, as +// the episode relation's do. +// +//nolint:goconst // The keys are column names, listed as the relation's data. +var seasonCatalogColumnOverrides = map[string]string{ + "content_id": "s.content_id", + "type": "'season'::text", + "title": seasonTitleSQL, + "sort_title": seasonTitleSQL, + "original_title": "COALESCE(s.original_title, '')", + "year": "COALESCE(EXTRACT(YEAR FROM s.air_date)::integer, si.year)", + "runtime": "0", + "overview": "COALESCE(s.overview, '')", + "tagline": "COALESCE(s.tagline, '')", + "rating_imdb": "NULL::double precision", + "rating_tmdb": "NULL::double precision", + "imdb_id": "COALESCE(s.imdb_id, '')", + "tmdb_id": "COALESCE(s.tmdb_id, '')", + "tvdb_id": "COALESCE(s.tvdb_id, '')", + "poster_path": "COALESCE(NULLIF(s.poster_path, ''), si.poster_path)", + "poster_source_path": "CASE WHEN COALESCE(s.poster_path, '') <> '' THEN s.poster_source_path ELSE si.poster_source_path END", + "poster_thumbhash": "CASE WHEN COALESCE(s.poster_path, '') <> '' THEN s.poster_thumbhash ELSE si.poster_thumbhash END", + "backdrop_source_path": "CASE WHEN COALESCE(s.backdrop_path, '') <> '' THEN s.backdrop_source_path ELSE si.backdrop_source_path END", + "backdrop_path": "COALESCE(NULLIF(s.backdrop_path, ''), si.backdrop_path)", + "backdrop_thumbhash": "CASE WHEN COALESCE(s.backdrop_path, '') <> '' THEN s.backdrop_thumbhash ELSE si.backdrop_thumbhash END", + "metadata_s3_path": "s.metadata_s3_path", + "metadata_etag": "s.metadata_etag", + "season_count": "NULL::integer", + "release_date": "s.air_date", + "created_at": "s.created_at", + "updated_at": "s.updated_at", +} + +var seasonTitleSQL = SeasonTitleSQL("s") + +// SeasonTitleSQL is the title a season row aliased alias shows: its own, or +// the default a season without one gets. +func SeasonTitleSQL(alias string) string { + return "COALESCE(NULLIF(BTRIM(" + alias + ".title), ''), " + defaultSeasonTitleSQL(alias+".season_number") + ")" +} + +// seasonCatalogBaseRelation presents seasons in the item columns' shape, +// aliased mi like episodeCatalogBaseRelation, with the series in +// season_series_id. Only seasons of a TV series, for the reason the episode +// relation gives, with an episode on disk, as that relation's episodes are. +var seasonCatalogBaseRelation = func() string { + exprs := make([]string, 0, len(itemColumnNames)+1) + for _, column := range itemColumnNames { + name, _, _ := strings.Cut(column, "::") + expr, ok := seasonCatalogColumnOverrides[name] + if !ok { + expr = "si." + name + } + exprs = append(exprs, expr+" AS "+name) + } + // The columns the catalog executor reads beyond the item's, as the + // episode relation projects them. + exprs = append(exprs, "s.series_id AS season_series_id", "si.content_rating_age", + "s.air_date AS last_air_date_at", "s.air_date AS "+latestAvailableAirDateColumn, + "NULL::timestamptz AS "+latestEpisodeAddedColumn) + return `(SELECT ` + strings.Join(exprs, ", ") + ` + FROM seasons s + JOIN media_items si ON si.content_id = s.series_id AND si.type = 'series' + WHERE EXISTS ( + SELECT 1 FROM episodes se + JOIN episode_libraries sel ON sel.episode_id = se.content_id + WHERE se.season_id = s.content_id)) mi` +}() + +// collectionMemberRelation is where a stored collection's episode or season +// members are read: the relation presenting them as items, the +// library_collection_items column that holds them, and the relation's +// column naming their series. onDiskIn tests whether a member has an episode +// file in a library, given a condition on fl.media_folder_id. +type collectionMemberRelation struct { + from, memberColumn, seriesColumn, onDiskIn string +} + +//nolint:goconst // The columns are library_collection_items names, listed as data. +var collectionMemberRelations = []collectionMemberRelation{ + {episodeCatalogBaseRelation, "episode_id", "mi.episode_series_id", + "EXISTS (SELECT 1 FROM episode_libraries fl WHERE fl.episode_id = mi.content_id AND %s)"}, + {seasonCatalogBaseRelation, "season_id", "mi.season_series_id", + "EXISTS (SELECT 1 FROM episodes fe JOIN episode_libraries fl ON fl.episode_id = fe.content_id WHERE fe.season_id = mi.content_id AND %s)"}, +} + +// accessConditions returns the conditions under which the viewer sees one of +// the relation's members: they can see its series, as detail and playback +// decide, and it has an episode file in a library they may open, as playback +// needs. A series can span libraries with different access. +func (rel collectionMemberRelation) accessConditions(access AccessFilter, args *[]any, argIdx *int) []string { + var conditions []string + appendListedLibraryAccessConditions(rel.seriesColumn, access, &conditions, args, argIdx) + if file := EpisodeFileLibraryAccessSQL("fl.media_folder_id", access, args, argIdx); file != "" { + conditions = append(conditions, fmt.Sprintf(rel.onDiskIn, file)) + } + // Maturity limits and excluded types judge the series row, which carries + // the rating ages the relations don't. + var series []string + applyAccessFilterKeyed("ser", "ser.content_id", AccessFilter{MaturityLimits: access.MaturityLimits, ExcludedMediaTypes: access.ExcludedMediaTypes}, &series, args, argIdx) + if len(series) > 0 { + conditions = append(conditions, "EXISTS (SELECT 1 FROM media_items ser WHERE ser.content_id = "+ + rel.seriesColumn+" AND "+strings.Join(series, " AND ")+")") + } + return conditions +} + +// EpisodeFileLibraryAccessSQL returns the condition, on column naming an +// episode_libraries library, under which the viewer may open an episode file +// there, or "" when access limits no library. +func EpisodeFileLibraryAccessSQL(column string, access AccessFilter, args *[]any, argIdx *int) string { + var file []string + if access.AllowedLibraryIDs != nil { + *args = append(*args, access.AllowedLibraryIDs) + file = append(file, fmt.Sprintf("%s = ANY($%d)", column, *argIdx)) + *argIdx++ + } + if len(access.DisabledLibraryIDs) > 0 { + *args = append(*args, access.DisabledLibraryIDs) + file = append(file, fmt.Sprintf("NOT %s = ANY($%d)", column, *argIdx)) + *argIdx++ + } + return strings.Join(file, " AND ") +} + +// LibraryCollectionHoldsEpisodesOrSeasons reports whether a stored +// collection has an episode or season member, which readers of its titles +// alone would leave out. +func LibraryCollectionHoldsEpisodesOrSeasons(ctx context.Context, pool *pgxpool.Pool, collectionID string) (bool, error) { + var holds bool + if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM library_collection_items + WHERE collection_id = $1 AND media_item_id IS NULL)`, collectionID).Scan(&holds); err != nil { + return false, fmt.Errorf("checking collection episode members: %w", err) + } + return holds, nil +} + +// readLibraryCollectionMembers points executor at a stored collection's +// members through useLibraryCollectionMembersRelation when the collection has +// an episode or season member and def lists titles, and returns the +// definition and access to apply. A titles-only collection, or an episode +// scope, keeps the executor's plain title query. +func readLibraryCollectionMembers(ctx context.Context, pool *pgxpool.Pool, executor *QueryExecutor, collectionID string, def QueryDefinition, access AccessFilter) (QueryDefinition, AccessFilter, error) { + if isEpisodeCatalogScope(def.MediaScope) { + return def, access, nil + } + holds, err := LibraryCollectionHoldsEpisodesOrSeasons(ctx, pool, collectionID) + if err != nil { + return def, access, err + } + if holds { + def, access = useLibraryCollectionMembersRelation(executor, collectionID, def, access) + } + return def, access, nil +} + +// useLibraryCollectionMembersRelation points executor at a stored +// collection's members that the viewer can see: its titles, episodes and +// seasons in one relation, as searchCandidatesExecutor mixes titles and +// episodes. Each branch applies the collection's membership, def's library +// and media scopes and the viewer's access itself, since the executor's own library +// and rating filters read media_items and would drop episodes and seasons. +// It returns the definition and access the executor applies over the +// relation, without what the branches already applied. +func useLibraryCollectionMembersRelation(executor *QueryExecutor, collectionID string, def QueryDefinition, access AccessFilter) (QueryDefinition, AccessFilter) { + branchAccess := access + if libraryIDs, none := access.LibraryScope(def.LibraryIDs); none { + branchAccess.AllowedLibraryIDs = []int{} + } else if libraryIDs != nil { + branchAccess.AllowedLibraryIDs = libraryIDs + } + columns := qualifiedItemColumns("mi") + ", mi.last_air_date_at, mi." + latestAvailableAirDateColumn + + ", mi." + latestEpisodeAddedColumn + ", mi.content_rating_age" + args := []any{collectionID} + argIdx := 2 + var relation strings.Builder + relation.WriteString("(SELECT " + columns + ` + FROM library_collection_items lci + JOIN media_items mi ON mi.content_id = lci.media_item_id + WHERE lci.collection_id = $1`) + if branchAccess.AllowedLibraryIDs != nil && len(branchAccess.AllowedLibraryIDs) == 0 { + relation.WriteString(" AND FALSE") + } + for _, condition := range listedItemAccessConditions(branchAccess, &args, &argIdx) { + relation.WriteString("\n\t AND " + condition) + } + // A media scope picks title types, and an episode or season stands in a + // series' place: a library's Series category keeps them, its Movies + // category leaves them out. + scopeTypes := MediaScopeItemTypes(def.MediaScope) + if len(scopeTypes) > 0 { + args = append(args, scopeTypes) + fmt.Fprintf(&relation, "\n\t AND mi.type = ANY($%d)", argIdx) + argIdx++ + } + if len(scopeTypes) == 0 || slices.Contains(scopeTypes, "series") { + relation.WriteString(CollectionEpisodeAndSeasonMembersSQL(columns, "lci.collection_id = $1", branchAccess, &args, &argIdx)) + } + relation.WriteString(") mi") + executor.BaseRelationSQL = relation.String() + executor.BaseRelationArgs = args + // The relation applied the scope; left on the executor it would judge + // every row as a title of that type, watch state included. + executor.Scope = "" + + def.LibraryIDs = nil + def.MediaScope = "" + access.AllowedLibraryIDs = nil + access.DisabledLibraryIDs = nil + access.MaturityLimits = AccessFilter{}.MaturityLimits + access.ExcludedMediaTypes = nil + return def, access +} + +// CollectionEpisodeAndSeasonMembersSQL returns UNION ALL branches that +// select selectList (over lci, library_collection_items, and mi, the member +// in an item's shape) for each stored episode and season member matching +// collectionMatch, a condition on lci, that the viewer sees. The branches +// read only non-title rows, through their partial index. Appended to a +// select of a collection's title members in the same columns, it lists every +// member the collection's page shows. +func CollectionEpisodeAndSeasonMembersSQL(selectList, collectionMatch string, access AccessFilter, args *[]any, argIdx *int) string { + var sql strings.Builder + for _, rel := range collectionMemberRelations { + sql.WriteString("\nUNION ALL\nSELECT " + selectList + "\nFROM library_collection_items lci\nJOIN " + + rel.from + " ON mi.content_id = lci." + rel.memberColumn + + "\nWHERE lci.media_item_id IS NULL AND " + collectionMatch) + for _, condition := range rel.accessConditions(access, args, argIdx) { + sql.WriteString("\n AND " + condition) + } + } + return sql.String() +} + +// GetListedMembersByIDsWithAccess is GetListedByIDsWithAccess for a stored +// collection's members, which can be titles, episodes, or seasons. An +// episode or season comes back in an item's shape with its own type, and +// the viewer sees it when they can see its series, as detail and playback +// decide. An episode needs a file in some library, and a season an episode +// that has one. +func (r *ItemRepository) GetListedMembersByIDsWithAccess(ctx context.Context, contentIDs []string, access AccessFilter) ([]*models.MediaItem, error) { + items, err := r.GetListedByIDsWithAccess(ctx, contentIDs, access) + if err != nil { + return nil, err + } + found := make(map[string]bool, len(items)) + for _, item := range items { + found[item.ContentID] = true + } + rest := make([]string, 0, len(contentIDs)-len(items)) + for _, id := range contentIDs { + if !found[id] { + rest = append(rest, id) + } + } + if len(rest) == 0 || (access.AllowedLibraryIDs != nil && len(access.AllowedLibraryIDs) == 0) { + return items, nil + } + for _, relation := range collectionMemberRelations { + args := []any{rest} + argIdx := 2 + conditions := relation.accessConditions(access, &args, &argIdx) + sql := `SELECT ` + itemColumns + ` FROM ` + relation.from + ` WHERE ` + + strings.Join(append([]string{"mi.content_id = ANY($1)"}, conditions...), " AND ") + rows, err := r.pool.Query(ctx, sql, args...) + if err != nil { + return nil, fmt.Errorf("fetching collection episode and season members: %w", err) + } + more, err := scanItems(rows) + if err != nil { + return nil, err + } + items = append(items, more...) + } + return items, nil +} + +// PreviewLibraryCollectionMembers lists up to limit of a stored collection's +// members that the viewer can see in def's libraries, titles, episodes and +// seasons alike: in curated order when def.Sort names no field, otherwise by +// it, as the collection's catalog page lists them. With includeTotal it also +// counts them. It is for a reader of a collection that holds episodes or +// seasons. +func PreviewLibraryCollectionMembers(ctx context.Context, pool *pgxpool.Pool, collectionID string, def QueryDefinition, access AccessFilter, limit int, includeTotal bool) ([]*models.MediaItem, int, error) { + executor := &QueryExecutor{Pool: pool, SourceArgs: []any{collectionID}} + if def.Sort.Field == "" { + applyCollectionPositionOrder(executor, libraryMembershipOrderJoin, "member_id") + } else { + executor.SourceWhere = libraryMembershipSourceWhere + } + def, access = useLibraryCollectionMembersRelation(executor, collectionID, QueryDefinition{Sort: def.Sort, LibraryIDs: def.LibraryIDs}, access) + items, total, _, err := executor.PreviewPage(ctx, def.Normalize(), access, limit, 0, includeTotal) + if err != nil { + return nil, 0, fmt.Errorf("listing collection members: %w", err) + } + return items, total, nil +} diff --git a/internal/catalog/collection_pages.go b/internal/catalog/collection_pages.go index 829ea33b02a..c4f8d4509f0 100644 --- a/internal/catalog/collection_pages.go +++ b/internal/catalog/collection_pages.go @@ -31,15 +31,15 @@ func (r *LibraryCollectionRepository) ListItemsPage(ctx context.Context, collect if opts.Revision != 0 && opts.Revision != page.Revision { return page, userstore.ErrCollectionChanged } - query := `SELECT collection_id, media_item_id, COALESCE(position, 0) FROM library_collection_items WHERE collection_id = $1` + query := `SELECT collection_id, member_id, COALESCE(position, 0) FROM library_collection_items WHERE collection_id = $1` args := []any{collectionID} limitParam := "$2" if opts.After != nil { - query += ` AND (COALESCE(position, 0), media_item_id) > ($2, $3)` + query += ` AND (COALESCE(position, 0), member_id) > ($2, $3)` args = append(args, opts.After.Position, opts.After.MediaItemID) limitParam = "$4" } - query += " ORDER BY COALESCE(position, 0), media_item_id LIMIT " + limitParam + query += " ORDER BY COALESCE(position, 0), member_id LIMIT " + limitParam args = append(args, opts.Limit+1) rows, err := tx.Query(ctx, query, args...) if err != nil { diff --git a/internal/catalog/collection_pages_test.go b/internal/catalog/collection_pages_test.go index b19d7e44f90..211dabf80c0 100644 --- a/internal/catalog/collection_pages_test.go +++ b/internal/catalog/collection_pages_test.go @@ -89,17 +89,18 @@ func TestLibraryCollectionContinuationDB(t *testing.T) { } } // The continuation predicate must be an index condition, not a sort or filter - // that scans all preceding membership rows. Disable sequential scans only to - // demonstrate the bounded access path on this intentionally tiny fixture. + // that scans all preceding membership rows. Disable sequential scans and + // sorts only to demonstrate the bounded access path on this intentionally + // tiny fixture, where any index on collection_id plus a sort costs the same. tx, err := pool.Begin(ctx) if err != nil { t.Fatal(err) } defer func() { _ = tx.Rollback(ctx) }() - if _, err := tx.Exec(ctx, `SET LOCAL enable_seqscan=off`); err != nil { + if _, err := tx.Exec(ctx, `SET LOCAL enable_seqscan=off; SET LOCAL enable_sort=off`); err != nil { t.Fatal(err) } - rows, err := tx.Query(ctx, `EXPLAIN SELECT media_item_id FROM library_collection_items WHERE collection_id=$1 AND (COALESCE(position,0),media_item_id)>($2,$3) ORDER BY COALESCE(position,0),media_item_id LIMIT 3`, c.ID, 2, "item") + rows, err := tx.Query(ctx, `EXPLAIN SELECT member_id FROM library_collection_items WHERE collection_id=$1 AND (COALESCE(position,0),member_id)>($2,$3) ORDER BY COALESCE(position,0),member_id LIMIT 3`, c.ID, 2, "item") if err != nil { t.Fatal(err) } diff --git a/internal/catalog/episode_file_number_db_test.go b/internal/catalog/episode_file_number_db_test.go index cb22f1e400e..075f607cfc0 100644 --- a/internal/catalog/episode_file_number_db_test.go +++ b/internal/catalog/episode_file_number_db_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "maps" "testing" "time" ) @@ -122,6 +123,57 @@ func TestGetBySeriesAndProviderNumberDB(t *testing.T) { } } +// The batch form of GetBySeriesAndProviderNumber, which MDBList episode lists +// resolve through: the same DVD-order series, plus a second series sharing +// numbers, so a ref only ever finds an episode of its own series. +func TestListByProviderNumbersDB(t *testing.T) { + ctx := context.Background() + pool := newTestPool(t) + seriesID := fmt.Sprintf("provider-numbers-batch-%d", time.Now().UnixNano()) + otherID := seriesID + "-other" + renumbered, shown, plain, parked, otherPilot := seriesID+"-s1e12", seriesID+"-s1e8", seriesID+"-s1e1", seriesID+"-s1e30", otherID+"-s1e1" + t.Cleanup(func() { + _, _ = pool.Exec(context.Background(), `DELETE FROM media_items WHERE content_id = ANY($1)`, []string{seriesID, otherID}) + }) + if _, err := pool.Exec(ctx, ` + INSERT INTO media_items (content_id, type, title, status, genres) + VALUES ($1, 'series', 'Provider Numbers Batch', 'matched', '{}'::text[]), + ($2, 'series', 'Provider Numbers Other', 'matched', '{}'::text[])`, seriesID, otherID); err != nil { + t.Fatalf("seed series: %v", err) + } + if _, err := pool.Exec(ctx, ` + INSERT INTO episodes (content_id, series_id, season_number, episode_number, provider_season_number, provider_episode_number, unlisted, title) + VALUES ($1, $5, 1, 12, 1, 8, false, 'TVDB 1x8'), + ($2, $5, 1, 8, 1, 3, false, 'TVDB 1x3'), + ($3, $5, 1, 1, NULL, NULL, false, 'Pilot'), + ($4, $5, 1, 30, 1, 30, true, 'Parked'), + ($6, $7, 1, 1, NULL, NULL, false, 'Other Pilot')`, + renumbered, shown, plain, parked, seriesID, otherPilot, otherID); err != nil { + t.Fatalf("seed episodes: %v", err) + } + + ref := func(series string, season, episode int) EpisodeProviderNumber { + return EpisodeProviderNumber{SeriesID: series, Season: season, Episode: episode} + } + want := map[EpisodeProviderNumber]string{ + ref(seriesID, 1, 8): renumbered, // provider numbers win over the row shown at 1×8 + ref(seriesID, 1, 1): plain, // no provider numbers: the shown numbers + ref(otherID, 1, 1): otherPilot, // same numbers, the other series' episode + } + refs := []EpisodeProviderNumber{ + ref(seriesID, 1, 8), ref(seriesID, 1, 1), ref(otherID, 1, 1), + ref(seriesID, 1, 12), // the row has provider numbers, so its shown ones don't match + ref(seriesID, 1, 30), // unlisted + } + got, err := NewEpisodeRepository(pool).ListByProviderNumbers(ctx, refs) + if err != nil { + t.Fatalf("ListByProviderNumbers: %v", err) + } + if !maps.Equal(got, want) { + t.Fatalf("ListByProviderNumbers = %v, want %v", got, want) + } +} + // A multi-episode file spans the listed episode at a file place, not a parked // (unlisted) row that kept that place from an earlier order: the parked row // would otherwise be marked watched with the file and counted as playable. diff --git a/internal/catalog/episode_repo.go b/internal/catalog/episode_repo.go index b5e13c5e3ea..95959cc878a 100644 --- a/internal/catalog/episode_repo.go +++ b/internal/catalog/episode_repo.go @@ -927,6 +927,82 @@ func (r *EpisodeRepository) GetBySeriesAndProviderNumber(ctx context.Context, se ) e ORDER BY probe LIMIT 1`, seriesID, season, episode)) } +// EpisodeProviderNumber names an episode by its series and the numbers its +// provider gives it in the default order, as GetBySeriesAndProviderNumber +// takes them, and by its TMDB ID when TMDBID is set. +type EpisodeProviderNumber struct { + SeriesID string + Season int + Episode int + TMDBID string +} + +// ListByProviderNumbers is GetBySeriesAndProviderNumber for many episodes in +// one query: it maps each ref that names a listed episode to that episode's +// content ID, and leaves the others out. A ref's TMDB ID, which holds when +// the series is numbered differently from TMDB, is tried before its numbers, +// which never match an episode with another TMDB ID. +func (r *EpisodeRepository) ListByProviderNumbers(ctx context.Context, refs []EpisodeProviderNumber) (map[EpisodeProviderNumber]string, error) { + result := make(map[EpisodeProviderNumber]string, len(refs)) + if len(refs) == 0 { + return result, nil + } + seriesIDs := make([]string, len(refs)) + seasons := make([]int, len(refs)) + episodes := make([]int, len(refs)) + tmdbIDs := make([]string, len(refs)) + for i, ref := range refs { + seriesIDs[i] = ref.SeriesID + seasons[i] = ref.Season + episodes[i] = ref.Episode + tmdbIDs[i] = ref.TMDBID + } + // The TMDB ID, then the same two probes as GetBySeriesAndProviderNumber + // per ref, best first: a row's provider numbers before the shown numbers + // of a row without them. + rows, err := r.pool.Query(ctx, ` + SELECT DISTINCT ON (req.series_id, req.season, req.episode, req.tmdb_id) + req.series_id, req.season, req.episode, req.tmdb_id, e.content_id + FROM unnest($1::text[], $2::bigint[], $3::bigint[], $4::text[]) AS req(series_id, season, episode, tmdb_id) + JOIN LATERAL ( + (SELECT -1 AS probe, content_id FROM episodes + WHERE req.tmdb_id <> '' AND tmdb_id = req.tmdb_id + AND series_id = req.series_id AND NOT unlisted + LIMIT 1) + UNION ALL + (SELECT 0 AS probe, content_id FROM episodes + WHERE series_id = req.series_id AND provider_season_number = req.season + AND provider_episode_number = req.episode AND NOT unlisted + AND (req.tmdb_id = '' OR COALESCE(tmdb_id, '') IN ('', req.tmdb_id)) + LIMIT 1) + UNION ALL + (SELECT 1 AS probe, content_id FROM episodes + WHERE series_id = req.series_id AND season_number = req.season + AND episode_number = req.episode + AND provider_season_number IS NULL AND NOT unlisted + AND (req.tmdb_id = '' OR COALESCE(tmdb_id, '') IN ('', req.tmdb_id)) + LIMIT 1) + ) e ON true + ORDER BY req.series_id, req.season, req.episode, req.tmdb_id, e.probe`, + seriesIDs, seasons, episodes, tmdbIDs) + if err != nil { + return nil, fmt.Errorf("listing episodes by provider numbers: %w", err) + } + defer rows.Close() + for rows.Next() { + var ref EpisodeProviderNumber + var contentID string + if err := rows.Scan(&ref.SeriesID, &ref.Season, &ref.Episode, &ref.TMDBID, &contentID); err != nil { + return nil, fmt.Errorf("scanning episode by provider numbers: %w", err) + } + result[ref] = contentID + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterating episodes by provider numbers: %w", err) + } + return result, nil +} + // ListBySeriesAndAirDates retrieves provider episode rows for a series keyed by // air date. It intentionally does not use episodeAvailabilityPredicate because // callers use it to link files before episode_libraries rows exist. It diff --git a/internal/catalog/library_collection_counts.go b/internal/catalog/library_collection_counts.go index 393e771182c..f9b6414865b 100644 --- a/internal/catalog/library_collection_counts.go +++ b/internal/catalog/library_collection_counts.go @@ -194,7 +194,8 @@ func buildCountVisibleStoredMembersSQL(collectionIDs []string, access AccessFilt args := []any{collectionIDs} argIdx := 2 var sql strings.Builder - sql.WriteString(`SELECT lci.collection_id, COUNT(*) + sql.WriteString(`SELECT collection_id, COUNT(*) FROM ( + SELECT lci.collection_id FROM library_collection_items lci JOIN media_items mi ON mi.content_id = lci.media_item_id WHERE lci.collection_id = ANY($1)`) @@ -203,6 +204,8 @@ func buildCountVisibleStoredMembersSQL(collectionIDs []string, access AccessFilt } // The catalog page a collection card opens never lists manga chapters. sql.WriteString("\n AND " + MangaChapterExclusionWhere("mi")) - sql.WriteString("\n GROUP BY lci.collection_id") + // Episode and season members count as the page shows them. + sql.WriteString(CollectionEpisodeAndSeasonMembersSQL("lci.collection_id", "lci.collection_id = ANY($1)", access, &args, &argIdx)) + sql.WriteString("\n ) members GROUP BY collection_id") return sql.String(), args } diff --git a/internal/catalog/library_collection_mdblist.go b/internal/catalog/library_collection_mdblist.go new file mode 100644 index 00000000000..35dd50ad3c4 --- /dev/null +++ b/internal/catalog/library_collection_mdblist.go @@ -0,0 +1,176 @@ +package catalog + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + + "github.com/Silo-Server/silo-server/internal/collectionutil" + "github.com/Silo-Server/silo-server/internal/mdblist" +) + +// errMDBListEmptyFeedNeedsKey is the sync's answer when MDBList's public feed +// lists nothing and the server has no key to ask the API. The empty feed says +// nothing about the list, so the sync ends in this warning and keeps the +// members a key synced before. Stored runs carry this text and +// SyncMessageReason matches it exactly: rewording it drops the reason from +// every run already stored. +var errMDBListEmptyFeedNeedsKey = errors.New("MDBList's public feed lists nothing for this list. A list of episodes or seasons syncs only with an MDBList API key; add one in Settings › Providers") + +// mdblistPrivateListKeyHint ends the message of a private list's sync on a +// server without an MDBList key. SyncMessageReason matches stored messages by +// this suffix: rewording it drops the reason from every run already stored. +const mdblistPrivateListKeyHint = ". To sync a private list, add an MDBList API key from the account that owns it in Settings › Providers" + +// SyncReasonMDBListAPIKeyRequired is the reason of a sync that read nothing +// because the list syncs only with an MDBList API key the server lacks. +const SyncReasonMDBListAPIKeyRequired = "mdblist_api_key_required" //nolint:gosec // A reason code that names a key, not a credential. + +// SyncMessageReason returns the reason code a stored sync message carries, +// for clients that show it in their own words, or "" when it carries none. +func SyncMessageReason(message string) string { + if message == errMDBListEmptyFeedNeedsKey.Error() || strings.HasSuffix(message, mdblistPrivateListKeyHint) { + return SyncReasonMDBListAPIKeyRequired + } + return "" +} + +// ErrMDBListLinkInvalid is MDBListLinkNeedsKey's answer for a link that is +// not an MDBList list page. +var ErrMDBListLinkInvalid = errors.New("not an MDBList list link") + +// MDBListLinkNeedsKey reports whether a server collection following listURL +// would sync only with an MDBList API key the server lacks: MDBList's public +// feed refuses the list, as it does a private one, or lists nothing, as it +// does a list of episodes or seasons. It reads one feed entry, and nothing +// when the server has a key. +func (s *LibraryCollectionService) MDBListLinkNeedsKey(ctx context.Context, listURL string) (bool, error) { + if _, err := collectionutil.CanonicalMDBListURL(listURL); err != nil { + return false, fmt.Errorf("%w: %w", ErrMDBListLinkInvalid, err) + } + if s.MDBList != nil && s.MDBList.Configured() { + return false, nil + } + entries, err := collectionutil.FetchMDBListJSON[collectionutil.MDBListEntry](ctx, s.httpClient, listURL, 1) + if feedErr, ok := errors.AsType[*collectionutil.MDBListFeedError](err); ok && feedErr != nil { + return true, nil //nolint:nilerr // A refused feed is the answer: the list is private. + } + if err != nil { + return false, err + } + return len(entries) == 0, nil +} + +// readMDBListWithServerKey reads a list the public feed refused or answered +// empty through the MDBList API with the server's key, so an admin's private +// list, or a list of episodes or seasons, can sync. +// Its errors are the messages the sync stores, which say what to change. +func (s *LibraryCollectionService) readMDBListWithServerKey(ctx context.Context, ref collectionutil.MDBListRef, maxEntries int, feedErr *collectionutil.MDBListFeedError) ([]collectionutil.MDBListEntry, error) { + noKey := func() error { + if feedErr == nil { + // The feed answered empty, as it does for a list of episodes + // or seasons, which only the API returns. + return errMDBListEmptyFeedNeedsKey + } + return fmt.Errorf("%w"+mdblistPrivateListKeyHint, feedErr) + } + if s.MDBList == nil || !s.MDBList.Configured() { + return nil, noKey() + } + entries, err := s.MDBList.ListItems(ctx, ref, maxEntries) + if err == nil { + return entries, nil + } + // The key can be cleared between the check above and the read. + if errors.Is(err, mdblist.ErrNotConfigured) { + return nil, noKey() + } + var readErr *collectionutil.MDBListReadError + if !errors.As(err, &readErr) { + return nil, err + } + switch readErr.Kind { + case collectionutil.MDBListKeyRejected: + return nil, errors.New("MDBList rejected the server's MDBList API key. Check it in Settings › Providers") + case collectionutil.MDBListRateLimited: + return nil, errors.New("the server's MDBList API key has used up its daily MDBList limit. The next sync tries again") + default: + return nil, fmt.Errorf("%w. The server's MDBList API key can't read this list; if it is private, use a key from the account that owns it in Settings › Providers", readErr) + } +} + +// mdblistMember is the catalog episode or season an MDBList entry names. +type mdblistMember struct { + id string + kind string +} + +// matchMDBListEpisodesAndSeasons maps the index of each episode or season +// entry that names one in the catalog to it. MDBList names them by their own +// TMDB ID, which finds them however the library numbers the series, and by +// their show's TMDB ID and TMDB's numbers, which are the provider numbers of +// a series matched with TMDB; a season's number is its own. +func (s *LibraryCollectionService) matchMDBListEpisodesAndSeasons(ctx context.Context, entries []collectionutil.MDBListEntry) (map[int]mdblistMember, error) { + var shows ExternalIDBatch + for _, entry := range entries { + switch { + case entry.Episode != nil: + shows.TMDBIDs = append(shows.TMDBIDs, strconv.Itoa(entry.Episode.ShowTMDBID)) + case entry.Season != nil: + shows.TMDBIDs = append(shows.TMDBIDs, strconv.Itoa(entry.Season.ShowTMDBID)) + } + } + if len(shows.TMDBIDs) == 0 || s.episodes == nil || s.seasons == nil { + return nil, nil + } + seriesLookup, err := s.items.GetByExternalIDs(ctx, shows, "series") + if err != nil { + return nil, err + } + episodeRefs := make(map[int]EpisodeProviderNumber) + seasonRefs := make(map[int]SeasonNumber) + var episodeList []EpisodeProviderNumber + var seasonList []SeasonNumber + for index, entry := range entries { + switch { + case entry.Episode != nil: + seriesID := seriesLookup.ByTMDB[strconv.Itoa(entry.Episode.ShowTMDBID)] + if seriesID == "" { + continue + } + ref := EpisodeProviderNumber{SeriesID: seriesID, Season: entry.Episode.Season, Episode: entry.Episode.Episode, TMDBID: positiveIDString(entry.Episode.TMDBID)} + episodeRefs[index] = ref + episodeList = append(episodeList, ref) + case entry.Season != nil: + seriesID := seriesLookup.ByTMDB[strconv.Itoa(entry.Season.ShowTMDBID)] + if seriesID == "" { + continue + } + ref := SeasonNumber{SeriesID: seriesID, Season: entry.Season.Season, TMDBID: positiveIDString(entry.Season.TMDBID)} + seasonRefs[index] = ref + seasonList = append(seasonList, ref) + } + } + episodes, err := s.episodes.ListByProviderNumbers(ctx, episodeList) + if err != nil { + return nil, err + } + seasons, err := s.seasons.ListIDsByNumbers(ctx, seasonList) + if err != nil { + return nil, err + } + members := make(map[int]mdblistMember, len(episodes)+len(seasons)) + for index, ref := range episodeRefs { + if id := episodes[ref]; id != "" { + members[index] = mdblistMember{id: id, kind: CollectionMemberEpisode} + } + } + for index, ref := range seasonRefs { + if id := seasons[ref]; id != "" { + members[index] = mdblistMember{id: id, kind: CollectionMemberSeason} + } + } + return members, nil +} diff --git a/internal/catalog/library_collection_mdblist_key_test.go b/internal/catalog/library_collection_mdblist_key_test.go new file mode 100644 index 00000000000..215dd77765d --- /dev/null +++ b/internal/catalog/library_collection_mdblist_key_test.go @@ -0,0 +1,87 @@ +package catalog + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/Silo-Server/silo-server/internal/collectionutil" +) + +type configuredMDBList struct{} + +func (configuredMDBList) Configured() bool { return true } +func (configuredMDBList) ListItems(context.Context, collectionutil.MDBListRef, int) ([]collectionutil.MDBListEntry, error) { + return nil, nil +} + +func feedAnswering(body string, requests *int) *http.Client { + return &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + *requests++ + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil + })} +} + +// A list syncs only with a server MDBList key when its public feed answers +// empty (a list of episodes or seasons) or refuses it (a private list). With +// a key on the server nothing needs checking. +func TestMDBListLinkNeedsKey(t *testing.T) { + const link = "https://mdblist.com/lists/alice/holiday-episodes" + for _, tc := range []struct { + name, feed string + key bool + want bool + requests int + }{ + {name: "episode list", feed: `[]`, want: true, requests: 1}, + {name: "private list", feed: `{"error": "This List is Private"}`, want: true, requests: 1}, + {name: "title list", feed: `[{"id": 603, "imdb_id": "tt0133093", "mediatype": "movie", "rank": 1}]`, want: false, requests: 1}, + {name: "server key", feed: `[]`, key: true, want: false, requests: 0}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests int + svc := NewLibraryCollectionService(nil, nil, nil, feedAnswering(tc.feed, &requests)) + if tc.key { + svc.MDBList = configuredMDBList{} + } + got, err := svc.MDBListLinkNeedsKey(t.Context(), link) + if err != nil || got != tc.want || requests != tc.requests { + t.Fatalf("needs key = %v, %v after %d requests; want %v after %d", got, err, requests, tc.want, tc.requests) + } + }) + } + var requests int + svc := NewLibraryCollectionService(nil, nil, nil, feedAnswering(`[]`, &requests)) + if _, err := svc.MDBListLinkNeedsKey(t.Context(), "https://example.com/lists/x"); !errors.Is(err, ErrMDBListLinkInvalid) || requests != 0 { + t.Fatalf("other link = %v after %d requests, want ErrMDBListLinkInvalid and none", err, requests) + } +} + +// The messages a keyless sync stores, for an empty feed and for a private +// list, carry the reason clients show in their own words. +func TestKeylessMDBListSyncMessagesNameTheReason(t *testing.T) { + svc := NewLibraryCollectionService(nil, nil, nil, http.DefaultClient) + ref := collectionutil.MDBListRef{User: "alice", Slug: "holiday"} + for name, feedErr := range map[string]*collectionutil.MDBListFeedError{ + "empty feed": nil, + "private list": {Message: "This List is Private"}, + } { + _, err := svc.readMDBListWithServerKey(t.Context(), ref, 10, feedErr) + if err == nil || SyncMessageReason(err.Error()) != SyncReasonMDBListAPIKeyRequired { + t.Errorf("%s: message %v has reason %q, want %q", name, err, SyncMessageReason(errString(err)), SyncReasonMDBListAPIKeyRequired) + } + } + if got := SyncMessageReason("Matched 3 of 4 entries"); got != "" { + t.Errorf("an ordinary message has reason %q, want none", got) + } +} + +func errString(err error) string { + if err == nil { + return "" + } + return err.Error() +} diff --git a/internal/catalog/library_collection_mdblist_members_db_test.go b/internal/catalog/library_collection_mdblist_members_db_test.go new file mode 100644 index 00000000000..f73e1144bb4 --- /dev/null +++ b/internal/catalog/library_collection_mdblist_members_db_test.go @@ -0,0 +1,430 @@ +package catalog + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/Silo-Server/silo-server/internal/access" + "github.com/Silo-Server/silo-server/internal/collectionutil" + "github.com/Silo-Server/silo-server/internal/models" + "github.com/Silo-Server/silo-server/internal/userstore/pgstore" +) + +// fakeMDBListReader answers every list with entries, as the MDBList API with +// the server's key does. +type fakeMDBListReader struct{ entries []collectionutil.MDBListEntry } + +func (fakeMDBListReader) Configured() bool { return true } + +func (f fakeMDBListReader) ListItems(context.Context, collectionutil.MDBListRef, int) ([]collectionutil.MDBListEntry, error) { + return f.entries, nil +} + +// An MDBList list of episodes and seasons, which the public feed answers +// empty, fills its collection with those episodes and seasons through the +// API, in list order. Each is found by its own TMDB ID, which holds where the +// library numbers it differently from TMDB, or else by its show's TMDB ID and +// TMDB numbers, unless the one at those numbers has another TMDB ID; one the +// library doesn't have (its episode has no file there) is left out. +func TestSyncMDBListCollectionStoresEpisodesAndSeasonsDB(t *testing.T) { + ctx := context.Background() + pool := newTestPool(t) + prefix := fmt.Sprintf("mdblist-members-%d", time.Now().UnixNano()) + series, season1, season2, season3 := prefix+"-series", prefix+"-s1", prefix+"-s2", prefix+"-s3" + inLibrary, missing := prefix+"-s1e2", prefix+"-s1e3" + show := int(time.Now().UnixNano() % 1_000_000_000) + tmdbID := strconv.Itoa(show) + + var tv int + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, true) RETURNING id`, prefix).Scan(&tv); err != nil { + t.Fatalf("seed library: %v", err) + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM library_collections WHERE slug = $1`, prefix) + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = $1`, series) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = $1`, tv) + }) + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title, status, tmdb_id, genres) VALUES ($1, 'series', 'Show', 'matched', $2, '{}'::text[])`, []any{series, tmdbID}}, + {`INSERT INTO media_item_libraries (content_id, media_folder_id) VALUES ($1, $2)`, []any{series, tv}}, + {`INSERT INTO seasons (content_id, series_id, season_number, tmdb_id) VALUES ($1, $3, 1, ''), ($2, $3, 2, $4), ($5, $3, 3, $6)`, []any{season1, season2, series, tmdbID + "02", season3, tmdbID + "03"}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title, tmdb_id) + VALUES ($1, $3, $4, 1, 2, 'Two', $7), ($2, $3, $4, 1, 3, 'Three', ''), ($5, $3, $6, 2, 1, 'Opener', ''), + ($8, $3, $6, 2, 2, 'Second', $9), ($10, $3, $11, 3, 1, 'Third Opener', '')`, + []any{inLibrary, missing, series, season1, prefix + "-s2e1", season2, tmdbID + "0102", prefix + "-s2e2", tmdbID + "0202", prefix + "-s3e1", season3}}, + {`INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $3), ($2, $3), ($4, $3), ($5, $3)`, []any{inLibrary, prefix + "-s2e1", tv, prefix + "-s2e2", prefix + "-s3e1"}}, + } { + if _, err := pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + + collections := NewLibraryCollectionRepository(pool) + config, _ := json.Marshal(map[string]string{"mode": "mdblist_json", "url": "https://mdblist.com/lists/alice/holiday-episodes"}) + collection, err := collections.Create(ctx, CreateLibraryCollectionInput{ + LibraryID: tv, LibraryIDs: []int{tv}, Slug: prefix, Title: "Holiday", CollectionType: "mdblist", + SourceURL: "https://mdblist.com/lists/alice/holiday-episodes", SourceConfig: config, + }) + if err != nil { + t.Fatalf("create collection: %v", err) + } + + emptyFeed := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`[]`)), Header: http.Header{}}, nil + })} + svc := NewLibraryCollectionService(collections, NewItemRepository(pool), NewLibraryItemRepository(pool), emptyFeed) + // TMDB numbers the season and the episode in it differently from the + // library, which only their TMDB IDs bridge. + tmdbEpisode, _ := strconv.Atoi(tmdbID + "0102") + tmdbSeason, _ := strconv.Atoi(tmdbID + "02") + svc.MDBList = fakeMDBListReader{entries: []collectionutil.MDBListEntry{ + {Rank: 1, MediaType: "season", Season: &collectionutil.MDBListSeason{TMDBID: tmdbSeason, ShowTMDBID: show, Season: 7}}, + {Rank: 2, MediaType: "episode", Episode: &collectionutil.MDBListEpisode{ShowTMDBID: show, Season: 1, Episode: 3}}, + {Rank: 3, MediaType: "episode", Episode: &collectionutil.MDBListEpisode{TMDBID: tmdbEpisode, ShowTMDBID: show, Season: 1, Episode: 9}}, + // The library's S2E2 and season 3 are other TMDB episodes and + // seasons than these, so their numbers don't match them. + {Rank: 4, MediaType: "episode", Episode: &collectionutil.MDBListEpisode{TMDBID: tmdbEpisode + 7, ShowTMDBID: show, Season: 2, Episode: 2}}, + {Rank: 5, MediaType: "season", Season: &collectionutil.MDBListSeason{TMDBID: tmdbSeason + 7, ShowTMDBID: show, Season: 3}}, + }} + if _, err := svc.SyncCollection(ctx, collection.ID); err != nil { + t.Fatalf("sync: %v", err) + } + + items, err := collections.ListItems(ctx, collection.ID) + if err != nil { + t.Fatalf("list items: %v", err) + } + got := make([]string, 0, len(items)) + for _, item := range items { + got = append(got, item.Kind+":"+item.MediaItemID) + } + if want := []string{"season:" + season2, "episode:" + inLibrary}; !slices.Equal(got, want) { + t.Fatalf("members = %v, want %v", got, want) + } +} + +// A collection's episode and season members count toward its card's item +// count, stored and per viewer, and lend its collage their posters: an +// episode while it has a file in some library, a season while one of its +// episodes does, and for a viewer only those of a series they can open. +func TestLibraryCollectionCardIncludesEpisodeAndSeasonMembersDB(t *testing.T) { + ctx := context.Background() + pool := newTestPool(t) + prefix := fmt.Sprintf("collection-member-counts-%d", time.Now().UnixNano()) + series, hiddenSeries := prefix+"-series", prefix+"-hidden" + season, emptySeason := prefix+"-s1", prefix+"-s2" + episode, hiddenEpisode := prefix+"-s1e1", prefix+"-hidden-s1e1" + var tv, hidden int + for name, id := range map[string]*int{prefix: &tv, prefix + "-hidden": &hidden} { + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, true) RETURNING id`, name).Scan(id); err != nil { + t.Fatal(err) + } + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM library_collections WHERE slug = $1`, prefix) + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = ANY($1)`, []string{series, hiddenSeries}) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = ANY($1)`, []int{tv, hidden}) + }) + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title, status, genres, poster_path) VALUES ($1, 'series', 'Show', 'matched', '{}'::text[], 'show.jpg'), ($2, 'series', 'Hidden', 'matched', '{}'::text[], 'hidden.jpg')`, []any{series, hiddenSeries}}, + {`INSERT INTO media_item_libraries (content_id, media_folder_id) VALUES ($1, $2), ($3, $4)`, []any{series, tv, hiddenSeries, hidden}}, + {`INSERT INTO seasons (content_id, series_id, season_number) VALUES ($1, $3, 1), ($2, $3, 2)`, []any{season, emptySeason, series}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title) VALUES ($1, $2, $3, 1, 1, 'One')`, []any{episode, series, season}}, + {`INSERT INTO episodes (content_id, series_id, season_number, episode_number, title) VALUES ($1, $2, 1, 1, 'Hidden One')`, []any{hiddenEpisode, hiddenSeries}}, + {`INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $2), ($3, $4)`, []any{episode, tv, hiddenEpisode, hidden}}, + } { + if _, err := pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + + repo := NewLibraryCollectionRepository(pool) + c, err := repo.Create(ctx, CreateLibraryCollectionInput{LibraryID: tv, LibraryIDs: []int{tv, hidden}, + Slug: prefix, Title: "Holiday", CollectionType: "mdblist", Visibility: "visible"}) + if err != nil { + t.Fatal(err) + } + if err := repo.ReplaceItems(ctx, c.ID, []LibraryCollectionItemInput{ + {MediaItemID: episode, Kind: CollectionMemberEpisode}, + {MediaItemID: hiddenEpisode, Kind: CollectionMemberEpisode}, + {MediaItemID: season, Kind: CollectionMemberSeason}, + {MediaItemID: emptySeason, Kind: CollectionMemberSeason}, + }); err != nil { + t.Fatal(err) + } + + stored, err := repo.GetByID(ctx, c.ID) + if err != nil { + t.Fatal(err) + } + if stored.ItemCount != 3 { + t.Errorf("stored count = %d, want 3 (the season with no episode on disk left out)", stored.ItemCount) + } + counts, err := repo.ViewerCollectionCounts(ctx, []*models.LibraryCollection{stored}, AccessFilter{AllowedLibraryIDs: []int{tv}}) + if err != nil { + t.Fatal(err) + } + if got := counts[c.ID]; got.Count != 2 { + t.Errorf("viewer count = %+v, want 2", got) + } + // The series are unrated, so a rating ceiling that hides unrated titles + // hides their episodes and seasons too. + counts, err = repo.ViewerCollectionCounts(ctx, []*models.LibraryCollection{stored}, AccessFilter{MaturityLimits: access.MaturityLimits{MaxContentRating: "PG-13"}}) + if err != nil { + t.Fatal(err) + } + if got := counts[c.ID]; got.Count != 0 || !got.HidesMembers { + t.Errorf("rating-limited count = %+v, want 0 with members hidden", got) + } + + // The episode and its season share the series poster, shown once. + sources, err := repo.ListCollectionCollageSources(ctx, []string{c.ID}, AccessFilter{AllowedLibraryIDs: []int{tv}}) + if err != nil { + t.Fatal(err) + } + if got, want := sources[c.ID], []string{"show.jpg"}; !slices.Equal(got, want) { + t.Errorf("collage sources = %v, want %v", got, want) + } +} + +// The catalog pages a collection's episode and season members with its +// titles, in curated order and under a sort alike, as the web collection +// page and Jellyfin's resolved order read them, and lists them for shuffle, +// leaving out an episode of a series the viewer can't open. A Series scope +// keeps them, as a Movies scope leaves them out. +func TestLibraryCollectionCatalogPagesEpisodeAndSeasonMembersDB(t *testing.T) { + ctx := context.Background() + pool := newTestPool(t) + prefix := fmt.Sprintf("collection-member-pages-%d", time.Now().UnixNano()) + movie, series, hiddenSeries := prefix+"-movie", prefix+"-series", prefix+"-hidden" + season, episode, hiddenEpisode := prefix+"-s1", prefix+"-s1e2", prefix+"-hidden-s1e1" + // A specials season with no title of its own is named as everywhere else. + specials, special := prefix+"-s0", prefix+"-s0e1" + var movies, tv, hidden int + for name, id := range map[string]*int{prefix + "-movies": &movies, prefix: &tv, prefix + "-hidden": &hidden} { + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, true) RETURNING id`, name).Scan(id); err != nil { + t.Fatal(err) + } + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM library_collections WHERE slug = $1`, prefix) + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = ANY($1)`, []string{movie, series, hiddenSeries}) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = ANY($1)`, []int{movies, tv, hidden}) + }) + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title, status, genres) VALUES ($1, 'movie', 'Alpha Movie', 'matched', '{}'::text[]), ($2, 'series', 'Show', 'matched', '{}'::text[]), ($3, 'series', 'Hidden', 'matched', '{}'::text[])`, []any{movie, series, hiddenSeries}}, + {`INSERT INTO media_item_libraries (content_id, media_folder_id) VALUES ($1, $2), ($3, $4), ($5, $6)`, []any{movie, movies, series, tv, hiddenSeries, hidden}}, + {`INSERT INTO seasons (content_id, series_id, season_number, title) VALUES ($1, $2, 1, 'Season 1'), ($3, $2, 0, NULL)`, []any{season, series, specials}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title) VALUES ($1, $2, $3, 1, 2, 'Two'), ($4, $2, $5, 0, 1, 'Special')`, []any{episode, series, season, special, specials}}, + {`INSERT INTO episodes (content_id, series_id, season_number, episode_number, title) VALUES ($1, $2, 1, 1, 'Hidden One')`, []any{hiddenEpisode, hiddenSeries}}, + {`INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $2), ($3, $4), ($5, $2)`, []any{episode, tv, hiddenEpisode, hidden, special}}, + } { + if _, err := pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + repo := NewLibraryCollectionRepository(pool) + c, err := repo.Create(ctx, CreateLibraryCollectionInput{LibraryID: tv, LibraryIDs: []int{movies, tv, hidden}, + Slug: prefix, Title: "Holiday", CollectionType: "mdblist", Visibility: "visible"}) + if err != nil { + t.Fatal(err) + } + if err := repo.ReplaceItems(ctx, c.ID, []LibraryCollectionItemInput{ + {MediaItemID: episode, Kind: CollectionMemberEpisode}, + {MediaItemID: hiddenEpisode, Kind: CollectionMemberEpisode}, + {MediaItemID: movie}, + {MediaItemID: season, Kind: CollectionMemberSeason}, + {MediaItemID: specials, Kind: CollectionMemberSeason}, + }); err != nil { + t.Fatal(err) + } + + viewer := AccessFilter{AllowedLibraryIDs: []int{movies, tv}} + resolver := NewCatalogResolver(NewBrowseRepository(pool), NewItemRepository(pool)) + req := CatalogRequest{Source: CatalogSourceLibraryCollection, CollectionID: c.ID, CursorPaging: true, UseSourceOrder: true, Limit: 1} + walkCollectionPages(t, resolver, req, viewer, []string{episode, movie, season, specials}) + sorted := req + sorted.UseSourceOrder = false + sorted.Query.Sort = QuerySort{Field: "title", Order: "asc"} + walkCollectionPages(t, resolver, sorted, viewer, []string{movie, season, specials, episode}) + // A library's Series category (Roku, Android TV) keeps the episodes and + // seasons, and its Movies category the movie alone. + seriesScope := req + seriesScope.Query.MediaScope = "series" + walkCollectionPages(t, resolver, seriesScope, viewer, []string{episode, season, specials}) + movieScope := req + movieScope.Query.MediaScope = "movie" + walkCollectionPages(t, resolver, movieScope, viewer, []string{movie}) + + ids, total, err := resolver.LibraryCollectionPage(ctx, c, viewer, QuerySort{Field: "title", Order: "asc"}, 0, 0) + if err != nil { + t.Fatal(err) + } + if want := []string{movie, season, specials, episode}; !slices.Equal(ids, want) || total != 4 { + t.Errorf("collection page = %v (total %d), want %v (total 4)", ids, total, want) + } + + // Shuffle reads the members it plays from here. + _, members, err := resolver.CollectionMembers(ctx, CatalogSourceLibraryCollection, c.ID, viewer) + if err != nil { + t.Fatal(err) + } + if got, want := contentIDsFromMediaItems(members), []string{episode, movie, season, specials}; !slices.Equal(got, want) { + t.Fatalf("collection members = %v, want %v", got, want) + } + if got := members[3].Title; got != "Specials" { + t.Errorf("specials member title = %q, want Specials", got) + } +} + +// A watched filter judges an episode member by the episode and a season +// member by its episodes, with or without a library's Series category. +func TestLibraryCollectionWatchedFilterJudgesEpisodeAndSeasonMembersDB(t *testing.T) { + ctx := context.Background() + pool := newTestPool(t) + prefix := fmt.Sprintf("collection-member-watched-%d", time.Now().UnixNano()) + series, season, episode := prefix+"-series", prefix+"-s1", prefix+"-s1e1" + var tv, userID int + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, true) RETURNING id`, prefix).Scan(&tv); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `INSERT INTO users (username, role) VALUES ($1, 'user') RETURNING id`, prefix).Scan(&userID); err != nil { + t.Fatal(err) + } + profile := uuid.NewString() + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM library_collections WHERE slug = $1`, prefix) + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = $1`, series) + _, _ = pool.Exec(cleanup, `DELETE FROM users WHERE id = $1`, userID) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = $1`, tv) + }) + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO user_profiles (id, user_id, name) VALUES ($1, $2, 'p')`, []any{profile, userID}}, + {`INSERT INTO media_items (content_id, type, title, status, genres) VALUES ($1, 'series', 'Show', 'matched', '{}'::text[])`, []any{series}}, + {`INSERT INTO media_item_libraries (content_id, media_folder_id) VALUES ($1, $2)`, []any{series, tv}}, + {`INSERT INTO seasons (content_id, series_id, season_number, title) VALUES ($1, $2, 1, 'Season 1')`, []any{season, series}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title) VALUES ($1, $2, $3, 1, 1, 'One')`, []any{episode, series, season}}, + {`INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $2)`, []any{episode, tv}}, + {`INSERT INTO user_watch_history (id, user_id, profile_id, media_item_id, completed, watched_at) VALUES ($1 || '-h', $2, $3, $1, true, NOW() - INTERVAL '1 day')`, []any{episode, userID, profile}}, + } { + if _, err := pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + repo := NewLibraryCollectionRepository(pool) + c, err := repo.Create(ctx, CreateLibraryCollectionInput{LibraryID: tv, LibraryIDs: []int{tv}, + Slug: prefix, Title: "Watched", CollectionType: "mdblist", Visibility: "visible"}) + if err != nil { + t.Fatal(err) + } + if err := repo.ReplaceItems(ctx, c.ID, []LibraryCollectionItemInput{ + {MediaItemID: episode, Kind: CollectionMemberEpisode}, + {MediaItemID: season, Kind: CollectionMemberSeason}, + }); err != nil { + t.Fatal(err) + } + + viewer := AccessFilter{UserID: userID, ProfileID: profile, AllowedLibraryIDs: []int{tv}} + resolver := NewCatalogResolver(NewBrowseRepository(pool), NewItemRepository(pool)).WithUserStoreProvider(pgstore.NewPostgresProvider(pool)) + for _, scope := range []string{"", "series"} { + for watched, want := range map[bool][]string{true: {episode, season}, false: nil} { + req := CatalogRequest{Source: CatalogSourceLibraryCollection, CollectionID: c.ID, CursorPaging: true, UseSourceOrder: true, Limit: 10} + req.Query.MediaScope = scope + req.Query.Match = "all" + req.Query.Groups = []QueryGroup{{Match: "all", Rules: []QueryRule{{Field: "watched", Op: "is", Value: watched}}}} + page, err := resolver.Resolve(ctx, req, viewer) + if err != nil { + t.Fatalf("scope %q watched %v: %v", scope, watched, err) + } + if got := contentIDsFromMediaItems(page.Items); !slices.Equal(got, want) { + t.Errorf("scope %q watched %v = %v, want %v", scope, watched, got, want) + } + } + } +} + +// Without a server MDBList key an episode list's feed answers empty, which +// says nothing about the list, so the sync ends in a warning naming the key +// and keeps a collection the key filled before, rather than emptying it or +// failing the import that runs the first sync. +func TestSyncMDBListWithoutKeyKeepsEpisodeMembersDB(t *testing.T) { + ctx := context.Background() + pool := newTestPool(t) + prefix := fmt.Sprintf("mdblist-nokey-%d", time.Now().UnixNano()) + series, episode := prefix+"-series", prefix+"-s1e1" + var tv int + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, true) RETURNING id`, prefix).Scan(&tv); err != nil { + t.Fatalf("seed library: %v", err) + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM library_collections WHERE slug = $1`, prefix) + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = $1`, series) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = $1`, tv) + }) + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title, status, genres) VALUES ($1, 'series', 'Show', 'matched', '{}'::text[])`, []any{series}}, + {`INSERT INTO episodes (content_id, series_id, season_number, episode_number, title) VALUES ($1, $2, 1, 1, 'One')`, []any{episode, series}}, + } { + if _, err := pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + collections := NewLibraryCollectionRepository(pool) + config, _ := json.Marshal(map[string]string{"mode": "mdblist_json", "url": "https://mdblist.com/lists/alice/holiday-episodes"}) + collection, err := collections.Create(ctx, CreateLibraryCollectionInput{ + LibraryID: tv, LibraryIDs: []int{tv}, Slug: prefix, Title: "Holiday", CollectionType: "mdblist", + SourceURL: "https://mdblist.com/lists/alice/holiday-episodes", SourceConfig: config, + }) + if err != nil { + t.Fatalf("create collection: %v", err) + } + if err := collections.ReplaceItems(ctx, collection.ID, []LibraryCollectionItemInput{{MediaItemID: episode, Kind: CollectionMemberEpisode}}); err != nil { + t.Fatalf("fill collection: %v", err) + } + + emptyFeed := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`[]`)), Header: http.Header{}}, nil + })} + svc := NewLibraryCollectionService(collections, NewItemRepository(pool), NewLibraryItemRepository(pool), emptyFeed) + run, err := svc.SyncCollection(ctx, collection.ID) + if err != nil || run == nil || run.Status != "warning" || !strings.Contains(run.Message, "MDBList API key") { + t.Fatalf("sync = %+v, %v; want a warning naming the MDBList API key", run, err) + } + items, err := collections.ListItems(ctx, collection.ID) + if err != nil { + t.Fatalf("list items: %v", err) + } + if len(items) != 1 || items[0].MediaItemID != episode { + t.Fatalf("members = %+v, want the episode kept", items) + } +} diff --git a/internal/catalog/library_collection_mutations.go b/internal/catalog/library_collection_mutations.go index 608bcf304d5..0c1f121c9b1 100644 --- a/internal/catalog/library_collection_mutations.go +++ b/internal/catalog/library_collection_mutations.go @@ -215,7 +215,7 @@ func (r *LibraryCollectionRepository) AddItemIfAbsent(ctx context.Context, colle ), inserted AS ( INSERT INTO library_collection_items(collection_id,media_item_id,position,source_rank) SELECT $1,media_item_id,$3,0 FROM eligible - ON CONFLICT(collection_id,media_item_id) DO NOTHING + ON CONFLICT DO NOTHING -- no target: skip a conflict on either unique index (docs/architecture/collection-members.md) RETURNING 1 ) SELECT EXISTS(SELECT 1 FROM eligible)`, collectionID, mediaItemID, position, legacyLibraryID).Scan(&eligible) if err != nil { @@ -317,7 +317,10 @@ func (r *LibraryCollectionRepository) RemoveManualItem(ctx context.Context, coll if _, err := lockManualLibraryCollection(ctx, tx, collectionID); err != nil { return err } - _, err := tx.Exec(ctx, `DELETE FROM library_collection_items WHERE collection_id=$1 AND media_item_id=$2`, collectionID, mediaItemID) + if err := AllowCollectionMemberDeletes(ctx, tx); err != nil { + return err + } + _, err := tx.Exec(ctx, `DELETE FROM library_collection_items WHERE collection_id=$1 AND member_id=$2`, collectionID, mediaItemID) return err }) } diff --git a/internal/catalog/library_collection_page.go b/internal/catalog/library_collection_page.go index 5da8964a237..0aa61e39457 100644 --- a/internal/catalog/library_collection_page.go +++ b/internal/catalog/library_collection_page.go @@ -67,8 +67,13 @@ func (r *CatalogResolver) LibraryCollectionPage(ctx context.Context, c *models.L } executor.SourceWhere, executor.SourceArgs = predicate, args } else { - executor.SourceWhere = "EXISTS (SELECT 1 FROM library_collection_items cursor_membership WHERE cursor_membership.collection_id=$1 AND cursor_membership.media_item_id=mi.content_id)" + executor.SourceWhere = libraryMembershipSourceWhere executor.SourceArgs = []any{c.ID} + var err error + def, access, err = readLibraryCollectionMembers(ctx, r.itemRepo.pool, executor, c.ID, def, access) + if err != nil { + return nil, 0, err + } } tx, err := r.itemRepo.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}) diff --git a/internal/catalog/library_collection_posters.go b/internal/catalog/library_collection_posters.go index 07e037a6719..59463537074 100644 --- a/internal/catalog/library_collection_posters.go +++ b/internal/catalog/library_collection_posters.go @@ -40,8 +40,11 @@ func AssignedCollectionPoster(c *models.LibraryCollection) (CollectionPoster, bo // ListCollectionCollageSources returns, for each collection, the poster paths // of up to CollectionCollageSourceLimit members the viewer can access, in // collection order. It applies the same access predicates as the collection's -// member list, so a collage never shows a member that list leaves out. -// Collections with no such member are absent from the result. +// member list, so a collage never shows a member that list leaves out. An +// episode or season member lends its season's or series' poster, and a +// poster already chosen is not repeated, so a list of one show's episodes +// shows that show once. Collections with no such member are absent from the +// result. func (r *LibraryCollectionRepository) ListCollectionCollageSources(ctx context.Context, collectionIDs []string, access AccessFilter) (map[string][]string, error) { sources := make(map[string][]string, len(collectionIDs)) if len(collectionIDs) == 0 || (access.AllowedLibraryIDs != nil && len(access.AllowedLibraryIDs) == 0) { @@ -61,7 +64,9 @@ func (r *LibraryCollectionRepository) ListCollectionCollageSources(ctx context.C if err := rows.Scan(&id, &path); err != nil { return nil, fmt.Errorf("scanning collection collage source: %w", err) } - sources[id] = append(sources[id], path) + if len(sources[id]) < CollectionCollageSourceLimit && !slices.Contains(sources[id], path) { + sources[id] = append(sources[id], path) + } } if err := rows.Err(); err != nil { return nil, fmt.Errorf("iterating collection collage sources: %w", err) @@ -69,26 +74,40 @@ func (r *LibraryCollectionRepository) ListCollectionCollageSources(ctx context.C return sources, nil } +// collageSourceWindow is how many members' posters a collage is chosen from, +// so repeats among the first members still leave it a full set. +const collageSourceWindow = 4 * CollectionCollageSourceLimit + func buildCollectionCollageSourcesSQL(collectionIDs []string, access AccessFilter) (string, []any) { - args := []any{collectionIDs, CollectionCollageSourceLimit} + args := []any{collectionIDs, collageSourceWindow} argIdx := 3 - var memberWhere strings.Builder + var members strings.Builder + // The title branch stops at the window in member order, as the + // collection's order index reads it, so a large collection of titles + // isn't read whole; the episode and season branches read only those + // members. + members.WriteString(` + (SELECT mi.poster_path, lci.position, lci.source_rank, lci.member_id + FROM library_collection_items lci + JOIN media_items mi ON mi.content_id = lci.media_item_id + WHERE lci.collection_id = c.id AND mi.poster_path <> ''`) for _, condition := range itemAccessConditions(access, &args, &argIdx) { - memberWhere.WriteString("\n\t\t\t AND " + condition) + members.WriteString("\n\t\t\t\t AND " + condition) } + members.WriteString("\n\t\t\t\tORDER BY lci.position, lci.source_rank, lci.member_id LIMIT $2)") + members.WriteString(CollectionEpisodeAndSeasonMembersSQL("mi.poster_path, lci.position, lci.source_rank, lci.member_id", "lci.collection_id = c.id", access, &args, &argIdx)) return ` SELECT c.id, src.poster_path FROM unnest($1::text[]) WITH ORDINALITY AS c(id, ord) CROSS JOIN LATERAL ( - SELECT mi.poster_path, lci.position, lci.source_rank, lci.media_item_id - FROM library_collection_items lci - JOIN media_items mi ON mi.content_id = lci.media_item_id - WHERE lci.collection_id = c.id - AND mi.poster_path <> ''` + memberWhere.String() + ` - ORDER BY lci.position, lci.source_rank, lci.media_item_id + SELECT m.poster_path, m.position, m.source_rank, m.member_id + FROM (` + members.String() + ` + ) m + WHERE m.poster_path <> '' + ORDER BY m.position, m.source_rank, m.member_id LIMIT $2 ) src - ORDER BY c.ord, src.position, src.source_rank, src.media_item_id`, args + ORDER BY c.ord, src.position, src.source_rank, src.member_id`, args } // GetCollectionCollages returns the stored collages among refs. diff --git a/internal/catalog/library_collection_replace_items_db_test.go b/internal/catalog/library_collection_replace_items_db_test.go index 426a8dbbbf9..ff600f56aec 100644 --- a/internal/catalog/library_collection_replace_items_db_test.go +++ b/internal/catalog/library_collection_replace_items_db_test.go @@ -62,6 +62,67 @@ func TestLibraryCollectionReplaceItemsWritesOnlyTheDifferenceDB(t *testing.T) { }) } +// TestLibraryCollectionReplaceItemsStoresEpisodesAndSeasonsDB pins that a +// synced collection holds episodes and seasons next to titles, in order and +// with their kind, and that each member follows its row: a content-ID rekey +// moves it, a delete removes it. +func TestLibraryCollectionReplaceItemsStoresEpisodesAndSeasonsDB(t *testing.T) { + f := newLibraryReplaceItemsFixture(t) + ctx := context.Background() + // The season member is another season than the episode's, so deleting it + // doesn't take the episode with it. + series, season, episodeSeason, episode := f.id("series"), f.id("s2"), f.id("s1"), f.id("s1e2") + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title, genres) VALUES ($1, 'series', 'Series', '{}'::text[])`, []any{series}}, + {`INSERT INTO seasons (content_id, series_id, season_number) VALUES ($1, $3, 1), ($2, $3, 2)`, []any{episodeSeason, season, series}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title) VALUES ($1, $2, $3, 1, 2, 'Two')`, []any{episode, series, episodeSeason}}, + } { + if _, err := f.pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + t.Cleanup(func() { + _, _ = f.pool.Exec(context.Background(), `DELETE FROM media_items WHERE content_id = $1`, series) + }) + + if err := f.repo.ReplaceItems(ctx, f.collectionID, []LibraryCollectionItemInput{ + {MediaItemID: f.id("a"), SourceRank: 10}, + {MediaItemID: episode, Kind: CollectionMemberEpisode, SourceRank: 20}, + {MediaItemID: season, Kind: CollectionMemberSeason, SourceRank: 30}, + }); err != nil { + t.Fatalf("replace items: %v", err) + } + members := func() []string { + t.Helper() + items, err := f.repo.ListItems(ctx, f.collectionID) + if err != nil { + t.Fatalf("list items: %v", err) + } + got := make([]string, 0, len(items)) + for _, item := range items { + got = append(got, item.Kind+":"+item.MediaItemID) + } + return got + } + if got, want := members(), []string{":" + f.id("a"), "episode:" + episode, "season:" + season}; !slices.Equal(got, want) { + t.Fatalf("members = %v, want %v", got, want) + } + + rekeyed := episode + "-rekeyed" + if _, err := f.pool.Exec(ctx, `UPDATE episodes SET content_id = $2 WHERE content_id = $1`, episode, rekeyed); err != nil { + t.Fatalf("rekey episode: %v", err) + } + if _, err := f.pool.Exec(ctx, `DELETE FROM seasons WHERE content_id = $1`, season); err != nil { + t.Fatalf("delete season: %v", err) + } + if got, want := members(), []string{":" + f.id("a"), "episode:" + rekeyed}; !slices.Equal(got, want) { + t.Fatalf("after rekey and delete, members = %v, want %v", got, want) + } +} + // TestLibraryCollectionReplaceItemsRacesMemberDeleteDB pins the lock order // of a replace against a concurrent media item delete. The delete's cascade // locks the member row before its trigger takes the collection revision, so a @@ -263,3 +324,127 @@ func (f *libraryReplaceItemsFixture) expect(t *testing.T, kept []string, names . t.Fatalf("members = %v, want %v", got, want) } } + +// TestPreviousReleaseCollectionWritesStillWorkDB runs the collection-item +// writes of the release before episode and season members, verbatim, against +// the current schema. During a rolling upgrade servers of that release share +// the migrated database, and their ON CONFLICT (collection_id, media_item_id) +// needs a unique index on exactly those columns. +func TestPreviousReleaseCollectionWritesStillWorkDB(t *testing.T) { + f := newLibraryReplaceItemsFixture(t) + ctx := context.Background() + f.replace(t, "a", "b") + writes := []struct { + name string + sql string + args []any + }{ + {"replace items", ` + INSERT INTO library_collection_items (collection_id, media_item_id, position, source_rank) + SELECT $1, desired.media_item_id, desired.position, desired.source_rank + FROM unnest($2::text[], $3::int[], $4::int[]) AS desired(media_item_id, position, source_rank) + ON CONFLICT (collection_id, media_item_id) DO NOTHING`, + []any{f.collectionID, []string{f.id("a"), f.id("c")}, []int32{0, 1}, []int32{10, 20}}}, + {"upsert item", ` + INSERT INTO library_collection_items (collection_id, media_item_id, position, source_rank) + VALUES ($1, $2, $3, 0) + ON CONFLICT (collection_id, media_item_id) + DO UPDATE SET position = EXCLUDED.position`, + []any{f.collectionID, f.id("b"), 5}}, + {"merge collection items", ` + INSERT INTO library_collection_items (collection_id, media_item_id, position, source_rank, created_at, updated_at) + SELECT collection_id, $2, MIN(position), MIN(source_rank), MIN(created_at), NOW() + FROM library_collection_items + WHERE media_item_id = $1 + GROUP BY collection_id + ON CONFLICT (collection_id, media_item_id) DO UPDATE + SET position = LEAST(library_collection_items.position, EXCLUDED.position), + source_rank = LEAST(library_collection_items.source_rank, EXCLUDED.source_rank), + updated_at = NOW()`, + []any{f.id("c"), f.id("a")}}, + } + for _, w := range writes { + if _, err := f.pool.Exec(ctx, w.sql, w.args...); err != nil { + t.Fatalf("%s: %v", w.name, err) + } + } + var position int + if err := f.pool.QueryRow(ctx, `SELECT position FROM library_collection_items WHERE collection_id = $1 AND media_item_id = $2`, f.collectionID, f.id("b")).Scan(&position); err != nil || position != 5 { + t.Fatalf("upserted item position = %d, %v; want 5", position, err) + } +} + +// TestPreviousReleaseReplaceKeepsEpisodeAndSeasonMembersDB runs the previous +// release's member replace, verbatim, on a collection holding an episode and +// a season. Its delete keeps only members whose media_item_id it lists, which +// an episode or season member never matches, so a server of that release +// syncing the list during a rolling upgrade would empty the collection. The +// schema refuses that delete: the old sync fails and the members stay. This +// release's own replace and a delete of the episode still remove members. +func TestPreviousReleaseReplaceKeepsEpisodeAndSeasonMembersDB(t *testing.T) { + f := newLibraryReplaceItemsFixture(t) + ctx := context.Background() + series, season, episodeSeason, episode := f.id("series"), f.id("s2"), f.id("s1"), f.id("s1e2") + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title, genres) VALUES ($1, 'series', 'Series', '{}'::text[])`, []any{series}}, + {`INSERT INTO seasons (content_id, series_id, season_number) VALUES ($1, $3, 1), ($2, $3, 2)`, []any{episodeSeason, season, series}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title) VALUES ($1, $2, $3, 1, 2, 'Two')`, []any{episode, series, episodeSeason}}, + } { + if _, err := f.pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + t.Cleanup(func() { + _, _ = f.pool.Exec(context.Background(), `DELETE FROM media_items WHERE content_id = $1`, series) + }) + members := []LibraryCollectionItemInput{ + {MediaItemID: f.id("a"), SourceRank: 10}, + {MediaItemID: episode, Kind: CollectionMemberEpisode, SourceRank: 20}, + {MediaItemID: season, Kind: CollectionMemberSeason, SourceRank: 30}, + } + if err := f.repo.ReplaceItems(ctx, f.collectionID, members); err != nil { + t.Fatalf("replace items: %v", err) + } + count := func() int { + t.Helper() + var n int + if err := f.pool.QueryRow(ctx, `SELECT COUNT(*) FROM library_collection_items WHERE collection_id = $1`, f.collectionID).Scan(&n); err != nil { + t.Fatalf("count members: %v", err) + } + return n + } + + // The previous release's replace with the empty list its sync reads from + // an episode list's public feed. + tx, err := f.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + _, err = tx.Exec(ctx, ` + DELETE FROM library_collection_items t + WHERE t.collection_id = $1 + AND NOT EXISTS ( + SELECT 1 FROM unnest($2::text[]) AS desired(media_item_id) + WHERE desired.media_item_id = t.media_item_id + )`, f.collectionID, []string{}) + _ = tx.Rollback(ctx) + if err == nil { + t.Fatal("the previous release's replace deleted episode and season members") + } + if got := count(); got != 3 { + t.Fatalf("members after the refused replace = %d, want 3", got) + } + + if err := f.repo.ReplaceItems(ctx, f.collectionID, members[:2]); err != nil { + t.Fatalf("replace without the season: %v", err) + } + if _, err := f.pool.Exec(ctx, `DELETE FROM episodes WHERE content_id = $1`, episode); err != nil { + t.Fatalf("delete episode: %v", err) + } + if got := count(); got != 1 { + t.Fatalf("members after removing the season and deleting the episode = %d, want 1", got) + } +} diff --git a/internal/catalog/library_collection_repo.go b/internal/catalog/library_collection_repo.go index d0cd4aa4d89..683fade1d8b 100644 --- a/internal/catalog/library_collection_repo.go +++ b/internal/catalog/library_collection_repo.go @@ -94,10 +94,25 @@ type ListLibraryCollectionsOptions struct { IncludeHidden bool } +// The kinds of collection member other than a title (movie or series), +// whose kind is "". A synced list can name episodes and seasons. +const ( + CollectionMemberEpisode = "episode" + CollectionMemberSeason = "season" +) + +// libraryCollectionMemberKindSQL reads a library_collection_items row's +// member kind, as LibraryCollectionItemInput.Kind names it. +const libraryCollectionMemberKindSQL = `CASE WHEN episode_id IS NOT NULL THEN 'episode' WHEN season_id IS NOT NULL THEN 'season' ELSE '' END` + type LibraryCollectionItemInput struct { + // MediaItemID is the member's content ID, of the kind Kind names. MediaItemID string - Position int - SourceRank int + // Kind is "" for a title, CollectionMemberEpisode or + // CollectionMemberSeason. + Kind string + Position int + SourceRank int } type RecordLibraryCollectionSyncRunInput struct { @@ -128,8 +143,12 @@ const libraryCollectionColumns = `lc.id, lc.library_id, lc.slug, lc.title, lc.de lc.management_mode, lc.management_source, lc.management_key, lc.last_sync_status, lc.last_sync_message, lc.last_sync_at, lc.sync_schedule, lc.next_sync_at, CASE WHEN lc.collection_type = 'smart' THEN lc.item_count_cached - ELSE COALESCE(COUNT(DISTINCT lci.media_item_id) FILTER (WHERE EXISTS ( - SELECT 1 FROM media_item_libraries in_library WHERE in_library.content_id = lci.media_item_id)), 0) END, + ELSE COALESCE(COUNT(DISTINCT lci.member_id) FILTER (WHERE EXISTS ( + SELECT 1 FROM media_item_libraries in_library WHERE in_library.content_id = lci.media_item_id) + OR EXISTS (SELECT 1 FROM episode_libraries in_library WHERE in_library.episode_id = lci.episode_id) + OR EXISTS (SELECT 1 FROM episodes season_episode + JOIN episode_libraries in_library ON in_library.episode_id = season_episode.content_id + WHERE season_episode.season_id = lci.season_id)), 0) END, lc.created_at, lc.updated_at, COALESCE(ARRAY_AGG(DISTINCT lcl.library_id) FILTER (WHERE lcl.library_id IS NOT NULL), ARRAY[]::integer[])` @@ -524,8 +543,9 @@ func (r *LibraryCollectionRepository) ListVisibleByIDs(ctx context.Context, ids } // ListContainingItem returns the visible collections that store a membership -// row for mediaItemID, ordered by title. The membership subquery is served by -// the library_collection_items media_item_id index. Smart (live-query) +// row for mediaItemID (a title, episode, or season), ordered by title. The +// membership subquery is served by the media_item_id, episode_id and +// season_id indexes. Smart (live-query) // collections derive their members at read time and store no rows, so they are // not reported. func (r *LibraryCollectionRepository) ListContainingItem(ctx context.Context, mediaItemID string) ([]*models.LibraryCollection, error) { @@ -539,7 +559,7 @@ func (r *LibraryCollectionRepository) ListContainingItem(ctx context.Context, me AND lc.id IN ( SELECT member.collection_id FROM library_collection_items member - WHERE member.media_item_id = $1 + WHERE member.media_item_id = $1 OR member.episode_id = $1 OR member.season_id = $1 ) GROUP BY lc.id, scope_lcl.group_id, scope_lcl.sort_order ORDER BY lower(lc.title) ASC, lc.title ASC, lc.id ASC @@ -943,13 +963,14 @@ func (r *LibraryCollectionRepository) Delete(ctx context.Context, id string) err // collection, so the item triggers leave the collection revision alone. The // statement count does not grow with the list size. func (r *LibraryCollectionRepository) ReplaceItems(ctx context.Context, collectionID string, items []LibraryCollectionItemInput) error { - // Dedupe by media_item_id. Different source entries can resolve to the + // Dedupe by member ID. Different source entries can resolve to the // same library item (e.g. an IMDb and a TMDB entry pointing at the same // local content_id, or one item present in several of the collection's // bound folders), and library_collection_items has a composite PK - // (collection_id, media_item_id). First occurrence wins, preserving rank + // (collection_id, member_id). First occurrence wins, preserving rank // order. Position is renumbered over the surviving rows so it stays dense. ids := make([]string, 0, len(items)) + kinds := make([]string, 0, len(items)) positions := make([]int, 0, len(items)) ranks := make([]int, 0, len(items)) seen := make(map[string]struct{}, len(items)) @@ -960,6 +981,7 @@ func (r *LibraryCollectionRepository) ReplaceItems(ctx context.Context, collecti seen[item.MediaItemID] = struct{}{} positions = append(positions, len(ids)) ids = append(ids, item.MediaItemID) + kinds = append(kinds, item.Kind) ranks = append(ranks, item.SourceRank) } @@ -980,18 +1002,21 @@ func (r *LibraryCollectionRepository) ReplaceItems(ctx context.Context, collecti if _, err := tx.Exec(ctx, ` SELECT 1 FROM library_collection_items WHERE collection_id = $1 - ORDER BY media_item_id + ORDER BY member_id FOR UPDATE `, collectionID); err != nil { return fmt.Errorf("locking collection items: %w", err) } + if err := AllowCollectionMemberDeletes(ctx, tx); err != nil { + return err + } deleted, err := tx.Exec(ctx, ` DELETE FROM library_collection_items t WHERE t.collection_id = $1 AND NOT EXISTS ( - SELECT 1 FROM unnest($2::text[]) AS desired(media_item_id) - WHERE desired.media_item_id = t.media_item_id + SELECT 1 FROM unnest($2::text[]) AS desired(member_id) + WHERE desired.member_id = t.member_id ) `, collectionID, ids) if err != nil { @@ -1001,8 +1026,8 @@ func (r *LibraryCollectionRepository) ReplaceItems(ctx context.Context, collecti updated, err := tx.Exec(ctx, ` UPDATE library_collection_items t SET position = desired.position, source_rank = desired.source_rank, updated_at = NOW() - FROM unnest($2::text[], $3::int[], $4::int[]) AS desired(media_item_id, position, source_rank) - WHERE t.collection_id = $1 AND t.media_item_id = desired.media_item_id + FROM unnest($2::text[], $3::int[], $4::int[]) AS desired(member_id, position, source_rank) + WHERE t.collection_id = $1 AND t.member_id = desired.member_id AND (t.position, t.source_rank) IS DISTINCT FROM (desired.position, desired.source_rank) `, collectionID, ids, positions, ranks) if err != nil { @@ -1010,11 +1035,15 @@ func (r *LibraryCollectionRepository) ReplaceItems(ctx context.Context, collecti } inserted, err := tx.Exec(ctx, ` - INSERT INTO library_collection_items (collection_id, media_item_id, position, source_rank) - SELECT $1, desired.media_item_id, desired.position, desired.source_rank - FROM unnest($2::text[], $3::int[], $4::int[]) AS desired(media_item_id, position, source_rank) - ON CONFLICT (collection_id, media_item_id) DO NOTHING - `, collectionID, ids, positions, ranks) + INSERT INTO library_collection_items (collection_id, media_item_id, episode_id, season_id, position, source_rank) + SELECT $1, + CASE WHEN desired.kind = '' THEN desired.member_id END, + CASE WHEN desired.kind = 'episode' THEN desired.member_id END, + CASE WHEN desired.kind = 'season' THEN desired.member_id END, + desired.position, desired.source_rank + FROM unnest($2::text[], $3::int[], $4::int[], $5::text[]) AS desired(member_id, position, source_rank, kind) + ON CONFLICT DO NOTHING -- no target: skip a conflict on either unique index (docs/architecture/collection-members.md) + `, collectionID, ids, positions, ranks, kinds) if err != nil { return fmt.Errorf("inserting collection items: %w", err) } @@ -1033,10 +1062,10 @@ func (r *LibraryCollectionRepository) ReplaceItems(ctx context.Context, collecti func (r *LibraryCollectionRepository) ListItems(ctx context.Context, collectionID string) ([]*models.LibraryCollectionItem, error) { rows, err := r.pool.Query(ctx, ` - SELECT collection_id, media_item_id, position, source_rank, created_at, updated_at + SELECT collection_id, member_id, `+libraryCollectionMemberKindSQL+`, position, source_rank, created_at, updated_at FROM library_collection_items WHERE collection_id = $1 - ORDER BY position ASC, source_rank ASC, media_item_id ASC + ORDER BY position ASC, source_rank ASC, member_id ASC `, collectionID) if err != nil { return nil, fmt.Errorf("listing collection items: %w", err) @@ -1049,6 +1078,7 @@ func (r *LibraryCollectionRepository) ListItems(ctx context.Context, collectionI if err := rows.Scan( &item.CollectionID, &item.MediaItemID, + &item.Kind, &item.Position, &item.SourceRank, &item.CreatedAt, @@ -1083,7 +1113,7 @@ func (r *LibraryCollectionRepository) AddItem(ctx context.Context, collectionID, if _, err := tx.Exec(ctx, ` INSERT INTO library_collection_items (collection_id, media_item_id, position, source_rank) VALUES ($1, $2, $3, 0) - ON CONFLICT (collection_id, media_item_id) + ON CONFLICT (collection_id, member_id) DO UPDATE SET position = EXCLUDED.position `, collectionID, mediaItemID, position); err != nil { return fmt.Errorf("upserting collection item: %w", err) @@ -1095,8 +1125,9 @@ func (r *LibraryCollectionRepository) AddItem(ctx context.Context, collectionID, } // AddMissingItemsInTx appends the items a collection lacks, in order, after -// its last item, in the caller's transaction. Items already in it keep their -// place, and ids with no catalog item are skipped. It returns the ids added. +// its last item, in the caller's transaction. An id may name a title, an +// episode, or a season. Items already in it keep their place, and ids with +// no catalog row are skipped. It returns the ids added. func AddMissingItemsInTx(ctx context.Context, tx pgx.Tx, collectionID string, mediaItemIDs []string) ([]string, error) { if len(mediaItemIDs) == 0 { return nil, nil @@ -1110,13 +1141,16 @@ func AddMissingItemsInTx(ctx context.Context, tx pgx.Tx, collectionID string, me ), base AS ( SELECT COALESCE(MAX(position), -1) AS last FROM library_collection_items WHERE collection_id = $1 ) - INSERT INTO library_collection_items (collection_id, media_item_id, position, source_rank) - SELECT $1, w.id, base.last + row_number() OVER (ORDER BY w.ord), 0 + INSERT INTO library_collection_items (collection_id, media_item_id, episode_id, season_id, position, source_rank) + SELECT $1, m.content_id, e.content_id, s.content_id, base.last + row_number() OVER (ORDER BY w.ord), 0 FROM wanted w CROSS JOIN base - JOIN media_items m ON m.content_id = w.id - WHERE NOT EXISTS (SELECT 1 FROM library_collection_items i WHERE i.collection_id = $1 AND i.media_item_id = w.id) - ON CONFLICT (collection_id, media_item_id) DO NOTHING - RETURNING media_item_id`, collectionID, mediaItemIDs) + LEFT JOIN media_items m ON m.content_id = w.id + LEFT JOIN episodes e ON m.content_id IS NULL AND e.content_id = w.id + LEFT JOIN seasons s ON m.content_id IS NULL AND e.content_id IS NULL AND s.content_id = w.id + WHERE COALESCE(m.content_id, e.content_id, s.content_id) IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM library_collection_items i WHERE i.collection_id = $1 AND i.member_id = w.id) + ON CONFLICT DO NOTHING -- no target: skip a conflict on either unique index (docs/architecture/collection-members.md) + RETURNING member_id`, collectionID, mediaItemIDs) if err != nil { return nil, fmt.Errorf("adding collection items: %w", err) } @@ -1201,7 +1235,7 @@ func (r *LibraryCollectionRepository) reorderItems(ctx context.Context, collecti UPDATE library_collection_items t SET position = supplied.pos - 1 FROM supplied - WHERE t.collection_id = $2 AND t.media_item_id = supplied.id + WHERE t.collection_id = $2 AND t.member_id = supplied.id RETURNING 1 ) SELECT (SELECT count(*) FROM upd), diff --git a/internal/catalog/library_collection_service.go b/internal/catalog/library_collection_service.go index 3d193b698de..ed3110a5fbe 100644 --- a/internal/catalog/library_collection_service.go +++ b/internal/catalog/library_collection_service.go @@ -7,6 +7,7 @@ import ( "fmt" "log/slog" "net/http" + "strconv" "strings" "sync" "time" @@ -14,7 +15,6 @@ import ( "github.com/Silo-Server/silo-server/internal/collage" "github.com/Silo-Server/silo-server/internal/collectionutil" "github.com/Silo-Server/silo-server/internal/logredact" - "github.com/Silo-Server/silo-server/internal/mdblist" "github.com/Silo-Server/silo-server/internal/models" "github.com/Silo-Server/silo-server/internal/ratingsources" ) @@ -109,7 +109,11 @@ type LibraryCollectionService struct { collections *LibraryCollectionRepository items *ItemRepository libraryItems *LibraryItemRepository - httpClient *http.Client + // episodes and seasons match the episodes and seasons of an MDBList + // list. + episodes *EpisodeRepository + seasons *SeasonRepository + httpClient *http.Client // TMDBCollections is nil when TMDB is not configured. TMDBCollections TMDBCollectionFetcher @@ -151,12 +155,17 @@ func NewLibraryCollectionService( ) *LibraryCollectionService { httpClient = collectionutil.MDBListHTTPClient(httpClient) - return &LibraryCollectionService{ + svc := &LibraryCollectionService{ collections: collections, items: items, libraryItems: libraryItems, httpClient: httpClient, } + if items != nil { + svc.episodes = NewEpisodeRepository(items.pool) + svc.seasons = NewSeasonRepository(items.pool) + } + return svc } // CollectionBuilders holds per-builder item limits for synced collections. @@ -296,6 +305,9 @@ func (s *LibraryCollectionService) syncMDBListCollection(ctx context.Context, co entries, err := collectionutil.FetchMDBListEntries(ctx, s.httpClient, listURLs, fetchLimit, func(ref collectionutil.MDBListRef, feedErr *collectionutil.MDBListFeedError) ([]collectionutil.MDBListEntry, error) { return s.readMDBListWithServerKey(ctx, ref, fetchLimit, feedErr) }) + if errors.Is(err, errMDBListEmptyFeedNeedsKey) { + return s.recordCollectionSyncOutcome(ctx, collection.ID, "warning", startedAt, err.Error()) + } if err != nil { return nil, err } @@ -334,6 +346,10 @@ func (s *LibraryCollectionService) syncMDBListCollection(ctx context.Context, co if err != nil { return nil, err } + parts, err := s.matchMDBListEpisodesAndSeasons(ctx, entries) + if err != nil { + return nil, err + } // First pass: collect ALL candidate content_ids per entry in priority // order. The legacy resolveMDBListEntry walked every external-ID hit and @@ -343,6 +359,9 @@ func (s *LibraryCollectionService) syncMDBListCollection(ctx context.Context, co type resolvedEntry struct { entryIndex int candidates []string + // kind is the member kind of every candidate: an entry names + // titles, or one episode or season. + kind string sourceRank int } resolved := make([]resolvedEntry, 0, len(entries)) @@ -360,6 +379,10 @@ func (s *LibraryCollectionService) syncMDBListCollection(ctx context.Context, co lookup = seriesLookup } candidates := pickCandidatesByPriority(lookup, entry, itemType) + var kind string + if part, ok := parts[index]; ok { + candidates, kind = []string{part.id}, part.kind + } if len(candidates) == 0 { continue } @@ -367,7 +390,7 @@ func (s *LibraryCollectionService) syncMDBListCollection(ctx context.Context, co if sourceRank <= 0 { sourceRank = index + 1 } - resolved = append(resolved, resolvedEntry{entryIndex: index, candidates: candidates, sourceRank: sourceRank}) + resolved = append(resolved, resolvedEntry{entryIndex: index, candidates: candidates, kind: kind, sourceRank: sourceRank}) for _, candidate := range candidates { if _, exists := candidateSet[candidate]; !exists { candidateSet[candidate] = struct{}{} @@ -409,6 +432,7 @@ func (s *LibraryCollectionService) syncMDBListCollection(ctx context.Context, co } matchedItems = append(matchedItems, LibraryCollectionItemInput{ MediaItemID: chosen, + Kind: r.kind, Position: len(matchedItems), SourceRank: r.sourceRank, }) @@ -801,13 +825,19 @@ func (s *LibraryCollectionService) recordTMDBEntrySync(ctx context.Context, coll } func (s *LibraryCollectionService) recordFailedCollectionSync(ctx context.Context, collectionID string, startedAt time.Time, message string) (*models.LibraryCollectionSyncRun, error) { + return s.recordCollectionSyncOutcome(ctx, collectionID, "failed", startedAt, message) +} + +// recordCollectionSyncOutcome records a sync run that matched nothing and left +// the members as they were, with message as its one warning. +func (s *LibraryCollectionService) recordCollectionSyncOutcome(ctx context.Context, collectionID, status string, startedAt time.Time, message string) (*models.LibraryCollectionSyncRun, error) { warningsJSON, err := json.Marshal([]string{message}) if err != nil { return nil, fmt.Errorf("marshaling sync warnings: %w", err) } return s.collections.RecordSyncRun(ctx, RecordLibraryCollectionSyncRunInput{ CollectionID: collectionID, - Status: "failed", + Status: status, Message: message, Warnings: warningsJSON, StartedAt: startedAt, @@ -841,38 +871,6 @@ func (s *LibraryCollectionService) matchTMDBEntriesInLibraries(ctx context.Conte return contentIDs, nil } -// readMDBListWithServerKey reads a list the public feed refused through the -// MDBList API with the server's key, so an admin's private list can sync. -// Its errors are the messages the sync stores, which say what to change. -func (s *LibraryCollectionService) readMDBListWithServerKey(ctx context.Context, ref collectionutil.MDBListRef, maxEntries int, feedErr *collectionutil.MDBListFeedError) ([]collectionutil.MDBListEntry, error) { - noKey := func() error { - return fmt.Errorf("%w. To sync a private list, add an MDBList API key from the account that owns it in Settings › Providers", feedErr) - } - if s.MDBList == nil || !s.MDBList.Configured() { - return nil, noKey() - } - entries, err := s.MDBList.ListItems(ctx, ref, maxEntries) - if err == nil { - return entries, nil - } - // The key can be cleared between the check above and the read. - if errors.Is(err, mdblist.ErrNotConfigured) { - return nil, noKey() - } - var readErr *collectionutil.MDBListReadError - if !errors.As(err, &readErr) { - return nil, err - } - switch readErr.Kind { - case collectionutil.MDBListKeyRejected: - return nil, errors.New("MDBList rejected the server's MDBList API key. Check it in Settings › Providers") - case collectionutil.MDBListRateLimited: - return nil, errors.New("the server's MDBList API key has used up its daily MDBList limit. The next sync tries again") - default: - return nil, fmt.Errorf("%w. The server's MDBList API key can't read this list; if it is private, use a key from the account that owns it in Settings › Providers", readErr) - } -} - // pickCandidatesByPriority returns all matching content_ids in priority order // (highest first), deduped. The caller resolves library membership against // this list and picks the first hit — matching the legacy resolveMDBListEntry @@ -964,3 +962,11 @@ func (s *LibraryCollectionService) MaybeGenerateCollage(ctx context.Context, col func syncTimestamp() time.Time { return time.Now().UTC().Truncate(time.Microsecond) } + +// positiveIDString is id in decimal, or "" for none. +func positiveIDString(id int) string { + if id <= 0 { + return "" + } + return strconv.Itoa(id) +} diff --git a/internal/catalog/library_repo.go b/internal/catalog/library_repo.go index 70e2faf3b00..3b8a4a04013 100644 --- a/internal/catalog/library_repo.go +++ b/internal/catalog/library_repo.go @@ -180,7 +180,9 @@ func (r *LibraryItemRepository) GetItemsInFolder(ctx context.Context, contentIDs } // GetItemsInFolders returns membership for the provided content IDs across -// any of the supplied folders. Used by the user-collection sync service to +// any of the supplied folders. A title is in a folder through its library +// link, an episode through its file, and a season through any of its +// episodes' files. Used by the user-collection sync service to // constrain imports to a chosen subset of libraries in one query rather than // looping GetItemsInFolder per library. func (r *LibraryItemRepository) GetItemsInFolders(ctx context.Context, contentIDs []string, folderIDs []int) (map[string]bool, error) { @@ -203,6 +205,13 @@ func (r *LibraryItemRepository) GetItemsInFolders(ctx context.Context, contentID FROM episode_libraries el WHERE el.media_folder_id = ANY($1) AND el.episode_id = req.content_id + ) + OR EXISTS ( + SELECT 1 + FROM episodes e + JOIN episode_libraries el ON el.episode_id = e.content_id + WHERE e.season_id = req.content_id + AND el.media_folder_id = ANY($1) )`, folderIDs, contentIDs, ) diff --git a/internal/catalog/query_cursor_test.go b/internal/catalog/query_cursor_test.go index 683be8d060f..e19b100e4ab 100644 --- a/internal/catalog/query_cursor_test.go +++ b/internal/catalog/query_cursor_test.go @@ -146,7 +146,7 @@ func TestQueryCursorAddedAtPagesEachType(t *testing.T) { added := QuerySort{Field: "added_at", Order: "desc"} watched := []QueryGroup{{Match: "all", Rules: []QueryRule{{Field: "last_watched", Op: "in_last", Value: "30d"}}}} collection := &QueryExecutor{} - applyCollectionPositionOrder(collection, "JOIN collection_items cursor_membership ON cursor_membership.media_item_id = mi.content_id") + applyCollectionPositionOrder(collection, "JOIN collection_items cursor_membership ON cursor_membership.media_item_id = mi.content_id", "media_item_id") for _, tc := range []struct { name string executor *QueryExecutor diff --git a/internal/catalog/query_executor.go b/internal/catalog/query_executor.go index 5733711cd9c..3991abefb49 100644 --- a/internal/catalog/query_executor.go +++ b/internal/catalog/query_executor.go @@ -41,6 +41,9 @@ type QueryExecutor struct { // BaseRelationSQL, when set, replaces the default "media_items mi" source. // The relation must already be aliased as "mi". BaseRelationSQL string + // BaseRelationArgs bind BaseRelationSQL's parameters, numbered from $1; + // the executor binds them before every other argument. + BaseRelationArgs []any // SnapshotAt, when set, restricts results to items created at or before // this timestamp. This prevents offset-based pagination drift when new // items are inserted between page fetches (e.g. during a scan). @@ -344,7 +347,7 @@ func (e *QueryExecutor) buildPreviewPagePlan( } baseRelation := e.BaseRelationSQL - baseArgs := []any(nil) + baseArgs := e.BaseRelationArgs libraryScopeHandledInBaseRelation := false if isEpisodeCatalogScope(effectiveScope) { var handled bool diff --git a/internal/catalog/reattribute/reattribute.go b/internal/catalog/reattribute/reattribute.go index 37acd0e676b..d665acd52cb 100644 --- a/internal/catalog/reattribute/reattribute.go +++ b/internal/catalog/reattribute/reattribute.go @@ -24,6 +24,8 @@ import ( "fmt" "github.com/jackc/pgx/v5" + + "github.com/Silo-Server/silo-server/internal/catalog" ) // HistoryMode selects how user_watch_history rows without decisive per-file @@ -178,6 +180,9 @@ var intentTables = []struct { {"profile_title_allowances", "content_id", []string{colUserID, colProfileID}}, {"user_personal_collection_items", colMediaItemID, []string{colUserID, "collection_id", "sub_item_id"}}, {"library_collection_items", colMediaItemID, []string{"collection_id"}}, + // An MDBList collection can hold episodes, so an episode merge moves + // them too. + {"library_collection_items", "episode_id", []string{"collection_id"}}, {"user_home_item_dismissals", colMediaItemID, []string{colUserID, colProfileID, "surface"}}, {historyCutoffTable, colMediaItemID, []string{colUserID, colProfileID}}, {"user_audio_preferences", colSeriesID, []string{colUserID, colProfileID}}, @@ -430,6 +435,11 @@ func moveIntentPairs(ctx context.Context, tx pgx.Tx, table, idColumn string, key return 0, err } } + if table == "library_collection_items" { + if err := catalog.AllowCollectionMemberDeletes(ctx, tx); err != nil { + return 0, err + } + } join := "" for _, col := range keyCols { join += fmt.Sprintf(" AND dest.%s = src.%s", col, col) diff --git a/internal/catalog/season_episode_locks.go b/internal/catalog/season_episode_locks.go index 8de474d5fb0..94515a2084d 100644 --- a/internal/catalog/season_episode_locks.go +++ b/internal/catalog/season_episode_locks.go @@ -32,13 +32,18 @@ const ( sqlEmptyText = "''" sqlNull = "NULL" - // The titles metadata's fallbackSeasonTitle and fallbackEpisodeTitle give a - // row the provider has no title for. A cleared row the new show doesn't - // have gets no refresh write, and lists show its title as stored. - sqlDefaultSeasonTitle = "CASE WHEN season_number = 0 THEN 'Specials' ELSE 'Season ' || season_number END" + // The title metadata's fallbackEpisodeTitle gives a row the provider has + // no title for. A cleared row the new show doesn't have gets no refresh + // write, and lists show its title as stored. sqlDefaultEpisodeTitle = "'Episode ' || episode_number" ) +// defaultSeasonTitleSQL is the title metadata's fallbackSeasonTitle gives a +// season numbered number, a column, that the provider has no title for. +func defaultSeasonTitleSQL(number string) string { + return "CASE WHEN " + number + " = 0 THEN 'Specials' ELSE 'Season ' || " + number + " END" +} + // childLockedColumn pairs a lockable column with its lock and the value it // takes when the edit it held is cleared. type childLockedColumn struct { @@ -52,7 +57,7 @@ type childLockedColumn struct { // FieldImages locks on the parent series instead. var ( seasonLockedColumns = []childLockedColumn{ - {childColumnTitle, fieldNameLocked, sqlDefaultSeasonTitle}, + {childColumnTitle, fieldNameLocked, defaultSeasonTitleSQL("season_number")}, {childColumnOverview, fieldOverviewLocked, sqlEmptyText}, {columnAirDate, fieldReleaseDatesLocked, sqlNull}, } diff --git a/internal/catalog/season_repo.go b/internal/catalog/season_repo.go index c06594c20e8..fd5178bef61 100644 --- a/internal/catalog/season_repo.go +++ b/internal/catalog/season_repo.go @@ -49,6 +49,95 @@ func NewSeasonRepository(pool *pgxpool.Pool) *SeasonRepository { return &SeasonRepository{pool: pool} } +// SeasonCardContext is what a season's card names besides the season: its +// series and its number. +type SeasonCardContext struct { + SeriesID string + SeriesTitle string + SeasonNumber int +} + +// ListCardContexts returns the card context of each season in contentIDs +// that exists, in one query. +func (r *SeasonRepository) ListCardContexts(ctx context.Context, contentIDs []string) (map[string]SeasonCardContext, error) { + result := make(map[string]SeasonCardContext, len(contentIDs)) + if len(contentIDs) == 0 { + return result, nil + } + rows, err := r.pool.Query(ctx, ` + SELECT s.content_id, s.series_id, COALESCE(si.title, ''), s.season_number + FROM seasons s + LEFT JOIN media_items si ON si.content_id = s.series_id + WHERE s.content_id = ANY($1)`, contentIDs) + if err != nil { + return nil, fmt.Errorf("listing season card contexts: %w", err) + } + defer rows.Close() + for rows.Next() { + var id string + var c SeasonCardContext + if err := rows.Scan(&id, &c.SeriesID, &c.SeriesTitle, &c.SeasonNumber); err != nil { + return nil, fmt.Errorf("scanning season card context: %w", err) + } + result[id] = c + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterating season card contexts: %w", err) + } + return result, nil +} + +// SeasonNumber names a season by its series and its season number. +type SeasonNumber struct { + SeriesID string + Season int + // TMDBID, when set, names the season by its TMDB ID, which holds when + // the series is numbered differently from TMDB. + TMDBID string +} + +// ListIDsByNumbers maps each ref that names a season to that season's +// content ID, and leaves the others out: the season of the series with the +// ref's TMDB ID, else the one with its number unless that season has another +// TMDB ID. +func (r *SeasonRepository) ListIDsByNumbers(ctx context.Context, refs []SeasonNumber) (map[SeasonNumber]string, error) { + result := make(map[SeasonNumber]string, len(refs)) + if len(refs) == 0 { + return result, nil + } + seriesIDs := make([]string, len(refs)) + seasons := make([]int, len(refs)) + tmdbIDs := make([]string, len(refs)) + for i, ref := range refs { + seriesIDs[i], seasons[i], tmdbIDs[i] = ref.SeriesID, ref.Season, ref.TMDBID + } + rows, err := r.pool.Query(ctx, ` + SELECT DISTINCT ON (req.series_id, req.season, req.tmdb_id) + req.series_id, req.season, req.tmdb_id, s.content_id + FROM unnest($1::text[], $2::bigint[], $3::text[]) AS req(series_id, season, tmdb_id) + JOIN seasons s ON s.series_id = req.series_id + AND ((req.tmdb_id <> '' AND s.tmdb_id = req.tmdb_id) + OR (s.season_number = req.season AND (req.tmdb_id = '' OR COALESCE(s.tmdb_id, '') IN ('', req.tmdb_id)))) + ORDER BY req.series_id, req.season, req.tmdb_id, (req.tmdb_id <> '' AND s.tmdb_id = req.tmdb_id) DESC`, + seriesIDs, seasons, tmdbIDs) + if err != nil { + return nil, fmt.Errorf("listing seasons by number: %w", err) + } + defer rows.Close() + for rows.Next() { + var ref SeasonNumber + var contentID string + if err := rows.Scan(&ref.SeriesID, &ref.Season, &ref.TMDBID, &contentID); err != nil { + return nil, fmt.Errorf("scanning season by number: %w", err) + } + result[ref] = contentID + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterating seasons by number: %w", err) + } + return result, nil +} + // seasonColumns is the list of columns returned by all SELECT queries on seasons. const seasonColumns = `content_id, series_id, season_number, title, default_metadata_language, overview, air_date, poster_path, poster_source_path, poster_thumbhash, diff --git a/internal/collectionutil/mdblist_private.go b/internal/collectionutil/mdblist_private.go index 34411ad2da1..e686b6ca635 100644 --- a/internal/collectionutil/mdblist_private.go +++ b/internal/collectionutil/mdblist_private.go @@ -22,11 +22,38 @@ type MDBListEntry struct { MediaType string `json:"mediatype"` Title string `json:"title"` ReleaseYear int `json:"release_year"` + // Episode is set on an episode entry and Season on a season entry, + // which only the MDBList API returns: the public feed leaves them out. + Episode *MDBListEpisode `json:"-"` + Season *MDBListSeason `json:"-"` } -// ItemType maps the entry's media type onto Silo's "movie" and "series" item -// types. +// MDBListEpisode names an episode the way MDBList does: by its own TMDB ID, +// and by its show's TMDB ID and its TMDB season and episode numbers. +type MDBListEpisode struct { + TMDBID int + ShowTMDBID int + Season int + Episode int +} + +// MDBListSeason names a season the way MDBList does: by its own TMDB ID, +// and by its show's TMDB ID and its TMDB season number. +type MDBListSeason struct { + TMDBID int + ShowTMDBID int + Season int +} + +// ItemType maps the entry's media type onto Silo's "movie", "series", +// "season" and "episode" item types. func (e MDBListEntry) ItemType() string { + switch { + case e.Episode != nil: + return "episode" + case e.Season != nil: + return "season" + } switch strings.ToLower(e.MediaType) { case "show", "tv", "series": return "series" @@ -156,9 +183,11 @@ func MDBListBoundedReason(body []byte) string { return mdblistFeedError(body) } -// MDBListPrivateRead reads a list the public feed refused. feedErr is the -// feed's refusal, for the message to show when the list can't be read -// another way. It returns the entries, or the error the sync stores. +// MDBListPrivateRead reads a list the public feed refused or answered empty. +// feedErr is the feed's refusal, for the message to show when the list can't +// be read another way, and nil for an empty answer: the feed leaves episodes +// out, so a list of episodes reads empty there. It returns the entries, or +// the error the sync stores. type MDBListPrivateRead func(ref MDBListRef, feedErr *MDBListFeedError) ([]MDBListEntry, error) // FetchMDBListEntries reads a list's public feed, trying each candidate URL @@ -166,7 +195,9 @@ type MDBListPrivateRead func(ref MDBListRef, feedErr *MDBListFeedError) ([]MDBLi // the feed refused one of them with its error object (as it does for a // private list), it reads that candidate's list with private instead and // returns that answer. A nil private, or a refused candidate that names no -// list, keeps the last candidate's error. Transport and HTTP failures never +// list, keeps the last candidate's error. A candidate the feed answers empty +// is read with private too, with a nil feedErr, since that is all the feed +// gives for a list of episodes. Transport and HTTP failures never // reach private: the API would fail the same way, at a cost to the key's // daily quota. func FetchMDBListEntries(ctx context.Context, client *http.Client, urls []string, maxEntries int, private MDBListPrivateRead) ([]MDBListEntry, error) { @@ -178,6 +209,11 @@ func FetchMDBListEntries(ctx context.Context, client *http.Client, urls []string for _, listURL := range urls { entries, err := FetchMDBListJSON[MDBListEntry](ctx, client, listURL, maxEntries) if err == nil { + if len(entries) == 0 && private != nil { + if parsed, ok := ParseMDBListRef(listURL); ok { + return private(parsed, nil) + } + } return entries, nil } lastErr = err diff --git a/internal/collectionutil/mdblist_test.go b/internal/collectionutil/mdblist_test.go index ed849e6690f..88acd2aa46f 100644 --- a/internal/collectionutil/mdblist_test.go +++ b/internal/collectionutil/mdblist_test.go @@ -108,9 +108,10 @@ func TestParseMDBListRef(t *testing.T) { } // The public feed answers first, so a public list costs no API quota; only -// the feed's refusal object hands the list to the private reader, and an -// HTTP failure never does. -func TestFetchMDBListEntriesReadsPrivatelyOnlyOnAFeedRefusal(t *testing.T) { +// the feed's refusal object or an empty answer, which is all the feed gives +// for a list of episodes, hands the list to the private reader, and an HTTP +// failure never does. +func TestFetchMDBListEntriesReadsPrivatelyOnlyOnAFeedRefusalOrEmptyAnswer(t *testing.T) { t.Parallel() const listURL = "https://mdblist.com/lists/alice/picks" @@ -118,10 +119,13 @@ func TestFetchMDBListEntriesReadsPrivatelyOnlyOnAFeedRefusal(t *testing.T) { status int body string wantPrivate bool + // wantFeedErr is the refusal the private reader gets, "" for none. + wantFeedErr string wantErr bool }{ "public list": {status: 200, body: `[{"id":1,"rank":1,"mediatype":"movie"}]`}, - "feed refusal": {status: 200, body: `{"error":"This List is Private"}`, wantPrivate: true}, + "feed refusal": {status: 200, body: `{"error":"This List is Private"}`, wantPrivate: true, wantFeedErr: "This List is Private"}, + "empty feed": {status: 200, body: `[]`, wantPrivate: true}, "feed HTTP 500": {status: 500, body: `oops`, wantErr: true}, "feed not found": {status: 404, body: `{"error":"nope"}`, wantErr: true}, } { @@ -134,8 +138,12 @@ func TestFetchMDBListEntriesReadsPrivatelyOnlyOnAFeedRefusal(t *testing.T) { entries, err := FetchMDBListEntries(context.Background(), client, MDBListURLCandidates(listURL), 0, func(ref MDBListRef, feedErr *MDBListFeedError) ([]MDBListEntry, error) { called = &ref - if feedErr.Message != "This List is Private" { - t.Errorf("feedErr = %q", feedErr.Message) + got := "" + if feedErr != nil { + got = feedErr.Message + } + if got != tc.wantFeedErr { + t.Errorf("feedErr = %q, want %q", got, tc.wantFeedErr) } return []MDBListEntry{{ID: 9}}, nil }) diff --git a/internal/jellycompat/batch_loaders.go b/internal/jellycompat/batch_loaders.go index f7f0d04047f..54b7af55bd0 100644 --- a/internal/jellycompat/batch_loaders.go +++ b/internal/jellycompat/batch_loaders.go @@ -508,6 +508,69 @@ func (h *ItemsHandler) fetchCompatEpisodeTargetsByContentIDsFallback(ctx context return result, nil } +// fetchCompatSeasonListItems loads the seasons among contentIDs that the +// session can see, as season list items keyed by content ID: a season of a +// series the viewer can see, with an episode on disk, as the native +// collection page lists them. A season advertises only its own poster, the +// one the image endpoint serves. Without a database pool it finds none. +func (h *ItemsHandler) fetchCompatSeasonListItems(ctx context.Context, session *Session, contentIDs []string) (map[string]upstreamListItem, error) { + normalized := normalizeContentIDs(contentIDs) + pool := h.compatPool() + if len(normalized) == 0 || pool == nil { + return map[string]upstreamListItem{}, nil + } + access := h.resolveAccessFilter(ctx, session) + conditions := []string{"se.content_id = ANY($1)", "si.type = 'series'"} + args := []any{normalized} + argIdx := 2 + if !applyCompatLibraryAccess(&access, nil, "si.content_id", &conditions, &args, &argIdx) { + return map[string]upstreamListItem{}, nil + } + // A series can span libraries, so the season needs an episode file in + // one the viewer may open, and counts only those episodes. + onDisk := "EXISTS (SELECT 1 FROM episode_libraries el WHERE el.episode_id = e.content_id" + if file := catalog.EpisodeFileLibraryAccessSQL("el.media_folder_id", access, &args, &argIdx); file != "" { + onDisk += " AND " + file + } + onDisk += ")" + conditions = append(conditions, "EXISTS (SELECT 1 FROM episodes e WHERE e.season_id = se.content_id AND "+onDisk+")") + conditions = append(conditions, catalog.InSomeLibraryWhere("si.content_id")) + catalog.ApplySectionAccessFilter("si", access, &conditions, &args, &argIdx) + rows, err := pool.Query(ctx, ` + SELECT + se.content_id, + `+catalog.SeasonTitleSQL("se")+`, + se.season_number, + COALESCE(se.poster_path, ''), + COALESCE(se.poster_thumbhash, ''), + se.updated_at, + (SELECT COUNT(*) FROM episodes e WHERE e.season_id = se.content_id AND `+onDisk+`)::int, + si.content_id, + si.title + FROM seasons se + JOIN media_items si ON si.content_id = se.series_id + WHERE `+strings.Join(conditions, " AND "), args...) + if err != nil { + return nil, fmt.Errorf("loading collection seasons: %w", err) + } + defer rows.Close() + result := make(map[string]upstreamListItem, len(normalized)) + for rows.Next() { + item := upstreamListItem{Type: compatCatalogTypeSeason} + var seasonNumber, episodeCount int + if err := rows.Scan(&item.ContentID, &item.Title, &seasonNumber, &item.PosterPath, &item.PosterThumbhash, + &item.UpdatedAt, &episodeCount, &item.SeriesID, &item.SeriesTitle); err != nil { + return nil, fmt.Errorf("scanning collection season: %w", err) + } + item.SeasonNumber, item.EpisodeCount = &seasonNumber, &episodeCount + if item.PosterPath != "" { + item.PosterURL = compatPresignImage(h.detailSvc, ctx, item.PosterPath, "poster", compatCardImageSize) + } + result[item.ContentID] = item + } + return result, rows.Err() +} + func (h *ItemsHandler) compatPool() *pgxpool.Pool { if h.browseRepo == nil { return nil diff --git a/internal/jellycompat/handlers_collections.go b/internal/jellycompat/handlers_collections.go index fdfdfaddcdd..e9833d5895e 100644 --- a/internal/jellycompat/handlers_collections.go +++ b/internal/jellycompat/handlers_collections.go @@ -669,13 +669,28 @@ func (h *ItemsHandler) handleBoxSetChildren(w http.ResponseWriter, r *http.Reque // filter browses the catalog joined to it, and the curated order pages it // directly, so neither path loads every member to serve one page. if !catalog.IsLiveQueryType(collection.CollectionType) { + pool := h.compatPool() + if query.sortExplicit && !query.hasItemTypeFilter && !query.hasMemberFilters() && pool != nil { + // Catalog browse reads titles only, so a collection that holds + // episodes or seasons keeps its curated order rather than lose + // them to a client's sort. + holds, err := catalog.LibraryCollectionHoldsEpisodesOrSeasons(r.Context(), pool, collection.ID) + if err != nil { + writeCompatUpstreamError(w, err) + return + } + if holds { + h.writeStoredCollectionPage(w, r, session, query, routeID, pool, collection.ID) + return + } + } if query.sortExplicit || query.hasItemTypeFilter || query.hasMemberFilters() { params := buildBrowseParams(query) params.Set("collection_id", collection.ID) h.writeCollectionBrowsePage(w, r, session, query, routeID, params) return } - if pool := h.compatPool(); pool != nil { + if pool != nil { h.writeStoredCollectionPage(w, r, session, query, routeID, pool, collection.ID) return } @@ -708,7 +723,7 @@ func (h *ItemsHandler) handleBoxSetChildren(w http.ResponseWriter, r *http.Reque return } } - ordered, episodeTargets, hydrateErr := h.hydrateCollectionMembers(r.Context(), session, slicePage(sorted, query.startIndex, query.limit), true) + ordered, episodeTargets, hydrateErr := h.hydrateCollectionMembers(r.Context(), session, slicePage(sorted, query.startIndex, query.limit)) if hydrateErr != nil { writeCompatUpstreamError(w, hydrateErr) return @@ -727,7 +742,7 @@ func (h *ItemsHandler) handleBoxSetChildren(w http.ResponseWriter, r *http.Reque // Position order without a database pool: hydrate the surviving members, // rebuild curated order, then page locally before building DTOs. - ordered, episodeTargets, err := h.hydrateCollectionMembers(r.Context(), session, contentIDs, catalog.IsLiveQueryType(collection.CollectionType)) + ordered, episodeTargets, err := h.hydrateCollectionMembers(r.Context(), session, contentIDs) if err != nil { writeCompatUpstreamError(w, err) return @@ -761,20 +776,20 @@ func (h *ItemsHandler) writeStoredCollectionPage(w http.ResponseWriter, r *http. writeJSON(w, http.StatusOK, result) return } - // Stored members only reference media_items, so no episode lookup. - ordered, _, err := h.hydrateCollectionMembers(r.Context(), session, pageIDs, false) + ordered, episodeTargets, err := h.hydrateCollectionMembers(r.Context(), session, pageIDs) if err != nil { writeCompatUpstreamError(w, err) return } - h.writeListItemsPage(w, r, session, query, routeID, ordered, nil, total) + h.writeListItemsPage(w, r, session, query, routeID, ordered, episodeTargets, total) } // storedCollectionContentIDPage returns the [offset, offset+limit) window of a // stored collection's members in curated order, plus the member total. Both // count only members the viewer can see, with the same access rules as // loadCompatItemsByContentIDs, so a hidden member neither shortens a page nor -// shifts later pages. limit <= 0 means no cap. +// shifts later pages. Episode and season members count as the native +// collection page shows them. limit <= 0 means no cap. func (h *ItemsHandler) storedCollectionContentIDPage(ctx context.Context, session *Session, pool *pgxpool.Pool, collectionID string, offset, limit int) ([]string, int, error) { access := h.resolveAccessFilter(ctx, session) conditions := []string{"lci.collection_id = $1"} @@ -787,7 +802,10 @@ func (h *ItemsHandler) storedCollectionContentIDPage(ctx context.Context, sessio // is gone from its library pages, so it is no child here either. conditions = append(conditions, catalog.InSomeLibraryWhere("mi.content_id")) catalog.ApplySectionAccessFilter("mi", access, &conditions, &args, &argIdx) - from := "library_collection_items lci JOIN media_items mi ON mi.content_id = lci.media_item_id WHERE " + strings.Join(conditions, " AND ") + const memberColumns = "lci.member_id, lci.position, lci.source_rank" + from := "(SELECT " + memberColumns + " FROM library_collection_items lci JOIN media_items mi ON mi.content_id = lci.media_item_id WHERE " + + strings.Join(conditions, " AND ") + + catalog.CollectionEpisodeAndSeasonMembersSQL(memberColumns, "lci.collection_id = $1", access, &args, &argIdx) + ") lci" offset = max(offset, 0) var limitArg any // NULL is LIMIT ALL @@ -802,7 +820,7 @@ func (h *ItemsHandler) storedCollectionContentIDPage(ctx context.Context, sessio ids []string ) if err := pool.QueryRow(ctx, fmt.Sprintf( - "SELECT (SELECT COUNT(*) FROM %[1]s), ARRAY(SELECT lci.media_item_id FROM %[1]s ORDER BY lci.position, lci.source_rank, lci.media_item_id LIMIT $%[2]d OFFSET $%[3]d)", + "SELECT (SELECT COUNT(*) FROM %[1]s), ARRAY(SELECT lci.member_id FROM %[1]s ORDER BY lci.position, lci.source_rank, lci.member_id LIMIT $%[2]d OFFSET $%[3]d)", from, argIdx, argIdx+1), args...).Scan(&total, &ids); err != nil { return nil, 0, fmt.Errorf("paging collection members: %w", err) } @@ -829,7 +847,7 @@ func (h *ItemsHandler) writeSmartCollectionPage(w http.ResponseWriter, r *http.R writeJSON(w, http.StatusOK, result) return } - ordered, episodeTargets, err := h.hydrateCollectionMembers(r.Context(), session, pageIDs, true) + ordered, episodeTargets, err := h.hydrateCollectionMembers(r.Context(), session, pageIDs) if err != nil { writeCompatUpstreamError(w, err) return @@ -936,7 +954,7 @@ func (h *ItemsHandler) writeResolvedCollectionPage(w http.ResponseWriter, r *htt writeJSON(w, http.StatusOK, result) return true } - ordered, episodeTargets, err := h.hydrateCollectionMembers(ctx, session, pageIDs, catalog.IsLiveQueryType(collection.CollectionType)) + ordered, episodeTargets, err := h.hydrateCollectionMembers(ctx, session, pageIDs) if err != nil { writeCompatUpstreamError(w, err) return true @@ -1130,7 +1148,7 @@ func (h *ItemsHandler) handleBoxSetLeaves(w http.ResponseWriter, r *http.Request rand.Shuffle(len(leaves), func(i, j int) { leaves[i], leaves[j] = leaves[j], leaves[i] }) } - listItems, episodeTargets, err := h.hydrateCollectionMembers(ctx, session, slicePage(leaves, query.startIndex, query.limit), true) + listItems, episodeTargets, err := h.hydrateCollectionMembers(ctx, session, slicePage(leaves, query.startIndex, query.limit)) if err != nil { writeCompatUpstreamError(w, err) return @@ -1139,11 +1157,10 @@ func (h *ItemsHandler) handleBoxSetLeaves(w http.ResponseWriter, r *http.Request h.writeListItemsPage(w, r, session, query, routeID, listItems, episodeTargets, len(leaves)) } -// expandCollectionLeaves turns movie and series members into playable leaf -// IDs in the order contentIDs lists the members: movies as they are, series as -// their visible episodes. Members missing from media_items are hidden from -// this session; only episode-scoped smart collections hold episodes, and those -// skip expansion. +// expandCollectionLeaves turns members into playable leaf IDs in the order +// contentIDs lists the members: movies and episodes as they are, series and +// seasons as their visible episodes, each leaf once. Members found nowhere +// are hidden from this session. func (h *ItemsHandler) expandCollectionLeaves(ctx context.Context, session *Session, query itemsQuery, contentIDs []string) ([]string, error) { members, err := h.loadCompatItemsByContentIDs(ctx, session, contentIDs, nil) if err != nil { @@ -1153,20 +1170,51 @@ func (h *ItemsHandler) expandCollectionLeaves(ctx context.Context, session *Sess for _, member := range members { memberTypes[member.ContentID] = strings.ToLower(member.Type) } - var seriesEpisodes map[string][]string + var seriesEpisodes, seasonEpisodes map[string][]string + var episodeMembers map[string]bool if query.allowsItemType(compatEpisodeType) { if seriesEpisodes, err = h.collectionSeriesEpisodeIDs(ctx, session, members); err != nil { return nil, err } + // Members missing from media_items are episodes or seasons of a + // synced list, or hidden from this session. + var missing []string + for _, contentID := range contentIDs { + if _, ok := memberTypes[contentID]; !ok { + missing = append(missing, contentID) + } + } + if len(missing) > 0 { + if episodeMembers, err = h.visibleEpisodeMembers(ctx, session, missing); err != nil { + return nil, err + } + missing = slices.DeleteFunc(missing, func(id string) bool { return episodeMembers[id] }) + if seasonEpisodes, err = h.collectionSeasonEpisodeIDs(ctx, session, missing); err != nil { + return nil, err + } + } } leaves := make([]string, 0, len(contentIDs)) + seen := make(map[string]bool, len(contentIDs)) + add := func(ids ...string) { + for _, id := range ids { + if !seen[id] { + seen[id] = true + leaves = append(leaves, id) + } + } + } for _, contentID := range contentIDs { switch itemType := memberTypes[contentID]; { case itemType == compatSeriesType: - leaves = append(leaves, seriesEpisodes[contentID]...) + add(seriesEpisodes[contentID]...) case isPlayableItemType(itemType) && query.allowsItemType(itemType): - leaves = append(leaves, contentID) + add(contentID) + case episodeMembers[contentID]: + add(contentID) + default: + add(seasonEpisodes[contentID]...) } } return leaves, nil @@ -1221,10 +1269,31 @@ func (h *ItemsHandler) visibleEpisodeIDs(ctx context.Context, session *Session, return visible, rows.Err() } +// visibleEpisodeMembers reports which of ids are episodes the viewer can +// play as collection members: those whose series they can see, under the +// same library, rating and type limits as the BoxSet's children, with a file +// in a library they may access. Without a database pool it checks the file +// alone, as visibleEpisodeIDs does. +func (h *ItemsHandler) visibleEpisodeMembers(ctx context.Context, session *Session, ids []string) (map[string]bool, error) { + pool := h.compatPool() + if pool == nil { + return h.visibleEpisodeIDs(ctx, session, ids) + } + members, err := catalog.NewItemRepository(pool).GetListedMembersByIDsWithAccess(ctx, ids, h.resolveAccessFilter(ctx, session)) + if err != nil { + return nil, err + } + visible := make(map[string]bool, len(members)) + for _, member := range members { + if member.Type == compatEpisodeType { + visible[member.ContentID] = true + } + } + return visible, nil +} + // collectionSeriesEpisodeIDs lists the visible episode IDs of each series -// member, regular seasons first and specials last. Series members were already -// access-filtered; each episode is checked too, since a series can span -// libraries with different access. +// member, in the order visibleSeriesEpisodes gives. func (h *ItemsHandler) collectionSeriesEpisodeIDs(ctx context.Context, session *Session, members []upstreamListItem) (map[string][]string, error) { var seriesIDs []string for _, member := range members { @@ -1232,6 +1301,26 @@ func (h *ItemsHandler) collectionSeriesEpisodeIDs(ctx context.Context, session * seriesIDs = append(seriesIDs, member.ContentID) } } + episodesBySeries, err := h.visibleSeriesEpisodes(ctx, session, seriesIDs) + if err != nil { + return nil, err + } + result := make(map[string][]string, len(episodesBySeries)) + for seriesID, episodes := range episodesBySeries { + ids := make([]string, 0, len(episodes)) + for _, episode := range episodes { + ids = append(ids, episode.ContentID) + } + result[seriesID] = ids + } + return result, nil +} + +// visibleSeriesEpisodes lists the visible episodes of each series, regular +// seasons first and specials last. The series were already access-filtered; +// each episode is checked too, since a series can span libraries with +// different access. +func (h *ItemsHandler) visibleSeriesEpisodes(ctx context.Context, session *Session, seriesIDs []string) (map[string][]*models.Episode, error) { if len(seriesIDs) == 0 || h.episodeRepo == nil { return nil, nil } @@ -1251,7 +1340,7 @@ func (h *ItemsHandler) collectionSeriesEpisodeIDs(ctx context.Context, session * return nil, err } - result := make(map[string][]string, len(episodesBySeries)) + result := make(map[string][]*models.Episode, len(episodesBySeries)) for seriesID, episodes := range episodesBySeries { kept := make([]*models.Episode, 0, len(episodes)) for _, episode := range episodes { @@ -1271,33 +1360,54 @@ func (h *ItemsHandler) collectionSeriesEpisodeIDs(ctx context.Context, session * } return cmp.Compare(a.EpisodeNumber, b.EpisodeNumber) }) - ids := make([]string, 0, len(kept)) - for _, episode := range kept { - ids = append(ids, episode.ContentID) + result[seriesID] = kept + } + return result, nil +} + +// collectionSeasonEpisodeIDs lists, for each of contentIDs that is a season +// the viewer can see, its visible episodes in order. +func (h *ItemsHandler) collectionSeasonEpisodeIDs(ctx context.Context, session *Session, contentIDs []string) (map[string][]string, error) { + seasons, err := h.fetchCompatSeasonListItems(ctx, session, contentIDs) + if err != nil || len(seasons) == 0 { + return nil, err + } + var seriesIDs []string + for _, season := range seasons { + seriesIDs = append(seriesIDs, season.SeriesID) + } + slices.Sort(seriesIDs) + episodesBySeries, err := h.visibleSeriesEpisodes(ctx, session, slices.Compact(seriesIDs)) + if err != nil { + return nil, err + } + result := make(map[string][]string, len(seasons)) + for seasonID, season := range seasons { + for _, episode := range episodesBySeries[season.SeriesID] { + if episode.SeasonID == seasonID { + result[seasonID] = append(result[seasonID], episode.ContentID) + } } - result[seriesID] = ids } return result, nil } // hydrateCollectionMembers resolves collection members to list items in the // given order, dropping any the session cannot see. Movies and series come -// from media_items. When episodesPossible, members missing there resolve as -// episodes, which reach a collection through episode-scoped smart queries or -// series expansion for Play all; the returned episode targets carry their -// season and series context. Stored collections pass false, since their -// members only reference media_items. -func (h *ItemsHandler) hydrateCollectionMembers(ctx context.Context, session *Session, contentIDs []string, episodesPossible bool) ([]upstreamListItem, map[string]compatEpisodeTarget, error) { +// from media_items; members missing there resolve as episodes, then as +// seasons. Episodes reach a collection through +// episode-scoped smart queries, series expansion for Play all, or a synced +// list of episodes; seasons only through a synced list. The returned +// episode targets carry their season and series context. +func (h *ItemsHandler) hydrateCollectionMembers(ctx context.Context, session *Session, contentIDs []string) ([]upstreamListItem, map[string]compatEpisodeTarget, error) { itemsByID, err := h.fetchCompatItemsByContentIDs(ctx, session, contentIDs, nil) if err != nil { return nil, nil, err } var missing []string - if episodesPossible { - for _, contentID := range contentIDs { - if _, ok := itemsByID[contentID]; !ok { - missing = append(missing, contentID) - } + for _, contentID := range contentIDs { + if _, ok := itemsByID[contentID]; !ok { + missing = append(missing, contentID) } } var episodeTargets map[string]compatEpisodeTarget @@ -1307,12 +1417,26 @@ func (h *ItemsHandler) hydrateCollectionMembers(ctx context.Context, session *Se return nil, nil, err } } + var seasons map[string]upstreamListItem + if len(missing) > len(episodeTargets) { + rest := make([]string, 0, len(missing)-len(episodeTargets)) + for _, contentID := range missing { + if _, ok := episodeTargets[contentID]; !ok { + rest = append(rest, contentID) + } + } + if seasons, err = h.fetchCompatSeasonListItems(ctx, session, rest); err != nil { + return nil, nil, err + } + } ordered := make([]upstreamListItem, 0, len(contentIDs)) for _, contentID := range contentIDs { if item, ok := itemsByID[contentID]; ok { ordered = append(ordered, item) } else if target, ok := episodeTargets[contentID]; ok { ordered = append(ordered, target.Item) + } else if season, ok := seasons[contentID]; ok { + ordered = append(ordered, season) } } return ordered, episodeTargets, nil @@ -1346,7 +1470,9 @@ func (h *ItemsHandler) writeListItemsPage(w http.ResponseWriter, r *http.Request items := make([]baseItemDTO, 0, len(listItems)) for _, item := range listItems { var dto baseItemDTO - if detail, ok := detailsByID[item.ContentID]; ok && detail != nil { + if item.Type == compatCatalogTypeSeason { + dto = h.mapper.seasonListItem(item, favorites[item.ContentID]) + } else if detail, ok := detailsByID[item.ContentID]; ok && detail != nil { h.rememberDetailImages(*detail) dto = h.mapper.itemFromDetailWithFields(*detail, favorites[item.ContentID], progress[item.ContentID], query.requestedFields) } else { diff --git a/internal/jellycompat/handlers_collections_members_db_test.go b/internal/jellycompat/handlers_collections_members_db_test.go new file mode 100644 index 00000000000..c66afe8b691 --- /dev/null +++ b/internal/jellycompat/handlers_collections_members_db_test.go @@ -0,0 +1,190 @@ +package jellycompat + +import ( + "context" + "fmt" + "net/url" + "slices" + "testing" + "time" + + "github.com/Silo-Server/silo-server/internal/access" + "github.com/Silo-Server/silo-server/internal/catalog" + "github.com/Silo-Server/silo-server/internal/config" +) + +// TestBoxSetChildrenListsEpisodeAndSeasonMembersDB: a stored collection's +// episode and season members are BoxSet children in curated order, sorted or +// not, as an Episode with its series and numbers and as a Season a client can +// open, and an episode of a series the viewer can't see (another library, or +// a rating above the viewer's) is neither listed nor counted. Play all plays +// an episode member as it is and a season member as its episodes, each once, +// and pages only what the viewer can play. +func TestBoxSetChildrenListsEpisodeAndSeasonMembersDB(t *testing.T) { + pool, suffix := jellyfin12CompatPool(t) + ctx := context.Background() + prefix := fmt.Sprintf("jf-boxset-members-%d", suffix) + series, hiddenSeries := prefix+"-series", prefix+"-hidden" + season, episode, hiddenEpisode := prefix+"-s1", prefix+"-s1e2", prefix+"-hidden-s1e1" + matureSeries, matureEpisode := prefix+"-mature", prefix+"-mature-s1e1" + + var tv, hidden int + for name, id := range map[string]*int{prefix: &tv, prefix + "-hidden": &hidden} { + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, TRUE) RETURNING id`, name).Scan(id); err != nil { + t.Fatalf("seed folder: %v", err) + } + } + collections := catalog.NewLibraryCollectionRepository(pool) + collection, err := collections.Create(ctx, catalog.CreateLibraryCollectionInput{ + LibraryID: tv, LibraryIDs: []int{tv, hidden}, Slug: prefix, Title: "Holiday", + CollectionType: "mdblist", Visibility: "visible", + }) + if err != nil { + t.Fatalf("create collection: %v", err) + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM library_collections WHERE id = $1`, collection.ID) + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = ANY($1)`, []string{series, hiddenSeries, matureSeries}) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = ANY($1)`, []int{tv, hidden}) + }) + jellyfin12Exec(t, pool, `INSERT INTO media_items (content_id, type, title, status, genres) VALUES ($1, 'series', 'The Series', 'matched', '{}'::text[]), ($2, 'series', 'Hidden Series', 'matched', '{}'::text[])`, series, hiddenSeries) + jellyfin12Exec(t, pool, `INSERT INTO media_items (content_id, type, title, status, genres, content_rating, content_rating_age) VALUES ($1, 'series', 'Mature Series', 'matched', '{}'::text[], 'TV-MA', 17)`, matureSeries) + jellyfin12Exec(t, pool, `INSERT INTO media_item_libraries (content_id, media_folder_id) VALUES ($1, $2), ($3, $4), ($5, $2)`, series, tv, hiddenSeries, hidden, matureSeries) + jellyfin12Exec(t, pool, `INSERT INTO episodes (content_id, series_id, season_number, episode_number, title, overview, runtime, still_path, imdb_id, tmdb_id, tvdb_id) VALUES ($1, $2, 1, 1, 'Mature One', '', 0, '', '', '', '')`, matureEpisode, matureSeries) + jellyfin12Exec(t, pool, `INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $2)`, matureEpisode, tv) + jellyfin12Exec(t, pool, `INSERT INTO seasons (content_id, series_id, season_number, title, poster_path) VALUES ($1, $2, 1, 'Season 1', 'season-1.jpg')`, season, series) + jellyfin12Exec(t, pool, `INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title, overview, runtime, still_path, imdb_id, tmdb_id, tvdb_id) VALUES ($1, $2, $3, 1, 2, 'Two', '', 0, '', '', '', '')`, episode, series, season) + jellyfin12Exec(t, pool, `INSERT INTO episodes (content_id, series_id, season_number, episode_number, title, overview, runtime, still_path, imdb_id, tmdb_id, tvdb_id) VALUES ($1, $2, 1, 1, 'Hidden One', '', 0, '', '', '', '')`, hiddenEpisode, hiddenSeries) + jellyfin12Exec(t, pool, `INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title, overview, runtime, still_path, imdb_id, tmdb_id, tvdb_id) VALUES ($1, $2, $3, 1, 3, 'Three', '', 0, '', '', '', '')`, prefix+"-s1e3", series, season) + jellyfin12Exec(t, pool, `INSERT INTO episodes (content_id, series_id, season_number, episode_number, title, overview, runtime, still_path, imdb_id, tmdb_id, tvdb_id) VALUES ($1, $2, 2, 1, 'Elsewhere', '', 0, '', '', '', '')`, prefix+"-s2e1", series) + jellyfin12Exec(t, pool, `INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $2), ($3, $4), ($5, $2), ($6, $4)`, episode, tv, hiddenEpisode, hidden, prefix+"-s1e3", prefix+"-s2e1") + if err := collections.ReplaceItems(ctx, collection.ID, []catalog.LibraryCollectionItemInput{ + {MediaItemID: matureEpisode, Kind: catalog.CollectionMemberEpisode}, + {MediaItemID: hiddenEpisode, Kind: catalog.CollectionMemberEpisode}, + {MediaItemID: episode, Kind: catalog.CollectionMemberEpisode}, + {MediaItemID: prefix + "-s2e1", Kind: catalog.CollectionMemberEpisode}, + {MediaItemID: season, Kind: catalog.CollectionMemberSeason}, + }); err != nil { + t.Fatalf("fill collection: %v", err) + } + + viewer := func(context.Context, int, string) catalog.AccessFilter { + return catalog.AccessFilter{AllowedLibraryIDs: []int{tv}, MaturityLimits: access.MaturityLimits{MaxContentRating: "PG", AllowUnratedContent: true}} + } + browse := catalog.NewBrowseRepository(pool) + codec := NewResourceIDCodec() + h := &ItemsHandler{ + content: &visibleLibrariesContent{ + directContentService: &directContentService{browseRepo: browse, accessFilter: viewer}, + libraries: []upstreamUserLibrary{{ID: tv, Name: "TV", Type: "series"}}, + }, + userData: &mockUserDataService{}, + codec: codec, + mapper: newMapper(codec, &config.Config{}), + images: NewImageCache(time.Hour, time.Now), + collections: collections, + browseRepo: browse, + episodeRepo: catalog.NewEpisodeRepository(pool), + accessFilter: viewer, + } + parentID := codec.EncodeStringID(EncodedIDCollection, collection.ID) + + seriesID := codec.EncodeStringID(EncodedIDItem, series) + want := []boxSetChild{ + {id: codec.EncodeStringID(EncodedIDItem, episode), kind: "Episode", name: "Two", seriesID: seriesID, index: 2, parentIndex: 1}, + {id: codec.EncodeStringID(EncodedIDSeason, season), kind: "Season", name: "Season 1", seriesID: seriesID, index: 1, primary: true}, + } + for _, query := range []string{"", "&SortBy=SortName"} { + result := performItemsRequest(t, h, "/Items?ParentId="+url.QueryEscape(parentID)+query) + if got := boxSetChildren(result.Items); fmt.Sprint(got) != fmt.Sprint(want) || result.TotalRecordCount != 2 { + t.Fatalf("children%s = %+v (total %d), want %+v (total 2)", query, got, result.TotalRecordCount, want) + } + } + // A season without its own poster advertises none: the image endpoint + // serves a season's own poster, never its series'. + jellyfin12Exec(t, pool, `UPDATE seasons SET poster_path = '' WHERE content_id = $1`, season) + jellyfin12Exec(t, pool, `UPDATE media_items SET poster_path = 'series.jpg' WHERE content_id = $1`, series) + want[1].primary = false + if got := boxSetChildren(performItemsRequest(t, h, "/Items?ParentId="+url.QueryEscape(parentID)).Items); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("children of a posterless season = %+v, want %+v", got, want) + } + + leaves := performItemsRequest(t, h, "/Items?ParentId="+url.QueryEscape(parentID)+"&Recursive=true&Filters=IsNotFolder") + names := make([]string, 0, len(leaves.Items)) + for _, item := range leaves.Items { + names = append(names, item.Type+" "+item.Name) + } + if want := []string{"Episode Two", "Episode Three"}; !slices.Equal(names, want) || leaves.TotalRecordCount != 2 { + t.Errorf("play all = %v (total %d), want %v (total 2)", names, leaves.TotalRecordCount, want) + } + first := performItemsRequest(t, h, "/Items?ParentId="+url.QueryEscape(parentID)+"&Recursive=true&Filters=IsNotFolder&Limit=1") + if len(first.Items) != 1 || first.Items[0].Name != "Two" || first.TotalRecordCount != 2 { + t.Errorf("play all first page = %d items (total %d), want Two (total 2)", len(first.Items), first.TotalRecordCount) + } +} + +// boxSetChild is what a BoxSet child shows of itself. +type boxSetChild struct { + id, kind, name, seriesID string + index, parentIndex int + primary bool +} + +func boxSetChildren(items []baseItemDTO) []boxSetChild { + got := make([]boxSetChild, 0, len(items)) + for _, item := range items { + c := boxSetChild{id: item.ID, kind: item.Type, name: item.Name, seriesID: item.SeriesID, primary: item.ImageTags["Primary"] != ""} + if item.IndexNumber != nil { + c.index = *item.IndexNumber + } + if item.ParentIndexNumber != nil { + c.parentIndex = *item.ParentIndexNumber + } + got = append(got, c) + } + return got +} + +// TestCompatSeasonListItemsNeedAnEpisodeTheViewerCanOpenDB: a season member +// of a series that spans libraries is listed only when one of its episodes +// sits in a library the viewer may open, and counts only those episodes. +func TestCompatSeasonListItemsNeedAnEpisodeTheViewerCanOpenDB(t *testing.T) { + pool, suffix := jellyfin12CompatPool(t) + ctx := context.Background() + prefix := fmt.Sprintf("jf-season-access-%d", suffix) + series, open, closed := prefix+"-series", prefix+"-s1", prefix+"-s2" + + var tv, hidden int + for name, id := range map[string]*int{prefix: &tv, prefix + "-hidden": &hidden} { + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, TRUE) RETURNING id`, name).Scan(id); err != nil { + t.Fatalf("seed folder: %v", err) + } + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = $1`, series) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = ANY($1)`, []int{tv, hidden}) + }) + jellyfin12Exec(t, pool, `INSERT INTO media_items (content_id, type, title, status, genres) VALUES ($1, 'series', 'The Series', 'matched', '{}'::text[])`, series) + jellyfin12Exec(t, pool, `INSERT INTO media_item_libraries (content_id, media_folder_id) VALUES ($1, $2), ($1, $3)`, series, tv, hidden) + jellyfin12Exec(t, pool, `INSERT INTO seasons (content_id, series_id, season_number, title) VALUES ($1, $3, 1, 'Season 1'), ($2, $3, 2, 'Season 2')`, open, closed, series) + jellyfin12Exec(t, pool, `INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title, overview, runtime, still_path, imdb_id, tmdb_id, tvdb_id) VALUES + ($1, $4, $5, 1, 1, 'One', '', 0, '', '', '', ''), ($2, $4, $5, 1, 2, 'Two', '', 0, '', '', '', ''), ($3, $4, $6, 2, 1, 'Closed', '', 0, '', '', '', '')`, + prefix+"-s1e1", prefix+"-s1e2", prefix+"-s2e1", series, open, closed) + jellyfin12Exec(t, pool, `INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $4), ($2, $5), ($3, $5)`, + prefix+"-s1e1", prefix+"-s1e2", prefix+"-s2e1", tv, hidden) + + viewer := func(context.Context, int, string) catalog.AccessFilter { + return catalog.AccessFilter{AllowedLibraryIDs: []int{tv}} + } + h := &ItemsHandler{browseRepo: catalog.NewBrowseRepository(pool), accessFilter: viewer} + seasons, err := h.fetchCompatSeasonListItems(ctx, &Session{}, []string{open, closed}) + if err != nil { + t.Fatalf("fetchCompatSeasonListItems: %v", err) + } + item, ok := seasons[open] + if len(seasons) != 1 || !ok || item.EpisodeCount == nil || *item.EpisodeCount != 1 { + t.Fatalf("seasons = %+v, want only %s with one episode", seasons, open) + } +} diff --git a/internal/jellycompat/mapping.go b/internal/jellycompat/mapping.go index 542e4dde4b8..01ef892b113 100644 --- a/internal/jellycompat/mapping.go +++ b/internal/jellycompat/mapping.go @@ -544,6 +544,29 @@ func (m *mapper) seasonFromUpstream(season upstreamSeason, seriesID string, isFa return dto } +// seasonListItem maps a season list item, such as a collection's season +// member, to the Season DTO the series' season list gives, with its series' +// name. +func (m *mapper) seasonListItem(item upstreamListItem, isFavorite bool) baseItemDTO { + season := upstreamSeason{ + ContentID: item.ContentID, + Title: item.Title, + PosterURL: item.PosterURL, + PosterPath: item.PosterPath, + PosterThumbhash: item.PosterThumbhash, + UpdatedAt: item.UpdatedAt, + } + if item.SeasonNumber != nil { + season.SeasonNumber = *item.SeasonNumber + } + if item.EpisodeCount != nil { + season.EpisodeCount = *item.EpisodeCount + } + dto := m.seasonFromUpstream(season, item.SeriesID, isFavorite) + dto.SeriesName = item.SeriesTitle + return dto +} + func (m *mapper) episodeFromUpstream(ep upstreamEpisode, isFavorite bool, progress *upstreamProgress) baseItemDTO { dto := baseItemDTO{ ID: m.codec.EncodeStringID(EncodedIDItem, ep.ContentID), diff --git a/internal/mdblist/lists.go b/internal/mdblist/lists.go index fe581cbd629..31dd1841836 100644 --- a/internal/mdblist/lists.go +++ b/internal/mdblist/lists.go @@ -31,6 +31,9 @@ const ( // The media types AccountList reports, as MDBList names them. mediaTypeMovie = "movie" mediaTypeShow = "show" + // The entry media types of a list's seasons and episodes. + mediaTypeSeason = "season" + mediaTypeEpisode = "episode" ) // AccountList is a list of the account that owns the API key: one of its @@ -62,15 +65,20 @@ type accountListJSON struct { Private bool `json:"private"` } -// listItemJSON is one movie or show of a /lists/{id}/items page. +// listItemJSON is one movie, show, season or episode of a /lists/{id}/items +// page. A season or episode carries its own TMDB ID in id and names its show +// by TMDB ID in show_id. type listItemJSON struct { - ID flexInt `json:"id"` - Rank flexInt `json:"rank"` - Title string `json:"title"` - IMDbID string `json:"imdb_id"` - TVDBID flexInt `json:"tvdb_id"` - ReleaseYear flexInt `json:"release_year"` - IDs struct { + ID flexInt `json:"id"` + Rank flexInt `json:"rank"` + Title string `json:"title"` + IMDbID string `json:"imdb_id"` + TVDBID flexInt `json:"tvdb_id"` + ReleaseYear flexInt `json:"release_year"` + ShowID flexInt `json:"show_id"` + SeasonNumber flexInt `json:"season_number"` + EpisodeNumber flexInt `json:"episode_number"` + IDs struct { IMDb string `json:"imdb"` TMDB flexInt `json:"tmdb"` TVDB flexInt `json:"tvdb"` @@ -80,6 +88,8 @@ type listItemJSON struct { type listItemsPage struct { Movies []listItemJSON `json:"movies"` Shows []listItemJSON `json:"shows"` + Seasons []listItemJSON `json:"seasons"` + Episodes []listItemJSON `json:"episodes"` Pagination *struct { NextCursor string `json:"next_cursor"` HasMore *bool `json:"has_more"` @@ -155,25 +165,39 @@ func (c *Client) listItemsByID(ctx context.Context, key string, id int64, maxEnt // cursor holds when the size changes, so the last page is trimmed below // instead of asked for short. limit := min(listItemsPageSize, maxEntries) - for len(entries) < maxEntries { + // read counts the items MDBList sent, skipped ones too: the offset and + // the bound go by it, so a page of unusable items still moves on. + read := 0 + for read < maxEntries { q := url.Values{"limit": {strconv.Itoa(limit)}} if cursor != "" { q.Set("cursor", cursor) - } else if len(entries) > 0 { - q.Set("offset", strconv.Itoa(len(entries))) + } else if read > 0 { + q.Set("offset", strconv.Itoa(read)) } var page listItemsPage header, err := c.getJSONHeader(ctx, key, path, q, &page) if err != nil { return nil, err } - fetched := len(page.Movies) + len(page.Shows) + fetched := len(page.Movies) + len(page.Shows) + len(page.Seasons) + len(page.Episodes) + read += fetched for _, item := range page.Movies { entries = append(entries, item.entry(mediaTypeMovie)) } for _, item := range page.Shows { entries = append(entries, item.entry(mediaTypeShow)) } + for _, item := range page.Seasons { + if entry, ok := item.seasonEntry(); ok { + entries = append(entries, entry) + } + } + for _, item := range page.Episodes { + if entry, ok := item.episodeEntry(); ok { + entries = append(entries, entry) + } + } if fetched == 0 { break } @@ -241,6 +265,39 @@ func (i listItemJSON) entry(mediaType string) collectionutil.MDBListEntry { return entry } +// episodeEntry maps an API episode onto an entry. An episode without its +// show or episode number names nothing Silo can match. +func (i listItemJSON) episodeEntry() (collectionutil.MDBListEntry, bool) { + if i.ShowID <= 0 || i.EpisodeNumber <= 0 || i.SeasonNumber < 0 { + return collectionutil.MDBListEntry{}, false + } + return collectionutil.MDBListEntry{ + Rank: int(i.Rank), + MediaType: mediaTypeEpisode, + Title: i.Title, + Episode: &collectionutil.MDBListEpisode{ + TMDBID: int(i.ID), + ShowTMDBID: int(i.ShowID), + Season: int(i.SeasonNumber), + Episode: int(i.EpisodeNumber), + }, + }, true +} + +// seasonEntry maps an API season onto an entry. A season without its show +// names nothing Silo can match. +func (i listItemJSON) seasonEntry() (collectionutil.MDBListEntry, bool) { + if i.ShowID <= 0 || i.SeasonNumber < 0 { + return collectionutil.MDBListEntry{}, false + } + return collectionutil.MDBListEntry{ + Rank: int(i.Rank), + MediaType: mediaTypeSeason, + Title: i.Title, + Season: &collectionutil.MDBListSeason{TMDBID: int(i.ID), ShowTMDBID: int(i.ShowID), Season: int(i.SeasonNumber)}, + }, true +} + // AccountLists returns the lists of the account that owns the configured // key: its own (private ones included), then the ones it liked, without // duplicates. External lists are left out; they sync through the feed. diff --git a/internal/mdblist/lists_test.go b/internal/mdblist/lists_test.go index 36cc6dae11e..44a6922c792 100644 --- a/internal/mdblist/lists_test.go +++ b/internal/mdblist/lists_test.go @@ -72,6 +72,89 @@ func TestListItemsResolvesTwinsAndMergesPagesInRankOrder(t *testing.T) { } } +// An episode list's /items page carries its episodes and seasons in arrays +// of their own, each named by its own TMDB ID (id), its show's TMDB ID and +// its numbers (the episode shape seen on the live API). A list with nothing in it is just +// empty: there is no other endpoint to try. +func TestListItemsReadsAnEpisodeList(t *testing.T) { + t.Parallel() + + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/lists/alice/holiday-episodes": + _, _ = w.Write([]byte(`[{"id":21,"mediatype":null,"movies":0,"shows":0,"episodes":2}]`)) + case "/lists/21/items": + _, _ = w.Write([]byte(`{"movies":[],"shows":[],"seasons":[ + {"id":7001,"show_id":1399,"mediatype":"season","title":"Season 3","rank":3,"season_number":3} + ],"episodes":[ + {"id":9001,"show_id":"1400","mediatype":"episode","imdb_id":null,"tvdb_id":null,"title":"Winter Special","rank":2,"season_number":0,"episode_number":3}, + {"id":9002,"show_id":1668,"mediatype":"episode","imdb_id":null,"tvdb_id":null,"title":"The Holiday One","rank":1,"season_number":5,"episode_number":10} + ],"pagination":{"has_more":false}}`)) + case "/lists/22/items": + _, _ = w.Write([]byte(`{"movies":[],"shows":[],"seasons":[],"episodes":[],"pagination":{"has_more":false}}`)) + default: + t.Errorf("unexpected request %s?%s", r.URL.Path, r.URL.RawQuery) + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) + + entries, err := c.ListItems(context.Background(), collectionutil.MDBListRef{User: "alice", Slug: "holiday-episodes"}, 0) + if err != nil { + t.Fatalf("ListItems: %v", err) + } + wantEpisodes := []collectionutil.MDBListEpisode{{TMDBID: 9002, ShowTMDBID: 1668, Season: 5, Episode: 10}, {TMDBID: 9001, ShowTMDBID: 1400, Season: 0, Episode: 3}} + wantSeason := collectionutil.MDBListSeason{TMDBID: 7001, ShowTMDBID: 1399, Season: 3} + if len(entries) != 3 { + t.Fatalf("entries = %+v, want two episodes and a season", entries) + } + for i, want := range wantEpisodes { + if e := entries[i]; e.ItemType() != "episode" || e.Episode == nil || *e.Episode != want { + t.Errorf("entry %d = %+v (episode %+v), want episode %+v", i, e, e.Episode, want) + } + } + if e := entries[2]; e.ItemType() != "season" || e.Season == nil || *e.Season != wantSeason { + t.Errorf("entry 2 = %+v (season %+v), want season %+v", e, e.Season, wantSeason) + } + + if entries, err := c.ListItems(context.Background(), collectionutil.MDBListRef{ID: 22}, 0); err != nil || len(entries) != 0 { + t.Fatalf("empty list = %+v, %v; want no entries and no error", entries, err) + } +} + +// Offset paging counts the items MDBList sent, including ones it skips, so a +// page of unusable episodes doesn't make it ask for the same page again. +func TestListItemsPagesPastSkippedItems(t *testing.T) { + t.Parallel() + + var offsets []string + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + offsets = append(offsets, r.URL.Query().Get("offset")) + if len(offsets) > 2 { + t.Errorf("request %d: paging should have ended", len(offsets)) + _, _ = w.Write([]byte(`{"pagination":{"has_more":false}}`)) + return + } + if r.URL.Query().Get("offset") == "" { + _, _ = w.Write([]byte(`{"episodes":[ + {"id":1,"show_id":0,"rank":1,"season_number":1,"episode_number":1}, + {"id":2,"show_id":0,"rank":2,"season_number":1,"episode_number":2} + ],"pagination":{"has_more":true}}`)) + return + } + _, _ = w.Write([]byte(`{"episodes":[ + {"id":3,"show_id":1668,"rank":3,"season_number":5,"episode_number":10} + ],"pagination":{"has_more":false}}`)) + }) + + entries, err := c.ListItems(context.Background(), collectionutil.MDBListRef{ID: 21}, 0) + if err != nil { + t.Fatalf("ListItems: %v", err) + } + if !slices.Equal(offsets, []string{"", "2"}) || len(entries) != 1 { + t.Fatalf("offsets = %q, entries = %+v; want offsets [\"\" \"2\"] and one entry", offsets, entries) + } +} + // A list read for fewer entries than it holds asks for the same page size on // every page and trims the last one, so a cursor is never sent with a size // other than the one it was issued for. diff --git a/internal/metadata/episode_renumber_db_test.go b/internal/metadata/episode_renumber_db_test.go index d7c857059f0..24d9876a796 100644 --- a/internal/metadata/episode_renumber_db_test.go +++ b/internal/metadata/episode_renumber_db_test.go @@ -156,6 +156,20 @@ func TestApplyEpisodeMergesDB(t *testing.T) { } t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM media_files WHERE id = $1`, fileID) }) + // A synced collection holds both rows; the merge leaves it the kept one. + collectionID := fmt.Sprintf("merge-collection-%d", nonce) + if _, err := pool.Exec(ctx, `INSERT INTO library_collections (id, library_id, slug, title, collection_type) + VALUES ($1, $2, $1, 'Merged', 'mdblist')`, collectionID, folder); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = pool.Exec(context.Background(), `DELETE FROM library_collections WHERE id = $1`, collectionID) + }) + if _, err := pool.Exec(ctx, `INSERT INTO library_collection_items (collection_id, episode_id, position, source_rank) + VALUES ($1, $2, 0, 10), ($1, $3, 1, 20)`, collectionID, keep, duplicate); err != nil { + t.Fatal(err) + } + userID := insertRenumberTestProgress(t, pool, "merge", nonce, duplicate, 700, 1440) // An admin's German description on the duplicate goes with it. if _, err := pool.Exec(ctx, `INSERT INTO episode_localizations (episode_content_id, language, title, overview, overview_source) @@ -200,6 +214,21 @@ func TestApplyEpisodeMergesDB(t *testing.T) { overview != "Meine Beschreibung" || source != "manual" { t.Fatalf("German localization on %s = %q (%s, %v), want the admin's", keep, overview, source, err) } + var members []string + rows, err := pool.Query(ctx, `SELECT episode_id FROM library_collection_items WHERE collection_id = $1`, collectionID) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + t.Fatal(err) + } + members = append(members, id) + } + if err := rows.Err(); err != nil || len(members) != 1 || members[0] != keep { + t.Fatalf("collection members = %v (%v), want only %s", members, err, keep) + } } // An order inserts a new episode before the pilot: the pilot shifts to S1E2 diff --git a/internal/metadata/provider_id_integrity.go b/internal/metadata/provider_id_integrity.go index 51e4a64b611..b3dc1b0f180 100644 --- a/internal/metadata/provider_id_integrity.go +++ b/internal/metadata/provider_id_integrity.go @@ -801,7 +801,7 @@ var mediaItemMergeSteps = []mediaItemMergeStep{ FROM library_collection_items WHERE media_item_id = $1 GROUP BY collection_id - ON CONFLICT (collection_id, media_item_id) DO UPDATE + ON CONFLICT (collection_id, member_id) DO UPDATE SET position = LEAST(library_collection_items.position, EXCLUDED.position), source_rank = LEAST(library_collection_items.source_rank, EXCLUDED.source_rank), updated_at = NOW()`}, diff --git a/internal/models/library_collection.go b/internal/models/library_collection.go index b982f3cbcfd..e467502acc4 100644 --- a/internal/models/library_collection.go +++ b/internal/models/library_collection.go @@ -81,11 +81,15 @@ type LibraryCollectionGroup struct { // LibraryCollectionItem is a resolved membership entry for a library collection. type LibraryCollectionItem struct { CollectionID string - MediaItemID string - Position int - SourceRank int - CreatedAt time.Time - UpdatedAt time.Time + // MediaItemID is the member's content ID: a title's, an episode's or a + // season's, as Kind says. + MediaItemID string + // Kind is "" for a title (movie or series), "episode" or "season". + Kind string + Position int + SourceRank int + CreatedAt time.Time + UpdatedAt time.Time } // LibraryCollectionSyncRun captures the outcome of a collection sync/import run. diff --git a/internal/sections/collection_rail_members_db_test.go b/internal/sections/collection_rail_members_db_test.go new file mode 100644 index 00000000000..131f99648cf --- /dev/null +++ b/internal/sections/collection_rail_members_db_test.go @@ -0,0 +1,101 @@ +package sections + +import ( + "context" + "encoding/json" + "fmt" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Silo-Server/silo-server/internal/catalog" +) + +// TestLibraryCollectionRailShowsEpisodeAndSeasonMembersDB checks that a row +// showing a server collection lists its episode and season members with its +// titles, in curated order and under the collection's sort, and leaves out +// an episode of a series the viewer can't open. +func TestLibraryCollectionRailShowsEpisodeAndSeasonMembersDB(t *testing.T) { + dsn := os.Getenv("SILO_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("SILO_TEST_DATABASE_URL is not set") + } + resetResolvedListCacheForTest() + t.Cleanup(resetResolvedListCacheForTest) + ctx := t.Context() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + + prefix := fmt.Sprintf("member-rail-%d", time.Now().UnixNano()) + movie, series, hiddenSeries := prefix+"-movie", prefix+"-series", prefix+"-hidden" + season, episode, hiddenEpisode := prefix+"-s1", prefix+"-s1e2", prefix+"-hidden-s1e1" + var movies, tv, hidden int + for name, id := range map[string]*int{prefix + "-movies": &movies, prefix + "-tv": &tv, prefix + "-hidden": &hidden} { + if err := pool.QueryRow(ctx, `INSERT INTO media_folders (type, name, enabled) VALUES ('series', $1, true) RETURNING id`, name).Scan(id); err != nil { + t.Fatal(err) + } + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = pool.Exec(cleanup, `DELETE FROM library_collections WHERE slug LIKE $1`, prefix+"%") + _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id = ANY($1)`, []string{movie, series, hiddenSeries}) + _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id = ANY($1)`, []int{movies, tv, hidden}) + }) + for _, q := range []struct { + sql string + args []any + }{ + {`INSERT INTO media_items (content_id, type, title, status, genres) VALUES ($1, 'movie', 'Alpha Movie', 'matched', '{}'::text[]), ($2, 'series', 'Show', 'matched', '{}'::text[]), ($3, 'series', 'Hidden', 'matched', '{}'::text[])`, []any{movie, series, hiddenSeries}}, + {`INSERT INTO media_item_libraries (content_id, media_folder_id) VALUES ($1, $2), ($3, $4), ($5, $6)`, []any{movie, movies, series, tv, hiddenSeries, hidden}}, + {`INSERT INTO seasons (content_id, series_id, season_number, title) VALUES ($1, $2, 1, 'Season 1')`, []any{season, series}}, + {`INSERT INTO episodes (content_id, series_id, season_id, season_number, episode_number, title) VALUES ($1, $2, $3, 1, 2, 'Two')`, []any{episode, series, season}}, + {`INSERT INTO episodes (content_id, series_id, season_number, episode_number, title) VALUES ($1, $2, 1, 1, 'Hidden One')`, []any{hiddenEpisode, hiddenSeries}}, + {`INSERT INTO episode_libraries (episode_id, media_folder_id) VALUES ($1, $2), ($3, $4)`, []any{episode, tv, hiddenEpisode, hidden}}, + } { + if _, err := pool.Exec(ctx, q.sql, q.args...); err != nil { + t.Fatalf("seed: %v", err) + } + } + + repo := catalog.NewLibraryCollectionRepository(pool) + fetcher := NewFetcher(pool) + fetcher.CollectionRepo = repo + viewer := catalog.AccessFilter{AllowedLibraryIDs: []int{movies, tv}} + for _, tc := range []struct { + name string + sort json.RawMessage + want []string + }{ + {"curated", nil, []string{episode, movie, season}}, + {"by title", json.RawMessage(`{"field":"title","order":"asc"}`), []string{movie, season, episode}}, + } { + t.Run(tc.name, func(t *testing.T) { + c, err := repo.Create(ctx, catalog.CreateLibraryCollectionInput{LibraryID: tv, LibraryIDs: []int{movies, tv, hidden}, + Slug: prefix + "-" + tc.name, Title: "Holiday " + tc.name, CollectionType: "mdblist", Visibility: "visible", SortConfig: tc.sort}) + if err != nil { + t.Fatal(err) + } + if err := repo.ReplaceItems(ctx, c.ID, []catalog.LibraryCollectionItemInput{ + {MediaItemID: episode, Kind: catalog.CollectionMemberEpisode}, + {MediaItemID: hiddenEpisode, Kind: catalog.CollectionMemberEpisode}, + {MediaItemID: movie}, + {MediaItemID: season, Kind: catalog.CollectionMemberSeason}, + }); err != nil { + t.Fatal(err) + } + got, err := fetcher.FetchOne(ctx, ResolvedSection{ + ID: prefix + "-" + tc.name, SectionType: SectionCollection, Title: "Row", ItemLimit: 5, + Config: json.RawMessage(fmt.Sprintf(`{"library_collection_id":%q}`, c.ID)), + }, nil, nil, 0, "", viewer) + if err != nil { + t.Fatal(err) + } + assertContentIDs(t, "rail", railContentIDs(got.Items), tc.want...) + }) + } +} diff --git a/internal/sections/fetcher.go b/internal/sections/fetcher.go index ee25f1c714e..f82e57ad4d5 100644 --- a/internal/sections/fetcher.go +++ b/internal/sections/fetcher.go @@ -1471,8 +1471,22 @@ func (f *Fetcher) fetchCollection(ctx context.Context, s ResolvedSection, librar } contentIDs := make([]string, 0, len(collectionItems)) + holdsEpisodes := false for _, item := range collectionItems { contentIDs = append(contentIDs, item.MediaItemID) + holdsEpisodes = holdsEpisodes || item.Kind != "" + } + if holdsEpisodes { + // Episodes and seasons are no media items, so the readers below + // would leave them out. + items, total, err := catalog.PreviewLibraryCollectionMembers(ctx, f.pool, collection.ID, catalog.QueryDefinition{Sort: membership.Sort}, queryAccess, s.ItemLimit, membership.Sort.Field != "") + if err != nil { + return nil, 0, err + } + if membership.Sort.Field == "" { + total = len(items) + } + return items, total, nil } if membership.Sort.Field != "" { items, total, err := catalog.QueryCollectionItemsBySort(ctx, f.pool, contentIDs, membership.Sort, queryAccess, s.ItemLimit, "") diff --git a/internal/shuffle/pool.go b/internal/shuffle/pool.go index 810cb0adee5..0d98369ffc3 100644 --- a/internal/shuffle/pool.go +++ b/internal/shuffle/pool.go @@ -26,10 +26,11 @@ type pool struct { seriesID string seasonNumber int hasSeason bool - // Collection members: movies play as themselves, a series plays its - // episodes, an episode plays itself. + // Collection members: movies play as themselves, a series or season + // plays its episodes, an episode plays itself. movieIDs []string seriesIDs []string + seasonIDs []string episodeIDs []string } @@ -172,12 +173,14 @@ func (s *Service) resolveCollection(ctx context.Context, scope Scope, access cat p.movieIDs = append(p.movieIDs, item.ContentID) case itemTypeSeries: p.seriesIDs = append(p.seriesIDs, item.ContentID) + case itemTypeSeason: + p.seasonIDs = append(p.seasonIDs, item.ContentID) case itemTypeEpisode: p.episodeIDs = append(p.episodeIDs, item.ContentID) } } p.movies = len(p.movieIDs) > 0 - p.episodes = len(p.seriesIDs) > 0 || len(p.episodeIDs) > 0 + p.episodes = len(p.seriesIDs) > 0 || len(p.seasonIDs) > 0 || len(p.episodeIDs) > 0 return scopeInfo{pool: p, title: title}, nil } @@ -345,11 +348,14 @@ func episodeCandidates(p pool, access catalog.AccessFilter, sampled bool, args * fmt.Sprintf("e.season_number = %s", bind(args, p.seasonNumber))) case p.seriesID != "": conditions = append(conditions, fmt.Sprintf("e.series_id = %s", bind(args, p.seriesID))) - case len(p.seriesIDs) > 0 || len(p.episodeIDs) > 0: + case len(p.seriesIDs) > 0 || len(p.seasonIDs) > 0 || len(p.episodeIDs) > 0: var members []string if len(p.seriesIDs) > 0 { members = append(members, fmt.Sprintf("e.series_id = ANY(%s)", bind(args, p.seriesIDs))) } + if len(p.seasonIDs) > 0 { + members = append(members, fmt.Sprintf("e.season_id = ANY(%s)", bind(args, p.seasonIDs))) + } if len(p.episodeIDs) > 0 { members = append(members, fmt.Sprintf("e.content_id = ANY(%s)", bind(args, p.episodeIDs))) } @@ -365,6 +371,7 @@ func episodeCandidates(p pool, access catalog.AccessFilter, sampled bool, args * const ( itemTypeMovie = "movie" itemTypeSeries = "series" + itemTypeSeason = "season" itemTypeEpisode = "episode" ) diff --git a/internal/usercollections/sync.go b/internal/usercollections/sync.go index 35711d641f1..3e71bdc00f2 100644 --- a/internal/usercollections/sync.go +++ b/internal/usercollections/sync.go @@ -316,6 +316,12 @@ func (s *Service) matchMDBList(ctx context.Context, userID int, collection *user // the owner profile's MDBList connection. Its errors are the messages the // sync stores, which say what to change. func (s *Service) readMDBListWithOwnerConnection(ctx context.Context, userID int, ownerProfileID string, ref collectionutil.MDBListRef, maxEntries int, feedErr *collectionutil.MDBListFeedError) ([]collectionutil.MDBListEntry, error) { + if feedErr == nil { + // The feed answered empty. The connection reads lists through the + // watch provider plugin, which returns no episodes either, so an + // episode list stays empty here. + return nil, nil + } if s.MDBList == nil || ownerProfileID == "" { return nil, feedErr } diff --git a/migrations/sql/20261206153438_library_collection_episode_season_members.sql b/migrations/sql/20261206153438_library_collection_episode_season_members.sql new file mode 100644 index 00000000000..d86e751d5d7 --- /dev/null +++ b/migrations/sql/20261206153438_library_collection_episode_season_members.sql @@ -0,0 +1,96 @@ +-- +goose Up +-- A synced library collection can hold episodes and seasons as well as titles +-- (an MDBList list of episodes). Each kind of member gets its own column with +-- its own foreign key, so a content-ID rekey or a delete of the episode, +-- season, or title still moves or removes the member through the cascade. +-- Exactly one of the three is set, and member_id is the one that is. +-- +-- Existing rows are titles: media_item_id stays set and member_id equals it, +-- so nothing is backfilled. Adding the stored generated column rewrites the +-- table under its ACCESS EXCLUSIVE lock; it holds one row per member, small +-- next to the catalog tables. +ALTER TABLE public.library_collection_items + DROP CONSTRAINT library_collection_items_pkey, + ALTER COLUMN media_item_id DROP NOT NULL, + ADD COLUMN episode_id text COLLATE "C" + REFERENCES public.episodes (content_id) ON UPDATE CASCADE ON DELETE CASCADE, + ADD COLUMN season_id text COLLATE "C" + REFERENCES public.seasons (content_id) ON UPDATE CASCADE ON DELETE CASCADE, + ADD COLUMN member_id text COLLATE "C" + GENERATED ALWAYS AS (COALESCE(media_item_id, episode_id, season_id)) STORED, + ADD CONSTRAINT library_collection_items_one_member + CHECK (num_nonnulls(media_item_id, episode_id, season_id) = 1); + +ALTER TABLE public.library_collection_items + ADD CONSTRAINT library_collection_items_pkey PRIMARY KEY (collection_id, member_id); +-- Servers of the previous release write titles with +-- ON CONFLICT (collection_id, media_item_id), which needs a unique index on +-- exactly those columns. Keeping one lets them share this schema during a +-- rolling upgrade. Episode and season members leave media_item_id NULL, and +-- NULLs are distinct, so they never collide here. +CREATE UNIQUE INDEX library_collection_items_media_item_key + ON public.library_collection_items (collection_id, media_item_id); +-- The same servers replace a collection's members by deleting every row whose +-- media_item_id their list leaves out, which an episode or season member never +-- matches, so syncing the list would empty the collection. This trigger +-- refuses a direct delete of an episode or season member unless the +-- transaction sets silo.collection_member_writes, as this release's writers +-- do; the older server's sync then fails and keeps the members. Deletes that +-- cascade from an episode, season or collection run nested inside another +-- trigger and go through. +-- +goose StatementBegin +CREATE FUNCTION public.library_collection_items_guard_member_delete() RETURNS trigger + LANGUAGE plpgsql AS $$ +BEGIN + IF pg_trigger_depth() = 1 + AND current_setting('silo.collection_member_writes', true) IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'library collection % holds episode or season members, which only a newer Silo release can remove', OLD.collection_id + USING ERRCODE = 'object_not_in_prerequisite_state'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd +CREATE TRIGGER library_collection_items_guard_member_delete + BEFORE DELETE ON public.library_collection_items + FOR EACH ROW WHEN (OLD.media_item_id IS NULL) + EXECUTE FUNCTION public.library_collection_items_guard_member_delete(); + +DROP INDEX public.idx_library_collection_items_order; +CREATE INDEX idx_library_collection_items_order + ON public.library_collection_items (collection_id, position, source_rank, member_id); +DROP INDEX public.library_collection_items_continuation_idx; +CREATE INDEX library_collection_items_continuation_idx + ON public.library_collection_items (collection_id, COALESCE(position, 0), member_id); +-- The cascades from episodes and seasons look members up by these. +CREATE INDEX idx_library_collection_items_episode_id + ON public.library_collection_items (episode_id) WHERE episode_id IS NOT NULL; +CREATE INDEX idx_library_collection_items_season_id + ON public.library_collection_items (season_id) WHERE season_id IS NOT NULL; +-- Readers look for a collection's episode and season members by this, which +-- for a collection of titles finds nothing without reading its rows. +CREATE INDEX idx_library_collection_items_non_title + ON public.library_collection_items (collection_id) WHERE media_item_id IS NULL; + +-- +goose Down +DROP TRIGGER library_collection_items_guard_member_delete ON public.library_collection_items; +DROP FUNCTION public.library_collection_items_guard_member_delete(); +DELETE FROM public.library_collection_items WHERE media_item_id IS NULL; +DROP INDEX public.library_collection_items_media_item_key; +DROP INDEX public.idx_library_collection_items_non_title; +DROP INDEX public.idx_library_collection_items_season_id; +DROP INDEX public.idx_library_collection_items_episode_id; +DROP INDEX public.library_collection_items_continuation_idx; +CREATE INDEX library_collection_items_continuation_idx + ON public.library_collection_items (collection_id, COALESCE(position, 0), media_item_id); +DROP INDEX public.idx_library_collection_items_order; +CREATE INDEX idx_library_collection_items_order + ON public.library_collection_items (collection_id, position, source_rank, media_item_id); +ALTER TABLE public.library_collection_items + DROP CONSTRAINT library_collection_items_pkey, + DROP CONSTRAINT library_collection_items_one_member, + DROP COLUMN member_id, + DROP COLUMN season_id, + DROP COLUMN episode_id, + ALTER COLUMN media_item_id SET NOT NULL, + ADD CONSTRAINT library_collection_items_pkey PRIMARY KEY (collection_id, media_item_id); diff --git a/scripts/ci/db-contracts.txt b/scripts/ci/db-contracts.txt index ec3398a4b5e..9a0e218cfc0 100644 --- a/scripts/ci/db-contracts.txt +++ b/scripts/ci/db-contracts.txt @@ -7,6 +7,7 @@ ./internal/catalog TestEpisodeOpensUnderEveryLibraryOfItsSeriesDB ./internal/catalog TestGetBySeriesAndFileNumberDB ./internal/catalog TestGetBySeriesAndProviderNumberDB +./internal/catalog TestListByProviderNumbersDB ./internal/catalog/filesplit TestMoveRelinksByFileNumbersDB ./internal/catalog/filesplit TestMoveSpannedEpisodeStateByFileNumbersDB ./internal/apiv2 TestItemReadsIgnoreLibraryWithoutTheItemDB @@ -21,6 +22,17 @@ ./internal/catalog TestLibraryCollectionDrawsFromItsRulesLibrariesDB ./internal/catalog TestLibraryCollectionReplaceItemsWritesOnlyTheDifferenceDB ./internal/catalog TestLibraryCollectionReplaceItemsRacesMemberDeleteDB +./internal/catalog TestLibraryCollectionReplaceItemsStoresEpisodesAndSeasonsDB +./internal/catalog TestPreviousReleaseCollectionWritesStillWorkDB +./internal/catalog TestPreviousReleaseReplaceKeepsEpisodeAndSeasonMembersDB +./internal/catalog TestSyncMDBListCollectionStoresEpisodesAndSeasonsDB +./internal/catalog TestSyncMDBListWithoutKeyKeepsEpisodeMembersDB +./internal/catalog TestLibraryCollectionCardIncludesEpisodeAndSeasonMembersDB +./internal/catalog TestLibraryCollectionCatalogPagesEpisodeAndSeasonMembersDB +./internal/catalog TestLibraryCollectionWatchedFilterJudgesEpisodeAndSeasonMembersDB +./internal/jellycompat TestBoxSetChildrenListsEpisodeAndSeasonMembersDB +./internal/jellycompat TestCompatSeasonListItemsNeedAnEpisodeTheViewerCanOpenDB +./internal/sections TestLibraryCollectionRailShowsEpisodeAndSeasonMembersDB ./internal/catalog TestLibraryCollectionNamesDB ./internal/catalog TestLibraryCollectionNameRacesDB ./internal/catalog TestCatalogManualCollectionCursorDB @@ -1373,6 +1385,8 @@ ./internal/api/handlers TestItemCollectionsPreviewDB ./internal/api/handlers TestItemCollectionsPreviewLibraryDB ./internal/api/handlers TestLibraryCollectionEpisodeCardsNameTheirSeriesDB +./internal/api/handlers TestLibraryCollectionPageShowsEpisodeAndSeasonMembersDB +./internal/api/handlers TestSectionSeasonCardNamesItsSeriesDB ./internal/api/handlers TestCollectionPagesContinueFromShownMembersDB ./internal/sections TestRowOfCollectionsReferencesItsCollectionsPostgres @@ -1624,6 +1638,7 @@ ./internal/backup TestRestoredLibrarySectionsWaitForTheRestoreDB ./internal/backup TestManagedSectionPointedElsewhereIsRestoredDB ./internal/backup TestRowOfCollectionsIsRestoredDB +./internal/backup TestCollectionPlanFindsEpisodeAndSeasonMembersDB ./internal/backup TestSelectiveRestoreOnOneConnectionDB ./internal/backup TestUnverifiedRestoreLeavesCostlyWorkOffDB ./internal/backup TestRestoreItemWritesDoNotGrowDB diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 541bb52160a..8cfb76f2f39 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -1699,6 +1699,8 @@ export interface LibraryCollection { management_key?: string; last_sync_status: "idle" | "running" | "success" | "failed" | "warning"; last_sync_message: string; + /** Admin only: why the last sync read nothing, for the client to word (`mdblist_api_key_required`). */ + last_sync_reason?: string; last_sync_at?: string; sync_schedule?: string; next_sync_at?: string; diff --git a/web/src/api/v2/operations.ts b/web/src/api/v2/operations.ts index f7fa573775b..593bddd3d13 100644 --- a/web/src/api/v2/operations.ts +++ b/web/src/api/v2/operations.ts @@ -166,6 +166,7 @@ export const v2Operations = { "GET /api/v2/admin/collection-jobs/{job_id}": "getAdminCollectionJob", "GET /api/v2/admin/collections": "listAdminCollections", "GET /api/v2/admin/collections/capabilities": "getAdminCollectionCapabilities", + "GET /api/v2/admin/collections/mdblist/link": "checkAdminMDBListLink", "GET /api/v2/admin/collections/mdblist/lists": "listAdminMDBListLists", "GET /api/v2/admin/collections/order": "getAdminCollectionOrder", "GET /api/v2/admin/collections/template-bundles": "listAdminCollectionTemplateBundles", diff --git a/web/src/api/v2/schema.ts b/web/src/api/v2/schema.ts index 0e6af04b47d..1a3379efd8c 100644 --- a/web/src/api/v2/schema.ts +++ b/web/src/api/v2/schema.ts @@ -1472,6 +1472,23 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v2/admin/collections/mdblist/link": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Report whether a server collection following an MDBList link syncs only with an MDBList API key the server lacks. Reads the list's public feed once when the server has no key. */ + get: operations["checkAdminMDBListLink"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v2/admin/collections/mdblist/lists": { parameters: { query?: never; @@ -18245,6 +18262,11 @@ export interface components { */ last_sync_at?: string; last_sync_message: string; + /** + * @description Why the last sync read nothing, for clients to say in their own words; absent when it gives none. mdblist_api_key_required: the list syncs only with an MDBList API key the server lacks (a private list, or a list of episodes or seasons) + * @enum {string} + */ + last_sync_reason?: "mdblist_api_key_required"; last_sync_status: string; /** * @description Opaque identifier @@ -18323,6 +18345,11 @@ export interface components { * @example true */ mdblist_account_lists: boolean; + /** + * @description checkAdminMDBListLink reports whether an MDBList link syncs only with an MDBList API key the server lacks + * @example true + */ + mdblist_link_check: boolean; /** * @description searchMDBListLists and listTopMDBListLists return lists; false when the server has no MDBList API key * @example true @@ -18541,6 +18568,11 @@ export interface components { /** Format: int64 */ items_unmatched: number; message: string; + /** + * @description Why the sync read nothing, as last_sync_reason on the collection; absent when it gives none + * @enum {string} + */ + reason?: "mdblist_api_key_required"; /** * Format: date-time * @description RFC 3339 instant in UTC with millisecond precision @@ -23103,6 +23135,13 @@ export interface components { /** Format: uri */ url: string; }; + AdminMDBListLinkOutputBody: { + /** + * @description A server collection following the link syncs only with an MDBList API key the server lacks: MDBList's public feed refuses the list (a private list) or lists nothing (a list of episodes or seasons). False whenever the server has a key + * @example true + */ + needs_api_key: boolean; + }; AdminMergeInputBody: { into: string; }; @@ -57789,6 +57828,115 @@ export interface operations { }; }; }; + checkAdminMDBListLink: { + parameters: { + query: { + /** @description The MDBList list link an administrator pasted */ + url: string; + }; + header?: { + /** @description Optional. When present, it must name the authenticated account's primary profile; an absent header is accepted. */ + "X-Profile-Id"?: string; + /** @description Verification proof for a PIN-locked profile, issued by POST /api/v2/profiles/{id}/verify-pin; required only when the declared profile is locked */ + "X-Profile-Token"?: string; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdminMDBListLinkOutputBody"]; + }; + }; + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Not Acceptable */ + 406: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Too Many Requests */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Internal Server Error */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Service Unavailable */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + }; + }; listAdminMDBListLists: { parameters: { query?: never; diff --git a/web/src/components/CollectionTemplateGallery/MDBListBrowser.tsx b/web/src/components/CollectionTemplateGallery/MDBListBrowser.tsx index 362cef88552..60051f2b155 100644 --- a/web/src/components/CollectionTemplateGallery/MDBListBrowser.tsx +++ b/web/src/components/CollectionTemplateGallery/MDBListBrowser.tsx @@ -133,6 +133,7 @@ export function MDBListBrowser({ onPick, link, onLinkChange, + linkNeedsKey = false, }: { scopeKind: ScopeKind; /** Creatable templates that name their list, by category. */ @@ -149,6 +150,8 @@ export function MDBListBrowser({ /** The pasted link, as typed. */ link: string; onLinkChange: (raw: string) => void; + /** The server checked the link: the list syncs only with an MDBList API key it lacks. */ + linkNeedsKey?: boolean; }) { const t = useT(); const id = useId(); @@ -444,7 +447,13 @@ export function MDBListBrowser({ className="h-11 ps-9" aria-invalid={linkInvalid || undefined} aria-describedby={ - linkInvalid ? `${id}-link-error` : privateHelp ? `${id}-link-help` : undefined + linkInvalid + ? `${id}-link-error` + : linkNeedsKey + ? `${id}-link-key` + : privateHelp + ? `${id}-link-help` + : undefined } value={link} onChange={(event) => onLinkChange(event.target.value)} @@ -454,6 +463,26 @@ export function MDBListBrowser({ + ) : linkNeedsKey ? ( + ) : privateHelp ? (