Files
plezy/test/models/catalog_item_test.dart
edde746 2cb2c3eb95 feat(ratings): show every rating source the server already sent
Plezy rendered exactly one score per item. MediaRatingBadge._ratingDataFor
took `rating` and fell back to `audienceRating` only when it was null, so a
Plex movie carrying four attributed scores surfaced one, and which one was
whatever the server happened to put in the scalar slot. #1755 asked for a
setting to choose the source; showing all of them answers it without one.

The data was already on the wire and being thrown away. `/library/metadata/
{id}` returns a `Rating[]` child array — IMDb, both Rotten Tomatoes panels,
TMDB — with no extra query parameter, but PlexMetadataDto declared no field
for it, so json_serializable dropped the key. The identical parse already
existed in plex_catalog_source for the Explore tab and had simply never been
wired to library items.

Model the scores as a list rather than widening the scalar pair. The neutral
MediaItem gains `ratings`; PlexMediaItem loses audienceRating, ratingImage
and audienceRatingImage, which the list subsumes — Plex sends those images
on listings too, so the same field covers both response shapes and no caller
narrows to a backend type to read a score any more. CatalogRatingSource is
promoted to lib/media as MediaRatingSource instead of growing a second
near-identical type beside it, and plex_catalog_source's _ratingsFor becomes
the shared plexRatingSources so one implementation serves both paths. There
is no persistence to migrate: MediaItem.toJson has no production caller, the
offline path re-parses raw Plex JSON through the same mapper, and Plex's
audienceRating sort is server-supplied data, not a model read.

Cards and the dashboard still show fewer scores than detail screens, and
that part is a real Plex limit rather than a shortcut. Section listings send
only the scalar pair; includeRatings, includeElements=Rating,
includeFields=Rating, includeChildren and includeExtras were each probed
against a live server and none surfaced the array, while includeGuids=1
demonstrably does add Guid[] — the probe works, the parameter does not
exist. Hydrating every card would be one request per row, so listings render
whatever their own response carried, which is one or two attributed scores
rather than the single one they showed before.

Jellyfin has no per-source array at all: the server collapses whatever its
fetchers found into CommunityRating and CriticRating. CommunityRating's
provenance is unknowable from the DTO — TMDB vote_average, IMDb via OMDb or
a local NFO, last writer wins — so it stays the generic `audience` source
with no brand mark. CriticRating is the Rotten Tomatoes Tomatometer as a
0-100 percent and is divided by ten explicitly rather than folded by
magnitude, because a Tomatometer of 9 means 9% and range-sniffing would have
promoted a rotten score to fresh. Photo rows are skipped, since Jellyfin
reuses CommunityRating for the EXIF 0-5 star.

The badges share one slot on every surface. On the phone hero the scores go
in a single pill because that chip row is a height-clipped Wrap and a chip
per source would push year, certification and runtime out of the visible
band on short heroes; on the TV detail line and the dashboard spotlight the
group occupies the one metadata slot so bullet separators do not multiply.
The group announces itself as a single semantics node naming each source,
because a bare row of four percentages tells a screen reader nothing about
which score is which. rating_utils drops parseRatingImage and
isRottenTomatoes — the URI vocabulary now lives only in the Plex mapper —
and the source-key resolver and label map, previously private to the Explore
detail screen, become the shared pair both screens use. The label strings
move from explore.ratingSource to common.ratingSource accordingly, which
costs no translations because every non-English value was empty; running
clean_translations also scaffolds startup.quitPlezy and
startup.restartRequiredBody, which were already drifted.

Verified against the live server the probes came from: a detail response now
yields TMDB 83%, IMDb 8.3 and Rotten Tomatoes audience 96% through the
production mapper and badge resolver, and the listing response for the same
title yields TMDB 83% alone. Both payloads are pinned verbatim as fixtures.
Coverage adds mapper ordering, dedupe against the array's repeat of the
scalar, out-of-range rejection, the Jellyfin scale and photo guard, the
CatalogItem conversion that feeds Explore's dashboard hubs, and the three
render surfaces including the semantics announcement.

close #1755
2026-08-02 03:59:56 +02:00

215 lines
7.9 KiB
Dart

import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/media/media_kind.dart';
import 'package:plezy/media/media_rating.dart';
import 'package:plezy/models/catalog/catalog_item.dart';
import 'package:plezy/models/catalog/catalog_metadata.dart';
import 'package:plezy/utils/external_ids.dart';
void main() {
group('CatalogItemIds', () {
test('round-trips provider-native ids through JSON', () {
const ids = CatalogItemIds(
plex: 'plex-4',
trakt: 8,
slug: 'title',
mal: 5,
anilist: 6,
simkl: 7,
imdb: 'tt123',
tmdb: 2,
tvdb: 3,
);
final json = ids.toJson();
final decoded = CatalogItemIds.fromJson(json);
expect(json, {
'plex': 'plex-4',
'trakt': 8,
'slug': 'title',
'mal': 5,
'anilist': 6,
'simkl': 7,
'imdb': 'tt123',
'tmdb': 2,
'tvdb': 3,
});
expect(decoded.plex, 'plex-4');
expect(decoded.anilist, 6);
expect(decoded.simkl, 7);
expect(decoded.hasAny, isTrue);
});
test('orders canonical and membership keys deterministically', () {
const ids = CatalogItemIds(
plex: 'plex-4',
trakt: 8,
slug: 'title',
mal: 5,
anilist: 6,
simkl: 7,
imdb: 'tt123',
tmdb: 2,
tvdb: 3,
);
expect(ids.canonicalKey, 'imdb:tt123');
expect(ids.allKeys, [
'imdb:tt123',
'tmdb:2',
'tvdb:3',
'mal:5',
'anilist:6',
'simkl:7',
'plex:plex-4',
'trakt:8',
'slug:title',
]);
expect(const CatalogItemIds(mal: 5, anilist: 6, simkl: 7).canonicalKey, 'mal:5');
expect(const CatalogItemIds(anilist: 6, simkl: 7).canonicalKey, 'anilist:6');
expect(const CatalogItemIds(simkl: 7, trakt: 8).canonicalKey, 'simkl:7');
expect(const CatalogItemIds(plex: 'plex-4', trakt: 8).canonicalKey, 'plex:plex-4');
});
test('entryKey identifies the entry, not the series it shares with its seasons', () {
// Every MAL/AniList season of one show carries the same series ids, so
// canonicalKey collides across seasons and cannot key a season-gated
// result. All five Mushoku Tensei entries collapse to imdb:tt13293588.
const s1 = CatalogItemIds(mal: 39535, imdb: 'tt13293588', tmdb: 94664, tvdb: 371310);
const s2 = CatalogItemIds(mal: 51179, imdb: 'tt13293588', tmdb: 94664, tvdb: 371310);
expect(s1.canonicalKey, s2.canonicalKey);
expect(s1.entryKey, 'mal:39535');
expect(s2.entryKey, 'mal:51179');
expect(const CatalogItemIds(anilist: 6, imdb: 'tt1').entryKey, 'anilist:6');
// Falls back to the series id when the entry has no provider-native id.
expect(const CatalogItemIds(imdb: 'tt1').entryKey, 'imdb:tt1');
});
});
group('CatalogItem', () {
const item = CatalogItem(
source: CatalogSourceId.anilist,
kind: MediaKind.show,
title: 'You and I Are Polar Opposites Season 2',
altTitles: ['Seihantai na Kimi to Boku 2nd Season', '\u6b63\u53cd\u5bfe\u306a\u541b\u3068\u50d5 \u7b2c2\u671f'],
season: ExternalSeasonRef(tvdb: 2, tmdb: 1),
year: 2026,
ids: CatalogItemIds(anilist: 210031, mal: 63832, tvdb: 457078),
);
test('survives the MediaItem.raw round trip the detail screen relies on', () {
// The Explore detail screen rebuilds the item out of MediaItem.raw, so a
// field that does not survive this seam silently disables the match fix
// in production while every source-level test still passes.
final raw = item.toMediaItem().raw?[CatalogItem.rawKey] as Map<String, Object?>?;
final decoded = CatalogItem.fromJson(raw!);
expect(decoded.altTitles, item.altTitles);
expect(decoded.season, const ExternalSeasonRef(tvdb: 2, tmdb: 1));
expect(decoded.title, item.title);
expect(decoded.ids.entryKey, 'mal:63832');
});
test('carries every attributed rating onto the synthesized MediaItem', () {
// Explore's dashboard hubs render through this conversion, so a rating
// dropped here means the TV spotlight silently falls back to one score.
const rated = CatalogItem(
source: CatalogSourceId.simkl,
kind: MediaKind.movie,
title: 'Rated',
ids: CatalogItemIds(tmdb: 603),
rating: 8.1,
ratings: [
MediaRatingSource(source: 'simkl', value: 8.1, votes: 11),
MediaRatingSource(source: 'imdb', value: 7.9, votes: 12),
],
);
final rendered = rated.toMediaItem();
expect(rendered.rating, 8.1);
expect(rendered.ratings?.map((rating) => rating.source), ['simkl', 'imdb']);
expect(rendered.ratings?.last.votes, 12);
});
test('survives an encode/decode cycle that erases the static map types', () {
// Persisted/transport JSON comes back as Map<String, dynamic> and
// List<dynamic>; the nested season object must not depend on its
// compile-time type to be read back.
final decoded = CatalogItem.fromJson(jsonDecode(jsonEncode(item.toJson())) as Map<String, dynamic>);
expect(decoded.altTitles, item.altTitles);
expect(decoded.season?.tvdb, 2);
expect(decoded.season?.tmdb, 1);
expect(decoded.season?.isSequel, isTrue);
expect(decoded.season?.agreedSeason, isNull);
});
test('omits both new fields when absent rather than emitting empties', () {
const bare = CatalogItem(
source: CatalogSourceId.trakt,
kind: MediaKind.movie,
title: 'Solo Movie',
ids: CatalogItemIds(imdb: 'tt1'),
);
expect(bare.toJson().containsKey('altTitles'), isFalse);
expect(bare.toJson().containsKey('season'), isFalse);
final decoded = CatalogItem.fromJson(bare.toJson());
expect(decoded.altTitles, isEmpty);
expect(decoded.season, isNull);
});
test('enrichedWith unions audience counters instead of replacing them', () {
// A Simkl trending row supplies windowed viewers and planning; its
// detail body supplies only a drop rate. Replacing the object wholesale
// silently dropped the row's counters.
const row = CatalogItem(
source: CatalogSourceId.simkl,
kind: MediaKind.show,
title: 'House of the Dragon',
ids: CatalogItemIds(simkl: 1197910),
audience: CatalogAudience(viewers: 7603, viewersPeriod: CatalogAudiencePeriod.week, planning: 8422),
);
const detail = CatalogItem(
source: CatalogSourceId.simkl,
kind: MediaKind.show,
title: 'House of the Dragon',
ids: CatalogItemIds(simkl: 1197910),
audience: CatalogAudience(dropRate: 0.031),
);
final merged = row.enrichedWith(detail).audience!;
expect(merged.viewers, 7603);
expect(merged.viewersPeriod, CatalogAudiencePeriod.week);
expect(merged.planning, 8422);
expect(merged.dropRate, 0.031);
});
test('enrichedWith lets detail replace a row value and merges ids per key', () {
const row = CatalogItem(
source: CatalogSourceId.seerr,
kind: MediaKind.movie,
title: 'The Matrix',
ids: CatalogItemIds(imdb: 'tt0133093'),
ranks: [CatalogRank(rank: 3, scope: CatalogRankScope.trending, allTime: false)],
);
const detail = CatalogItem(
source: CatalogSourceId.seerr,
kind: MediaKind.movie,
title: 'The Matrix',
overview: 'A full synopsis the row never carried.',
ids: CatalogItemIds(tmdb: 603),
);
final merged = row.enrichedWith(detail);
expect(merged.overview, 'A full synopsis the row never carried.');
expect(merged.ids.imdb, 'tt0133093', reason: 'row-only id must survive');
expect(merged.ids.tmdb, 603, reason: 'detail id must be adopted');
expect(merged.ranks?.single.rank, 3, reason: 'a rank is row context a detail body cannot know');
});
});
}