Repository navigation
feat(collections): back collections with user-authored Trakt lists - #286
Conversation
Collections could sync only Trakt's built-in trending/popular/recommended feeds; a server admin could not populate a collection from a specific user's Trakt list (e.g. a curated 'Saw in timeline order' list) (Silo-Server#214). - trakt.Client.GetUserList fetches /users/{user}/lists/{slug}/items in list order, mixing movies and shows and skipping non-title entries. - New 'trakt_list' collection source mode: catalog.ParseTraktListURL accepts a trakt.tv list URL (or bare user/slug), and syncTraktListCollection reuses the preset pipeline's matching/ordering via an extracted completeTraktEntrySync helper. Public lists need no access token. - Trakt import handler accepts list_url as an alternative to preset; the admin collection editor's Trakt form gains a Source toggle (discovery feed vs user list) with a list-URL input. Additive-only: new source mode + optional request field; preset path unchanged. Fixes Silo-Server#214 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Warning Review limit reached
Next review available in: 52 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThis PR adds support for importing and syncing Trakt collections from user-authored list URLs in addition to existing preset-based imports. Changes span the Trakt API client (GetUserList), catalog sync service (trakt_list mode, URL parsing), API handler (list URL request handling), router adapter wiring, and frontend form with a source-mode selector. ChangesTrakt user list support
Estimated code review effort: 3 (Moderate) | ~30 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant Frontend as TraktPresetForm
participant Handler as HandleImportTraktCollection
participant Service as LibraryCollectionService
participant Adapter as traktCollectionAdapter
participant TraktAPI as Trakt Client
User->>Frontend: Selects "User list" source, enters list URL
Frontend->>Handler: POST import request (list_url)
Handler->>Handler: ParseTraktListURL(list_url)
Handler->>Handler: buildTraktListSourceConfig
Handler-->>Frontend: Collection created (source_config, source_url)
Service->>Service: SyncCollectionWithOptions (trakt_list mode)
Service->>Adapter: GetUserList(user, list, limit, token)
Adapter->>TraktAPI: GetUserList(user, list, limit, token)
TraktAPI-->>Adapter: paginated list items
Adapter-->>Service: []TraktCollectionEntry
Service->>Service: completeTraktEntrySync(entries, limit)
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2834c7b99d
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| URL string `json:"url"` | ||
| Limit *int `json:"limit,omitempty"` | ||
| }{ | ||
| Mode: "trakt_list", |
There was a problem hiding this comment.
Preserve Trakt list source when editing
Creating collections with this new mode: "trakt_list" makes them enter the existing admin edit flow as collection_type === "trakt", but that form still parses only preset config and on every save rewrites the source as mode: "trakt_preset" with a trakt://... URL (web/src/pages/adminCollectionsShared.tsx:1349-1422). In practice, an admin who edits only the title, artwork, or libraries of a Trakt-list collection will silently replace the user list with the default/picked preset, so future syncs no longer use the list. The edit flow needs to detect and preserve trakt_list (or lock those source fields) before enabling this mode.
Useful? React with 👍 / 👎.
| <SelectItem value="preset"> | ||
| Discovery feed (Trending / Popular / Recommended) | ||
| </SelectItem> | ||
| <SelectItem value="list">User list (trakt.tv URL)</SelectItem> |
There was a problem hiding this comment.
Allow all library kinds for Trakt lists
When this new User list source is selected, the media-type control is hidden, but the library picker above still receives eligibility derived from the hidden mediaType state (defaulting to movie). On servers with separate movie and TV libraries, switching to list mode leaves TV-only libraries disabled by default, even though Trakt lists can contain both movies and shows and the backend matches each entry by type. Use mixed/no eligibility in list mode so admins can select both library kinds for mixed lists.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
internal/api/router.go (1)
2965-2984: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate entry-mapping logic between
GetCollectionPresetandGetUserList.Both adapter methods now contain the identical field-by-field mapping loop from client results to
catalog.TraktCollectionEntry. Consider extracting a shared helper.♻️ Proposed refactor to share the mapping logic
+func mapTraktCollectionEntries(results []metatrakt.CollectionEntry) []catalog.TraktCollectionEntry { + entries := make([]catalog.TraktCollectionEntry, len(results)) + for i, r := range results { + entries[i] = catalog.TraktCollectionEntry{ + TraktID: r.TraktID, + TMDBID: r.TMDBID, + TVDBID: r.TVDBID, + IMDbID: r.IMDbID, + MediaType: r.MediaType, + Title: r.Title, + Year: r.Year, + Rank: r.Rank, + } + } + return entries +} + func (a *traktCollectionAdapter) GetCollectionPreset(ctx context.Context, preset, mediaType string, limit int, accessToken string) ([]catalog.TraktCollectionEntry, error) { results, err := a.client.GetCollectionPreset(ctx, preset, mediaType, limit, accessToken) if err != nil { return nil, err } - entries := make([]catalog.TraktCollectionEntry, len(results)) - for i, r := range results { - entries[i] = catalog.TraktCollectionEntry{ - TraktID: r.TraktID, - TMDBID: r.TMDBID, - TVDBID: r.TVDBID, - IMDbID: r.IMDbID, - MediaType: r.MediaType, - Title: r.Title, - Year: r.Year, - Rank: r.Rank, - } - } - return entries, nil + return mapTraktCollectionEntries(results), nil } func (a *traktCollectionAdapter) GetUserList(ctx context.Context, user, list string, limit int, accessToken string) ([]catalog.TraktCollectionEntry, error) { results, err := a.client.GetUserList(ctx, user, list, limit, accessToken) if err != nil { return nil, err } - entries := make([]catalog.TraktCollectionEntry, len(results)) - for i, r := range results { - entries[i] = catalog.TraktCollectionEntry{ - TraktID: r.TraktID, - TMDBID: r.TMDBID, - TVDBID: r.TVDBID, - IMDbID: r.IMDbID, - MediaType: r.MediaType, - Title: r.Title, - Year: r.Year, - Rank: r.Rank, - } - } - return entries, nil + return mapTraktCollectionEntries(results), nil }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/router.go` around lines 2965 - 2984, The entry-to-catalog mapping in GetUserList duplicates the same field-by-field loop already used in GetCollectionPreset, so extract that shared conversion into a helper and have both adapter methods call it. Reuse the existing traktCollectionAdapter methods and the catalog.TraktCollectionEntry mapping logic so the conversion stays in one place and both paths remain identical.internal/metadata/trakt/user_list_test.go (1)
10-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winGood coverage for single-page decode/validation; consider adding a multi-page pagination test.
The pagination loop in
GetUserList(page increment,pageLimitshrinking, termination vialen(resp) < pageLimit) is the most intricate part of the new method and isn't exercised here — both tests return a single page.🧪 Suggested additional test sketch
func TestGetUserListPaginatesAcrossPages(t *testing.T) { var requests int server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests++ if requests == 1 { writeJSON(t, w, []map[string]any{ {"rank": 1, "type": "movie", "movie": map[string]any{"title": "A", "ids": map[string]any{"tmdb": 1}}}, }) return } writeJSON(t, w, []map[string]any{}) })) defer server.Close() client := NewClient("client-id", 1000) client.SetBaseURL(server.URL) results, err := client.GetUserList(context.Background(), "user", "list", 5, "") if err != nil { t.Fatalf("GetUserList: %v", err) } if len(results) != 1 || requests < 2 { t.Fatalf("results = %d, requests = %d; want pagination to terminate correctly", len(results), requests) } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/metadata/trakt/user_list_test.go` around lines 10 - 72, Add a pagination-focused test for GetUserList because the current coverage only exercises a single response page. Create a test around GetUserList that uses an httptest.Server to return data on the first request and an empty page on the next, then assert the client makes multiple requests, preserves results across pages, and stops when len(resp) drops below the requested pageLimit. Use the GetUserList method, NewClient, and SetBaseURL symbols to locate the code path.internal/api/handlers/library_collections.go (1)
3002-3015: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSync-failure log loses context for list-based imports.
When
listURLis set,preset/mediaTypestay empty strings, but the failure log further down (slog.Error("failed to sync imported Trakt collection", ..., "preset", preset, "media_type", mediaType, ...)) still logs those now-blank fields without anylist_url, making it hard to diagnose which list failed to sync.📝 Proposed fix to add list_url to the failure log
slog.Error("failed to sync imported Trakt collection", "collection_id", collection.ID, "library_id", req.LibraryID, "title", req.Title, "preset", preset, "media_type", mediaType, + "list_url", listURL, "error", err, )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/library_collections.go` around lines 3002 - 3015, The Trakt sync failure log in the import handler is missing context for list-based imports because the `preset` and `mediaType` fields are empty when `listURL` is used. Update the error logging in the same handler that calls `catalog.ParseTraktListURL` and `normalizeTraktPresetRequest` so the `slog.Error("failed to sync imported Trakt collection", ...)` path includes `list_url` when `listURL` is set, while still logging `preset`, `media_type`, and `profile_id` for preset-based imports.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/catalog/library_collection_service.go`:
- Around line 1012-1050: ParseTraktListURL currently accepts any URL with the
right path shape because it never checks the host. Update the URL branch in
ParseTraktListURL to validate parsed.Hostname() is trakt.tv (and optionally
www.trakt.tv if supported) before extracting the /users/{user}/lists/{slug}
path, and return badFormat() for any other host. Keep the shorthand
"{user}/{slug}" handling unchanged, and ensure the existing ParseTraktListURL
validation messages still cover malformed or non-Trakt inputs.
In `@web/src/pages/adminCollectionsShared.tsx`:
- Around line 1002-1060: The Trakt edit form is not preserving list-backed
configurations, so saving a `trakt_list` collection gets rewritten as a preset
and loses `list_url`. Update the Trakt edit/save flow in
`adminCollectionsShared.tsx` so the edit state detects and round-trips `mode:
"trakt_list"` alongside `trakt_preset`, and ensure
`parseTraktPresetSourceConfig()` and the submit handler keep `source_config`,
`source_url`, and `list_url` intact for list sources instead of defaulting to
`trending`.
---
Nitpick comments:
In `@internal/api/handlers/library_collections.go`:
- Around line 3002-3015: The Trakt sync failure log in the import handler is
missing context for list-based imports because the `preset` and `mediaType`
fields are empty when `listURL` is used. Update the error logging in the same
handler that calls `catalog.ParseTraktListURL` and `normalizeTraktPresetRequest`
so the `slog.Error("failed to sync imported Trakt collection", ...)` path
includes `list_url` when `listURL` is set, while still logging `preset`,
`media_type`, and `profile_id` for preset-based imports.
In `@internal/api/router.go`:
- Around line 2965-2984: The entry-to-catalog mapping in GetUserList duplicates
the same field-by-field loop already used in GetCollectionPreset, so extract
that shared conversion into a helper and have both adapter methods call it.
Reuse the existing traktCollectionAdapter methods and the
catalog.TraktCollectionEntry mapping logic so the conversion stays in one place
and both paths remain identical.
In `@internal/metadata/trakt/user_list_test.go`:
- Around line 10-72: Add a pagination-focused test for GetUserList because the
current coverage only exercises a single response page. Create a test around
GetUserList that uses an httptest.Server to return data on the first request and
an empty page on the next, then assert the client makes multiple requests,
preserves results across pages, and stops when len(resp) drops below the
requested pageLimit. Use the GetUserList method, NewClient, and SetBaseURL
symbols to locate the code path.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b4fc9a61-b0fe-49d3-8573-aba9004267f1
📒 Files selected for processing (9)
internal/api/handlers/library_collections.gointernal/api/router.gointernal/catalog/library_collection_service.gointernal/catalog/trakt_list_url_test.gointernal/metadata/trakt/client.gointernal/metadata/trakt/user_list_test.gointernal/sections/trending_refresher_test.goweb/src/api/types.tsweb/src/pages/adminCollectionsShared.tsx
Code reviewFound 3 issues (the first two confirm the earlier Codex/CodeRabbit inline comments — I validated each against the code):
silo-server/web/src/pages/adminCollectionsShared.tsx Lines 1410 to 1423 in 2834c7b
silo-server/web/src/pages/adminCollectionsShared.tsx Lines 885 to 889 in 2834c7b
silo-server/internal/catalog/library_collection_service.go Lines 1022 to 1027 in 2834c7b I am pushing fixes for all three to this branch. 🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
… mixed libraries, validate list host Three review fixes for user-list-backed collections: - The admin edit form now detects mode "trakt_list", shows an editable list URL (mirroring the create form) and saves the source back as trakt_list with list_url preserved — previously any edit silently rewrote the collection into a trakt_preset Trending Movies feed. - Library eligibility in list mode is mixed (movies + shows) instead of inheriting the hidden media-type default of movie, since Trakt lists mix both and entries match by their own type. - ParseTraktListURL only accepts trakt.tv / www.trakt.tv hosts, so a list-shaped URL on another domain fails fast with the format error instead of a confusing later sync failure. source_config now carries list_url alongside the legacy url key (additive); sync reads list_url, then url, then source_url. Co-Authored-By: Claude Fable 5 <[email protected]>
|
All three issues addressed in 821d258:
|
…ilo-Server#286) * feat(collections): back collections with user-authored Trakt lists Collections could sync only Trakt's built-in trending/popular/recommended feeds; a server admin could not populate a collection from a specific user's Trakt list (e.g. a curated 'Saw in timeline order' list) (Silo-Server#214). - trakt.Client.GetUserList fetches /users/{user}/lists/{slug}/items in list order, mixing movies and shows and skipping non-title entries. - New 'trakt_list' collection source mode: catalog.ParseTraktListURL accepts a trakt.tv list URL (or bare user/slug), and syncTraktListCollection reuses the preset pipeline's matching/ordering via an extracted completeTraktEntrySync helper. Public lists need no access token. - Trakt import handler accepts list_url as an alternative to preset; the admin collection editor's Trakt form gains a Source toggle (discovery feed vs user list) with a list-URL input. Additive-only: new source mode + optional request field; preset path unchanged. Fixes Silo-Server#214 Co-Authored-By: Claude Fable 5 <[email protected]> * fix(collections): round-trip trakt_list through the edit form, unlock mixed libraries, validate list host Three review fixes for user-list-backed collections: - The admin edit form now detects mode "trakt_list", shows an editable list URL (mirroring the create form) and saves the source back as trakt_list with list_url preserved — previously any edit silently rewrote the collection into a trakt_preset Trending Movies feed. - Library eligibility in list mode is mixed (movies + shows) instead of inheriting the hidden media-type default of movie, since Trakt lists mix both and entries match by their own type. - ParseTraktListURL only accepts trakt.tv / www.trakt.tv hosts, so a list-shaped URL on another domain fails fast with the format error instead of a confusing later sync failure. source_config now carries list_url alongside the legacy url key (additive); sync reads list_url, then url, then source_url. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Quick <[email protected]>
Problem
Collections could sync only Trakt's built-in trending/popular/recommended feeds. A server admin couldn't populate a collection from a specific user's Trakt list — e.g. a curated "Saw cinematic universe in timeline order" list pulled from a Kometa config (#214). The biggest community-signal item on the board (a 43-reply thread).
Approach
trakt.Client.GetUserListfetches/users/{user}/lists/{slug}/itemsin list order, mixing movies and shows and skipping non-title entries (people/episodes/seasons). Public lists need only the app client id; the access token is passed through for a private owner list.trakt_listcollection source mode:catalog.ParseTraktListURLaccepts atrakt.tv/users/{user}/lists/{slug}URL (with or without scheme/query) or a bareuser/slugshorthand;syncTraktListCollectionfetches the list and reuses the preset pipeline's matching, dedupe, ranking, and sync-run recording via an extractedcompleteTraktEntrySynchelper (no logic duplicated between preset and list paths).list_urlas an alternative topreset; the admin collection editor's Trakt form gains a Source toggle (discovery feed vs user list) with a list-URL input and summary row.Reuses the whole existing collection machinery (auto-sync schedule, collage, library matching) that #227's provider work and the earlier preset modes already established — this is a new source, not a new subsystem.
API contract
Additive-only: a new accepted
source_config.mode, a new optionallist_urlrequest field;preset/media_typebecome optional but the preset path is unchanged. No renames or type changes.Testing
GetUserList: httptest-backed mixed movie/show decoding in list order, unknown-type skipping, and required user/slug validation.ParseTraktListURL: full URL, query string, no-scheme, shorthand, trailing slash, and rejection of non-list URLs / missing slug (these caught two parser bugs during development — a non-list URL that resolved and a no-scheme URL that didn't).tsc+ prettier clean.Fixes #214
AI-use disclosure
Implemented with Claude Code (test-first); human-reviewed before submission.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes