fix(anilist): resolve later seasons past split-cour halves and specials (#335)

This commit is contained in:
sudacode authored and GitHub committed 2026-11-22 21:03:11 -08:00
1 parent ac3ceab856
commit 9d2057cc30
10 files changed
+1539 -153

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
type: fixed
area: anilist
- Later seasons now resolve to the right AniList entry when the sequel chain contains split-season halves ("Part 2", "Cour 2"), specials, or movies. Mushoku Tensei S3, Re:ZERO S4, Dr. STONE S3, KonoSuba S3, and Attack on Titan S4 used to land one season short or on a movie.
- An entry whose title names the season ("Season 3", "III", "第3期") is preferred over counting sequels.
- Episodes past the first half of a split season update the second half's AniList entry at the right episode (episode 15 of an 11 + 12 season updates the second entry to episode 4).
- Character dictionary AniList matches cached by older versions are re-resolved once.
+5 -3
View File
@@ -26,8 +26,8 @@ On Linux, the token is stored with `gnome-libsecret` by default. If your keyring
An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then:
1. Reads the title, season, and episode from the file name and folder. Install [guessit](https://github.com/guessit-io/guessit) for better parsing. A folder named `Season 2` is a strong season hint.
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels.
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode.
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels. Specials, movies, and the second half of a split season ("Part 2", "Cour 2") do not count as seasons, and an entry whose title names the season ("Season 3", "III") wins.
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode. AniList lists the second half of a split season as its own entry, so an episode past the first half goes there: episode 15 of a season split 11 + 12 is episode 4 of the second entry.
If the show is not on your list yet, SubMiner adds it as Watching, but only when the file title exactly matches an AniList title or you pinned the entry with the character dictionary's AniList override. For a looser match, add the show to Planning or Watching yourself. SubMiner never changes entries marked Completed, Paused, Dropped, or Rewatching, and it never lowers your progress.
@@ -37,7 +37,9 @@ Failed updates are saved and retried in the background, up to 8 times with growi
If a cover or title in the stats Library is wrong, open the title and use **Change AniList Entry**.
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary).
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary). The override is also the fix when AniList splits a season without marking the second half in any title.
Library entries matched by older versions keep their match after an update. If one points at the wrong season, use **Change AniList Entry**.
## Commands
+1 -1
View File
@@ -67,7 +67,7 @@ Read when: you need to find the owner module for a behavior or test surface
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`. Every consumer maps a parsed title + season to an AniList entry through `anilist/season-resolver.ts` (sequel-chain walk; see its header for what counts as a season). Changing what it returns needs a `MEDIA_RESOLUTION_CACHE_VERSION` bump in `character-dictionary-runtime/cache.ts`, or old matches keep being served from `anilist-resolution-cache.json`.
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
assembled by `src/main/assemblies/jellyfin.ts`
@@ -0,0 +1,651 @@
// Captured from live AniList responses on 2026-11-22, trimmed to the fields the resolver reads.
// Each chain is in SEQUEL order: entry i's only SEQUEL is entry i + 1.
import type { AnilistSeasonMedia } from '../season-resolver';
/** Mushoku Tensei: S1 -> "Cour 2" -> S2 -> "Season 2 Part 2" -> S3 -> S3 Part 2. */
export const MUSHOKU_CHAIN: AnilistSeasonMedia[] = [
{
id: 108465,
episodes: 11,
format: 'TV',
seasonYear: 2021,
synonyms: [
'Jobless Reincarnation: I Will Seriously Try If I Go To Another World',
'无职转生 ~到了异世界就拿出真本事~',
'เกิดชาตินี้พี่ต้องเทพ',
'Thất nghiệp chuyển sinh',
],
title: {
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu',
english: 'Mushoku Tensei: Jobless Reincarnation',
native: '無職転生 ~異世界行ったら本気だす~',
},
},
{
id: 127720,
episodes: 12,
format: 'TV',
seasonYear: 2021,
synonyms: ['Mushoku Tensei: Jobless Reincarnation Part 2', 'เกิดชาตินี้พี่ต้องเทพ พาร์ท 2'],
title: {
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu Part 2',
english: 'Mushoku Tensei: Jobless Reincarnation Cour 2',
native: '無職転生 ~異世界行ったら本気だす~ 第2クール',
},
},
{
id: 146065,
episodes: 13,
format: 'TV',
seasonYear: 2023,
synonyms: [
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2',
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season',
'Mushoku Tensei II: Jobless Reincarnation',
'Mushoku Tensei II: Reencarnación desde cero',
'无职转生~到了异世界就拿出真本事~第2季',
],
title: {
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu',
english: 'Mushoku Tensei: Jobless Reincarnation Season 2',
native: '無職転生Ⅱ ~異世界行ったら本気だす~',
},
},
{
id: 166873,
episodes: 12,
format: 'TV',
seasonYear: 2024,
synonyms: [
'Mushoku Tensei: Jobless Reincarnation Season 2 Cour 2',
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2 ครึ่งหลัง',
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season Part 2',
'Mushoku Tensei II: Jobless Reincarnation Part 2',
'Mushoku Tensei II: Reencarnación desde cero',
'无职转生~到了异世界就拿出真本事~第2季',
],
title: {
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu Part 2',
english: 'Mushoku Tensei: Jobless Reincarnation Season 2 Part 2',
native: '無職転生Ⅱ ~異世界行ったら本気だす~ 第2クール',
},
},
{
id: 178789,
episodes: 14,
format: 'TV',
seasonYear: 2026,
synonyms: [
'無職転生 ~異世界行ったら本気だす~ 第3期',
'Mushoku Tensei: Isekai Ittara Honki Dasu 3rd Season',
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 3',
],
title: {
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu',
english: 'Mushoku Tensei: Jobless Reincarnation Season 3',
native: '無職転生Ⅲ ~異世界行ったら本気だす~',
},
},
{
id: 217434,
episodes: null,
format: 'TV',
seasonYear: 2027,
synonyms: ['Mushoku Tensei: Jobless Reincarnation Season 3 Part 2'],
title: {
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu Part 2',
english: null,
native: '無職転生Ⅲ ~異世界行ったら本気だす~ 第2クール',
},
},
];
/** Re:ZERO: S1 -> S2 -> "Season 2 Part 2" -> S3 -> S4 -> S5 (unaired). */
export const REZERO_CHAIN: AnilistSeasonMedia[] = [
{
id: 21355,
episodes: 25,
format: 'TV',
seasonYear: 2016,
synonyms: [
'Re: Life in a different world from zero',
'ReZero',
'Re Zero',
'Re:从零开始的异世界生活',
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก',
'Re:Zero — жизнь с нуля в другом мире',
'Re:Zero Empezar de cero en un mundo diferente',
'Re:Zero – Bắt đầu lại ở thế giới khác',
],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu',
english: 'Re:ZERO -Starting Life in Another World-',
native: 'Re:ゼロから始める異世界生活',
},
},
{
id: 108632,
episodes: 13,
format: 'TV',
seasonYear: 2020,
synonyms: [
'Re:Zero kara Hajimeru Isekai Seikatsu (2020)',
'Re: 제로부터 시작하는 이세계 생활 2기',
'Re:从零开始的异世界生活第二季(上半)',
'Re:从零开始的异世界生活 2 上半',
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2',
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season',
english: 'Re:ZERO -Starting Life in Another World- Season 2',
native: 'Re:ゼロから始める異世界生活 2nd Season',
},
},
{
id: 119661,
episodes: 12,
format: 'TV',
seasonYear: 2021,
synonyms: [
'Re:Zero kara Hajimeru Isekai Seikatsu (2021)',
'Re: 제로부터 시작하는 이세계 생활 2기 파트 2',
'Re:从零开始的异世界生活第二季(下半)',
'Re:从零开始的异世界生活 2 下半',
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2 พาร์ท 2',
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season Part 2',
english: 'Re:ZERO -Starting Life in Another World- Season 2 Part 2',
native: 'Re:ゼロから始める異世界生活 2nd Season Part 2',
},
},
{
id: 163134,
episodes: 16,
format: 'TV',
seasonYear: 2024,
synonyms: ['Re:ZERO – Жизнь с нуля в альтернативном мире 3'],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 3rd Season',
english: 'Re:ZERO -Starting Life in Another World- Season 3',
native: 'Re:ゼロから始める異世界生活 3rd season',
},
},
{
id: 189046,
episodes: 19,
format: 'TV',
seasonYear: 2026,
synonyms: [
'Re:ZERO รีเซทชีวิต ฝ่าวิกฤตต่างโลก ซีซั่น 4',
'Re:ZERO – Жизнь с нуля в альтернативном мире 4',
],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 4th Season',
english: 'Re:ZERO -Starting Life in Another World- Season 4',
native: 'Re:ゼロから始める異世界生活 4th season',
},
},
{
id: 219904,
episodes: null,
format: 'TV',
seasonYear: null,
synonyms: ['Re:ZERO -Starting Life in Another World- Season 5'],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 5th Season',
english: null,
native: 'Re:ゼロから始める異世界生活 5th season',
},
},
];
/** Dr. STONE: STONE WARS reaches NEW WORLD through a one-episode SPECIAL. */
export const DR_STONE_CHAIN: AnilistSeasonMedia[] = [
{
id: 105333,
episodes: 24,
format: 'TV',
seasonYear: 2019,
synonyms: [
'Dcst',
'石纪元',
'ドクターストーン',
'ดร.สโตน เจ้าแห่งวิทยาศาสตร์กู้คืนอารยธรรมโลก',
'Доктор Стоун',
],
title: {
romaji: 'Dr. STONE',
english: 'Dr. STONE',
native: 'Dr.STONE',
},
},
{
id: 113936,
episodes: 11,
format: 'TV',
seasonYear: 2021,
synonyms: [
'ドクターストーン STONE WARS',
'Dr.STONE第2期',
'Dr. STONE 2',
'닥터 스톤 STONE WARS',
'石纪元第二季',
'DR.STONE ภาค 2',
'Доктор Стоун: Каменные войны',
],
title: {
romaji: 'Dr. STONE: STONE WARS',
english: 'Dr. STONE: STONE WARS',
native: 'Dr.STONE STONE WARS',
},
},
{
id: 142876,
episodes: 1,
format: 'SPECIAL',
seasonYear: 2022,
synonyms: ['Dr. STONE: Ryusui', 'Доктор Стоун: Рюсуй'],
title: {
romaji: 'Dr. STONE: Ryuusui',
english: 'Dr. STONE Special Episode – RYUSUI',
native: 'Dr.STONE 龍水',
},
},
{
id: 131518,
episodes: 11,
format: 'TV',
seasonYear: 2023,
synonyms: [
'石纪元第三季',
'Dr.STONE Season 3',
'DR.STONE ภาค 3',
'Dr.STONE 第3期',
'Dr. STONE 新石紀(第三季)',
'Доктор Стоун: Новый Свет',
],
title: {
romaji: 'Dr. STONE: NEW WORLD',
english: 'Dr. STONE New World',
native: 'Dr.STONE NEW WORLD',
},
},
{
id: 162670,
episodes: 11,
format: 'TV',
seasonYear: 2023,
synonyms: [
'石纪元第三季',
'Dr.STONE Season 3 Part 2',
'DR.STONE ภาค 3',
'Dr.STONE 第3期 第2クール',
],
title: {
romaji: 'Dr. STONE: NEW WORLD Part 2',
english: 'Dr. STONE New World Part 2',
native: 'Dr.STONE NEW WORLD 第2クール',
},
},
{
id: 172019,
episodes: 12,
format: 'TV',
seasonYear: 2025,
synonyms: ['Dr.STONE Season 4', 'Dr.STONE 第4期', 'ドクターストーン'],
title: {
romaji: 'Dr. STONE: SCIENCE FUTURE',
english: 'Dr. STONE SCIENCE FUTURE',
native: 'Dr.STONE SCIENCE FUTURE',
},
},
];
/** Bleach TYBW: cours named after arcs; "Part N" only in synonyms, spelled "Thousand Year". */
export const BLEACH_TYBW_CHAIN: AnilistSeasonMedia[] = [
{
id: 116674,
episodes: 13,
format: 'TV',
seasonYear: 2022,
synonyms: [
'بليتش: حرب الألف سنة الدموية',
'Bleach: La guerre sanglante de mille ans',
'BLEACH TYBW',
],
title: {
romaji: 'BLEACH: Sennen Kessen-hen',
english: 'BLEACH: Thousand-Year Blood War',
native: 'BLEACH 千年血戦篇',
},
},
{
id: 159322,
episodes: 13,
format: 'TV',
seasonYear: 2023,
synonyms: [
'BLEACH: Thousand Year Blood War Part 2',
'BLEACH 千年血戦篇 第2クール',
'BLEACH TYBW',
],
title: {
romaji: 'BLEACH: Sennen Kessen-hen - Ketsubetsu-tan',
english: 'BLEACH: Thousand-Year Blood War - The Separation',
native: 'BLEACH 千年血戦篇-訣別譚-',
},
},
{
id: 169755,
episodes: 14,
format: 'TV',
seasonYear: 2024,
synonyms: [
'BLEACH: Thousand Year Blood War Part 3',
'BLEACH 千年血戦篇 第3クール',
'BLEACH TYBW',
],
title: {
romaji: 'BLEACH: Sennen Kessen-hen - Soukoku-tan',
english: 'BLEACH: Thousand-Year Blood War - The Conflict',
native: 'BLEACH 千年血戦篇-相剋譚-',
},
},
{
id: 185874,
episodes: 10,
format: 'TV',
seasonYear: 2026,
synonyms: [
'BLEACH: Thousand-Year Blood War Part 4',
'BLEACH 千年血戦篇 第4クール',
'BLEACH: Thousand-Year Blood War The Final Season',
'BLEACH TYBW',
],
title: {
romaji: 'BLEACH: Sennen Kessen-hen - Kashin-tan',
english: 'BLEACH: Thousand-Year Blood War - The Calamity',
native: 'BLEACH 千年血戦篇-禍進譚-',
},
},
];
/** Attack on Titan: season 3 carries the Thai synonym "... ภาค 3 Part 1"; the chain ends in SPECIALs. */
export const AOT_CHAIN: AnilistSeasonMedia[] = [
{
id: 16498,
episodes: 25,
format: 'TV',
seasonYear: 2013,
synonyms: [
'SnK',
'AoT',
'Ataque a los Titanes',
'Ataque dos Titãs',
"L'Attacco dei Giganti",
'מתקפת הטיטאנים',
'进击的巨人',
'L’Attaque des Titans',
'الهجوم على العمالقة',
'ผ่าพิภพไททัน',
'حمله به تایتان',
'Ataque de Titãs',
'Atak Tytanów',
'Атака титанов',
'Đại Chiến Titan',
],
title: {
romaji: 'Shingeki no Kyojin',
english: 'Attack on Titan',
native: '進撃の巨人',
},
},
{
id: 20958,
episodes: 12,
format: 'TV',
seasonYear: 2017,
synonyms: [
'SnK 2',
'AoT 2',
'+מתקפת הטיטאנים עונה 2',
"L'Attacco dei Giganti 2",
"L'Attacco dei Giganti - Seconda Stagione",
'ผ่าพิภพไททัน ภาค 2',
'حمله به تایتان فصل 2',
'Атака титанов 2',
],
title: {
romaji: 'Shingeki no Kyojin Season 2',
english: 'Attack on Titan Season 2',
native: '進撃の巨人 Season2',
},
},
{
id: 99147,
episodes: 12,
format: 'TV',
seasonYear: 2018,
synonyms: [
'SnK 3',
'AoT 3',
'מתקפת הטיטאנים עונה 3',
"L'Attacco dei Giganti 3",
"L'Attacco dei Giganti - Terza Stagione",
'ผ่าพิภพไททัน ภาค 3',
'حمله به تایتان فصل 3',
'ผ่าพิภพไททัน ภาค 3 Part 1',
'Атака титанов 3',
],
title: {
romaji: 'Shingeki no Kyojin Season 3',
english: 'Attack on Titan Season 3',
native: '進撃の巨人 Season3',
},
},
{
id: 104578,
episodes: 10,
format: 'TV',
seasonYear: 2019,
synonyms: [
'SnK 3',
'AoT 3',
'Shingeki no Kyojin Season 3 (2019)',
"L'Attaco dei Giganti 3 Parte 2",
"L'Attacco dei Giganti - Terza Stagione Parte 2",
'מתקפת הטיטאנים עונה 3 חלק 2',
"L'Attaque des Titans Saison 3 Partie 2 ",
'ผ่าพิภพไททัน ภาค 3 Part 2',
'ผ่าพิภพไททัน ภาค 3 พาร์ท 2',
'حمله به تایتان فصل 3',
],
title: {
romaji: 'Shingeki no Kyojin Season 3 Part 2',
english: 'Attack on Titan Season 3 Part 2',
native: '進撃の巨人 Season3 Part.2',
},
},
{
id: 110277,
episodes: 16,
format: 'TV',
seasonYear: 2021,
synonyms: [
'SnK 4',
'AoT 4',
'Shingeki no Kyojin 4',
'進撃の巨人4',
'Attack on Titan Season 4',
'진격의 거인 더 파이널 시즌',
'מתקפת הטיטאנים העונה האחרונה',
"L'Attaque des Titans Saison Finale",
"L'Attacco dei Giganti 4",
"L'Attacco dei Giganti - La Stagione Finale",
'حمله به تایتان فصل 4 ',
' ผ่าพิภพไททัน ไฟนอล ซีซั่น',
'ผ่าพิภพไททัน Final Season',
'ผ่าพิภพไททัน ภาค 4',
'هجوم العملاقة الجزء الأخير',
'Атака Титанов: Финал',
],
title: {
romaji: 'Shingeki no Kyojin: The Final Season',
english: 'Attack on Titan Final Season',
native: '進撃の巨人 The Final Season',
},
},
{
id: 131681,
episodes: 12,
format: 'TV',
seasonYear: 2022,
synonyms: [
'SnK 4',
'AoT 4',
"L'attaque des titans Saison Finale Partie 2",
'Shingeki no Kyojin: The Final Season (2022)',
'اتک عن تایتان',
'حمله به غول ها',
'حمله به تایتان فصل 4 ',
' ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 2',
'ผ่าพิภพไททัน ภาค 4',
"L'Attacco dei Giganti 4 Parte 2",
'Атака титанов: Финал. Часть 2',
],
title: {
romaji: 'Shingeki no Kyojin: The Final Season Part 2',
english: 'Attack on Titan Final Season Part 2',
native: '進撃の巨人 The Final Season Part 2',
},
},
{
id: 146984,
episodes: 1,
format: 'SPECIAL',
seasonYear: 2023,
synonyms: [
'Shingeki no Kyojin: The Final Season Final Edition',
'Shingeki no Kyojin: The Final Season Part 3',
'ผ่าพิภพไททัน ภาค 4',
'ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 3',
'Attack on Titan Final Season Part 3 Final Arc Part 1',
'Attack on Titan The Final Season The Final Part Special',
'Attack on Titan The Final Season The Final Part Part 1',
'حمله به تایتان فصل آخر قسمت ویژه 1 ',
'SnK 4',
'AoT 4',
],
title: {
romaji: 'Shingeki no Kyojin: The Final Season - Kanketsu-hen Zenpen',
english: 'Attack on Titan Final Season THE FINAL CHAPTERS Special 1',
native: '進撃の巨人 The Final Season完結編 前編',
},
},
];
/** Overlord: seasons named only by a trailing roman numeral. */
export const OVERLORD_CHAIN: AnilistSeasonMedia[] = [
{
id: 20832,
episodes: 13,
format: 'TV',
seasonYear: 2015,
synonyms: ['Over Lord', 'โอเวอร์ลอร์ด', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก'],
title: {
romaji: 'Overlord',
english: 'Overlord',
native: 'オーバーロード',
},
},
{
id: 98437,
episodes: 13,
format: 'TV',
seasonYear: 2018,
synonyms: ['Over Lord 2', 'โอเวอร์ลอร์ด ภาค 2', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 2'],
title: {
romaji: 'Overlord II',
english: 'Overlord II',
native: 'オーバーロードⅡ',
},
},
{
id: 101474,
episodes: 13,
format: 'TV',
seasonYear: 2018,
synonyms: ['Over Lord 3', 'โอเวอร์ลอร์ด ภาค 3', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 3'],
title: {
romaji: 'Overlord III',
english: 'Overlord III',
native: 'オーバーロードⅢ',
},
},
];
/** JoJo: Golden Wind ends in the synonym "Part 5", Stone Ocean in "Part 6"; both are new seasons. */
export const JOJO_CHAIN: AnilistSeasonMedia[] = [
{
id: 21450,
episodes: 39,
format: 'TV',
seasonYear: 2016,
synonyms: [
'JoJo no Kimyou na Bouken Part 4: Diamond wa Kudakenai',
"JoJo's Bizarre Adventure Part 4: Diamond is Unbreakable",
'مغامرات جوجو العجيبة: الألماس غير قابل للكسر',
'Le bizzarre avventure di JoJo: Diamond is Unbreakable',
'Невероятные приключения ДжоДжо: Diamond is Unbreakable',
],
title: {
romaji: 'JoJo no Kimyou na Bouken: Diamond wa Kudakenai',
english: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
native: 'ジョジョの奇妙な冒険 ダイヤモンドは砕けない',
},
},
{
id: 102883,
episodes: 39,
format: 'TV',
seasonYear: 2018,
synonyms: [
"JoJo's Bizarre Adventure Part 5",
"JoJo's Bizarre Adventure: Vento Aureo",
'Le Bizzarre Avventure Di GioGio: Vento Aureo',
'مغامرات جوجو العجيبة: الرياح الذهبية',
'Невероятные приключения ДжоДжо: Золотой ветер',
],
title: {
romaji: 'JoJo no Kimyou na Bouken: Ougon no Kaze',
english: "JoJo's Bizarre Adventure: Golden Wind",
native: 'ジョジョの奇妙な冒険 黄金の風',
},
},
{
id: 131942,
episodes: 12,
format: 'ONA',
seasonYear: 2021,
synonyms: [
"JoJo's Bizarre Adventure: Stone Ocean",
"JoJo's Bizarre Adventure Part 6",
'JoJo no Kimyou na Bouken Part 6',
'Le bizzarre avventure di JoJo: Stone Ocean',
'โจโจ้ ล่าข้ามศตวรรษ: สโตนโอเชียน ',
'โจโจ้ ล่าข้ามศตวรรษ ภาค 6',
'مغامرات جوجو العجيبة: محيط الأحجار',
"ההרפתקה המוזרה של ג'וג'ו: אוקיינוס האבן",
'Невероятные приключения ДжоДжо: Каменный океан ',
"Химерні пригоди ДжоДжо: Кам'яний океан",
],
title: {
romaji: 'JoJo no Kimyou na Bouken: Stone Ocean',
english: "JoJo's Bizarre Adventure: STONE OCEAN",
native: 'ジョジョの奇妙な冒険 ストーンオーシャン',
},
},
];
@@ -585,6 +585,11 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
});
}
if (call === 3) {
// Looks one season past the count for an entry naming season 2; there is none.
assert.equal(body.variables?.id, 202);
return createJsonResponse({ data: { Media: { relations: { edges: [] } } } });
}
if (call === 4) {
assert.equal(body.variables?.mediaId, 202);
return createJsonResponse({
data: {
@@ -608,7 +613,68 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
assert.deepEqual(searchTerms, ['Demo Show']);
assert.equal(result.status, 'updated');
assert.match(result.message, /Demo Show Sequel/);
assert.equal(call, 4);
assert.equal(call, 5);
} finally {
globalThis.fetch = originalFetch;
}
});
test('updateAnilistPostWatchProgress writes a split-cour episode to the part that airs it', async () => {
const originalFetch = globalThis.fetch;
const saved: Array<Record<string, unknown> | undefined> = [];
globalThis.fetch = (async (_input, init) => {
const body = JSON.parse(String(init?.body)) as {
query: string;
variables?: Record<string, unknown>;
};
if (body.query.includes('Page(')) {
return createJsonResponse({
data: {
Page: {
media: [{ id: 101, episodes: 11, format: 'TV', title: { english: 'Demo Show' } }],
},
},
});
}
if (body.query.includes('relations')) {
assert.equal(body.variables?.id, 101);
return createJsonResponse({
data: {
Media: {
relations: {
edges: [
{
relationType: 'SEQUEL',
node: {
id: 202,
type: 'ANIME',
episodes: 12,
format: 'TV',
title: { english: 'Demo Show Cour 2' },
},
},
],
},
},
},
});
}
if (body.query.includes('SaveMediaListEntry')) {
saved.push(body.variables);
return createJsonResponse({ data: { SaveMediaListEntry: { progress: 4 } } });
}
assert.equal(body.variables?.mediaId, 202);
return createJsonResponse({
data: { Media: { id: 202, mediaListEntry: { progress: 3, status: 'CURRENT' } } },
});
}) as typeof fetch;
try {
// Episode 15 of an 11 + 12 season is episode 4 of the second cour's entry.
const result = await updateAnilistPostWatchProgress('token', 'Demo Show', 15, { season: 1 });
assert.equal(result.status, 'updated');
assert.match(result.message, /Demo Show Cour 2.*episode 4/);
assert.deepEqual(saved, [{ mediaId: 202, progress: 4, status: 'CURRENT' }]);
} finally {
globalThis.fetch = originalFetch;
}
+18 -11
View File
@@ -273,6 +273,9 @@ export async function updateAnilistPostWatchProgress(
let mediaId = pinnedMediaId;
let resolvedTitle: string | null = null;
let resolvedEpisodes: number | null = null;
// Episode number within the entry being updated; differs from `episode` only for a
// split-cour back half.
let progress = episode;
// A missing list entry is only created when we trust the match; otherwise a fuzzy
// search hit would add an unrelated show to the user's list.
let confidentMatch = pinnedMediaId !== null;
@@ -312,14 +315,18 @@ export async function updateAnilistPostWatchProgress(
};
}
mediaId = resolution.id;
resolvedTitle = resolution.title;
resolvedEpisodes = resolution.episodes;
// A split-cour back half is its own AniList entry with its own episode numbering:
// "S1E15" of an 11 + 12 season is progress 4 on the second entry.
const target = resolution.episodeEntry ?? resolution;
mediaId = target.id;
resolvedTitle = target.title;
resolvedEpisodes = target.episodes;
progress = resolution.episodeEntry?.episode ?? episode;
// With no parsed season, an exact match on a season-stripped title ("Show S2" ->
// "Show") only certifies the season 1 anchor, not the entry being watched.
const seasonMarkerStripped = stripSeasonSuffix(title).trim() !== title.trim();
confidentMatch =
resolution.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
target.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
}
const entryResponse = await anilistGraphQl<AnilistMediaEntryData>(
@@ -376,8 +383,8 @@ export async function updateAnilistPostWatchProgress(
}
const currentProgress = entry?.progress ?? 0;
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, episode);
if (typeof currentProgress === 'number' && currentProgress >= episode && !shouldMarkCompleted) {
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, progress);
if (typeof currentProgress === 'number' && currentProgress >= progress && !shouldMarkCompleted) {
return {
status: 'skipped',
message: `AniList already at episode ${currentProgress} (${pickedTitle}).`,
@@ -396,7 +403,7 @@ export async function updateAnilistPostWatchProgress(
`,
{
mediaId,
progress: episode,
progress,
status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT',
},
options,
@@ -410,15 +417,15 @@ export async function updateAnilistPostWatchProgress(
return {
status: 'updated',
message: shouldMarkCompleted
? `AniList added "${pickedTitle}" at episode ${episode} and marked it completed.`
: `AniList added "${pickedTitle}" to Watching at episode ${episode}.`,
? `AniList added "${pickedTitle}" at episode ${progress} and marked it completed.`
: `AniList added "${pickedTitle}" to Watching at episode ${progress}.`,
};
}
return {
status: 'updated',
message: shouldMarkCompleted
? `AniList updated "${pickedTitle}" to episode ${episode} and marked it completed.`
: `AniList updated "${pickedTitle}" to episode ${episode}.`,
? `AniList updated "${pickedTitle}" to episode ${progress} and marked it completed.`
: `AniList updated "${pickedTitle}" to episode ${progress}.`,
};
}
@@ -4,11 +4,22 @@ import assert from 'node:assert/strict';
import {
ANILIST_SEASON_RELATIONS_QUERY,
ANILIST_SEASON_SEARCH_QUERY,
namedSeasons,
pickByAirOrder,
resolveAnilistSeasonMedia,
splitPartMarker,
stripSeasonSuffix,
type AnilistSeasonMedia,
} from './season-resolver';
import {
AOT_CHAIN,
BLEACH_TYBW_CHAIN,
DR_STONE_CHAIN,
JOJO_CHAIN,
MUSHOKU_CHAIN,
OVERLORD_CHAIN,
REZERO_CHAIN,
} from './__fixtures__/anilist-season-chains';
/** Real AniList payloads for "My Teen Romantic Comedy SNAFU", trimmed to used fields. */
const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [
@@ -161,7 +172,8 @@ test('resolves season 3 by walking sequel relations', async () => {
assert.equal(result?.via, 'sequel-chain');
// Searches the bare title only; "Season 3" returns nothing on AniList.
assert.deepEqual(searches, ['My Teen Romantic Comedy SNAFU']);
assert.deepEqual(relationLookups, [14813, 20698]);
// The last lookup checks one season past the count for an entry naming season 3.
assert.deepEqual(relationLookups, [14813, 20698, 108489]);
});
test('season 1 resolves to the anchor without relation lookups', async () => {
@@ -215,7 +227,7 @@ test('a sequel resolution whose own title matches the parsed title stays exact',
);
assert.equal(result?.id, 2);
assert.equal(result?.via, 'sequel-chain');
assert.equal(result?.via, 'named-season');
assert.equal(result?.exactTitleMatch, true);
});
@@ -325,7 +337,7 @@ test('prefers the TV sequel when a franchise branches into other formats', async
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
assert.equal(result?.id, 2);
assert.equal(result?.via, 'sequel-chain');
assert.equal(result?.via, 'named-season');
});
test('air-order fallback refuses when the anchor is not the earliest entry', () => {
@@ -399,3 +411,288 @@ test('air-order fallback declines when a franchise entry has no air year', async
assert.equal(result?.seasonResolved, false);
assert.equal(result?.via, 'anchor');
});
/** Executor over a fixture chain: search returns the whole chain, entry i's SEQUEL is i + 1. */
function createChainExecutor(chain: AnilistSeasonMedia[]) {
const relations: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {};
chain.forEach((entry, index) => {
const next = chain[index + 1];
relations[entry.id] = next ? [{ relationType: 'SEQUEL', node: next }] : [];
});
return createExecutor(chain, relations);
}
async function resolveInChain(
chain: AnilistSeasonMedia[],
input: { title: string; season?: number | null; episode?: number | null },
) {
const executor = createChainExecutor(chain);
const result = await resolveAnilistSeasonMedia(input, { execute: executor.execute });
return { result, relationLookups: executor.relationLookups };
}
test('split-cour back halves do not count as seasons', async () => {
const title = 'Mushoku Tensei: Jobless Reincarnation';
const s2 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 2, episode: 1 });
assert.equal(s2.result?.id, 146065);
assert.equal(s2.result?.seasonResolved, true);
const s3 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 3, episode: 1 });
assert.equal(s3.result?.id, 178789);
// Four hops for two seasons: "Cour 2" and "Season 2 Part 2" were walked through.
assert.deepEqual(s3.relationLookups, [108465, 127720, 146065, 166873]);
const reZeroS3 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 3 });
assert.equal(reZeroS3.result?.id, 163134);
const reZeroS4 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 4 });
assert.equal(reZeroS4.result?.id, 189046);
});
test('a special in the sequel chain is walked through without counting', async () => {
const s3 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 3 });
assert.equal(s3.result?.id, 131518);
const s4 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 4 });
assert.equal(s4.result?.id, 172019);
});
test('season names ignore part and cour numbers, including localized ones', () => {
// "Cour 2" carries the Thai synonym "... พาร์ท 2" ("part 2").
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[1]!)], []);
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[3]!)], [2]);
assert.deepEqual([...namedSeasons(OVERLORD_CHAIN[1]!)], [2]);
assert.deepEqual([...namedSeasons(DR_STONE_CHAIN[1]!)], [2]);
assert.deepEqual([...namedSeasons(AOT_CHAIN[4]!)], [4]);
});
test('an entry naming the requested season beats the hop count', async () => {
// The second cour has no marker anywhere, so counting alone would call it season 2.
const chain: AnilistSeasonMedia[] = [
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show: Arc Two' } },
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
];
const { result } = await resolveInChain(chain, { title: 'Show', season: 2 });
assert.equal(result?.id, 3);
assert.equal(result?.via, 'named-season');
const overlord = await resolveInChain(OVERLORD_CHAIN, { title: 'Overlord', season: 2 });
assert.equal(overlord.result?.id, 98437);
assert.equal(overlord.result?.via, 'named-season');
});
test('a counted entry whose title names another season is not accepted', async () => {
const chain: AnilistSeasonMedia[] = [
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2021, title: { english: 'Show: Arc Two' } },
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
];
// Counting lands on id 3 for season 3, but it says it is season 2.
const { result } = await resolveInChain(chain, { title: 'Show', season: 3 });
assert.equal(result?.seasonResolved, false);
});
test('JoJo parts are seasons, not split-cour continuations', async () => {
assert.equal(splitPartMarker('JoJo no Kimyou na Bouken Part 5: Ougon no Kaze'), null);
assert.deepEqual(splitPartMarker("JoJo's Bizarre Adventure Part 5"), {
base: 'jojo s bizarre adventure',
part: 5,
});
// Golden Wind ends in "Part 5" and Stone Ocean in "Part 6": same base, different
// parts, so Stone Ocean must still count as the next season.
const { result } = await resolveInChain(JOJO_CHAIN, {
title: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
season: 3,
});
assert.equal(result?.id, 131942);
assert.equal(result?.via, 'sequel-chain');
});
test('Attack on Titan resolves its final season past the season 3 back half', async () => {
const { result } = await resolveInChain(AOT_CHAIN, { title: 'Attack on Titan', season: 4 });
assert.equal(result?.id, 110277);
});
test('air-order fallback drops back halves but keeps a season spelled "Part 1"', () => {
// AoT season 3 carries the synonym "ผ่าพิภพไททัน ภาค 3 Part 1".
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 3, AOT_CHAIN)?.id, 99147);
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 4, AOT_CHAIN)?.id, 110277);
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 3, MUSHOKU_CHAIN)?.id, 178789);
// Only three real seasons have aired, so a fourth must not fall out of the list.
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 4, MUSHOKU_CHAIN.slice(0, 5)), null);
});
test('a TYBW cour marked only in a differently spelled synonym is not season 2', async () => {
const { result } = await resolveInChain(BLEACH_TYBW_CHAIN, {
title: 'BLEACH: Thousand-Year Blood War',
season: 2,
});
// Every sequel is a later cour of the same season, so there is no season 2 to find.
assert.equal(result?.seasonResolved, false);
assert.equal(result?.id, 116674);
});
test('an episode past the season entry lands on the split-cour part that airs it', async () => {
const mushoku = await resolveInChain(MUSHOKU_CHAIN, {
title: 'Mushoku Tensei: Jobless Reincarnation',
season: 1,
episode: 15,
});
assert.equal(mushoku.result?.id, 108465);
assert.equal(mushoku.result?.episodeEntry?.id, 127720);
assert.equal(mushoku.result?.episodeEntry?.episode, 4);
const mushokuS2 = await resolveInChain(MUSHOKU_CHAIN, {
title: 'Mushoku Tensei: Jobless Reincarnation',
season: 2,
episode: 20,
});
assert.equal(mushokuS2.result?.id, 146065);
assert.equal(mushokuS2.result?.episodeEntry?.id, 166873);
assert.equal(mushokuS2.result?.episodeEntry?.episode, 7);
// Three cours of 13 + 13 + 14: episode 28 is the third cour's second.
const bleach = await resolveInChain(BLEACH_TYBW_CHAIN, {
title: 'BLEACH: Thousand-Year Blood War',
episode: 28,
});
assert.equal(bleach.result?.id, 116674);
assert.equal(bleach.result?.episodeEntry?.id, 169755);
assert.equal(bleach.result?.episodeEntry?.episode, 2);
});
test('an episode inside the season entry needs no remap or relation lookup', async () => {
const { result, relationLookups } = await resolveInChain(MUSHOKU_CHAIN, {
title: 'Mushoku Tensei: Jobless Reincarnation',
season: 1,
episode: 5,
});
assert.equal(result?.id, 108465);
assert.equal(result?.episodeEntry, null);
assert.deepEqual(relationLookups, []);
});
test('an episode past a season with no continuation is not moved into the next season', async () => {
const { result } = await resolveInChain(OVERLORD_CHAIN, {
title: 'Overlord',
season: 1,
episode: 20,
});
assert.equal(result?.id, 20832);
assert.equal(result?.episodeEntry, null);
});
test('a sequel naming its own season is not a back half, even with a part synonym', async () => {
const sequel: AnilistSeasonMedia = {
id: 2,
episodes: 12,
format: 'TV',
seasonYear: 2022,
title: { english: 'Part Synonym Show Season 2' },
synonyms: ['Part Synonym Show Part 2'],
};
// The anchor names season 1 itself...
const named = await resolveInChain(
[
{
id: 1,
episodes: 12,
format: 'TV',
seasonYear: 2020,
title: { english: 'Part Synonym Show' },
synonyms: ['Part Synonym Show Season 1'],
},
sequel,
],
{ title: 'Part Synonym Show', season: 2 },
);
assert.equal(named.result?.id, 2);
// ...or is season 1 because the walk starts there.
const unnamed = await resolveInChain(
[
{
id: 1,
episodes: 12,
format: 'TV',
seasonYear: 2020,
title: { english: 'Part Synonym Show' },
},
sequel,
],
{ title: 'Part Synonym Show', season: 2 },
);
assert.equal(unnamed.result?.id, 2);
});
test('air order keeps a sequel naming its own season despite a part synonym', () => {
const anchor: AnilistSeasonMedia = {
id: 1,
episodes: 12,
format: 'TV',
seasonYear: 2020,
title: { english: 'Air Order Show' },
};
const sequel: AnilistSeasonMedia = {
id: 2,
episodes: 12,
format: 'TV',
seasonYear: 2022,
title: { english: 'Air Order Show Season 2' },
synonyms: ['Air Order Show Part 2'],
};
assert.equal(pickByAirOrder(anchor, 2, [anchor, sequel])?.id, 2);
});
test('a season 1 episode past its length does not move to a longer later season', async () => {
const { result } = await resolveInChain(
[
{
id: 1,
episodes: 12,
format: 'TV',
seasonYear: 2020,
title: { english: 'Long Later Show' },
},
{
id: 2,
episodes: 24,
format: 'TV',
seasonYear: 2022,
title: { english: 'Long Later Show Season 2' },
},
],
{ title: 'Long Later Show', season: 1, episode: 20 },
);
assert.equal(result?.id, 1);
assert.equal(result?.episodeEntry, null);
});
test('a sequel that repeats its predecessor name is still a new season', async () => {
// No part marker, so the identical title must not be read as a continuation.
const chain: AnilistSeasonMedia[] = [
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Same Name Show' } },
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Same Name Show' } },
];
const { result } = await resolveInChain(chain, { title: 'Same Name Show', season: 2 });
assert.equal(result?.id, 2);
assert.equal(result?.seasonResolved, true);
});
test('a rate limit mid-walk is surfaced instead of answered from air order', async () => {
const { execute } = createChainExecutor(MUSHOKU_CHAIN);
let relationCalls = 0;
const failing = async <T>(query: string, variables: Record<string, unknown>): Promise<T> => {
if (query === ANILIST_SEASON_RELATIONS_QUERY && ++relationCalls === 2) {
throw new Error('AniList rate limited (429)');
}
return execute<T>(query, variables);
};
// Air order alone would answer season 3 correctly from this search result, but it must
// not answer from a franchise picture the failed walk never confirmed.
await assert.rejects(
resolveAnilistSeasonMedia(
{ title: 'Mushoku Tensei: Jobless Reincarnation', season: 3 },
{ execute: failing },
),
/429/,
);
});
+452 -132
View File
@@ -9,6 +9,14 @@ import { sanitizeMediaTitle } from '../../../shared/media-identity';
* season 1 anchor and then walking AniList SEQUEL relations, with an air-order fallback
* when the relation chain is incomplete. When the seasonal entry cannot be located it
* reports `seasonResolved: false` so callers can refuse to act instead of guessing.
*
* Not every SEQUEL hop is a new season. Along the chain:
* - the back half of a split cour ("Part 2", "Cour 2", "第2クール") is its own entry,
* - movies, specials and OVAs sit between seasons,
* so the walk only counts entries that start a new TV season, and prefers an entry whose
* title names the requested season ("Season 3", "3rd Season", "III", "第3期") over the
* count. A continuation with no marker anywhere is indistinguishable from a new season;
* the manual AniList override covers those.
*/
import { normalizeTitleIdentity } from '../../utils/title-normalization';
@@ -35,9 +43,29 @@ export type AnilistQueryExecutor = <T>(
variables: Record<string, unknown>,
) => Promise<T>;
export type AnilistSeasonResolutionVia = 'anchor' | 'sequel-chain' | 'air-order';
export type AnilistSeasonResolutionVia = 'anchor' | 'named-season' | 'sequel-chain' | 'air-order';
/**
* The entry that actually airs the parsed episode when it runs past the season entry
* into a later part of the same season ("S1E15" of an 11 + 12 split cour is episode 4
* of the "Cour 2" entry).
*/
export interface AnilistEpisodeEntry {
id: number;
title: string;
episodes: number | null;
media: AnilistSeasonMedia;
/** Episode number within this entry. */
episode: number;
exactTitleMatch: boolean;
}
export interface AnilistSeasonResolution {
/**
* The season's own entry (its first part). Season-level consumers (cover art, the
* anime row's AniList link, the character dictionary) use this so every episode of a
* split-cour season agrees on one id.
*/
id: number;
title: string;
episodes: number | null;
@@ -48,6 +76,8 @@ export interface AnilistSeasonResolution {
via: AnilistSeasonResolutionVia;
/** Exact normalized match against an AniList title or synonym. */
exactTitleMatch: boolean;
/** Set only when the parsed episode belongs to a later part of the season. */
episodeEntry: AnilistEpisodeEntry | null;
}
export interface ResolveAnilistSeasonMediaInput {
@@ -119,8 +149,79 @@ interface AnilistSeasonRelationsResponse {
/** Formats that can carry a numbered TV season, best first. */
const SEASONAL_FORMAT_PRIORITY = ['TV', 'TV_SHORT', 'ONA'];
/** An ONA this short is a special released online, not a season. */
const MIN_ONA_SEASON_EPISODES = 3;
/** Largest season the chain walk will count to. */
const MAX_SEQUEL_HOPS = 12;
/**
* Hops the walk may take in total. Continuations and specials add hops without adding
* seasons, so this has to leave room beyond the season number.
*/
const MAX_SEQUEL_STEPS = 24;
/** Parts a single season can be split into before the episode remap gives up. */
const MAX_SEASON_PARTS = 6;
/**
* Markers AniList appends when one broadcast season is listed as several entries,
* matched against normalized titles. Anchored to the end so a numbered *work*
* ("JoJo no Kimyou na Bouken Part 5: Ougon no Kaze") is not read as a continuation:
* those carry a subtitle after the number and really are separate seasons.
*/
const PART_MARKER_PATTERNS: RegExp[] = [
/\bpart\s*(\d{1,2}|i{1,3}|iv|v)$/u,
/\bcour\s*(\d{1,2})$/u,
/\b(\d{1,2})(?:st|nd|rd|th)\s+(?:part|cour)$/u,
/\b(second|final)\s+(?:part|cour)$/u,
/第\s*(\d{1,2})\s*(?:部|クール)$/u,
];
const NUMBER_WORDS: Record<string, number> = {
i: 1,
ii: 2,
iii: 3,
iv: 4,
v: 5,
vi: 6,
second: 2,
third: 3,
fourth: 4,
fifth: 5,
sixth: 6,
一: 1,
二: 2,
三: 3,
四: 4,
五: 5,
六: 6,
七: 7,
八: 8,
九: 9,
};
/**
* Patterns that state a season outright. Safe on any title or synonym, because none of
* them can be confused with a part or cour number.
*/
const EXPLICIT_SEASON_PATTERNS: RegExp[] = [
/\bseason\s*(\d{1,2})\b/u,
/\b(\d{1,2})(?:st|nd|rd|th)\s+season\b/u,
/\b(second|third|fourth|fifth|sixth)\s+season\b/u,
/\bs(\d{1,2})\b/u,
/第\s*(\d{1,2}|[二三四五六七八九])\s*[期季]/u,
/(\d{1,2})\s*(?:期|기)/u,
];
/** Words after which a trailing number counts parts, not seasons. */
const PART_WORDS = new Set(['part', 'cour', 'parte', 'partie']);
function parseNumberToken(token: string): number | null {
if (/^\d{1,2}$/.test(token)) return Number(token);
return NUMBER_WORDS[token] ?? null;
}
/**
* Drops season markers a release name carries but AniList titles never do,
* so "Some Show Season 3" and "Some Show S3" both search as "Some Show".
@@ -134,13 +235,65 @@ export function stripSeasonSuffix(title: string): string {
.trim();
}
function mediaTitles(media: AnilistSeasonMedia): string[] {
const synonyms = Array.isArray(media.synonyms) ? media.synonyms : [];
return [media.title?.english, media.title?.romaji, media.title?.native, ...synonyms]
/**
* Splits a trailing part/cour marker off a title, or returns null when it has none.
*
* "Mushoku Tensei: Jobless Reincarnation Season 2 Part 2" is the back half of season 2,
* not season 3. `part` is null for an unnumbered marker ("Final Cour").
*/
export function splitPartMarker(title: string): { base: string; part: number | null } | null {
const normalized = normalizeTitleIdentity(title);
for (const pattern of PART_MARKER_PATTERNS) {
const match = normalized.match(pattern);
if (!match || match.index === undefined) continue;
const base = normalized.slice(0, match.index).trim();
if (!base) continue;
const token = match[1] ?? '';
return { base, part: token === 'final' ? null : parseNumberToken(token) };
}
return null;
}
function mainTitles(media: AnilistSeasonMedia): string[] {
return [media.title?.english, media.title?.romaji, media.title?.native]
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
.map((value) => normalizeTitleIdentity(value));
}
function mediaTitles(media: AnilistSeasonMedia): string[] {
const synonyms = (Array.isArray(media.synonyms) ? media.synonyms : [])
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
.map((value) => normalizeTitleIdentity(value));
return [...mainTitles(media), ...synonyms].filter((value) => value.length > 0);
}
/**
* Season numbers an entry's titles name.
*
* A bare trailing number ("Overlord II", "Konosuba 2") is only trusted on the main
* titles: localized synonyms end in part numbers spelled in other scripts (Mushoku
* Tensei's "Cour 2" carries the Thai "... พาร์ท 2", "part 2").
*/
export function namedSeasons(media: AnilistSeasonMedia): Set<number> {
const seasons = new Set<number>();
for (const title of mediaTitles(media)) {
for (const pattern of EXPLICIT_SEASON_PATTERNS) {
const token = title.match(pattern)?.[1];
const value = token ? parseNumberToken(token) : null;
if (value !== null && value > 0) seasons.add(value);
}
}
for (const title of mainTitles(media)) {
const words = title.split(' ');
const last = words.at(-1) ?? '';
const before = words.at(-2) ?? '';
if (PART_WORDS.has(before)) continue;
const value = parseNumberToken(last);
if (value !== null && value > 1) seasons.add(value);
}
return seasons;
}
function displayTitle(media: AnilistSeasonMedia, fallback: string): string {
return (
media.title?.english?.trim() ||
@@ -167,29 +320,64 @@ function isSeasonalFormat(media: AnilistSeasonMedia): boolean {
return SEASONAL_FORMAT_PRIORITY.includes(format);
}
function formatRank(media: AnilistSeasonMedia): number {
const index = SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
return index < 0 ? SEASONAL_FORMAT_PRIORITY.length : index;
/** Whether an entry can be a season: a TV series, or an ONA long enough not to be a special. */
function isSeasonEntry(media: AnilistSeasonMedia): boolean {
if (!isSeasonalFormat(media)) return false;
if ((media.format || '').toUpperCase() !== 'ONA') return true;
const episodes = episodeCount(media);
return episodes === null || episodes >= MIN_ONA_SEASON_EPISODES;
}
function toResolution(
media: AnilistSeasonMedia,
fallbackTitle: string,
season: number | null,
via: AnilistSeasonResolutionVia,
seasonResolved: boolean,
exactTitleMatch: boolean,
): AnilistSeasonResolution {
return {
id: media.id,
title: displayTitle(media, fallbackTitle),
episodes: episodeCount(media),
media,
seasonResolved,
requestedSeason: season,
via,
exactTitleMatch,
};
function formatRank(media: AnilistSeasonMedia): number {
if (!isSeasonEntry(media)) return SEASONAL_FORMAT_PRIORITY.length;
return SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
}
/**
* Whether `next` continues the season `seasonStart` began rather than starting a new one.
*
* Compared against the season's first entry, not the previous hop, so a special between
* a season and its second cour cannot hide the link. The marker is required, not just a
* matching base: a sequel that repeats its predecessor's name exactly is a new season
* AniList did not number. "Part 1" never marks a back half, and a season's own marker is
* only stripped when it is "Part 1" (AoT season 3 carries "... ภาค 3 Part 1"); stripping
* any number would read JoJo's "Part 6" as a continuation of its "Part 5".
*
* An entry naming a season never continues a different one: "Show Season 2" with the
* synonym "Show Part 2" is season 2, not a back half of "Show". The season `seasonStart`
* stands for is taken from its own titles, else from `startSeason` when the caller
* knows it (the chain walk counts it, the episode remap was asked for it).
*/
function isSeasonContinuation(
seasonStart: AnilistSeasonMedia,
next: AnilistSeasonMedia,
startSeason: number | null = null,
): boolean {
const markers = mediaTitles(next)
.map((title) => splitPartMarker(title))
.filter((marker): marker is NonNullable<typeof marker> => marker !== null && marker.part !== 1);
if (markers.length === 0) return false;
const nextSeasons = namedSeasons(next);
if (nextSeasons.size > 0) {
const startNamed = namedSeasons(seasonStart);
const startSeasons =
startNamed.size > 0 ? startNamed : startSeason !== null ? new Set([startSeason]) : null;
if (startSeasons && ![...nextSeasons].some((value) => startSeasons.has(value))) return false;
}
const seasonKeys = new Set<string>();
for (const title of mediaTitles(seasonStart)) {
seasonKeys.add(title);
const own = splitPartMarker(title);
if (own?.part === 1) seasonKeys.add(own.base);
}
return markers.some((marker) => seasonKeys.has(marker.base));
}
function exactMatchFor(candidate: AnilistSeasonMedia, titles: string[]): boolean {
const candidateTitles = mediaTitles(candidate);
return titles.some((title) => candidateTitles.includes(normalizeTitleIdentity(title)));
}
/**
@@ -250,49 +438,31 @@ export function pickAnchorMedia(
return scored[0]?.entry ?? null;
}
async function walkSequelChain(
anchor: AnilistSeasonMedia,
season: number,
deps: ResolveAnilistSeasonMediaDeps,
): Promise<AnilistSeasonMedia | null> {
// Walking fewer hops than requested would land on the wrong season and report it as
// resolved, so refuse instead and let the caller fall through to its guarded fallback.
const hops = season - 1;
if (hops > MAX_SEQUEL_HOPS) {
return null;
}
const visited = new Set<number>([anchor.id]);
let current = anchor;
/** SEQUEL entries of a media id, minus those already visited, best continuation first. */
type SequelLookup = (id: number, visited: Set<number>) => Promise<AnilistSeasonMedia[]>;
for (let hop = 0; hop < hops; hop += 1) {
// Transport errors propagate: a failed hop must not be mistaken for "no sequel exists".
/**
* Relation lookups for one resolution, memoized so the episode remap does not refetch
* what the chain walk already loaded. Sorted with a season over a special, then the TV
* line over other formats, then the earliest. Transport errors propagate: a failed lookup
* must not be mistaken for "no sequel exists".
*/
function createSequelLookup(deps: ResolveAnilistSeasonMediaDeps): SequelLookup {
const cache = new Map<number, Promise<AnilistSeasonMedia[]>>();
const load = async (id: number): Promise<AnilistSeasonMedia[]> => {
const response = await deps.execute<AnilistSeasonRelationsResponse>(
ANILIST_SEASON_RELATIONS_QUERY,
{ id: current.id },
{ id },
);
const sequels = (response.Media?.relations?.edges ?? [])
.map((edge) => edge ?? null)
.filter(
(
edge,
): edge is {
relationType?: string | null;
node: AnilistSeasonMedia & { type?: string | null };
} =>
Boolean(edge?.node) &&
(edge?.relationType || '').toUpperCase() === 'SEQUEL' &&
(edge?.node?.type || 'ANIME').toUpperCase() === 'ANIME',
)
.map((edge) => edge.node)
.filter((node) => !visited.has(node.id));
if (sequels.length === 0) {
return null;
const sequels: AnilistSeasonMedia[] = [];
for (const edge of response.Media?.relations?.edges ?? []) {
const node = edge?.node;
if (!node || typeof node.id !== 'number') continue;
if ((edge.relationType || '').toUpperCase() !== 'SEQUEL') continue;
if ((node.type || 'ANIME').toUpperCase() !== 'ANIME') continue;
sequels.push(node);
}
// A franchise can branch (a TV sequel plus an ONA spinoff); prefer the TV line.
sequels.sort((a, b) => {
return sequels.sort((a, b) => {
const rankDelta = formatRank(a) - formatRank(b);
if (rankDelta !== 0) return rankDelta;
const yearDelta =
@@ -300,12 +470,121 @@ async function walkSequelChain(
if (yearDelta !== 0) return yearDelta;
return a.id - b.id;
});
};
return async (id, visited) => {
let pending = cache.get(id);
if (!pending) {
pending = load(id);
cache.set(id, pending);
// A failed lookup is retried by the next caller rather than cached.
pending.catch(() => cache.delete(id));
}
return (await pending).filter((node) => !visited.has(node.id));
};
}
current = sequels[0]!;
visited.add(current.id);
type ChainResult = { media: AnilistSeasonMedia; via: 'named-season' | 'sequel-chain' };
async function walkSequelChain(
anchor: AnilistSeasonMedia,
season: number,
sequelsOf: SequelLookup,
): Promise<ChainResult | null> {
// Advancing fewer seasons than requested would land on the wrong one and report it as
// resolved, so refuse instead and let the caller fall through to its guarded fallback.
const targetAdvances = season - 1;
if (targetAdvances > MAX_SEQUEL_HOPS) {
return null;
}
const visited = new Set<number>([anchor.id]);
let current = anchor;
// The last entry that counted as a season.
let seasonStart = anchor;
let advances = 0;
// The unnamed entry the count landed on. The walk looks one season further before
// accepting it, because an entry naming the requested season outranks the count: the
// counted entry may be a continuation with no marker.
let counted: AnilistSeasonMedia | null = null;
// Set once counting reached the requested season on an entry whose title names a
// different one. Only a named match can answer after that.
let countContradicted = false;
for (let step = 0; step < MAX_SEQUEL_STEPS; step += 1) {
const next = (await sequelsOf(current.id, visited))[0];
if (!next) break;
current = next;
visited.add(next.id);
// Specials, movies and OVAs are walked through, because the rest of the franchise
// hangs off them, but never counted.
if (!isSeasonEntry(next)) continue;
const named = namedSeasons(next);
if (isSeasonContinuation(seasonStart, next, advances + 1)) {
// A back half naming the requested season ("Season 3 Part 2") vouches for the
// entry its season started on.
if (named.has(season)) return { media: seasonStart, via: 'named-season' };
continue;
}
if (named.has(season)) return { media: next, via: 'named-season' };
// The season after the counted one does not claim the requested number either.
if (counted) break;
if (countContradicted) {
// Past the requested season by name: it is not on this chain.
if ([...named].some((value) => value > season)) return null;
continue;
}
advances += 1;
seasonStart = next;
if (advances === targetAdvances) {
if (named.size === 0) counted = next;
else countContradicted = true;
}
}
return current.id === anchor.id ? null : current;
return counted ? { media: counted, via: 'sequel-chain' } : null;
}
/**
* Whether the parsed episode runs past `seasonEntry` into a later part of the same season,
* and if so, which entry airs it and at what episode number. Null when the episode fits
* the season entry, its length is unknown, or no continuation covers the episode (e.g.
* absolute numbering across seasons).
*/
async function findEpisodeEntry(
seasonEntry: AnilistSeasonMedia,
season: number,
episode: number,
sequelsOf: SequelLookup,
): Promise<{ media: AnilistSeasonMedia; episode: number } | null> {
const seasonLength = episodeCount(seasonEntry);
if (seasonLength === null || episode <= seasonLength) return null;
const visited = new Set<number>([seasonEntry.id]);
let current = seasonEntry;
// The last part whose episodes are still counted in `remaining`; its length is known.
let lastPart = seasonEntry;
let remaining = episode;
let parts = 1;
for (let step = 0; step < MAX_SEQUEL_STEPS; step += 1) {
const next = (await sequelsOf(current.id, visited))[0];
if (!next) return null;
visited.add(next.id);
current = next;
// A recap special between the two halves airs none of the season's episodes.
if (!isSeasonEntry(next)) continue;
if (!isSeasonContinuation(seasonEntry, next, season)) return null;
remaining -= episodeCount(lastPart) ?? 0;
lastPart = next;
parts += 1;
const length = episodeCount(next);
if (length === null || remaining <= length) return { media: next, episode: remaining };
if (parts >= MAX_SEASON_PARTS) return null;
}
return null;
}
/**
@@ -317,24 +596,45 @@ export function pickByAirOrder(
season: number,
media: AnilistSeasonMedia[],
): AnilistSeasonMedia | null {
const anchorTitles = mediaTitles(anchor).map((value) => stripSeasonSuffix(value));
const anchorBase = anchorTitles.sort((a, b) => a.length - b.length)[0];
if (!anchorBase) return null;
// Any of the anchor's main titles, matched on word boundaries. Synonyms are too short
// and loose ("SnK", "ReZero") to define a franchise, and a single title misses entries
// that only spell another one out (Mushoku Tensei II's native title adds "Ⅱ" to the
// word the season 1 native title ends on).
const anchorBases = mainTitles(anchor)
.map((value) => stripSeasonSuffix(value))
.filter((value) => value.length > 0);
if (anchorBases.length === 0) return null;
const franchise = media.filter((entry) => {
if (!isSeasonalFormat(entry)) return false;
if (!isSeasonEntry(entry)) return false;
if (entry.id === anchor.id) return true;
return mediaTitles(entry).some((candidate) =>
stripSeasonSuffix(candidate).includes(anchorBase),
return mediaTitles(entry).some((candidate) => {
const padded = ` ${stripSeasonSuffix(candidate)} `;
return anchorBases.some((base) => padded.includes(` ${base} `));
});
});
// Drop the back halves of split-cour seasons, which are separate entries here but not
// separate seasons: counting them shifts every later season index. An entry is only
// compared against the *other* entries' titles, so a season whose own localized synonym
// spells it "<season> Part 1" is kept.
const seasons = franchise.filter((entry) => {
if (entry.id === anchor.id) return true;
// The anchor is season 1 here, which lets the continuation check reject an entry
// naming another season even when the anchor's own titles name none.
return !franchise.some(
(other) =>
other.id !== entry.id &&
isSeasonContinuation(other, entry, other.id === anchor.id ? 1 : null),
);
});
if (franchise.length < season) return null;
if (seasons.length < season) return null;
// Ordering by air date is only meaningful when every entry has one: an unknown year
// would sort last and shift the season index while still reporting a resolved match.
if (franchise.some((entry) => airYear(entry) === null)) return null;
if (seasons.some((entry) => airYear(entry) === null)) return null;
const ordered = [...franchise].sort((a, b) => {
const ordered = [...seasons].sort((a, b) => {
const yearDelta = (airYear(a) ?? 0) - (airYear(b) ?? 0);
if (yearDelta !== 0) return yearDelta;
return a.id - b.id;
@@ -343,7 +643,12 @@ export function pickByAirOrder(
// The anchor has to be the first entry, otherwise this ordering is not a season list.
if (ordered[0]?.id !== anchor.id) return null;
return ordered[season - 1] ?? null;
const picked = ordered[season - 1] ?? null;
if (!picked) return null;
// An entry that names some other season shows this ordering is off.
const named = namedSeasons(picked);
if (named.size > 0 && !named.has(season)) return null;
return picked;
}
export async function resolveAnilistSeasonMedia(
@@ -359,6 +664,10 @@ export async function resolveAnilistSeasonMedia(
typeof input.season === 'number' && Number.isInteger(input.season) && input.season > 0
? input.season
: null;
const episode =
typeof input.episode === 'number' && Number.isInteger(input.episode) && input.episode > 0
? input.episode
: null;
const response = await deps.execute<AnilistSeasonSearchResponse>(ANILIST_SEASON_SEARCH_QUERY, {
search: searchTitle,
@@ -368,72 +677,83 @@ export async function resolveAnilistSeasonMedia(
);
if (media.length === 0) return null;
// Season 1 (or unknown) resolves against the episode count; later seasons must not,
// because the anchor is season 1 and may be shorter than the requested episode.
const anchor = pickAnchorMedia(searchTitle, media, {
episode: season === null || season <= 1 ? input.episode : null,
});
if (!anchor) return null;
// Certifies the media actually returned, never the anchor on its behalf: a
// sequel-chain hop can land one season short (split-cour entries) while the
// anchor title still matches perfectly, and that certainty must not carry
// over to the hopped-to entry.
const exactMatchFor = (candidate: AnilistSeasonMedia): boolean => {
const titles = mediaTitles(candidate);
return (
titles.includes(normalizeTitleIdentity(searchTitle)) ||
titles.includes(normalizeTitleIdentity(input.title))
);
// Certifies the media actually returned, never the anchor on its behalf: a hop can land
// on the wrong entry while the anchor title still matches perfectly, and that certainty
// must not carry over to the hopped-to entry.
const parsedTitles = [searchTitle, input.title];
const sequelsOf = createSequelLookup(deps);
const finish = (
seasonEntry: AnilistSeasonMedia,
via: AnilistSeasonResolutionVia,
split: { media: AnilistSeasonMedia; episode: number } | null = null,
seasonResolved = true,
): AnilistSeasonResolution => {
if (split) {
deps.logInfo?.(
`[anilist] episode ${episode} of "${searchTitle}" is episode ${split.episode} of ${displayTitle(split.media, searchTitle)} (${split.media.id})`,
);
}
return {
id: seasonEntry.id,
title: displayTitle(seasonEntry, searchTitle),
episodes: episodeCount(seasonEntry),
media: seasonEntry,
seasonResolved,
requestedSeason: season,
via,
exactTitleMatch: exactMatchFor(seasonEntry, parsedTitles),
episodeEntry: split
? {
id: split.media.id,
title: displayTitle(split.media, searchTitle),
episodes: episodeCount(split.media),
media: split.media,
episode: split.episode,
exactTitleMatch: exactMatchFor(split.media, parsedTitles),
}
: null,
};
};
if (season === null || season <= 1) {
return toResolution(anchor, searchTitle, season, 'anchor', true, exactMatchFor(anchor));
// The best title match first. If the episode runs past it, a split-cour continuation
// may air it ("S1E15" of 11 + 12). Only when none does, and the title match is not a
// season itself (a same-titled movie or special), is the episode count used to pick
// a longer entry; it must not swap season 1 for a later, longer season.
const titleAnchor = pickAnchorMedia(searchTitle, media);
if (!titleAnchor) return null;
if (episode === null) return finish(titleAnchor, 'anchor');
const split = await findEpisodeEntry(titleAnchor, 1, episode, sequelsOf);
if (split) return finish(titleAnchor, 'anchor', split);
if (isSeasonEntry(titleAnchor)) return finish(titleAnchor, 'anchor');
const fitted = pickAnchorMedia(searchTitle, media, { episode });
const laterSeason = fitted !== null && [...namedSeasons(fitted)].some((value) => value > 1);
return finish(fitted && !laterSeason ? fitted : titleAnchor, 'anchor');
}
let chainError: unknown = null;
let viaChain: AnilistSeasonMedia | null = null;
try {
viaChain = await walkSequelChain(anchor, season, deps);
} catch (error) {
chainError = error;
}
if (viaChain) {
// Later seasons must not filter by episode, because the anchor is season 1 and may be
// shorter than the requested episode.
const anchor = pickAnchorMedia(searchTitle, media);
if (!anchor) return null;
// Transport failures propagate from here: the air-order fallback is for a chain that
// answered and had no edge to follow, and running it after a failed hop would turn a
// rate limit into a confident wrong season.
const viaChain = await walkSequelChain(anchor, season, sequelsOf);
const seasonEntry = viaChain?.media ?? pickByAirOrder(anchor, season, media);
if (seasonEntry) {
const via = viaChain?.via ?? 'air-order';
deps.logInfo?.(
`[anilist] season ${season} of "${searchTitle}" resolved via sequel chain: ${displayTitle(viaChain, searchTitle)} (${viaChain.id})`,
`[anilist] season ${season} of "${searchTitle}" resolved via ${via}: ${displayTitle(seasonEntry, searchTitle)} (${seasonEntry.id})`,
);
return toResolution(
viaChain,
searchTitle,
season,
'sequel-chain',
true,
exactMatchFor(viaChain),
);
}
const viaAirOrder = pickByAirOrder(anchor, season, media);
if (viaAirOrder) {
deps.logInfo?.(
`[anilist] season ${season} of "${searchTitle}" resolved via air order: ${displayTitle(viaAirOrder, searchTitle)} (${viaAirOrder.id})`,
);
return toResolution(
viaAirOrder,
searchTitle,
season,
'air-order',
true,
exactMatchFor(viaAirOrder),
);
}
// The chain failed for transport reasons rather than because the season is absent;
// surface that so callers retry instead of reporting an unresolvable season.
if (chainError) {
throw chainError;
const split =
episode === null ? null : await findEpisodeEntry(seasonEntry, season, episode, sequelsOf);
return finish(seasonEntry, via, split);
}
deps.logInfo?.(
`[anilist] could not resolve season ${season} of "${searchTitle}"; falling back to ${displayTitle(anchor, searchTitle)} (${anchor.id})`,
);
return toResolution(anchor, searchTitle, season, 'anchor', false, exactMatchFor(anchor));
return finish(anchor, 'anchor', null, false);
}
@@ -4,7 +4,13 @@ import * as os from 'os';
import * as path from 'path';
import test from 'node:test';
import { isDeepStrictEqual } from 'node:util';
import { getSnapshotPath, readSnapshot, writeSnapshot } from './cache';
import {
getSnapshotPath,
readCachedMediaResolution,
readSnapshot,
writeCachedMediaResolution,
writeSnapshot,
} from './cache';
import { CHARACTER_DICTIONARY_FORMAT_VERSION } from './constants';
import type { CharacterDictionarySnapshot } from './types';
@@ -121,3 +127,20 @@ test('readSnapshot ignores snapshots written with an older format version', asyn
assert.equal(await readSnapshot(snapshotPath), null);
});
test('media resolutions cached before the season resolver fix are re-resolved', () => {
const outputDir = makeTempDir();
const cachePath = path.join(outputDir, 'anilist-resolution-cache.json');
// Written by the old resolver, which counted "Season 2 Part 2" as season 3.
fs.writeFileSync(
cachePath,
JSON.stringify({
entries: [{ seriesKey: 'mushoku-tensei-s3', mediaId: 166873, mediaTitle: 'Part 2' }],
}),
);
assert.equal(readCachedMediaResolution(outputDir, 'mushoku-tensei-s3'), null);
const entry = { seriesKey: 'mushoku-tensei-s3', mediaId: 178789, mediaTitle: 'Season 3' };
writeCachedMediaResolution(outputDir, entry);
assert.deepEqual(readCachedMediaResolution(outputDir, 'mushoku-tensei-s3'), entry);
});
+14 -1
View File
@@ -28,9 +28,17 @@ type MediaResolutionCacheEntry = {
};
type MediaResolutionCacheFile = {
version?: number;
entries?: MediaResolutionCacheEntry[];
};
/**
* Bump when the AniList season resolver changes what it returns, so matches it used to get
* wrong are re-resolved instead of being served from here forever. Version 2: split-cour
* continuations and specials no longer count as seasons.
*/
const MEDIA_RESOLUTION_CACHE_VERSION = 2;
function getMediaResolutionCachePath(outputDir: string): string {
return path.join(outputDir, 'anilist-resolution-cache.json');
}
@@ -55,6 +63,7 @@ function readMediaResolutionEntries(outputDir: string): MediaResolutionCacheEntr
const parsed = JSON.parse(
fs.readFileSync(getMediaResolutionCachePath(outputDir), 'utf8'),
) as MediaResolutionCacheFile;
if (parsed.version !== MEDIA_RESOLUTION_CACHE_VERSION) return [];
if (!Array.isArray(parsed.entries)) return [];
const byKey = new Map<string, MediaResolutionCacheEntry>();
for (const value of parsed.entries) {
@@ -74,7 +83,11 @@ function writeMediaResolutionEntries(
ensureDir(outputDir);
fs.writeFileSync(
getMediaResolutionCachePath(outputDir),
JSON.stringify({ entries }, null, 2),
JSON.stringify(
{ version: MEDIA_RESOLUTION_CACHE_VERSION, entries } satisfies MediaResolutionCacheFile,
null,
2,
),
'utf8',
);
}