fix(explore): match Plex Discover titles to the library again
Two defects sank Explore's Plex integration. Discover started rejecting X-Plex-Container-Size=500 with a 400, so the watchlist membership snapshot never loaded: hearts stayed unknown and toggles dead. The snapshot now pages at 100, and getWatchlist refetches a rejected page in chunks of the row fetch's field-proven 25, so the next cap drift degrades gracefully instead of failing and callers' offset math survives either way. Worse, every Plex catalog item reached the library matcher carrying only its Discover rating key: listings were fetched without includeGuids, so the lookup rested entirely on exact plex:// guid equality between two metadata universes (Discover duplicate entries break it, notoriously for anime), and the title fallback can never confirm a candidate without external ids to intersect - "Not in your library" for owned titles the MAL provider matched fine. Discover listings now request Guids, the detail screen re-runs the matcher when enrichment gains id forms (generation-guarded so the slower bare lookup cannot overwrite the richer verdict), the matcher keys its memo by id fingerprint so the poor form's cached negative cannot answer for the rich one, and the Plex client stops burning title requests that external-id verification is guaranteed to reject. Discover requests are now logged like every other API surface; this bug shipped blind because they were not. close #1715
This commit is contained in:
@@ -103,7 +103,7 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_syncDetailCollections(widget.item);
|
||||
unawaited(_resolveMatches());
|
||||
unawaited(_resolveMatches(widget.item));
|
||||
unawaited(_loadDetail());
|
||||
final sources = context.read<CatalogSourcesProvider>();
|
||||
_watchlistSource = sources.watchlistSourceFor(widget.item);
|
||||
@@ -149,13 +149,22 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> _resolveMatches() async {
|
||||
/// Monotonic guard for match resolution: the bare row item and its
|
||||
/// detail-enriched form resolve concurrently, and only the latest-issued
|
||||
/// resolution may publish (a slow bare lookup must not overwrite the
|
||||
/// enriched verdict with its own).
|
||||
int _matchGeneration = 0;
|
||||
|
||||
Future<void> _resolveMatches(CatalogItem item) async {
|
||||
final generation = ++_matchGeneration;
|
||||
List<MediaItem> matches;
|
||||
try {
|
||||
_setMatches(await context.read<CatalogLibraryMatcher>().match(widget.item));
|
||||
matches = await context.read<CatalogLibraryMatcher>().match(item);
|
||||
} catch (e) {
|
||||
appLogger.w('Catalog library match failed for ${widget.item.identityKey}', error: e);
|
||||
_setMatches(const []);
|
||||
appLogger.w('Catalog library match failed for ${item.identityKey}', error: e);
|
||||
matches = const [];
|
||||
}
|
||||
if (generation == _matchGeneration) _setMatches(matches);
|
||||
}
|
||||
|
||||
void _setMatches(List<MediaItem> matches) {
|
||||
@@ -221,6 +230,14 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
|
||||
_related = detail.related;
|
||||
_relationEntries = relationEntries;
|
||||
});
|
||||
// The row form of a Plex Discover item carries only its rating key;
|
||||
// the detail body brings the external ids (#1715). When enrichment
|
||||
// added id forms and the bare lookup found nothing, ask again with
|
||||
// the full set.
|
||||
final gainedIds = !widget.item.ids.allKeys.toSet().containsAll(detail.item.ids.allKeys);
|
||||
if (gainedIds && (_matches?.isEmpty ?? true)) {
|
||||
unawaited(_resolveMatches(detail.item));
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.d('Catalog detail load failed for ${widget.item.identityKey}', error: e);
|
||||
}
|
||||
|
||||
@@ -33,8 +33,12 @@ class CatalogLibraryMatcher {
|
||||
// `mal45576 s1`, `mal51179 s2`, `mal55888 s2`, `mal59193 s3`) collapse to
|
||||
// `imdb:tt13293588`, so the first season-gated result would poison the rest.
|
||||
// Namespace by source too: MAL and AniList can share a MAL id while
|
||||
// contributing different localized title candidates.
|
||||
final key = '${item.source.name}/${item.entryIdentityKey}';
|
||||
// contributing different localized title candidates. The id forms join
|
||||
// the key because a detail load can enrich an item with external ids its
|
||||
// row form lacked (#1715: Plex rows carry only a rating key); the richer
|
||||
// lookup must not be short-circuited by the poorer form's cached
|
||||
// negative.
|
||||
final key = '${item.source.name}/${item.entryIdentityKey}/${item.ids.allKeys.join(',')}';
|
||||
final cached = _cache[key];
|
||||
if (cached != null && (cached.items.isNotEmpty || _now().difference(cached.at) < negativeTtl)) {
|
||||
return cached.items;
|
||||
|
||||
@@ -35,11 +35,16 @@ class PlexCatalogSource with CatalogWatchlistMachinery implements CatalogSource,
|
||||
@override
|
||||
String get watchlistLogLabel => 'Plex: watchlist';
|
||||
|
||||
// Discover validates X-Plex-Container-Size against a cap it drifts
|
||||
// without notice (#1715: 500 became invalid). 100 keeps the snapshot at
|
||||
// few requests while staying well under the observed cap, and the client
|
||||
// degrades to 25-item chunks if the cap ever drops below it; more pages
|
||||
// preserve the 5000-entry coverage.
|
||||
@override
|
||||
int get watchlistPageLimit => 500;
|
||||
int get watchlistPageLimit => 100;
|
||||
|
||||
@override
|
||||
int get watchlistMaxPages => 10;
|
||||
int get watchlistMaxPages => 50;
|
||||
|
||||
@override
|
||||
Future<CatalogPage> fetchRow(CatalogRowId row, {int page = 1, int limit = 25}) async {
|
||||
|
||||
@@ -3876,6 +3876,11 @@ class PlexClient
|
||||
}
|
||||
}
|
||||
|
||||
// Title attempts confirm candidates by external-id intersection, so
|
||||
// without external ids they cannot match anything — stop at the exact
|
||||
// guid lookup instead of burning requests that always come back empty.
|
||||
if (!ids.hasAny) return null;
|
||||
|
||||
Future<({Map<String, dynamic>? modern, Map<String, dynamic>? legacy})> attempt(
|
||||
String title, {
|
||||
required int size,
|
||||
|
||||
@@ -85,14 +85,41 @@ class PlexDiscoverClient {
|
||||
PlexDiscoverClient(this.session, {http.Client? httpClient, this.requestTimeout = const Duration(seconds: 20)})
|
||||
: _http = httpClient ?? http.Client();
|
||||
|
||||
/// Largest container size field-proven against Discover's request
|
||||
/// validation: the Explore row fetch uses it on every load. Oversized
|
||||
/// pages refetch as chunks of it, so the cap can drift below a caller's
|
||||
/// page size without breaking that caller's offset math (#1715: 500
|
||||
/// became "Invalid value provided for x-plex-container-size!").
|
||||
static const int _watchlistChunkSize = 25;
|
||||
|
||||
Future<PlexDiscoverPage> getWatchlist({int page = 1, int limit = 25}) async {
|
||||
final safePage = page < 1 ? 1 : page;
|
||||
final safeLimit = limit.clamp(1, 500);
|
||||
final offset = (safePage - 1) * safeLimit;
|
||||
try {
|
||||
return await _watchlistRange(offset, safeLimit);
|
||||
} on PlexDiscoverException catch (error) {
|
||||
if (safeLimit <= _watchlistChunkSize || !_isContainerSizeRejection(error)) rethrow;
|
||||
appLogger.w('Plex Discover: container size $safeLimit rejected, refetching in chunks of $_watchlistChunkSize');
|
||||
final items = <Map<String, dynamic>>[];
|
||||
PlexDiscoverPage chunk;
|
||||
do {
|
||||
final remaining = safeLimit - items.length;
|
||||
chunk = await _watchlistRange(
|
||||
offset + items.length,
|
||||
remaining > _watchlistChunkSize ? _watchlistChunkSize : remaining,
|
||||
);
|
||||
items.addAll(chunk.items);
|
||||
} while (items.length < safeLimit && chunk.hasMore && chunk.items.isNotEmpty);
|
||||
return PlexDiscoverPage(items: items, hasMore: chunk.hasMore, totalResults: chunk.totalResults);
|
||||
}
|
||||
}
|
||||
|
||||
Future<PlexDiscoverPage> _watchlistRange(int offset, int size) async {
|
||||
final data = await _request(
|
||||
'GET',
|
||||
'/library/sections/watchlist/all',
|
||||
query: {'X-Plex-Container-Start': offset, 'X-Plex-Container-Size': safeLimit, 'includeMeta': 1},
|
||||
query: {'X-Plex-Container-Start': offset, 'X-Plex-Container-Size': size, 'includeGuids': 1, 'includeMeta': 1},
|
||||
);
|
||||
final container = _mediaContainer(data!);
|
||||
final items = flexibleMapList(container['Metadata']);
|
||||
@@ -101,6 +128,9 @@ class PlexDiscoverClient {
|
||||
return PlexDiscoverPage(items: items, hasMore: offset + items.length < total, totalResults: reportedTotal);
|
||||
}
|
||||
|
||||
static bool _isContainerSizeRejection(PlexDiscoverException error) =>
|
||||
error.statusCode == 400 && error.message.toLowerCase().contains('container-size');
|
||||
|
||||
/// Discover's Home shelves — the rows Plex's own web client renders on its
|
||||
/// Home ▸ Trending tab, which reads
|
||||
/// `provider://tv.plex.provider.discover/hubs/sections/home`.
|
||||
@@ -188,6 +218,7 @@ class PlexDiscoverClient {
|
||||
key,
|
||||
query: {
|
||||
'limit': safeLimit,
|
||||
'includeGuids': 1,
|
||||
'includeMeta': 1,
|
||||
'includeUserState': 1,
|
||||
// Allowing Image on the measured 26-item hub grew 27,287 -> 55,925
|
||||
@@ -216,6 +247,7 @@ class PlexDiscoverClient {
|
||||
'limit': limit.clamp(1, 100),
|
||||
'searchTypes': 'movies,tv',
|
||||
'searchProviders': 'discover',
|
||||
'includeGuids': 1,
|
||||
'includeMetadata': 1,
|
||||
'filterPeople': 1,
|
||||
},
|
||||
@@ -237,7 +269,12 @@ class PlexDiscoverClient {
|
||||
_ => null,
|
||||
};
|
||||
if (guid == null) return null;
|
||||
final data = await _request('GET', '/library/metadata/matches', query: {'guid': guid}, allowNotFound: true);
|
||||
final data = await _request(
|
||||
'GET',
|
||||
'/library/metadata/matches',
|
||||
query: {'guid': guid, 'includeGuids': 1},
|
||||
allowNotFound: true,
|
||||
);
|
||||
if (data == null) return null;
|
||||
return firstFlexibleMap(_mediaContainer(data)['Metadata']);
|
||||
}
|
||||
@@ -306,7 +343,11 @@ class PlexDiscoverClient {
|
||||
'PUT' => _http.put(uri, headers: headers),
|
||||
_ => throw ArgumentError.value(method, 'method', 'Unsupported Plex Discover method'),
|
||||
};
|
||||
final stopwatch = Stopwatch()..start();
|
||||
final response = await request.timeout(requestTimeout);
|
||||
// The other API surfaces log every request; without this line Discover
|
||||
// drift is invisible in reporter logs (#1715 shipped blind).
|
||||
appLogger.d('Discover $method ${relative.path} → ${response.statusCode} (${stopwatch.elapsedMilliseconds}ms)');
|
||||
if (allowNotFound && response.statusCode == 404) return null;
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw PlexDiscoverException(response.statusCode, _errorMessage(response.body));
|
||||
|
||||
Reference in New Issue
Block a user