Repository navigation
feat(historyimport): import the Plex account watchlist alongside watch history - #285
Conversation
…h history The Plex import migrated only watch history; the user's saved watchlist had to be rebuilt by hand (Silo-Server#245). - PlexClient gains FetchWatchlist: pages the account-level watchlist on the Plex discover API (discover.provider.plex.tv). It authenticates with the plex.tv ACCOUNT token — the PIN/OAuth session token, which resolvePlexAuth now threads through plexAuth.AccountToken (manual-token imports pass the user token, which doubles as the account token). - Watchlist entries become import Records flagged Watchlisted, carrying identity only (movie/show → KindMovie/KindSeries, guids parsed) and no watch state. They ride the existing matcher (series matching already exists), and matched entries are added to the importing profile's watchlist via the idempotent AddToWatchlistAt — re-imports do not duplicate. A watchlist fetch failure downgrades to a run warning so the history import still completes. - Run summaries gain a watchlist_added counter (new column + repo plumbing + client/admin UI cards). Fixes Silo-Server#245 Co-Authored-By: Claude Fable 5 <[email protected]>
📝 WalkthroughWalkthroughThis PR adds Plex watchlist import support: fetching watchlist items via Plex's discover API, normalizing them into import records, and inserting them into the user's watchlist during history import, tracked via new run metrics (watchlist_added). Separately, AddToWatchlistAt across all stores now returns a bool indicating whether a row was inserted, with callers and stubs updated accordingly. ChangesPlex watchlist import feature
AddToWatchlistAt return-type change
Estimated code review effort: 3 (Moderate) | ~30 minutes Sequence Diagram(s)sequenceDiagram
participant Service
participant PlexServerProvider
participant PlexClient
participant PlexDiscoverAPI
participant UserStore
Service->>PlexServerProvider: Fetch(accountToken)
PlexServerProvider->>PlexClient: FetchWatchlist(ctx, accountToken)
PlexClient->>PlexDiscoverAPI: GET watchlist/all (paginated)
PlexDiscoverAPI-->>PlexClient: Metadata pages
PlexClient-->>PlexServerProvider: []PlexItem
PlexServerProvider->>PlexServerProvider: NormalizePlexWatchlistItem
PlexServerProvider-->>Service: records (Watchlisted=true)
Service->>Service: addToWatchlist(record)
Service->>UserStore: AddToWatchlistAt(profileID, mediaItemID, addedAt)
UserStore-->>Service: (inserted bool, err)
Service->>Service: increment WatchlistAdded if inserted
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: 0da655e52f
ℹ️ 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".
| if err := s.addToWatchlist(ctx, run.UserID, run.ProfileID, match.MediaItemID, record.UpdatedAt); err != nil { | ||
| summary.Warnings = append(summary.Warnings, err.Error()) | ||
| } else { | ||
| summary.WatchlistAdded++ |
There was a problem hiding this comment.
Count only newly inserted watchlist rows
When a Plex watchlist item is already on the profile's watchlist, AddToWatchlistAt still returns nil because the insert uses ON CONFLICT DO NOTHING, so this branch increments WatchlistAdded even though no row was added. Re-importing the same Plex account, or processing duplicate matched watchlist entries, will persist and display inflated watchlist_added counts; have addToWatchlist report rows affected or check existing membership before incrementing.
Useful? React with 👍 / 👎.
Code reviewFound 1 issue (confirms the earlier Codex inline comment — validated against the code):
silo-server/internal/historyimport/service.go Lines 503 to 513 in 0da655e I am pushing a fix to this branch. 🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
…listAdded AddToWatchlistAt now reports whether a row was actually inserted (the insert is ON CONFLICT DO NOTHING / INSERT OR IGNORE), and the import summary increments WatchlistAdded only for genuine inserts, so re-importing the same Plex account no longer inflates the count. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Addressed in f7f11ab: |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
internal/historyimport/plex_normalize.go (1)
50-72: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winConsider preserving the actual Plex "watchlistedAt" timestamp instead of
time.Now().
UpdatedAtis set to the processing-timetime.Now().UTC()rather than any value from the source item. Sincerecord.UpdatedAtis later passed as the "added at" timestamp toaddToWatchlist(perservice.go), all watchlist entries imported in one run end up with nearly identical timestamps, losing the user's original watchlist ordering. Plex's discover API supports sorting bywatchlistedAt("Added At"), suggesting the source data may carry a genuine add-date that could be threaded throughPlexItem/FetchWatchlistinstead.If preserving original order isn't feasible or the field isn't exposed by the discover response used here, this is fine to leave as-is — please confirm via the Plex discover API response shape.
🤖 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/historyimport/plex_normalize.go` around lines 50 - 72, NormalizePlexWatchlistItem is stamping UpdatedAt with processing time, which causes imported watchlist entries to lose their original ordering; update PlexItem/FetchWatchlist plumbing to carry Plex’s watchlistedAt (Added At) value through, and have NormalizePlexWatchlistItem set record.UpdatedAt from that source timestamp instead of time.Now().UTC(). If the discover response does not expose watchlistedAt, confirm that in the fetch path and keep the current behavior only after verifying no source timestamp is available.web/src/pages/settings/HistoryImportSettings.tsx (1)
837-844: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSame odd-item-count grid issue as
AdminHistoryImport.tsx.7
MetricCards in agrid-cols-3 … sm:grid-cols-6grid leaves the last card dangling alone on a row.💅 Optional: adjust grid columns to fit 7 items evenly
- <div className="grid grid-cols-3 gap-2 sm:grid-cols-6"> + <div className="grid grid-cols-4 gap-2 sm:grid-cols-7">🤖 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 `@web/src/pages/settings/HistoryImportSettings.tsx` around lines 837 - 844, The Metrics card section in HistoryImportSettings renders 7 MetricCard items inside a grid-cols-3 sm:grid-cols-6 layout, leaving the last card isolated on its own row. Update the grid configuration in the MetricCard container so the cards distribute evenly for 7 items, using the same approach as the related AdminHistoryImport layout, and keep the change localized to the metrics grid wrapper.web/src/pages/AdminHistoryImport.tsx (1)
1217-1217: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueGrid now has an odd item count (7) for a 3/6-column layout.
Adding the "Watchlist" block makes 7 metrics in a
grid-cols-3 … sm:grid-cols-6grid, leaving a dangling last cell on both breakpoints (3+3+1 mobile, 6+1 desktop).💅 Optional: adjust grid columns to fit 7 items evenly
- <div className="text-muted-foreground grid grid-cols-3 gap-2 text-xs sm:grid-cols-6"> + <div className="text-muted-foreground grid grid-cols-4 gap-2 text-xs sm:grid-cols-7">Also applies to: 1238-1245
🤖 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 `@web/src/pages/AdminHistoryImport.tsx` at line 1217, The metrics grid in AdminHistoryImport now has 7 items, which leaves an uneven last cell in the current grid-cols-3 / sm:grid-cols-6 layout. Update the layout around the metrics blocks (including the Watchlist block and the related section at the other referenced location) so the grid column count matches 7 items evenly at each breakpoint, or otherwise restructure the items so the rows are balanced. Use the AdminHistoryImport page’s grid container and the Watchlist metric block as the key spots to adjust.
🤖 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/historyimport/plex_client.go`:
- Around line 267-301: FetchWatchlist currently paginates only until TotalSize
or an empty page, so it can loop indefinitely on a misbehaving discover host.
Add a hard upper bound to the pagination loop in PlexClient.FetchWatchlist,
using the existing page/offset flow to stop after a reasonable maximum number of
pages or items even if responses keep coming. Keep the normal offset
accumulation and existing exit conditions intact, and add a test that exercises
the runaway pagination case to verify the cap breaks the loop.
---
Nitpick comments:
In `@internal/historyimport/plex_normalize.go`:
- Around line 50-72: NormalizePlexWatchlistItem is stamping UpdatedAt with
processing time, which causes imported watchlist entries to lose their original
ordering; update PlexItem/FetchWatchlist plumbing to carry Plex’s watchlistedAt
(Added At) value through, and have NormalizePlexWatchlistItem set
record.UpdatedAt from that source timestamp instead of time.Now().UTC(). If the
discover response does not expose watchlistedAt, confirm that in the fetch path
and keep the current behavior only after verifying no source timestamp is
available.
In `@web/src/pages/AdminHistoryImport.tsx`:
- Line 1217: The metrics grid in AdminHistoryImport now has 7 items, which
leaves an uneven last cell in the current grid-cols-3 / sm:grid-cols-6 layout.
Update the layout around the metrics blocks (including the Watchlist block and
the related section at the other referenced location) so the grid column count
matches 7 items evenly at each breakpoint, or otherwise restructure the items so
the rows are balanced. Use the AdminHistoryImport page’s grid container and the
Watchlist metric block as the key spots to adjust.
In `@web/src/pages/settings/HistoryImportSettings.tsx`:
- Around line 837-844: The Metrics card section in HistoryImportSettings renders
7 MetricCard items inside a grid-cols-3 sm:grid-cols-6 layout, leaving the last
card isolated on its own row. Update the grid configuration in the MetricCard
container so the cards distribute evenly for 7 items, using the same approach as
the related AdminHistoryImport layout, and keep the change localized to the
metrics grid wrapper.
🪄 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: 8aad54f5-a656-4374-9142-c5079f243af0
📒 Files selected for processing (20)
internal/access/resolver_test.gointernal/historyimport/plex_client.gointernal/historyimport/plex_normalize.gointernal/historyimport/plex_provider.gointernal/historyimport/plex_watchlist_test.gointernal/historyimport/repo.gointernal/historyimport/repo_admin.gointernal/historyimport/service.gointernal/historyimport/types.gointernal/jellycompat/content_direct_test.gointernal/userdb/favorites.gointernal/userdb/sqlitestore.gointernal/userdb/watchlist_order_test.gointernal/userstore/pgstore/favorites.gointernal/userstore/store.gointernal/watchsync/lists.gomigrations/sql/20260702193158_history_import_watchlist_added.sqlweb/src/api/types.tsweb/src/pages/AdminHistoryImport.tsxweb/src/pages/settings/HistoryImportSettings.tsx
| // FetchWatchlist pages through the user's account-level watchlist on the | ||
| // Plex discover API. It authenticates with the plex.tv ACCOUNT token (from | ||
| // the PIN/OAuth session), not a server access token: the watchlist belongs | ||
| // to the account, not to any PMS. | ||
| func (c *PlexClient) FetchWatchlist(ctx context.Context, accountToken string) ([]PlexItem, error) { | ||
| base := c.discoverBaseURL | ||
| if base == "" { | ||
| base = plexDiscoverBaseURL | ||
| } | ||
| var allItems []PlexItem | ||
| offset := 0 | ||
| for { | ||
| query := url.Values{} | ||
| query.Set("includeGuids", "1") | ||
| query.Set("X-Plex-Container-Start", strconv.Itoa(offset)) | ||
| query.Set("X-Plex-Container-Size", strconv.Itoa(plexPageSize)) | ||
| reqURL := fmt.Sprintf("%s/library/sections/watchlist/all?%s", base, query.Encode()) | ||
| req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| c.setPlexHeaders(req, accountToken) | ||
| var container plexMediaContainer | ||
| if err := c.doJSON(req, &container); err != nil { | ||
| return nil, fmt.Errorf("fetching Plex watchlist (offset %d): %w", offset, err) | ||
| } | ||
| allItems = append(allItems, container.MediaContainer.Metadata...) | ||
| offset += len(container.MediaContainer.Metadata) | ||
| if offset >= container.MediaContainer.TotalSize || len(container.MediaContainer.Metadata) == 0 { | ||
| break | ||
| } | ||
| } | ||
| return allItems, nil | ||
| } | ||
|
|
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate the target file and related tests.
git ls-files | rg '^internal/historyimport/plex_client\.go$|runaway pagination|watchlist|FetchWatchlist|plex_client_test\.go$'
# Show a compact outline of the target file.
ast-grep outline internal/historyimport/plex_client.go --view expanded
# Search for pagination-related tests and helpers.
rg -n "runaway pagination|FetchWatchlist|watchlist|pagination|TotalSize|maxWatchlistPages|Container-Start|Container-Size" internal -g '!**/*vendor*'Repository: Silo-Server/silo-server
Length of output: 50379
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Read the relevant implementation around FetchWatchlist.
start=$(rg -n "^func \\(c \\*PlexClient\\) FetchWatchlist\\(" internal/historyimport/plex_client.go | cut -d: -f1 | head -n1)
end=$((start + 80))
sed -n "${start},${end}p" internal/historyimport/plex_client.go | cat -n
# Read tests in the same package that mention watchlist/pagination.
for f in $(git ls-files 'internal/historyimport/*_test.go'); do
if rg -n "FetchWatchlist|watchlist|pagination|runaway|TotalSize" "$f" >/dev/null; then
echo "### $f"
rg -n -A3 -B3 "FetchWatchlist|watchlist|pagination|runaway|TotalSize" "$f"
fi
doneRepository: Silo-Server/silo-server
Length of output: 7190
Add a hard cap to FetchWatchlist pagination. The loop only stops on TotalSize or an empty page, so a discover host that keeps returning non-empty pages while TotalSize advances can spin forever and grow allItems without bound. The existing tests cover normal pagination and the empty-page exit, but not this runaway case.
🤖 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/historyimport/plex_client.go` around lines 267 - 301, FetchWatchlist
currently paginates only until TotalSize or an empty page, so it can loop
indefinitely on a misbehaving discover host. Add a hard upper bound to the
pagination loop in PlexClient.FetchWatchlist, using the existing page/offset
flow to stop after a reasonable maximum number of pages or items even if
responses keep coming. Keep the normal offset accumulation and existing exit
conditions intact, and add a test that exercises the runaway pagination case to
verify the cap breaks the loop.
…h history (Silo-Server#285) * feat(historyimport): import the Plex account watchlist alongside watch history The Plex import migrated only watch history; the user's saved watchlist had to be rebuilt by hand (Silo-Server#245). - PlexClient gains FetchWatchlist: pages the account-level watchlist on the Plex discover API (discover.provider.plex.tv). It authenticates with the plex.tv ACCOUNT token — the PIN/OAuth session token, which resolvePlexAuth now threads through plexAuth.AccountToken (manual-token imports pass the user token, which doubles as the account token). - Watchlist entries become import Records flagged Watchlisted, carrying identity only (movie/show → KindMovie/KindSeries, guids parsed) and no watch state. They ride the existing matcher (series matching already exists), and matched entries are added to the importing profile's watchlist via the idempotent AddToWatchlistAt — re-imports do not duplicate. A watchlist fetch failure downgrades to a run warning so the history import still completes. - Run summaries gain a watchlist_added counter (new column + repo plumbing + client/admin UI cards). Fixes Silo-Server#245 Co-Authored-By: Claude Fable 5 <[email protected]> * fix(historyimport): count only newly inserted watchlist rows in WatchlistAdded AddToWatchlistAt now reports whether a row was actually inserted (the insert is ON CONFLICT DO NOTHING / INSERT OR IGNORE), and the import summary increments WatchlistAdded only for genuine inserts, so re-importing the same Plex account no longer inflates the count. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Quick <[email protected]>
Problem
The Plex import migrated only watch history — the user's saved Plex watchlist was left behind and had to be rebuilt manually (#245).
Approach
PlexClient.FetchWatchlistpages the account-level watchlist on the Plex discover API (discover.provider.plex.tv). Watchlists belong to the plex.tv account, not a PMS, so it authenticates with the account token: the PIN/OAuth session token, now threaded throughplexAuth.AccountToken(manual-token imports pass the user-supplied token, which doubles as the account token).Records flaggedWatchlisted— identity only (movie/show→ movie/series kinds, guids parsed into imdb/tmdb/tvdb ids), no watch state. They ride the existing matcher (series matching already existed), and matched entries land on the importing profile's watchlist via the idempotentAddToWatchlistAt(ON CONFLICT DO NOTHING) — re-imports never duplicate or reorder.watchlist_addedcounter: new column + repo plumbing + a metric card in both the client settings page and the admin import view.Distinct from #227 (continuous Trakt/Simkl/MDBList sync) — this is the one-time Plex migration path.
Testing
FetchWatchlisttests: pagination, account-token header, and a runaway-pagination guard (huge totalSize + empty pages must not loop).tscclean.Fixes #245
AI-use disclosure
Implemented with Claude Code (test-first); human-reviewed before submission.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Tests