mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-22 16:46:10 -08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b6e589ab3
|
||
|
|
11da02e4e9
|
||
|
|
593c7cbc30
|
||
|
|
b7b9400aae
|
No files matched your search
@@ -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.
|
||||
@@ -1,5 +0,0 @@
|
||||
type: added
|
||||
area: stats
|
||||
|
||||
- Library lists each anime once: seasons, movies, and OVAs that AniList links as sequels, prequels, side stories, summaries, or compilations share one card, named after the first TV series. Opening it lists the parts in release order with their own stats. Spin-offs and alternative versions keep their own cards.
|
||||
- A title's page has **Move to Another Anime…**, **Show On Its Own**, and **Put Back Where AniList Has It** to correct the grouping. `subminer sync` keeps the most recent choice.
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -50,15 +50,11 @@ Deleting a session or session group refreshes the Overview totals, charts, calen
|
||||
|
||||
Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel.
|
||||
|
||||
Seasons, movies, and OVAs of one anime share a card. SubMiner follows AniList's sequel, prequel, parent, side-story, summary, and compilation links, including through entries you have not watched, so two films can meet at a TV series you never played. Spin-offs and alternative versions keep their own cards. A shared card is named after the anime's first TV series, shows the cover of the earliest part you have, and opens to a list of its parts in release order. Relations come from AniList in the background and refresh weekly, so a newly linked show can take a minute to join its card.
|
||||
|
||||
If a part lands on the wrong card, open it and choose **Move to Another Anime…** (the target must be linked to AniList) or **Show On Its Own**. **Put Back Where AniList Has It** undoes either. This only changes how the library is listed; duplicate entries for the same season still need a merge.
|
||||
|
||||
Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
|
||||
Seasons get separate cards when a season number is detected. Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
|
||||
|
||||
The same show can end up on several cards when release names disagree. To fix that:
|
||||
|
||||
- Merge: click **Select** (the grid then lists every entry on its own), tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
|
||||
- Merge: click **Select**, tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
|
||||
- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction.
|
||||
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
|
||||
|
||||
|
||||
@@ -145,7 +145,7 @@ subminer sync macbook --remote-cmd ~/Apps/SubMiner.AppImage # SubMiner in a cu
|
||||
subminer sync --ui # open the sync window
|
||||
```
|
||||
|
||||
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. The one setting it carries is a library title's anime card choice (**Move to Another Anime…**), where the most recent change wins. `--push` and `--pull` do not delete anything on the receiving side.
|
||||
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. `--push` and `--pull` do not delete anything on the receiving side.
|
||||
|
||||
Before a command-line sync, close SubMiner on both machines and stop the stats server with `subminer stats -s`, or pass `--force`. The sync window does not need this. It syncs while SubMiner and playback are running, and skips the session in progress until it finishes.
|
||||
|
||||
|
||||
@@ -64,12 +64,10 @@ Read when: you need to find the owner module for a behavior or test surface
|
||||
the stats overlay window options, and the `--stats` command are assembled by `src/main/assemblies/stats.ts`
|
||||
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
|
||||
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
|
||||
Franchise grouping is a view over `imm_anime`, never a merge: `query-library-groups.ts` groups library rows by union-find over the AniList relation cache (`imm_anilist_media` + `imm_anilist_relations`, written by `anilist-relation-cache.ts`; pure graph and walk in `anilist/franchise-graph.ts`, where `FRANCHISE_RELATION_TYPES` is the joining set). `franchise-relation-refresher.ts` walks from owned AniList ids (bounded depth and fetches per run, 7-day staleness, shared AniList rate limiter) when the grouped library is read, after cover art links an id, and after manual AniList or group changes; a failed fetch leaves cached rows untouched. `imm_anime.group_override` (NULL = AniList, 0 = on its own, positive = join the franchise containing that AniList id) is the only user state; `/api/stats/anime/groups` and `PUT /api/stats/anime/:id/group` expose it.
|
||||
`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`.
|
||||
`imm_anime.group_override` merges last-writer-wins on `group_override_updated_at` (clears carry a timestamp too); its values are AniList ids, so no id remapping. The AniList relation cache is not merged: each machine rebuilds it, and stale or partial remote cache rows would otherwise outlive the 7-day refresh.
|
||||
`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`
|
||||
|
||||
@@ -25,9 +25,7 @@ export const IMMERSION_DB_FIXTURE_DDL = `
|
||||
tmdb_type TEXT,
|
||||
metadata_json TEXT,
|
||||
CREATED_DATE TEXT,
|
||||
LAST_UPDATE_DATE TEXT,
|
||||
group_override INTEGER,
|
||||
group_override_updated_at TEXT
|
||||
LAST_UPDATE_DATE TEXT
|
||||
);
|
||||
CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key);
|
||||
CREATE TABLE imm_videos(
|
||||
|
||||
@@ -338,7 +338,6 @@ function createMockTracker(
|
||||
hasAnime: async (animeId: number) => animeId === 1,
|
||||
getAnimeEpisodes: async () => ANIME_EPISODES,
|
||||
getAnimeAnilistEntries: async () => [],
|
||||
getAnimeGroupPlacement: async () => null,
|
||||
getAnimeWords: async () => ANIME_WORDS,
|
||||
getAnimeDailyRollups: async () => DAILY_ROLLUPS,
|
||||
getEpisodesPerDay: async () => EPISODES_PER_DAY,
|
||||
@@ -713,7 +712,7 @@ const MALFORMED_IDS = [
|
||||
|
||||
/** Every route that takes a positive resource id; `:id` is replaced per request. */
|
||||
const ID_ROUTES: Array<{
|
||||
method: 'GET' | 'DELETE' | 'PATCH' | 'POST' | 'PUT';
|
||||
method: 'GET' | 'DELETE' | 'PATCH' | 'POST';
|
||||
path: string;
|
||||
body?: unknown;
|
||||
}> = [
|
||||
@@ -740,7 +739,6 @@ const ID_ROUTES: Array<{
|
||||
{ method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } },
|
||||
{ method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } },
|
||||
{ method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } },
|
||||
{ method: 'PUT', path: '/api/stats/anime/:id/group', body: { mode: 'standalone' } },
|
||||
{ method: 'POST', path: '/api/stats/anki/browse?noteId=:id' },
|
||||
];
|
||||
|
||||
@@ -2431,50 +2429,6 @@ describe('stats server API routes', () => {
|
||||
assert.equal(mergeCalls, 0);
|
||||
});
|
||||
|
||||
it('PUT /api/stats/anime/:animeId/group validates the body and maps refusals', async () => {
|
||||
const calls: unknown[] = [];
|
||||
const app = createStatsApp(
|
||||
createMockTracker({
|
||||
setAnimeGroupOverride: async (animeId, target) => {
|
||||
calls.push([animeId, target]);
|
||||
if (target.mode === 'join' && target.targetAnimeId === 9) {
|
||||
return { ok: false, reason: 'target-not-grouped' };
|
||||
}
|
||||
if (animeId === 404) return { ok: false, reason: 'not-found' };
|
||||
return { ok: true };
|
||||
},
|
||||
}),
|
||||
);
|
||||
const put = (path: string, body: unknown) =>
|
||||
app.request(path, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(body) });
|
||||
|
||||
for (const body of [
|
||||
{},
|
||||
{ mode: 'join' },
|
||||
{ mode: 'join', targetAnimeId: 0 },
|
||||
{ mode: 'join', targetAnimeId: '8' },
|
||||
{ mode: 'join', targetAnimeId: 3 },
|
||||
{ mode: 'reset' },
|
||||
]) {
|
||||
assert.equal((await put('/api/stats/anime/3/group', body)).status, 400, JSON.stringify(body));
|
||||
}
|
||||
assert.deepEqual(calls, []);
|
||||
|
||||
assert.equal(
|
||||
(await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 8 })).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await put('/api/stats/anime/3/group', { mode: 'anilist' })).status, 200);
|
||||
assert.equal((await put('/api/stats/anime/404/group', { mode: 'standalone' })).status, 404);
|
||||
const refused = await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 9 });
|
||||
assert.equal(refused.status, 409);
|
||||
assert.match((await refused.json()).error, /no AniList entry/);
|
||||
assert.deepEqual(calls.slice(0, 2), [
|
||||
[3, { mode: 'join', targetAnimeId: 8 }],
|
||||
[3, { mode: 'anilist' }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => {
|
||||
let moved: { videoId: number; animeId: number } | null = null;
|
||||
const app = createStatsApp(
|
||||
|
||||
@@ -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: 'ジョジョの奇妙な冒険 ストーンオーシャン',
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { AnilistRateLimiter } from './rate-limiter';
|
||||
|
||||
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
|
||||
|
||||
export class AnilistRateLimitedError extends Error {
|
||||
constructor() {
|
||||
super('Anilist rate limit reached');
|
||||
this.name = 'AnilistRateLimitedError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one anonymous AniList GraphQL query through the shared rate limiter.
|
||||
* Throws AnilistRateLimitedError on HTTP 429 (the limiter has already recorded
|
||||
* the retry window) and a plain Error for other HTTP or GraphQL failures.
|
||||
*/
|
||||
export async function executeAnilistQuery<T>(
|
||||
rateLimiter: AnilistRateLimiter,
|
||||
query: string,
|
||||
variables: Record<string, unknown>,
|
||||
): Promise<T> {
|
||||
await rateLimiter.acquire();
|
||||
|
||||
const res = await fetch(ANILIST_GRAPHQL_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ query, variables }),
|
||||
});
|
||||
|
||||
rateLimiter.recordResponse(res.headers);
|
||||
|
||||
if (res.status === 429) {
|
||||
throw new AnilistRateLimitedError();
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
|
||||
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
|
||||
if (firstError?.message) {
|
||||
throw new Error(firstError.message);
|
||||
}
|
||||
if (!json.data) {
|
||||
throw new Error('Anilist response missing data');
|
||||
}
|
||||
return json.data;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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}.`,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { AnilistRateLimiter } from './rate-limiter';
|
||||
import { AnilistRateLimitedError, executeAnilistQuery } from './anilist-graphql';
|
||||
import type { DatabaseSync } from '../immersion-tracker/sqlite';
|
||||
import {
|
||||
getAnimeCoverArt,
|
||||
@@ -21,6 +20,7 @@ import { getVideoTmdbLink, linkAnimeToTmdbTitle } from '../immersion-tracker/liv
|
||||
import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver';
|
||||
import type { TmdbTitleDetails } from '../tmdb/tmdb-client';
|
||||
|
||||
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
|
||||
const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
|
||||
|
||||
export interface CoverArtFetcher {
|
||||
@@ -76,6 +76,47 @@ export function stripFilenameTags(raw: string): string {
|
||||
return title.trim().replace(/\s{2,}/g, ' ');
|
||||
}
|
||||
|
||||
class AnilistRateLimitedError extends Error {
|
||||
constructor() {
|
||||
super('Anilist rate limit reached');
|
||||
this.name = 'AnilistRateLimitedError';
|
||||
}
|
||||
}
|
||||
|
||||
async function executeAnilistQuery<T>(
|
||||
rateLimiter: AnilistRateLimiter,
|
||||
query: string,
|
||||
variables: Record<string, unknown>,
|
||||
): Promise<T> {
|
||||
await rateLimiter.acquire();
|
||||
|
||||
const res = await fetch(ANILIST_GRAPHQL_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ query, variables }),
|
||||
});
|
||||
|
||||
rateLimiter.recordResponse(res.headers);
|
||||
|
||||
if (res.status === 429) {
|
||||
throw new AnilistRateLimitedError();
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
|
||||
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
|
||||
if (firstError?.message) {
|
||||
throw new Error(firstError.message);
|
||||
}
|
||||
if (!json.data) {
|
||||
throw new Error('Anilist response missing data');
|
||||
}
|
||||
return json.data;
|
||||
}
|
||||
|
||||
async function downloadImage(url: string): Promise<Buffer | null> {
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
buildFranchiseGraph,
|
||||
walkFranchiseRelations,
|
||||
type AnilistMediaNode,
|
||||
type FranchiseWalkOptions,
|
||||
} from './franchise-graph';
|
||||
|
||||
function entry(
|
||||
anilistId: number,
|
||||
format: string | null,
|
||||
startDate: number | null,
|
||||
relations: Array<[string, number]> = [],
|
||||
): AnilistMediaNode {
|
||||
return {
|
||||
anilistId,
|
||||
format,
|
||||
titleRomaji: `romaji ${anilistId}`,
|
||||
titleEnglish: null,
|
||||
titleNative: null,
|
||||
startDate,
|
||||
episodes: null,
|
||||
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
|
||||
fetchedAtMs: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Overlord: two recap films sit between seasons one and two; Isekai Quartet only shares characters.
|
||||
const overlord = [
|
||||
entry(20832, 'TV', 20150707, [
|
||||
['SEQUEL', 98437],
|
||||
['SUMMARY', 98873],
|
||||
['CHARACTER', 104454],
|
||||
]),
|
||||
entry(98873, 'MOVIE', 20170225, [
|
||||
['PARENT', 20832],
|
||||
['SEQUEL', 98874],
|
||||
]),
|
||||
entry(98874, 'MOVIE', 20170311, [
|
||||
['PREQUEL', 98873],
|
||||
['SEQUEL', 98437],
|
||||
]),
|
||||
entry(98437, 'TV', 20180109, [
|
||||
['PREQUEL', 20832],
|
||||
['PREQUEL', 98874],
|
||||
]),
|
||||
entry(104454, 'TV_SHORT', 20190410, [['CHARACTER', 20832]]),
|
||||
];
|
||||
|
||||
test('seasons, films and recaps share a root named after the first TV series', () => {
|
||||
const graph = buildFranchiseGraph(overlord);
|
||||
for (const id of [20832, 98873, 98874, 98437]) assert.equal(graph.rootOf(id), 20832);
|
||||
assert.equal(graph.rootOf(104454), 104454);
|
||||
assert.equal(graph.rootOf(1), undefined);
|
||||
});
|
||||
|
||||
test('excluded relation types keep franchises apart even when the other end says PARENT', () => {
|
||||
const graph = buildFranchiseGraph([
|
||||
entry(1, 'TV', 20060101, [
|
||||
['SPIN_OFF', 2],
|
||||
['ALTERNATIVE', 3],
|
||||
['ADAPTATION', 4],
|
||||
['OTHER', 5],
|
||||
]),
|
||||
// A spin-off pointing back at its original as PARENT.
|
||||
entry(2, 'TV', 20130101, [['PARENT', 1]]),
|
||||
entry(3, 'TV', 20140101, [['ALTERNATIVE', 1]]),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
[1, 2, 3, 4, 5].map((id) => graph.rootOf(id)),
|
||||
[1, 2, 3, undefined, undefined],
|
||||
);
|
||||
});
|
||||
|
||||
test('root falls back to episodic formats, then earliest entry, then lowest id', () => {
|
||||
const ona = buildFranchiseGraph([
|
||||
entry(10, 'MOVIE', 20000101, [['SEQUEL', 11]]),
|
||||
entry(11, 'ONA', 20050101, [['PREQUEL', 10]]),
|
||||
]);
|
||||
assert.equal(ona.rootOf(10), 11);
|
||||
const films = buildFranchiseGraph([
|
||||
entry(20, 'MOVIE', 20100101, [['PREQUEL', 21]]),
|
||||
entry(21, 'MOVIE', 20090101, [['SEQUEL', 20]]),
|
||||
entry(22, 'OVA', null, [['PARENT', 20]]),
|
||||
]);
|
||||
assert.equal(films.rootOf(22), 21);
|
||||
});
|
||||
|
||||
test('owned films join through an unowned, uncached TV entry they both point at', () => {
|
||||
const graph = buildFranchiseGraph([
|
||||
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
|
||||
entry(1526, 'MOVIE', 20050716, [['PARENT', 527]]),
|
||||
]);
|
||||
assert.equal(graph.rootOf(528), graph.rootOf(1526));
|
||||
});
|
||||
|
||||
test('relation cycles terminate and form one franchise', () => {
|
||||
const graph = buildFranchiseGraph([
|
||||
entry(1, 'TV', 20000101, [['SEQUEL', 2]]),
|
||||
entry(2, 'TV', 20010101, [['SEQUEL', 3]]),
|
||||
entry(3, 'TV', 20020101, [['SEQUEL', 1]]),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
[1, 2, 3].map((id) => graph.rootOf(id)),
|
||||
[1, 1, 1],
|
||||
);
|
||||
});
|
||||
|
||||
function walkHarness(all: AnilistMediaNode[], overrides: Partial<FranchiseWalkOptions> = {}) {
|
||||
const asked: number[][] = [];
|
||||
const known = new Map<number, AnilistMediaNode>();
|
||||
const options: FranchiseWalkOptions = {
|
||||
seeds: [],
|
||||
known,
|
||||
isFresh: () => true,
|
||||
fetchNodes: async (ids) => {
|
||||
asked.push([...ids].sort((a, b) => a - b));
|
||||
return all.filter((node) => ids.includes(node.anilistId));
|
||||
},
|
||||
onBatch: () => {},
|
||||
now: () => 5,
|
||||
maxDepth: 6,
|
||||
maxFetch: 500,
|
||||
...overrides,
|
||||
};
|
||||
return { asked, known, options };
|
||||
}
|
||||
|
||||
test('walk follows franchise links through entries the user does not own', async () => {
|
||||
const pokemon = [
|
||||
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
|
||||
entry(527, 'TV', 19970401, [
|
||||
['SIDE_STORY', 528],
|
||||
['SEQUEL', 1564],
|
||||
]),
|
||||
entry(1564, 'TV', 20021121, [
|
||||
['PREQUEL', 527],
|
||||
['SIDE_STORY', 1526],
|
||||
['OTHER', 9],
|
||||
]),
|
||||
entry(1526, 'MOVIE', 20050716, [['PARENT', 1564]]),
|
||||
entry(9, 'TV', 20000101),
|
||||
];
|
||||
const { asked, known, options } = walkHarness(pokemon, { seeds: [528, 1526, 404] });
|
||||
await walkFranchiseRelations(options);
|
||||
assert.deepEqual(asked, [
|
||||
[404, 528, 1526],
|
||||
[527, 1564],
|
||||
]);
|
||||
const graph = buildFranchiseGraph(known.values());
|
||||
assert.equal(graph.rootOf(528), 527);
|
||||
assert.equal(graph.rootOf(1526), 527);
|
||||
// Missing ids are remembered so they are not asked about again; OTHER links are not followed.
|
||||
assert.equal(known.get(404)?.format, null);
|
||||
assert.equal(known.has(9), false);
|
||||
});
|
||||
|
||||
test('walk does not follow the links of an entry that vetoes how it was reached', async () => {
|
||||
const { asked, options } = walkHarness(
|
||||
[
|
||||
entry(2, 'TV', 20130101, [['PARENT', 1]]),
|
||||
entry(1, 'TV', 20060101, [
|
||||
['SPIN_OFF', 2],
|
||||
['SEQUEL', 3],
|
||||
]),
|
||||
entry(3, 'TV', 20070101),
|
||||
],
|
||||
{ seeds: [2] },
|
||||
);
|
||||
await walkFranchiseRelations(options);
|
||||
assert.deepEqual(asked, [[2], [1]]);
|
||||
});
|
||||
|
||||
test('walk follows an entry reached through any link it accepts, whatever the seed order', async () => {
|
||||
const nodes = [
|
||||
entry(1, 'TV', 20100101, [['SEQUEL', 3]]),
|
||||
entry(2, 'TV', 20110101, [['SEQUEL', 3]]),
|
||||
// Rejects seed 1 but accepts seed 2, so its own links are still followed.
|
||||
entry(3, 'TV', 20120101, [
|
||||
['SPIN_OFF', 1],
|
||||
['PREQUEL', 2],
|
||||
['PARENT', 4],
|
||||
]),
|
||||
entry(4, 'TV', 20000101),
|
||||
];
|
||||
for (const seeds of [
|
||||
[1, 2],
|
||||
[2, 1],
|
||||
]) {
|
||||
const { asked, options } = walkHarness(nodes, { seeds });
|
||||
await walkFranchiseRelations(options);
|
||||
assert.deepEqual(asked, [[1, 2], [3], [4]]);
|
||||
}
|
||||
});
|
||||
|
||||
test('a cancelled walk starts no further request and drops the in-flight result', async () => {
|
||||
const seeds = Array.from({ length: 51 }, (_, index) => index + 1);
|
||||
let cancelled = false;
|
||||
const batches: number[] = [];
|
||||
const { asked, known, options } = walkHarness(
|
||||
seeds.map((id) => entry(id, 'TV', 20200101)),
|
||||
{
|
||||
seeds,
|
||||
isFresh: () => false,
|
||||
onBatch: (nodes) => batches.push(nodes.length),
|
||||
isCancelled: () => cancelled,
|
||||
},
|
||||
);
|
||||
const fetchNodes = options.fetchNodes;
|
||||
options.fetchNodes = async (ids) => {
|
||||
cancelled = true;
|
||||
return fetchNodes(ids);
|
||||
};
|
||||
const result = await walkFranchiseRelations(options);
|
||||
assert.equal(asked.length, 1);
|
||||
assert.deepEqual(batches, []);
|
||||
assert.equal(known.size, 0);
|
||||
assert.equal(result.truncated, true);
|
||||
});
|
||||
|
||||
test('walk respects the depth and fetch bounds', async () => {
|
||||
const chain = Array.from({ length: 10 }, (_, i) =>
|
||||
entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []),
|
||||
);
|
||||
const deep = walkHarness(chain, { seeds: [1], maxDepth: 3 });
|
||||
await walkFranchiseRelations(deep.options);
|
||||
assert.deepEqual([...deep.known.keys()], [1, 2, 3, 4]);
|
||||
|
||||
const budget = walkHarness(chain, { seeds: [1], maxFetch: 2 });
|
||||
const result = await walkFranchiseRelations(budget.options);
|
||||
assert.deepEqual(result, { fetched: 2, truncated: true });
|
||||
assert.deepEqual([...budget.known.keys()], [1, 2]);
|
||||
});
|
||||
|
||||
test('walk follows fresh cached entries without asking and keeps old data on a failed fetch', async () => {
|
||||
const cached = entry(1, 'TV', 20000101, [['SEQUEL', 2]]);
|
||||
const stale = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
|
||||
const { known, options } = walkHarness([], {
|
||||
seeds: [1],
|
||||
isFresh: (node) => node.fetchedAtMs >= 0,
|
||||
fetchNodes: async () => {
|
||||
throw new Error('AniList unavailable');
|
||||
},
|
||||
});
|
||||
known.set(1, cached);
|
||||
known.set(2, stale);
|
||||
await assert.rejects(walkFranchiseRelations(options), /AniList unavailable/);
|
||||
assert.deepEqual(known.get(2), stale);
|
||||
});
|
||||
|
||||
test('an entry AniList stops returning keeps its cached links', async () => {
|
||||
const previous = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
|
||||
const { known, options } = walkHarness([], {
|
||||
seeds: [2],
|
||||
isFresh: (node) => node.fetchedAtMs >= 0,
|
||||
});
|
||||
known.set(2, previous);
|
||||
await walkFranchiseRelations(options);
|
||||
assert.deepEqual(known.get(2), { ...previous, fetchedAtMs: 5 });
|
||||
});
|
||||
@@ -1,250 +0,0 @@
|
||||
/**
|
||||
* Franchise grouping over AniList's relation graph. AniList keeps every
|
||||
* season, movie and OVA as its own entry and says how entries relate; the
|
||||
* stats library lists a franchise once by following those links, including
|
||||
* through entries the user does not own (two movies meet at a TV series that
|
||||
* is not in the library). Nothing here touches the database or the network.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Relation types that make two entries parts of one franchise. SPIN_OFF,
|
||||
* ALTERNATIVE, CHARACTER, OTHER, ADAPTATION and SOURCE are left out on purpose:
|
||||
* following them collapses Gundam or Fate into a single card.
|
||||
*/
|
||||
export const FRANCHISE_RELATION_TYPES: ReadonlySet<string> = new Set([
|
||||
'PREQUEL',
|
||||
'SEQUEL',
|
||||
'PARENT',
|
||||
'SIDE_STORY',
|
||||
'SUMMARY',
|
||||
'COMPILATION',
|
||||
'CONTAINS',
|
||||
]);
|
||||
|
||||
export interface AnilistRelationEdge {
|
||||
relationType: string;
|
||||
targetId: number;
|
||||
}
|
||||
|
||||
/** One cached AniList entry and its links to other anime entries. */
|
||||
export interface AnilistMediaNode {
|
||||
anilistId: number;
|
||||
/** TV, MOVIE, OVA...; null when AniList did not return the entry. */
|
||||
format: string | null;
|
||||
titleRomaji: string | null;
|
||||
titleEnglish: string | null;
|
||||
titleNative: string | null;
|
||||
/** First air date as yyyymmdd (month/day 0 when unknown); null when AniList has no year. */
|
||||
startDate: number | null;
|
||||
episodes: number | null;
|
||||
relations: AnilistRelationEdge[];
|
||||
fetchedAtMs: number;
|
||||
}
|
||||
|
||||
export interface FranchiseGraph {
|
||||
node(anilistId: number): AnilistMediaNode | undefined;
|
||||
/** AniList id the franchise containing `anilistId` is named after; undefined when unknown. */
|
||||
rootOf(anilistId: number): number | undefined;
|
||||
}
|
||||
|
||||
export function anilistNodeTitle(node: AnilistMediaNode): string | null {
|
||||
return node.titleEnglish ?? node.titleRomaji ?? node.titleNative;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `node` names `targetId` only through relations that do not join a
|
||||
* franchise. AniList records most links from both ends; a spin-off can point
|
||||
* back at its original as PARENT, so the original's SPIN_OFF edge has to veto
|
||||
* the join or excluding SPIN_OFF would not keep the two apart.
|
||||
*/
|
||||
function vetoes(node: AnilistMediaNode, targetId: number): boolean {
|
||||
const edges = node.relations.filter((edge) => edge.targetId === targetId);
|
||||
return edges.length > 0 && !edges.some((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType));
|
||||
}
|
||||
|
||||
function franchiseTargets(node: AnilistMediaNode): number[] {
|
||||
return node.relations
|
||||
.filter((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType))
|
||||
.map((edge) => edge.targetId);
|
||||
}
|
||||
|
||||
// TV first, then other episodic formats, then films/OVAs/specials, then entries with no data.
|
||||
function formatRank(format: string | null): number {
|
||||
if (format === 'TV') return 0;
|
||||
if (format === 'TV_SHORT' || format === 'ONA') return 1;
|
||||
return format === null ? 3 : 2;
|
||||
}
|
||||
|
||||
export function buildFranchiseGraph(nodes: Iterable<AnilistMediaNode>): FranchiseGraph {
|
||||
const byId = new Map<number, AnilistMediaNode>();
|
||||
for (const node of nodes) byId.set(node.anilistId, node);
|
||||
|
||||
const parent = new Map<number, number>();
|
||||
const find = (id: number): number => {
|
||||
let top = parent.get(id) ?? id;
|
||||
if (!parent.has(id)) parent.set(id, id);
|
||||
while (parent.get(top) !== top) top = parent.get(top)!;
|
||||
// Path compression keeps long sequel chains cheap.
|
||||
let at = id;
|
||||
while (at !== top) {
|
||||
const next = parent.get(at)!;
|
||||
parent.set(at, top);
|
||||
at = next;
|
||||
}
|
||||
return top;
|
||||
};
|
||||
|
||||
for (const node of byId.values()) {
|
||||
find(node.anilistId);
|
||||
for (const targetId of franchiseTargets(node)) {
|
||||
const target = byId.get(targetId);
|
||||
if (target && vetoes(target, node.anilistId)) continue;
|
||||
const a = find(node.anilistId);
|
||||
const b = find(targetId);
|
||||
if (a !== b) parent.set(b, a);
|
||||
}
|
||||
}
|
||||
|
||||
const members = new Map<number, number[]>();
|
||||
for (const id of parent.keys()) {
|
||||
const top = find(id);
|
||||
const list = members.get(top);
|
||||
if (list) list.push(id);
|
||||
else members.set(top, [id]);
|
||||
}
|
||||
|
||||
// A franchise is named after its first TV series, else its first episodic
|
||||
// entry, else its earliest entry; ties go to the lower id.
|
||||
const compareRoots = (a: number, b: number): number => {
|
||||
const left = byId.get(a);
|
||||
const right = byId.get(b);
|
||||
return (
|
||||
formatRank(left?.format ?? null) - formatRank(right?.format ?? null) ||
|
||||
(left?.startDate ?? Number.MAX_SAFE_INTEGER) -
|
||||
(right?.startDate ?? Number.MAX_SAFE_INTEGER) ||
|
||||
a - b
|
||||
);
|
||||
};
|
||||
const roots = new Map<number, number>();
|
||||
for (const ids of members.values()) {
|
||||
const root = [...ids].sort(compareRoots)[0]!;
|
||||
for (const id of ids) roots.set(id, root);
|
||||
}
|
||||
|
||||
return {
|
||||
node: (anilistId) => byId.get(anilistId),
|
||||
rootOf: (anilistId) => roots.get(anilistId),
|
||||
};
|
||||
}
|
||||
|
||||
const FETCH_CHUNK_SIZE = 50;
|
||||
|
||||
export interface FranchiseWalkOptions {
|
||||
/** AniList ids the walk starts from (the library's own entries). */
|
||||
seeds: readonly number[];
|
||||
/** Cached entries; updated in place with everything fetched. */
|
||||
known: Map<number, AnilistMediaNode>;
|
||||
isFresh: (node: AnilistMediaNode) => boolean;
|
||||
/** Entries AniList returned for `ids` (at most 50). Throws on transport or API failure. */
|
||||
fetchNodes: (ids: number[]) => Promise<AnilistMediaNode[]>;
|
||||
/** Called once per fetched batch so progress survives a later failure. */
|
||||
onBatch: (nodes: AnilistMediaNode[]) => void;
|
||||
now: () => number;
|
||||
/** Hops from a seed; entries at this depth are fetched but not followed. */
|
||||
maxDepth: number;
|
||||
/** Most entries fetched in one walk; the rest wait for the next walk. */
|
||||
maxFetch: number;
|
||||
/** When true, the walk starts no further request and drops an in-flight result. */
|
||||
isCancelled?: () => boolean;
|
||||
}
|
||||
|
||||
export interface FranchiseWalkResult {
|
||||
fetched: number;
|
||||
/** True when the fetch budget ran out before every stale entry was refreshed. */
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Breadth-first walk from the seeds along franchise relations, fetching
|
||||
* entries that are missing or stale. Fresh cached entries are followed without
|
||||
* a request. An entry AniList does not return keeps its previous data (or gets
|
||||
* an empty placeholder) so it is not asked about again until it goes stale; a
|
||||
* thrown fetch error stops the walk and leaves the cache as it was.
|
||||
*/
|
||||
export async function walkFranchiseRelations(
|
||||
options: FranchiseWalkOptions,
|
||||
): Promise<FranchiseWalkResult> {
|
||||
const { known } = options;
|
||||
const visited = new Set<number>();
|
||||
// `from` lists every entry the walk reached this one through at this depth
|
||||
// (empty for a seed), so the order seeds are given in cannot change the result.
|
||||
let frontier: Array<{ id: number; from: number[] }> = [...new Set(options.seeds)].map((id) => ({
|
||||
id,
|
||||
from: [],
|
||||
}));
|
||||
let fetched = 0;
|
||||
let truncated = false;
|
||||
|
||||
for (let depth = 0; frontier.length > 0; depth += 1) {
|
||||
for (const step of frontier) visited.add(step.id);
|
||||
|
||||
const stale = frontier
|
||||
.map((step) => step.id)
|
||||
.filter((id) => {
|
||||
const node = known.get(id);
|
||||
return !node || !options.isFresh(node);
|
||||
});
|
||||
const allowed = stale.slice(0, Math.max(0, options.maxFetch - fetched));
|
||||
if (allowed.length < stale.length) truncated = true;
|
||||
|
||||
for (let start = 0; start < allowed.length; start += FETCH_CHUNK_SIZE) {
|
||||
if (options.isCancelled?.()) return { fetched, truncated: true };
|
||||
const chunk = allowed.slice(start, start + FETCH_CHUNK_SIZE);
|
||||
const fetchedNodes = await options.fetchNodes(chunk);
|
||||
if (options.isCancelled?.()) return { fetched, truncated: true };
|
||||
const found = new Map(fetchedNodes.map((node) => [node.anilistId, node] as const));
|
||||
const fetchedAtMs = options.now();
|
||||
const batch = chunk.map((id): AnilistMediaNode => {
|
||||
const node = found.get(id);
|
||||
if (node) return node;
|
||||
const previous = known.get(id);
|
||||
if (previous) return { ...previous, fetchedAtMs };
|
||||
return {
|
||||
anilistId: id,
|
||||
format: null,
|
||||
titleRomaji: null,
|
||||
titleEnglish: null,
|
||||
titleNative: null,
|
||||
startDate: null,
|
||||
episodes: null,
|
||||
relations: [],
|
||||
fetchedAtMs,
|
||||
};
|
||||
});
|
||||
for (const node of batch) known.set(node.anilistId, node);
|
||||
options.onBatch(batch);
|
||||
fetched += chunk.length;
|
||||
}
|
||||
|
||||
if (depth >= options.maxDepth) break;
|
||||
|
||||
const next = new Map<number, number[]>();
|
||||
for (const step of frontier) {
|
||||
const node = known.get(step.id);
|
||||
if (!node) continue;
|
||||
// Reached only through links the entry itself rejects (a spin-off's
|
||||
// original): it is not part of the franchise, so its own links are not
|
||||
// followed. One accepted incoming link is enough.
|
||||
if (step.from.length > 0 && step.from.every((fromId) => vetoes(node, fromId))) continue;
|
||||
for (const targetId of franchiseTargets(node)) {
|
||||
if (visited.has(targetId)) continue;
|
||||
const from = next.get(targetId);
|
||||
if (from) from.push(node.anilistId);
|
||||
else next.set(targetId, [node.anilistId]);
|
||||
}
|
||||
}
|
||||
frontier = [...next].map(([id, from]) => ({ id, from }));
|
||||
}
|
||||
|
||||
return { fetched, truncated };
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
import { executeAnilistQuery } from './anilist-graphql';
|
||||
import type { AnilistMediaNode, AnilistRelationEdge } from './franchise-graph';
|
||||
import type { AnilistRateLimiter } from './rate-limiter';
|
||||
|
||||
/** Loads AniList entries with their relations, for the library's franchise grouping. */
|
||||
export interface AnilistRelationFetcher {
|
||||
/** Entries AniList returned for `ids` (at most 50); ids it does not know are absent. */
|
||||
fetchMedia(ids: number[]): Promise<AnilistMediaNode[]>;
|
||||
}
|
||||
|
||||
const RELATIONS_QUERY = `
|
||||
query ($ids: [Int], $perPage: Int) {
|
||||
Page(page: 1, perPage: $perPage) {
|
||||
media(id_in: $ids, type: ANIME) {
|
||||
id
|
||||
format
|
||||
episodes
|
||||
title { romaji english native }
|
||||
startDate { year month day }
|
||||
relations { edges { relationType(version: 2) node { id type } } }
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
interface RelationsMedia {
|
||||
id: number;
|
||||
format: string | null;
|
||||
episodes: number | null;
|
||||
title: { romaji: string | null; english: string | null; native: string | null } | null;
|
||||
startDate: { year: number | null; month: number | null; day: number | null } | null;
|
||||
relations: {
|
||||
edges: Array<{
|
||||
relationType: string | null;
|
||||
node: { id: number; type: string | null } | null;
|
||||
} | null> | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface RelationsResponse {
|
||||
Page: { media: Array<RelationsMedia | null> | null } | null;
|
||||
}
|
||||
|
||||
export function toAnilistMediaNode(media: RelationsMedia, fetchedAtMs: number): AnilistMediaNode {
|
||||
const start = media.startDate;
|
||||
const relations: AnilistRelationEdge[] = [];
|
||||
for (const edge of media.relations?.edges ?? []) {
|
||||
// Manga and novels are not part of a watch library.
|
||||
if (!edge?.relationType || edge.node?.type !== 'ANIME') continue;
|
||||
relations.push({ relationType: edge.relationType, targetId: edge.node.id });
|
||||
}
|
||||
return {
|
||||
anilistId: media.id,
|
||||
format: media.format,
|
||||
titleRomaji: media.title?.romaji ?? null,
|
||||
titleEnglish: media.title?.english ?? null,
|
||||
titleNative: media.title?.native ?? null,
|
||||
startDate: start?.year
|
||||
? start.year * 10_000 + (start.month ?? 0) * 100 + (start.day ?? 0)
|
||||
: null,
|
||||
episodes: media.episodes,
|
||||
relations,
|
||||
fetchedAtMs,
|
||||
};
|
||||
}
|
||||
|
||||
export function createAnilistRelationFetcher(
|
||||
rateLimiter: AnilistRateLimiter,
|
||||
now: () => number = Date.now,
|
||||
): AnilistRelationFetcher {
|
||||
return {
|
||||
async fetchMedia(ids) {
|
||||
if (ids.length === 0) return [];
|
||||
const data = await executeAnilistQuery<RelationsResponse>(rateLimiter, RELATIONS_QUERY, {
|
||||
ids,
|
||||
perPage: ids.length,
|
||||
});
|
||||
const fetchedAtMs = now();
|
||||
return (data.Page?.media ?? [])
|
||||
.filter((media): media is RelationsMedia => media !== null)
|
||||
.map((media) => toAnilistMediaNode(media, fetchedAtMs));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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/,
|
||||
);
|
||||
});
|
||||
@@ -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,18 +4,6 @@ import { createLogger } from '../../logger';
|
||||
import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity';
|
||||
import { MediaGenerator } from '../../media-generator';
|
||||
import type { CoverArtFetcher } from './anilist/cover-art-fetcher';
|
||||
import type { AnilistRelationFetcher } from './anilist/franchise-relation-fetcher';
|
||||
import {
|
||||
createFranchiseRelationRefresher,
|
||||
type FranchiseRelationRefresher,
|
||||
} from './immersion-tracker/franchise-relation-refresher';
|
||||
import {
|
||||
getAnimeGroupPlacement,
|
||||
getAnimeLibraryGroups,
|
||||
setAnimeGroupOverride,
|
||||
type AnimeGroupOverrideResult,
|
||||
type AnimeGroupOverrideTarget,
|
||||
} from './immersion-tracker/query-library-groups';
|
||||
import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata';
|
||||
import {
|
||||
pruneRawRetention,
|
||||
@@ -73,7 +61,6 @@ import type {
|
||||
StatsTrendGroupBy,
|
||||
StatsTrendRange,
|
||||
} from '../../types/stats-http-contract';
|
||||
import type { AnimeGroupPlacement, AnimeLibraryGroup } from '../../types/stats-wire';
|
||||
import {
|
||||
getKanjiAnimeAppearances,
|
||||
getKanjiDetail,
|
||||
@@ -465,7 +452,6 @@ export class ImmersionTrackerService {
|
||||
private readonly mediaGenerator = new MediaGenerator();
|
||||
private readonly preparedStatements: TrackerPreparedStatements;
|
||||
private coverArtFetcher: CoverArtFetcher | null = null;
|
||||
private franchiseRelations: FranchiseRelationRefresher | null = null;
|
||||
private readonly pendingCoverFetches = new Map<number, Promise<boolean>>();
|
||||
private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>();
|
||||
private readonly recordedSubtitleKeys = new Set<string>();
|
||||
@@ -635,7 +621,6 @@ export class ImmersionTrackerService {
|
||||
}
|
||||
this.finalizeActiveSession();
|
||||
this.isDestroyed = true;
|
||||
this.franchiseRelations?.stop();
|
||||
this.deleteMaintenanceScheduler.destroy();
|
||||
this.destroyDeleteMaintenanceRunner();
|
||||
this.destroyVocabularySummaryRunner();
|
||||
@@ -848,27 +833,6 @@ export class ImmersionTrackerService {
|
||||
return getAnimeLibrary(this.db);
|
||||
}
|
||||
|
||||
/** The library as franchise cards; also schedules a background AniList relation refresh. */
|
||||
async getAnimeLibraryGroups(): Promise<AnimeLibraryGroup[]> {
|
||||
this.relinkYoutubeAnimeLibrary();
|
||||
const groups = getAnimeLibraryGroups(this.db);
|
||||
this.franchiseRelations?.requestRefresh();
|
||||
return groups;
|
||||
}
|
||||
|
||||
async getAnimeGroupPlacement(animeId: number): Promise<AnimeGroupPlacement | null> {
|
||||
return getAnimeGroupPlacement(this.db, animeId);
|
||||
}
|
||||
|
||||
async setAnimeGroupOverride(
|
||||
animeId: number,
|
||||
target: AnimeGroupOverrideTarget,
|
||||
): Promise<AnimeGroupOverrideResult> {
|
||||
const result = setAnimeGroupOverride(this.db, animeId, target);
|
||||
if (result.ok) this.franchiseRelations?.requestRefresh({ force: true });
|
||||
return result;
|
||||
}
|
||||
|
||||
async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> {
|
||||
return getAnimeMergeRecommendations(this.db);
|
||||
}
|
||||
@@ -1158,7 +1122,6 @@ export class ImmersionTrackerService {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
this.franchiseRelations?.requestRefresh({ force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1285,19 +1248,6 @@ export class ImmersionTrackerService {
|
||||
this.coverArtFetcher = fetcher;
|
||||
}
|
||||
|
||||
/** Enables franchise grouping refreshes; null disables them (tests, offline runs). */
|
||||
setAnilistRelationFetcher(fetcher: AnilistRelationFetcher | null): void {
|
||||
this.franchiseRelations?.stop();
|
||||
this.franchiseRelations = fetcher
|
||||
? createFranchiseRelationRefresher({
|
||||
db: this.db,
|
||||
fetcher,
|
||||
logger: createLogger('immersion-tracker:franchise-relations'),
|
||||
})
|
||||
: null;
|
||||
this.franchiseRelations?.requestRefresh();
|
||||
}
|
||||
|
||||
async ensureAnimeCoverArt(animeId: number): Promise<boolean> {
|
||||
const existing = await this.getAnimeCoverArt(animeId);
|
||||
if (existing?.coverBlob) {
|
||||
@@ -1350,8 +1300,6 @@ export class ImmersionTrackerService {
|
||||
if (!fetched) {
|
||||
return false;
|
||||
}
|
||||
// A fresh AniList link may join this entry to a franchise card.
|
||||
this.franchiseRelations?.requestRefresh({ force: true });
|
||||
const cover = await this.getCoverArt(videoId);
|
||||
return cover?.coverBlob != null;
|
||||
})();
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
import type { AnilistMediaNode } from '../anilist/franchise-graph';
|
||||
import type { DatabaseSync } from './sqlite';
|
||||
import { fromDbTimestamp, toDbTimestamp } from './query-shared';
|
||||
|
||||
/**
|
||||
* Franchise grouping state. `imm_anilist_media` and `imm_anilist_relations`
|
||||
* cache AniList entries (owned or reached through relations) and every
|
||||
* anime-to-anime edge, whatever its type, so the grouping rule can change
|
||||
* without a refetch. The cache is rebuildable from AniList and is not synced.
|
||||
*
|
||||
* `imm_anime.group_override` is the user's choice for one library entry:
|
||||
* NULL follows AniList, 0 keeps the entry on its own, and a positive value is
|
||||
* an AniList id whose franchise the entry joins. `group_override_updated_at`
|
||||
* records when it was set (or cleared) so sync can keep the newer choice.
|
||||
*/
|
||||
export function ensureAnimeGroupingSchema(db: DatabaseSync): void {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS imm_anilist_media(
|
||||
anilist_id INTEGER PRIMARY KEY,
|
||||
format TEXT,
|
||||
title_romaji TEXT,
|
||||
title_english TEXT,
|
||||
title_native TEXT,
|
||||
start_date INTEGER,
|
||||
episodes INTEGER,
|
||||
fetched_at_ms TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS imm_anilist_relations(
|
||||
anilist_id INTEGER NOT NULL,
|
||||
relation_type TEXT NOT NULL,
|
||||
target_anilist_id INTEGER NOT NULL,
|
||||
PRIMARY KEY(anilist_id, relation_type, target_anilist_id),
|
||||
FOREIGN KEY(anilist_id) REFERENCES imm_anilist_media(anilist_id) ON DELETE CASCADE
|
||||
);
|
||||
`);
|
||||
const columns = new Set(
|
||||
(db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>).map(
|
||||
(column) => column.name,
|
||||
),
|
||||
);
|
||||
if (!columns.has('group_override')) {
|
||||
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override INTEGER');
|
||||
}
|
||||
if (!columns.has('group_override_updated_at')) {
|
||||
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override_updated_at TEXT');
|
||||
}
|
||||
}
|
||||
|
||||
export function readAnilistRelationCache(db: DatabaseSync): Map<number, AnilistMediaNode> {
|
||||
const nodes = new Map<number, AnilistMediaNode>();
|
||||
const mediaRows = db
|
||||
.prepare(
|
||||
`SELECT anilist_id AS anilistId, format, title_romaji AS titleRomaji,
|
||||
title_english AS titleEnglish, title_native AS titleNative,
|
||||
start_date AS startDate, episodes, fetched_at_ms AS fetchedAtMs
|
||||
FROM imm_anilist_media`,
|
||||
)
|
||||
.all() as Array<Omit<AnilistMediaNode, 'relations' | 'fetchedAtMs'> & { fetchedAtMs: string }>;
|
||||
for (const row of mediaRows) {
|
||||
nodes.set(row.anilistId, {
|
||||
...row,
|
||||
relations: [],
|
||||
fetchedAtMs: fromDbTimestamp(row.fetchedAtMs) ?? 0,
|
||||
});
|
||||
}
|
||||
const edgeRows = db
|
||||
.prepare(
|
||||
`SELECT anilist_id AS anilistId, relation_type AS relationType, target_anilist_id AS targetId
|
||||
FROM imm_anilist_relations
|
||||
ORDER BY anilist_id, relation_type, target_anilist_id`,
|
||||
)
|
||||
.all() as Array<{ anilistId: number; relationType: string; targetId: number }>;
|
||||
for (const edge of edgeRows) {
|
||||
nodes.get(edge.anilistId)?.relations.push({
|
||||
relationType: edge.relationType,
|
||||
targetId: edge.targetId,
|
||||
});
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/** Replaces each node's cached row and edges in one transaction. */
|
||||
export function writeAnilistRelationNodes(db: DatabaseSync, nodes: AnilistMediaNode[]): void {
|
||||
if (nodes.length === 0) return;
|
||||
const upsertMedia = db.prepare(`
|
||||
INSERT INTO imm_anilist_media(anilist_id, format, title_romaji, title_english, title_native,
|
||||
start_date, episodes, fetched_at_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(anilist_id) DO UPDATE SET
|
||||
format = excluded.format,
|
||||
title_romaji = excluded.title_romaji,
|
||||
title_english = excluded.title_english,
|
||||
title_native = excluded.title_native,
|
||||
start_date = excluded.start_date,
|
||||
episodes = excluded.episodes,
|
||||
fetched_at_ms = excluded.fetched_at_ms
|
||||
`);
|
||||
const deleteEdges = db.prepare('DELETE FROM imm_anilist_relations WHERE anilist_id = ?');
|
||||
const insertEdge = db.prepare(`
|
||||
INSERT OR IGNORE INTO imm_anilist_relations(anilist_id, relation_type, target_anilist_id)
|
||||
VALUES (?, ?, ?)
|
||||
`);
|
||||
db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
for (const node of nodes) {
|
||||
upsertMedia.run(
|
||||
node.anilistId,
|
||||
node.format,
|
||||
node.titleRomaji,
|
||||
node.titleEnglish,
|
||||
node.titleNative,
|
||||
node.startDate,
|
||||
node.episodes,
|
||||
toDbTimestamp(node.fetchedAtMs),
|
||||
);
|
||||
deleteEdges.run(node.anilistId);
|
||||
for (const edge of node.relations) {
|
||||
insertEdge.run(node.anilistId, edge.relationType, edge.targetId);
|
||||
}
|
||||
}
|
||||
db.exec('COMMIT');
|
||||
} catch (error) {
|
||||
db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import type { AnilistMediaNode } from '../anilist/franchise-graph';
|
||||
import { readAnilistRelationCache } from './anilist-relation-cache';
|
||||
import {
|
||||
createFranchiseRelationRefresher,
|
||||
FRANCHISE_RELATION_STALE_MS,
|
||||
} from './franchise-relation-refresher';
|
||||
import { Database } from './sqlite';
|
||||
import { ensureSchema } from './storage';
|
||||
|
||||
const silent = { info: () => {}, warn: () => {} };
|
||||
|
||||
function media(anilistId: number, relations: Array<[string, number]>, fetchedAtMs: number) {
|
||||
return {
|
||||
anilistId,
|
||||
format: 'TV',
|
||||
titleRomaji: null,
|
||||
titleEnglish: null,
|
||||
titleNative: null,
|
||||
startDate: null,
|
||||
episodes: null,
|
||||
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
|
||||
fetchedAtMs,
|
||||
} satisfies AnilistMediaNode;
|
||||
}
|
||||
|
||||
test('refresh walks from linked entries and override targets, then keeps the cache on failure', async () => {
|
||||
const db = new Database(':memory:');
|
||||
try {
|
||||
ensureSchema(db);
|
||||
db.exec(`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, media_kind)
|
||||
VALUES ('a', 'A', 1, 'anime'), ('c', 'C', 77, 'youtube');
|
||||
INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override)
|
||||
VALUES ('b', 'B', 50)`);
|
||||
let clock = 1_000;
|
||||
let failing = false;
|
||||
const asked: number[][] = [];
|
||||
const refresher = createFranchiseRelationRefresher({
|
||||
db,
|
||||
logger: silent,
|
||||
now: () => clock,
|
||||
fetcher: {
|
||||
fetchMedia: async (ids) => {
|
||||
if (failing) throw new Error('AniList down');
|
||||
asked.push([...ids].sort((a, b) => a - b));
|
||||
return ids.map((id) => media(id, id === 1 ? [['SEQUEL', 2]] : [], clock));
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
refresher.requestRefresh();
|
||||
await refresher.whenIdle();
|
||||
assert.deepEqual(asked, [[1, 50], [2]]);
|
||||
assert.deepEqual(
|
||||
[...readAnilistRelationCache(db).keys()].sort((a, b) => a - b),
|
||||
[1, 2, 50],
|
||||
);
|
||||
|
||||
// Throttled until forced; everything is fresh, so a forced run asks nothing.
|
||||
refresher.requestRefresh({ force: true });
|
||||
await refresher.whenIdle();
|
||||
assert.equal(asked.length, 2);
|
||||
|
||||
clock += FRANCHISE_RELATION_STALE_MS;
|
||||
failing = true;
|
||||
refresher.requestRefresh({ force: true });
|
||||
await refresher.whenIdle();
|
||||
assert.deepEqual(readAnilistRelationCache(db).get(1)?.relations, [
|
||||
{ relationType: 'SEQUEL', targetId: 2 },
|
||||
]);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
import { walkFranchiseRelations } from '../anilist/franchise-graph';
|
||||
import type { AnilistRelationFetcher } from '../anilist/franchise-relation-fetcher';
|
||||
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
|
||||
import type { DatabaseSync } from './sqlite';
|
||||
|
||||
/** Cached AniList entries are asked about again after a week. */
|
||||
export const FRANCHISE_RELATION_STALE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
/** Hops followed from a library entry; keeps long-running franchises bounded. */
|
||||
export const FRANCHISE_WALK_MAX_DEPTH = 6;
|
||||
/** Entries fetched per refresh (five AniList requests); the rest wait for the next refresh. */
|
||||
export const FRANCHISE_WALK_MAX_FETCH = 250;
|
||||
/** Unforced refreshes (library polls) run at most this often. */
|
||||
const MIN_INTERVAL_MS = 10 * 60 * 1000;
|
||||
|
||||
interface RefresherLogger {
|
||||
info(message: string, ...args: unknown[]): void;
|
||||
warn(message: string, ...args: unknown[]): void;
|
||||
}
|
||||
|
||||
export interface FranchiseRelationRefresherDeps {
|
||||
db: DatabaseSync;
|
||||
fetcher: AnilistRelationFetcher;
|
||||
logger: RefresherLogger;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export interface FranchiseRelationRefresher {
|
||||
/**
|
||||
* Starts a background refresh unless one ran recently. `force` skips that
|
||||
* throttle, for when an entry has just been linked to AniList.
|
||||
*/
|
||||
requestRefresh(options?: { force?: boolean }): void;
|
||||
/** Resolves once no refresh is running; for tests and shutdown. */
|
||||
whenIdle(): Promise<void>;
|
||||
/** Stops writing; a running refresh finishes its request and discards the result. */
|
||||
stop(): void;
|
||||
}
|
||||
|
||||
function readSeeds(db: DatabaseSync): number[] {
|
||||
return (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT anilist_id AS id FROM imm_anime WHERE media_kind = 'anime' AND anilist_id IS NOT NULL
|
||||
UNION
|
||||
SELECT group_override AS id FROM imm_anime WHERE group_override > 0`,
|
||||
)
|
||||
.all() as Array<{ id: number }>
|
||||
).map((row) => row.id);
|
||||
}
|
||||
|
||||
export function createFranchiseRelationRefresher(
|
||||
deps: FranchiseRelationRefresherDeps,
|
||||
): FranchiseRelationRefresher {
|
||||
const now = deps.now ?? Date.now;
|
||||
let running: Promise<void> | null = null;
|
||||
let pending = false;
|
||||
let stopped = false;
|
||||
let lastStartedAtMs: number | null = null;
|
||||
|
||||
const refreshOnce = async (): Promise<void> => {
|
||||
const known = readAnilistRelationCache(deps.db);
|
||||
const result = await walkFranchiseRelations({
|
||||
seeds: readSeeds(deps.db),
|
||||
known,
|
||||
isFresh: (node) => now() - node.fetchedAtMs < FRANCHISE_RELATION_STALE_MS,
|
||||
fetchNodes: (ids) => deps.fetcher.fetchMedia(ids),
|
||||
onBatch: (nodes) => writeAnilistRelationNodes(deps.db, nodes),
|
||||
isCancelled: () => stopped,
|
||||
now,
|
||||
maxDepth: FRANCHISE_WALK_MAX_DEPTH,
|
||||
maxFetch: FRANCHISE_WALK_MAX_FETCH,
|
||||
});
|
||||
if (result.fetched > 0) {
|
||||
deps.logger.info(
|
||||
'franchise-relations: refreshed %d AniList entries%s',
|
||||
result.fetched,
|
||||
result.truncated ? ' (more next time)' : '',
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const run = (): void => {
|
||||
lastStartedAtMs = now();
|
||||
running = (async () => {
|
||||
try {
|
||||
do {
|
||||
pending = false;
|
||||
await refreshOnce();
|
||||
} while (pending && !stopped);
|
||||
} catch (error) {
|
||||
// Cached rows stay as they were; the next request (after the throttle) retries.
|
||||
deps.logger.warn(
|
||||
'franchise-relations: refresh failed: %s',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
} finally {
|
||||
running = null;
|
||||
}
|
||||
})();
|
||||
};
|
||||
|
||||
return {
|
||||
requestRefresh(options = {}) {
|
||||
if (stopped) return;
|
||||
if (running) {
|
||||
if (options.force) pending = true;
|
||||
return;
|
||||
}
|
||||
if (!options.force && lastStartedAtMs !== null && now() - lastStartedAtMs < MIN_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
run();
|
||||
},
|
||||
async whenIdle() {
|
||||
while (running) await running;
|
||||
},
|
||||
stop() {
|
||||
stopped = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { buildFranchiseGraph, type AnilistMediaNode } from '../anilist/franchise-graph';
|
||||
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
|
||||
import {
|
||||
getAnimeGroupPlacement,
|
||||
getAnimeLibraryGroups,
|
||||
groupAnimeLibrary,
|
||||
setAnimeGroupOverride,
|
||||
type GroupableLibraryRow,
|
||||
} from './query-library-groups';
|
||||
import { Database, type DatabaseSync } from './sqlite';
|
||||
import { ensureSchema } from './storage';
|
||||
import { SCHEMA_VERSION } from './types';
|
||||
|
||||
function node(
|
||||
anilistId: number,
|
||||
format: string,
|
||||
startDate: number,
|
||||
relations: Array<[string, number]>,
|
||||
titleEnglish: string | null = null,
|
||||
): AnilistMediaNode {
|
||||
return {
|
||||
anilistId,
|
||||
format,
|
||||
titleRomaji: `romaji ${anilistId}`,
|
||||
titleEnglish,
|
||||
titleNative: null,
|
||||
startDate,
|
||||
episodes: null,
|
||||
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
|
||||
fetchedAtMs: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// Owned: season 2 and a film. The first season (the root) is not in the library.
|
||||
const overlordNodes = [
|
||||
node(
|
||||
20832,
|
||||
'TV',
|
||||
20150707,
|
||||
[
|
||||
['SEQUEL', 98437],
|
||||
['SUMMARY', 98873],
|
||||
],
|
||||
'Overlord',
|
||||
),
|
||||
node(98873, 'MOVIE', 20170225, [['PARENT', 20832]]),
|
||||
node(98437, 'TV', 20180109, [['PREQUEL', 20832]]),
|
||||
];
|
||||
|
||||
function row(
|
||||
animeId: number,
|
||||
anilistId: number | null,
|
||||
overrides: Partial<GroupableLibraryRow> = {},
|
||||
): GroupableLibraryRow {
|
||||
return {
|
||||
mediaKind: 'anime',
|
||||
animeId,
|
||||
canonicalTitle: `Entry ${animeId}`,
|
||||
anilistId,
|
||||
tmdbId: null,
|
||||
tmdbType: null,
|
||||
totalSessions: 1,
|
||||
totalActiveMs: 1000 * animeId,
|
||||
totalCards: animeId,
|
||||
totalTokensSeen: 10,
|
||||
episodeCount: 2,
|
||||
episodesTotal: null,
|
||||
lastWatchedMs: 100 * animeId,
|
||||
groupOverride: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test('owned parts join under the unowned root, in release order, with summed totals', () => {
|
||||
const graph = buildFranchiseGraph(overlordNodes);
|
||||
const groups = groupAnimeLibrary([row(1, 98437), row(2, 98873), row(3, null)], graph);
|
||||
assert.equal(groups.length, 2);
|
||||
const overlord = groups.find((group) => group.groupKey === 20832)!;
|
||||
assert.equal(overlord.title, 'Overlord');
|
||||
assert.deepEqual(
|
||||
overlord.parts.map((part) => [part.animeId, part.format, part.startDate]),
|
||||
[
|
||||
[2, 'MOVIE', 20170225],
|
||||
[1, 'TV', 20180109],
|
||||
],
|
||||
);
|
||||
assert.equal(overlord.coverAnimeId, 2);
|
||||
assert.deepEqual(
|
||||
[overlord.totalActiveMs, overlord.totalCards, overlord.episodeCount, overlord.lastWatchedMs],
|
||||
[3000, 3, 4, 200],
|
||||
);
|
||||
});
|
||||
|
||||
test('entries without AniList data stay single cards that look like the entry', () => {
|
||||
const graph = buildFranchiseGraph([]);
|
||||
const lone = row(7, 555, { canonicalTitle: 'Bocchi the Rock!' });
|
||||
const [linked, unlinked, channel] = groupAnimeLibrary(
|
||||
[lone, row(3, null), row(2, null, { mediaKind: 'youtube', groupOverride: 555 })],
|
||||
graph,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[linked!.groupKey, linked!.title, linked!.coverAnimeId, linked!.parts.length],
|
||||
[555, 'Bocchi the Rock!', 7, 1],
|
||||
);
|
||||
const { groupOverride: _override, ...item } = lone;
|
||||
assert.deepEqual(linked!.parts[0], { ...item, format: null, startDate: null });
|
||||
assert.equal(unlinked!.groupKey, -3);
|
||||
// Overrides never apply to YouTube or live-action entries.
|
||||
assert.equal(channel!.groupKey, -2);
|
||||
});
|
||||
|
||||
test('overrides move an entry to another franchise or keep it on its own', () => {
|
||||
const graph = buildFranchiseGraph(overlordNodes);
|
||||
const groups = groupAnimeLibrary(
|
||||
[
|
||||
row(1, 98437),
|
||||
row(2, 98873, { groupOverride: 0 }),
|
||||
// Unlinked specials moved in by the user, pointing at any part of the franchise.
|
||||
row(3, null, { groupOverride: 98437 }),
|
||||
],
|
||||
graph,
|
||||
);
|
||||
assert.deepEqual(
|
||||
groups
|
||||
.map((group) => [group.groupKey, group.parts.map((part) => part.animeId)] as const)
|
||||
.sort((a, b) => a[0] - b[0]),
|
||||
[
|
||||
[-2, [2]],
|
||||
[20832, [1, 3]],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
function seed(db: DatabaseSync, title: string, anilistId: number | null): number {
|
||||
const animeId = Number(
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id) VALUES (?, ?, ?)`,
|
||||
)
|
||||
.run(title.toLowerCase(), title, anilistId).lastInsertRowid,
|
||||
);
|
||||
db.prepare(
|
||||
`INSERT INTO imm_videos(video_key, anime_id, canonical_title, source_type, duration_ms)
|
||||
VALUES (?, ?, ?, 1, 0)`,
|
||||
).run(`key:${title}`, animeId, title);
|
||||
db.prepare(
|
||||
'INSERT INTO imm_lifetime_anime(anime_id, total_active_ms, total_cards) VALUES (?, 60000, 1)',
|
||||
).run(animeId);
|
||||
return animeId;
|
||||
}
|
||||
|
||||
test('library groups and overrides round-trip through the database', () => {
|
||||
const db = new Database(':memory:');
|
||||
try {
|
||||
ensureSchema(db);
|
||||
const season2 = seed(db, 'Overlord II', 98437);
|
||||
const film = seed(db, 'The Undead King', 98873);
|
||||
const specials = seed(db, 'Overlord specials', null);
|
||||
const other = seed(db, 'Bocchi the Rock!', 130003);
|
||||
|
||||
// No cached relations yet: every entry is its own card.
|
||||
assert.equal(getAnimeLibraryGroups(db).length, 4);
|
||||
|
||||
writeAnilistRelationNodes(db, overlordNodes);
|
||||
assert.deepEqual(readAnilistRelationCache(db).get(20832), overlordNodes[0]);
|
||||
assert.deepEqual(getAnimeGroupPlacement(db, film), {
|
||||
groupKey: 20832,
|
||||
title: 'Overlord',
|
||||
partCount: 2,
|
||||
overrideMode: 'anilist',
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
setAnimeGroupOverride(db, specials, { mode: 'join', targetAnimeId: season2 }),
|
||||
{
|
||||
ok: true,
|
||||
},
|
||||
);
|
||||
assert.deepEqual(setAnimeGroupOverride(db, film, { mode: 'standalone' }), { ok: true });
|
||||
assert.deepEqual(setAnimeGroupOverride(db, other, { mode: 'join', targetAnimeId: film }), {
|
||||
ok: false,
|
||||
reason: 'target-not-grouped',
|
||||
});
|
||||
assert.deepEqual(setAnimeGroupOverride(db, 999, { mode: 'standalone' }), {
|
||||
ok: false,
|
||||
reason: 'not-found',
|
||||
});
|
||||
const stored = db
|
||||
.prepare('SELECT group_override AS value FROM imm_anime WHERE anime_id = ?')
|
||||
.get(specials) as { value: number };
|
||||
assert.equal(stored.value, 20832);
|
||||
assert.deepEqual(getAnimeGroupPlacement(db, specials), {
|
||||
groupKey: 20832,
|
||||
title: 'Overlord',
|
||||
partCount: 2,
|
||||
overrideMode: 'joined',
|
||||
});
|
||||
assert.equal(getAnimeGroupPlacement(db, film)?.overrideMode, 'standalone');
|
||||
|
||||
setAnimeGroupOverride(db, film, { mode: 'anilist' });
|
||||
assert.equal(getAnimeGroupPlacement(db, film)?.partCount, 3);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('schema 27 upgrade adds the relation cache and override columns', () => {
|
||||
const db = new Database(':memory:');
|
||||
try {
|
||||
ensureSchema(db);
|
||||
db.exec(`DROP TABLE imm_anilist_relations; DROP TABLE imm_anilist_media;
|
||||
ALTER TABLE imm_anime DROP COLUMN group_override;
|
||||
ALTER TABLE imm_anime DROP COLUMN group_override_updated_at;`);
|
||||
db.prepare('UPDATE imm_schema_version SET schema_version = ?').run(SCHEMA_VERSION - 1);
|
||||
ensureSchema(db);
|
||||
const columns = (db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>)
|
||||
.map((column) => column.name)
|
||||
.filter((name) => name.startsWith('group_override'));
|
||||
assert.deepEqual(columns, ['group_override', 'group_override_updated_at']);
|
||||
assert.equal(readAnilistRelationCache(db).size, 0);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
});
|
||||
@@ -1,192 +0,0 @@
|
||||
import type {
|
||||
AnimeGroupOverrideMode,
|
||||
AnimeGroupPlacement,
|
||||
AnimeLibraryGroup,
|
||||
AnimeLibraryGroupPart,
|
||||
} from '../../../types/stats-wire';
|
||||
import {
|
||||
anilistNodeTitle,
|
||||
buildFranchiseGraph,
|
||||
type FranchiseGraph,
|
||||
} from '../anilist/franchise-graph';
|
||||
import { readAnilistRelationCache } from './anilist-relation-cache';
|
||||
import { toDbTimestamp } from './query-shared';
|
||||
import { getAnimeLibrary } from './query-library';
|
||||
import type { DatabaseSync } from './sqlite';
|
||||
import { nowMs } from './time';
|
||||
import type { AnimeLibraryRow } from './types';
|
||||
|
||||
/** `imm_anime.group_override` value that keeps an entry on its own. */
|
||||
export const GROUP_OVERRIDE_STANDALONE = 0;
|
||||
|
||||
export interface GroupableLibraryRow extends AnimeLibraryRow {
|
||||
groupOverride: number | null;
|
||||
}
|
||||
|
||||
function overrideMode(row: GroupableLibraryRow): AnimeGroupOverrideMode {
|
||||
if (row.mediaKind !== 'anime' || row.groupOverride === null || row.groupOverride < 0) {
|
||||
return 'anilist';
|
||||
}
|
||||
return row.groupOverride === GROUP_OVERRIDE_STANDALONE ? 'standalone' : 'joined';
|
||||
}
|
||||
|
||||
/**
|
||||
* The card an entry belongs to: positive keys are AniList ids (the franchise
|
||||
* root once its relations are cached, the entry's own id until then), negative
|
||||
* keys are `-animeId` for entries listed on their own. Overrides only apply to
|
||||
* anime entries; live-action and YouTube rows always stand alone.
|
||||
*/
|
||||
function groupKeyFor(row: GroupableLibraryRow, graph: FranchiseGraph): number {
|
||||
const mode = overrideMode(row);
|
||||
if (mode === 'standalone') return -row.animeId;
|
||||
if (mode === 'joined') return graph.rootOf(row.groupOverride!) ?? row.groupOverride!;
|
||||
if (row.mediaKind === 'anime' && row.anilistId !== null) {
|
||||
return graph.rootOf(row.anilistId) ?? row.anilistId;
|
||||
}
|
||||
return -row.animeId;
|
||||
}
|
||||
|
||||
function toPart(row: GroupableLibraryRow, graph: FranchiseGraph): AnimeLibraryGroupPart {
|
||||
const { groupOverride: _groupOverride, ...item } = row;
|
||||
const node =
|
||||
row.mediaKind === 'anime' && row.anilistId !== null ? graph.node(row.anilistId) : undefined;
|
||||
return { ...item, format: node?.format ?? null, startDate: node?.startDate ?? null };
|
||||
}
|
||||
|
||||
// Release order; entries AniList has no date for go last, in library order.
|
||||
function compareParts(a: AnimeLibraryGroupPart, b: AnimeLibraryGroupPart): number {
|
||||
return (
|
||||
(a.startDate ?? Number.MAX_SAFE_INTEGER) - (b.startDate ?? Number.MAX_SAFE_INTEGER) ||
|
||||
a.animeId - b.animeId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups library rows into franchise cards. A card with one part keeps that
|
||||
* entry's own title, so ungrouped entries render exactly as before; a card with
|
||||
* several parts is named after the franchise root, even when the root itself
|
||||
* is not in the library.
|
||||
*/
|
||||
export function groupAnimeLibrary(
|
||||
rows: GroupableLibraryRow[],
|
||||
graph: FranchiseGraph,
|
||||
): AnimeLibraryGroup[] {
|
||||
const byKey = new Map<number, GroupableLibraryRow[]>();
|
||||
for (const row of rows) {
|
||||
const key = groupKeyFor(row, graph);
|
||||
const members = byKey.get(key);
|
||||
if (members) members.push(row);
|
||||
else byKey.set(key, [row]);
|
||||
}
|
||||
|
||||
const groups: AnimeLibraryGroup[] = [];
|
||||
for (const [groupKey, members] of byKey) {
|
||||
const parts = members.map((row) => toPart(row, graph)).sort(compareParts);
|
||||
const first = parts[0]!;
|
||||
const rootNode = groupKey > 0 ? graph.node(groupKey) : undefined;
|
||||
const title =
|
||||
parts.length === 1
|
||||
? first.canonicalTitle
|
||||
: ((rootNode ? anilistNodeTitle(rootNode) : null) ??
|
||||
parts.find((part) => part.anilistId === groupKey)?.canonicalTitle ??
|
||||
first.canonicalTitle);
|
||||
groups.push({
|
||||
groupKey,
|
||||
title,
|
||||
mediaKind: first.mediaKind,
|
||||
coverAnimeId: first.animeId,
|
||||
totalSessions: parts.reduce((sum, part) => sum + part.totalSessions, 0),
|
||||
totalActiveMs: parts.reduce((sum, part) => sum + part.totalActiveMs, 0),
|
||||
totalCards: parts.reduce((sum, part) => sum + part.totalCards, 0),
|
||||
totalTokensSeen: parts.reduce((sum, part) => sum + part.totalTokensSeen, 0),
|
||||
episodeCount: parts.reduce((sum, part) => sum + part.episodeCount, 0),
|
||||
lastWatchedMs: Math.max(...parts.map((part) => part.lastWatchedMs)),
|
||||
parts,
|
||||
});
|
||||
}
|
||||
return groups.sort((a, b) => b.totalActiveMs - a.totalActiveMs || a.groupKey - b.groupKey);
|
||||
}
|
||||
|
||||
function readGroupableLibrary(db: DatabaseSync): GroupableLibraryRow[] {
|
||||
const overrides = new Map(
|
||||
(
|
||||
db
|
||||
.prepare(
|
||||
'SELECT anime_id AS animeId, group_override AS groupOverride FROM imm_anime WHERE group_override IS NOT NULL',
|
||||
)
|
||||
.all() as Array<{ animeId: number; groupOverride: number }>
|
||||
).map((row) => [row.animeId, row.groupOverride] as const),
|
||||
);
|
||||
return getAnimeLibrary(db).map((row) => ({
|
||||
...row,
|
||||
groupOverride: overrides.get(row.animeId) ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
export function getAnimeLibraryGroups(db: DatabaseSync): AnimeLibraryGroup[] {
|
||||
return groupAnimeLibrary(
|
||||
readGroupableLibrary(db),
|
||||
buildFranchiseGraph(readAnilistRelationCache(db).values()),
|
||||
);
|
||||
}
|
||||
|
||||
/** The card an entry is listed under, or null when the entry is not in the library list. */
|
||||
export function getAnimeGroupPlacement(
|
||||
db: DatabaseSync,
|
||||
animeId: number,
|
||||
): AnimeGroupPlacement | null {
|
||||
const rows = readGroupableLibrary(db);
|
||||
const row = rows.find((candidate) => candidate.animeId === animeId);
|
||||
if (!row) return null;
|
||||
const group = groupAnimeLibrary(
|
||||
rows,
|
||||
buildFranchiseGraph(readAnilistRelationCache(db).values()),
|
||||
).find((candidate) => candidate.parts.some((part) => part.animeId === animeId));
|
||||
if (!group) return null;
|
||||
return {
|
||||
groupKey: group.groupKey,
|
||||
title: group.title,
|
||||
partCount: group.parts.length,
|
||||
overrideMode: overrideMode(row),
|
||||
};
|
||||
}
|
||||
|
||||
/** Where to put an entry: with another entry's franchise, on its own, or where AniList has it. */
|
||||
export type AnimeGroupOverrideTarget =
|
||||
| { mode: 'join'; targetAnimeId: number }
|
||||
| { mode: 'standalone' }
|
||||
| { mode: 'anilist' };
|
||||
|
||||
export type AnimeGroupOverrideResult =
|
||||
| { ok: true }
|
||||
| { ok: false; reason: 'not-found' | 'unsupported-kind' | 'target-not-grouped' };
|
||||
|
||||
/**
|
||||
* Stores the user's grouping choice for one anime entry. Joining stores the
|
||||
* target's current card key, which is always an AniList id: entries without
|
||||
* one cannot be joined (merge them instead).
|
||||
*/
|
||||
export function setAnimeGroupOverride(
|
||||
db: DatabaseSync,
|
||||
animeId: number,
|
||||
target: AnimeGroupOverrideTarget,
|
||||
): AnimeGroupOverrideResult {
|
||||
const row = db
|
||||
.prepare('SELECT media_kind AS mediaKind FROM imm_anime WHERE anime_id = ?')
|
||||
.get(animeId) as { mediaKind: string } | undefined;
|
||||
if (!row) return { ok: false, reason: 'not-found' };
|
||||
if (row.mediaKind !== 'anime') return { ok: false, reason: 'unsupported-kind' };
|
||||
|
||||
let value: number | null = null;
|
||||
if (target.mode === 'standalone') value = GROUP_OVERRIDE_STANDALONE;
|
||||
if (target.mode === 'join') {
|
||||
const placement = getAnimeGroupPlacement(db, target.targetAnimeId);
|
||||
if (!placement) return { ok: false, reason: 'not-found' };
|
||||
if (placement.groupKey <= 0) return { ok: false, reason: 'target-not-grouped' };
|
||||
value = placement.groupKey;
|
||||
}
|
||||
db.prepare(
|
||||
'UPDATE imm_anime SET group_override = ?, group_override_updated_at = ? WHERE anime_id = ?',
|
||||
).run(value, toDbTimestamp(nowMs()), animeId);
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import { isVocabularyStatsRowVisible, type VocabularyVisibilityRow } from './voc
|
||||
import { SCHEMA_VERSION } from './types';
|
||||
import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types';
|
||||
import { toDbTimestamp } from './query-shared';
|
||||
import { ensureAnimeGroupingSchema } from './anilist-relation-cache';
|
||||
|
||||
export interface TrackerPreparedStatements {
|
||||
telemetryInsertStmt: ReturnType<DatabaseSync['prepare']>;
|
||||
@@ -999,7 +998,6 @@ export function ensureSchema(db: DatabaseSync): void {
|
||||
ensureLifetimeSummaryTables(db);
|
||||
ensureStatsExcludedWordsTable(db);
|
||||
ensureAnimeMergeTables(db);
|
||||
ensureAnimeGroupingSchema(db);
|
||||
ensureSubtitleLineEventIndex(db);
|
||||
return;
|
||||
}
|
||||
@@ -1066,8 +1064,6 @@ export function ensureSchema(db: DatabaseSync): void {
|
||||
'INTEGER NOT NULL DEFAULT 0 CHECK(anime_assignment_locked IN (0, 1))',
|
||||
);
|
||||
ensureAnimeMergeTables(db);
|
||||
// Schema 27: franchise grouping (AniList relation cache + per-entry override).
|
||||
ensureAnimeGroupingSchema(db);
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS imm_sessions(
|
||||
session_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { MediaKind, TmdbMediaType } from '../../../shared/media-kind';
|
||||
|
||||
// 26: live-action entries (TMDB link) and YouTube channels share the media_kind column.
|
||||
// 27: AniList relation cache and imm_anime.group_override for franchise grouping.
|
||||
export const SCHEMA_VERSION = 27;
|
||||
export const SCHEMA_VERSION = 26;
|
||||
export const DEFAULT_QUEUE_CAP = 1_000;
|
||||
export const DEFAULT_BATCH_SIZE = 25;
|
||||
export const DEFAULT_FLUSH_INTERVAL_MS = 500;
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
enrichSessionsWithKnownWordMetrics,
|
||||
isPositiveSafeInteger,
|
||||
loadKnownWordsSet,
|
||||
parseAnimeGroupOverrideBody,
|
||||
parseBooleanQuery,
|
||||
parseDuplicateLineCleanupBody,
|
||||
parseExcludedWordsBody,
|
||||
@@ -191,11 +190,6 @@ export function registerStatsLibraryRoutes(
|
||||
return c.json(statsJson('animeLibrary', rows));
|
||||
});
|
||||
|
||||
// Registered before `/api/stats/anime/:animeId` so `groups` is not read as an id.
|
||||
app.get('/api/stats/anime/groups', async (c) => {
|
||||
return c.json(statsJson('animeLibraryGroups', await tracker.getAnimeLibraryGroups()));
|
||||
});
|
||||
|
||||
app.get('/api/stats/anime/merge-recommendations', async (c) => {
|
||||
const recommendations = await tracker.getAnimeMergeRecommendations();
|
||||
return c.json(statsJson('animeMergeRecommendations', { recommendations }));
|
||||
@@ -214,12 +208,11 @@ export function registerStatsLibraryRoutes(
|
||||
if (animeId === null) return c.body(null, 400);
|
||||
const detail = await tracker.getAnimeDetail(animeId);
|
||||
if (!detail) return c.body(null, 404);
|
||||
const [episodes, anilistEntries, group] = await Promise.all([
|
||||
const [episodes, anilistEntries] = await Promise.all([
|
||||
tracker.getAnimeEpisodes(animeId),
|
||||
tracker.getAnimeAnilistEntries(animeId),
|
||||
tracker.getAnimeGroupPlacement(animeId),
|
||||
]);
|
||||
return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries, group }));
|
||||
return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries }));
|
||||
});
|
||||
|
||||
app.get('/api/stats/anime/:animeId/words', async (c) => {
|
||||
@@ -274,22 +267,6 @@ export function registerStatsLibraryRoutes(
|
||||
return c.json(statsJson('deleteAnime', { ok: true }));
|
||||
});
|
||||
|
||||
app.put('/api/stats/anime/:animeId/group', async (c) => {
|
||||
const animeId = parsePositiveId(c.req.param('animeId'));
|
||||
if (animeId === null) return c.body(null, 400);
|
||||
const request = parseAnimeGroupOverrideBody(await c.req.json().catch(() => null));
|
||||
if (!request) return c.body(null, 400);
|
||||
if (request.mode === 'join' && request.targetAnimeId === animeId) return c.body(null, 400);
|
||||
const result = await tracker.setAnimeGroupOverride(animeId, request);
|
||||
if (result.ok) return c.json(statsJson('setAnimeGroupOverride', { ok: true }));
|
||||
if (result.reason === 'not-found') return c.body(null, 404);
|
||||
const error =
|
||||
result.reason === 'unsupported-kind'
|
||||
? 'Only anime entries can be grouped.'
|
||||
: 'That title has no AniList entry to group with. Link it to AniList or merge the entries instead.';
|
||||
return c.json(statsJson('error', { error }), 409);
|
||||
});
|
||||
|
||||
app.post('/api/stats/anime/:animeId/merge', async (c) => {
|
||||
const animeId = parsePositiveId(c.req.param('animeId'));
|
||||
if (animeId === null) return c.body(null, 400);
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
import { createLogger } from '../../../logger.js';
|
||||
import type { AnkiConnectConfig } from '../../../types.js';
|
||||
import type {
|
||||
StatsAnimeGroupOverrideRequest,
|
||||
StatsDayRange,
|
||||
StatsDictionaryWordQuery,
|
||||
StatsDictionaryWordSort,
|
||||
@@ -60,15 +59,6 @@ export function isPositiveSafeInteger(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
/** Validates a `PUT /api/stats/anime/:animeId/group` body; null for anything malformed. */
|
||||
export function parseAnimeGroupOverrideBody(body: unknown): StatsAnimeGroupOverrideRequest | null {
|
||||
if (!body || typeof body !== 'object') return null;
|
||||
const { mode, targetAnimeId } = body as Record<string, unknown>;
|
||||
if (mode === 'standalone' || mode === 'anilist') return { mode };
|
||||
if (mode === 'join' && isPositiveSafeInteger(targetAnimeId)) return { mode, targetAnimeId };
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parsePositiveId(raw: string | undefined): number | null {
|
||||
if (raw === undefined) return null;
|
||||
const value = Number(raw);
|
||||
|
||||
@@ -58,78 +58,3 @@ for (const [localKind, remoteKind, sameEntry] of [
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('franchise override follows whichever side set or cleared it last', () => {
|
||||
const adapt = (db: DatabaseSync) => ({
|
||||
query: (sql: string) => db.prepare(sql),
|
||||
exec: (sql: string) => {
|
||||
db.exec(sql);
|
||||
},
|
||||
close: () => {
|
||||
db.close();
|
||||
},
|
||||
});
|
||||
const cases: Array<{
|
||||
name: string;
|
||||
local: [number | null, string | null];
|
||||
remote: [number | null, string | null];
|
||||
expected: number | null;
|
||||
}> = [
|
||||
{
|
||||
name: 'newer remote join wins',
|
||||
local: [null, null],
|
||||
remote: [20832, '2000'],
|
||||
expected: 20832,
|
||||
},
|
||||
{ name: 'newer remote clear wins', local: [0, '1000'], remote: [null, '2000'], expected: null },
|
||||
{ name: 'older remote loses', local: [0, '3000'], remote: [20832, '2000'], expected: 0 },
|
||||
{ name: 'untouched remote keeps local', local: [0, '1000'], remote: [null, null], expected: 0 },
|
||||
];
|
||||
for (const c of cases) {
|
||||
const local = new Database(':memory:');
|
||||
const remote = new Database(':memory:');
|
||||
try {
|
||||
for (const [db, [override, updatedAt]] of [
|
||||
[local, c.local],
|
||||
[remote, c.remote],
|
||||
] as const) {
|
||||
ensureSchema(db);
|
||||
db.prepare(
|
||||
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, group_override, group_override_updated_at)
|
||||
VALUES ('overlord ii', 'Overlord II', 98437, ?, ?)`,
|
||||
).run(override, updatedAt);
|
||||
}
|
||||
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
|
||||
const row = local.prepare('SELECT group_override AS value FROM imm_anime').get() as {
|
||||
value: number | null;
|
||||
};
|
||||
assert.equal(row.value, c.expected, c.name);
|
||||
} finally {
|
||||
local.close();
|
||||
remote.close();
|
||||
}
|
||||
}
|
||||
|
||||
const local = new Database(':memory:');
|
||||
const remote = new Database(':memory:');
|
||||
try {
|
||||
ensureSchema(local);
|
||||
ensureSchema(remote);
|
||||
remote
|
||||
.prepare(
|
||||
`INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override, group_override_updated_at)
|
||||
VALUES ('specials', 'Specials', 20832, '1000')`,
|
||||
)
|
||||
.run();
|
||||
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
|
||||
const row = local
|
||||
.prepare(
|
||||
'SELECT group_override AS value, group_override_updated_at AS updatedAt FROM imm_anime',
|
||||
)
|
||||
.get() as { value: number | null; updatedAt: string | null };
|
||||
assert.deepEqual([row.value, row.updatedAt], [20832, '1000']);
|
||||
} finally {
|
||||
local.close();
|
||||
remote.close();
|
||||
}
|
||||
});
|
||||
@@ -15,8 +15,6 @@ const ANIME_COPY_COLUMNS = [
|
||||
'tmdb_id',
|
||||
'tmdb_type',
|
||||
'metadata_json',
|
||||
'group_override',
|
||||
'group_override_updated_at',
|
||||
'CREATED_DATE',
|
||||
'LAST_UPDATE_DATE',
|
||||
] as const;
|
||||
@@ -148,13 +146,6 @@ export function mergeAnime(
|
||||
END
|
||||
WHERE anime_id = ?`,
|
||||
);
|
||||
// The franchise override holds AniList ids (or 0 / NULL), so it needs no id
|
||||
// remapping. The side that set or cleared it last wins.
|
||||
const takeNewerGroupOverride = local.query(
|
||||
`UPDATE imm_anime SET group_override = ?, group_override_updated_at = ?
|
||||
WHERE anime_id = ? AND (group_override_updated_at IS NULL
|
||||
OR CAST(group_override_updated_at AS INTEGER) < CAST(? AS INTEGER))`,
|
||||
);
|
||||
|
||||
for (const row of selectAll(
|
||||
remote,
|
||||
@@ -204,14 +195,6 @@ export function mergeAnime(
|
||||
row.media_kind,
|
||||
localId,
|
||||
);
|
||||
if (row.group_override_updated_at !== null) {
|
||||
takeNewerGroupOverride.run(
|
||||
row.group_override,
|
||||
row.group_override_updated_at,
|
||||
localId,
|
||||
row.group_override_updated_at,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Conflicting providers can share a title, but the stored title key is
|
||||
|
||||
@@ -20,11 +20,6 @@ export type { SyncMergeSummary } from './shared';
|
||||
* are updated incrementally so history older than the session retention
|
||||
* window is preserved on both sides. Idempotent: re-merging the same
|
||||
* snapshot is a no-op.
|
||||
*
|
||||
* A library entry's franchise override (`group_override`) is last-writer-wins
|
||||
* by `group_override_updated_at`. The AniList relation cache
|
||||
* (`imm_anilist_media`, `imm_anilist_relations`) is not merged: each machine
|
||||
* rebuilds it from AniList.
|
||||
*/
|
||||
export function mergeSnapshotIntoDb(localDbPath: string, snapshotPath: string): SyncMergeSummary {
|
||||
if (!fs.existsSync(localDbPath)) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import path from 'node:path';
|
||||
import { ImmersionTrackerService } from '../../core/services';
|
||||
import { createCoverArtFetcher } from '../../core/services/anilist/cover-art-fetcher';
|
||||
import { createAnilistRelationFetcher } from '../../core/services/anilist/franchise-relation-fetcher';
|
||||
import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter';
|
||||
import { resolveLegacyVocabularyPosFromTokens } from '../../core/services/immersion-tracker/legacy-vocabulary-pos';
|
||||
import type { StatsWindowOptions } from '../../core/services/stats-window';
|
||||
@@ -173,8 +172,6 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
|
||||
},
|
||||
);
|
||||
|
||||
const anilistRelationFetcher = createAnilistRelationFetcher(deps.anilistRateLimiter);
|
||||
|
||||
// One options object serves the overlay's IPC toggle and the session-action toggle.
|
||||
const statsOverlayOptions: StatsWindowOptions = {
|
||||
preloadPath: path.join(deps.mainDirname, 'preload-stats.js'),
|
||||
@@ -238,7 +235,6 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
|
||||
|
||||
appState.immersionTracker = tracker as ImmersionTrackerService | null;
|
||||
appState.immersionTracker?.setCoverArtFetcher(coverArtFetcher);
|
||||
appState.immersionTracker?.setAnilistRelationFetcher(anilistRelationFetcher);
|
||||
if (tracker) {
|
||||
// Start HTTP stats server
|
||||
if (!appState.statsServer) {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { ConfigService } from './config/service';
|
||||
import { createLogger, setLogLevel } from './logger';
|
||||
import { ImmersionTrackerService } from './core/services/immersion-tracker-service';
|
||||
import { createCoverArtFetcher } from './core/services/anilist/cover-art-fetcher';
|
||||
import { createAnilistRelationFetcher } from './core/services/anilist/franchise-relation-fetcher';
|
||||
import { createAnilistRateLimiter } from './core/services/anilist/rate-limiter';
|
||||
import { createLiveActionMetadataResolver } from './core/services/tmdb/live-action-resolver';
|
||||
import { createTmdbClient, createTmdbApiKeyResolver } from './core/services/tmdb/tmdb-client';
|
||||
@@ -213,14 +212,11 @@ async function main(): Promise<void> {
|
||||
() => bundledTmdbApiKey,
|
||||
),
|
||||
});
|
||||
// Cover art and franchise relations share one AniList request budget.
|
||||
const anilistRateLimiter = createAnilistRateLimiter();
|
||||
tracker.setCoverArtFetcher(
|
||||
createCoverArtFetcher(anilistRateLimiter, createLogger('stats-daemon:cover-art'), {
|
||||
createCoverArtFetcher(createAnilistRateLimiter(), createLogger('stats-daemon:cover-art'), {
|
||||
liveAction: createLiveActionMetadataResolver(tmdbClient, createLogger('stats-daemon:tmdb')),
|
||||
}),
|
||||
);
|
||||
tracker.setAnilistRelationFetcher(createAnilistRelationFetcher(anilistRateLimiter));
|
||||
|
||||
statsServer = await startStatsServer({
|
||||
port: config.stats.serverPort,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type {
|
||||
AnimeDetailData,
|
||||
AnimeLibraryGroup,
|
||||
AnimeLibraryItem,
|
||||
AnimeWord,
|
||||
DailyRollup,
|
||||
@@ -188,16 +187,6 @@ export interface StatsMoveVideoRequest {
|
||||
animeId: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Body of `PUT /api/stats/anime/:animeId/group`: list the entry with another
|
||||
* entry's franchise (`join`), on its own (`standalone`), or where AniList's
|
||||
* relations put it (`anilist`, which clears the override).
|
||||
*/
|
||||
export type StatsAnimeGroupOverrideRequest =
|
||||
| { mode: 'join'; targetAnimeId: number }
|
||||
| { mode: 'standalone' }
|
||||
| { mode: 'anilist' };
|
||||
|
||||
export interface StatsAnimeMergeRecommendation {
|
||||
recommendationId: number;
|
||||
animeIds: [number, number];
|
||||
@@ -262,7 +251,6 @@ export interface StatsJsonResponseMap {
|
||||
mediaLibrary: MediaLibraryItem[];
|
||||
mediaDetail: MediaDetailData;
|
||||
animeLibrary: AnimeLibraryItem[];
|
||||
animeLibraryGroups: AnimeLibraryGroup[];
|
||||
animeMergeRecommendations: StatsAnimeMergeRecommendationsResponse;
|
||||
animeDetail: AnimeDetailData;
|
||||
animeWords: AnimeWord[];
|
||||
@@ -274,7 +262,6 @@ export interface StatsJsonResponseMap {
|
||||
deleteAnime: StatsOkResponse;
|
||||
mergeAnime: StatsMergeAnimeResponse;
|
||||
moveVideoToAnime: StatsMoveVideoResponse;
|
||||
setAnimeGroupOverride: StatsOkResponse;
|
||||
dismissAnimeMergeRecommendation: StatsOkResponse;
|
||||
anilistSearch: StatsAnilistSearchResult[];
|
||||
tmdbSearch: StatsTmdbSearchResult[];
|
||||
@@ -343,7 +330,6 @@ export interface StatsHttpClient {
|
||||
getMediaLibrary: () => Promise<MediaLibraryItem[]>;
|
||||
getMediaDetail: (videoId: number) => Promise<MediaDetailData>;
|
||||
getAnimeLibrary: () => Promise<AnimeLibraryItem[]>;
|
||||
getAnimeLibraryGroups: () => Promise<AnimeLibraryGroup[]>;
|
||||
getAnimeMergeRecommendations: () => Promise<StatsAnimeMergeRecommendationsResponse>;
|
||||
getAnimeDetail: (animeId: number) => Promise<AnimeDetailData>;
|
||||
getAnimeWords: (animeId: number, limit?: number) => Promise<AnimeWord[]>;
|
||||
@@ -370,10 +356,6 @@ export interface StatsHttpClient {
|
||||
deleteAnime: (animeId: number) => Promise<void>;
|
||||
mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<StatsMergeAnimeResponse>;
|
||||
moveVideoToAnime: (videoId: number, animeId: number) => Promise<StatsMoveVideoResponse>;
|
||||
setAnimeGroupOverride: (
|
||||
animeId: number,
|
||||
request: StatsAnimeGroupOverrideRequest,
|
||||
) => Promise<void>;
|
||||
dismissAnimeMergeRecommendation: (recommendationId: number) => Promise<void>;
|
||||
getKnownWords: () => Promise<string[]>;
|
||||
getKnownWordsSummary: () => Promise<StatsKnownWordsSummary>;
|
||||
|
||||
@@ -306,46 +306,6 @@ export interface AnimeLibraryItem {
|
||||
lastWatchedMs: number;
|
||||
}
|
||||
|
||||
/** One library entry inside a franchise group, with its AniList format and start date when cached. */
|
||||
export interface AnimeLibraryGroupPart extends AnimeLibraryItem {
|
||||
/** AniList format (TV, MOVIE, OVA...); null without a cached AniList entry. */
|
||||
format: string | null;
|
||||
/** AniList start date as yyyymmdd (month/day 0 when unknown); null when unknown. */
|
||||
startDate: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A library card: one franchise (seasons, movies and OVAs that AniList links
|
||||
* together) or a single entry. Totals add up the parts; `lastWatchedMs` is the
|
||||
* latest part's. Parts are in AniList release order.
|
||||
*/
|
||||
export interface AnimeLibraryGroup {
|
||||
/** AniList id the franchise is named after, or minus the entry's animeId for a card of its own. */
|
||||
groupKey: number;
|
||||
title: string;
|
||||
mediaKind: MediaKind;
|
||||
/** Entry whose cover the card shows: the first part by release date. */
|
||||
coverAnimeId: number;
|
||||
totalSessions: number;
|
||||
totalActiveMs: number;
|
||||
totalCards: number;
|
||||
totalTokensSeen: number;
|
||||
episodeCount: number;
|
||||
lastWatchedMs: number;
|
||||
parts: AnimeLibraryGroupPart[];
|
||||
}
|
||||
|
||||
/** How a library entry's franchise was chosen: by AniList, moved by the user, or kept on its own. */
|
||||
export type AnimeGroupOverrideMode = 'anilist' | 'joined' | 'standalone';
|
||||
|
||||
/** Where one library entry sits in the grouped library. */
|
||||
export interface AnimeGroupPlacement {
|
||||
groupKey: number;
|
||||
title: string;
|
||||
partCount: number;
|
||||
overrideMode: AnimeGroupOverrideMode;
|
||||
}
|
||||
|
||||
export interface AnilistEntry {
|
||||
anilistId: number;
|
||||
titleRomaji: string | null;
|
||||
@@ -378,8 +338,6 @@ export interface AnimeDetailData {
|
||||
};
|
||||
episodes: AnimeEpisode[];
|
||||
anilistEntries: AnilistEntry[];
|
||||
/** Null when the entry has no watch history to list in the library. */
|
||||
group: AnimeGroupPlacement | null;
|
||||
}
|
||||
|
||||
export interface AnimeEpisode {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { AnimeCoverImage } from './AnimeCoverImage';
|
||||
import { formatDuration, formatNumber } from '../../lib/formatters';
|
||||
import type { AnimeCardData } from '../../lib/anime-groups';
|
||||
import type { AnimeLibraryItem } from '../../types/stats';
|
||||
|
||||
interface AnimeCardProps {
|
||||
anime: AnimeCardData;
|
||||
anime: AnimeLibraryItem;
|
||||
onClick: () => void;
|
||||
/** While selecting, clicking the card toggles it instead of opening it. */
|
||||
selectable?: boolean;
|
||||
@@ -16,7 +16,6 @@ export function AnimeCard({
|
||||
selectable = false,
|
||||
selected = false,
|
||||
}: AnimeCardProps) {
|
||||
const unit = anime.mediaKind === 'youtube' ? 'video' : 'episode';
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
@@ -45,16 +44,11 @@ export function AnimeCard({
|
||||
{'✓'}
|
||||
</span>
|
||||
)}
|
||||
{anime.partCount ? (
|
||||
<span className="absolute top-2 right-2 px-1.5 py-0.5 rounded text-[10px] font-medium bg-ctp-crust/80 text-ctp-text border border-ctp-surface2">
|
||||
{anime.partCount} parts
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<div className="text-sm font-medium text-ctp-text truncate">{anime.canonicalTitle}</div>
|
||||
<div className="text-xs text-ctp-overlay2 mt-1">
|
||||
{anime.episodeCount} {unit}
|
||||
{anime.episodeCount} {anime.mediaKind === 'youtube' ? 'video' : 'episode'}
|
||||
{anime.episodeCount !== 1 ? 's' : ''}
|
||||
</div>
|
||||
<div className="text-xs text-ctp-overlay2">
|
||||
|
||||
@@ -9,16 +9,13 @@ import { AnimeWordList } from './AnimeWordList';
|
||||
import { AnilistSelector } from './AnilistSelector';
|
||||
import { TmdbSelector } from './TmdbSelector';
|
||||
import { AnimeOverviewStats } from './AnimeOverviewStats';
|
||||
import { LibraryEntryPicker } from './LibraryEntryPicker';
|
||||
import { CHART_THEME } from '../../lib/chart-theme';
|
||||
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
|
||||
import type { DailyRollup, StatsAnimeGroupOverrideRequest } from '../../types/stats';
|
||||
import type { DailyRollup } from '../../types/stats';
|
||||
|
||||
interface AnimeDetailViewProps {
|
||||
animeId: number;
|
||||
onBack: () => void;
|
||||
/** Defaults to "Back to Library"; a part opened from a franchise card returns there. */
|
||||
backLabel?: string;
|
||||
onNavigateToWord?: (wordId: number) => void;
|
||||
onOpenEpisodeDetail?: (videoId: number) => void;
|
||||
/** Called after the whole library entry is deleted, so the caller can refresh. */
|
||||
@@ -31,23 +28,6 @@ interface AnimeDetailViewProps {
|
||||
onProviderRelinked?: () => void;
|
||||
/** Called after an episode is reassigned to another entry. */
|
||||
onEpisodeMoved?: () => void;
|
||||
/** Called after the entry is moved to another franchise card or back. */
|
||||
onGroupChanged?: () => void;
|
||||
}
|
||||
|
||||
/** The server explains a refused move (409) in its JSON body; show that text. */
|
||||
function describeGroupError(err: unknown): string {
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
const refused = /^Stats API error: 409 (.*)$/s.exec(message);
|
||||
if (refused) {
|
||||
try {
|
||||
const body = JSON.parse(refused[1]!) as { error?: unknown };
|
||||
if (typeof body.error === 'string') return body.error;
|
||||
} catch {
|
||||
// Fall through to the raw message.
|
||||
}
|
||||
}
|
||||
return message || 'Failed to move this title.';
|
||||
}
|
||||
|
||||
type Range = 14 | 30 | 90;
|
||||
@@ -169,13 +149,11 @@ function useAnimeKnownWords(animeId: number) {
|
||||
export function AnimeDetailView({
|
||||
animeId,
|
||||
onBack,
|
||||
backLabel = 'Back to Library',
|
||||
onNavigateToWord,
|
||||
onOpenEpisodeDetail,
|
||||
onAnimeDeleted,
|
||||
onProviderRelinked,
|
||||
onEpisodeMoved,
|
||||
onGroupChanged,
|
||||
}: AnimeDetailViewProps) {
|
||||
const { data, loading, error, reload } = useAnimeDetail(animeId);
|
||||
const [showAnilistSelector, setShowAnilistSelector] = useState(false);
|
||||
@@ -184,9 +162,6 @@ export function AnimeDetailView({
|
||||
const [isDeletingAnime, setIsDeletingAnime] = useState(false);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
const isDeletingAnimeRef = useRef(false);
|
||||
const [showGroupPicker, setShowGroupPicker] = useState(false);
|
||||
const [groupBusyTargetId, setGroupBusyTargetId] = useState<number | null>(null);
|
||||
const [groupError, setGroupError] = useState<string | null>(null);
|
||||
const knownWordsSummary = useAnimeKnownWords(animeId);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -197,23 +172,7 @@ export function AnimeDetailView({
|
||||
if (error) return <div className="text-ctp-red p-4">Error: {error}</div>;
|
||||
if (!data?.detail) return <div className="text-ctp-overlay2 p-4">Library entry not found</div>;
|
||||
|
||||
const { detail, episodes, anilistEntries, group } = data;
|
||||
|
||||
// `busyId` marks which picker row shows progress; the entry's own id for header actions.
|
||||
const applyGroupOverride = async (request: StatsAnimeGroupOverrideRequest, busyId: number) => {
|
||||
setGroupBusyTargetId(busyId);
|
||||
setGroupError(null);
|
||||
try {
|
||||
await getStatsClient().setAnimeGroupOverride(animeId, request);
|
||||
setShowGroupPicker(false);
|
||||
reload();
|
||||
onGroupChanged?.();
|
||||
} catch (err) {
|
||||
setGroupError(describeGroupError(err));
|
||||
} finally {
|
||||
setGroupBusyTargetId(null);
|
||||
}
|
||||
};
|
||||
const { detail, episodes, anilistEntries } = data;
|
||||
|
||||
const handleDeleteAnime = async () => {
|
||||
if (isDeletingAnimeRef.current) return;
|
||||
@@ -255,18 +214,11 @@ export function AnimeDetailView({
|
||||
onClick={onBack}
|
||||
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
|
||||
>
|
||||
← {backLabel}
|
||||
← Back to Library
|
||||
</button>
|
||||
<AnimeHeader
|
||||
detail={detail}
|
||||
anilistEntries={anilistEntries ?? []}
|
||||
group={group}
|
||||
groupBusy={groupBusyTargetId !== null}
|
||||
onMoveToGroup={() => {
|
||||
setGroupError(null);
|
||||
setShowGroupPicker(true);
|
||||
}}
|
||||
onSetGroupMode={(mode) => void applyGroupOverride({ mode }, animeId)}
|
||||
coverRetryToken={coverRetryToken}
|
||||
onChangeAnilist={() => setShowAnilistSelector(true)}
|
||||
onChangeTmdb={() => setShowTmdbSelector(true)}
|
||||
@@ -274,25 +226,6 @@ export function AnimeDetailView({
|
||||
isDeletingAnime={isDeletingAnime}
|
||||
/>
|
||||
{deleteError ? <div className="text-sm text-ctp-red">{deleteError}</div> : null}
|
||||
{groupError && !showGroupPicker ? (
|
||||
<div role="alert" className="text-sm text-ctp-red">
|
||||
{groupError}
|
||||
</div>
|
||||
) : null}
|
||||
{showGroupPicker && (
|
||||
<LibraryEntryPicker
|
||||
heading="Move to another anime"
|
||||
mediaKind="anime"
|
||||
excludeAnimeIds={[animeId]}
|
||||
filter={(entry) => entry.anilistId !== null}
|
||||
busyAnimeId={groupBusyTargetId}
|
||||
error={groupError}
|
||||
onSelect={(entry) =>
|
||||
void applyGroupOverride({ mode: 'join', targetAnimeId: entry.animeId }, entry.animeId)
|
||||
}
|
||||
onClose={() => setShowGroupPicker(false)}
|
||||
/>
|
||||
)}
|
||||
<AnimeOverviewStats detail={detail} knownWordsSummary={knownWordsSummary} />
|
||||
<EpisodeList
|
||||
episodes={episodes}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import { describeAnimePart } from '../../lib/anime-groups';
|
||||
import { formatDuration, formatNumber, formatRelativeDate } from '../../lib/formatters';
|
||||
import type { AnimeLibraryGroup } from '../../types/stats';
|
||||
import { AnimeCoverImage } from './AnimeCoverImage';
|
||||
|
||||
interface AnimeGroupViewProps {
|
||||
group: AnimeLibraryGroup;
|
||||
onBack: () => void;
|
||||
onOpenPart: (animeId: number) => void;
|
||||
}
|
||||
|
||||
/** A franchise card opened: its library entries in release order, each opening its own page. */
|
||||
export function AnimeGroupView({ group, onBack, onOpenPart }: AnimeGroupViewProps) {
|
||||
const cover = group.parts.find((part) => part.animeId === group.coverAnimeId) ?? group.parts[0]!;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBack}
|
||||
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
|
||||
>
|
||||
← Back to Library
|
||||
</button>
|
||||
<div className="flex gap-4">
|
||||
<AnimeCoverImage
|
||||
animeId={cover.animeId}
|
||||
title={group.title}
|
||||
coverRetryToken={cover.anilistId ?? 0}
|
||||
className="w-32 h-44 rounded-lg shrink-0"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="text-lg font-bold text-ctp-text truncate">{group.title}</h2>
|
||||
<div className="text-sm text-ctp-subtext0 mt-2">
|
||||
{group.parts.length} parts · {group.episodeCount} episode
|
||||
{group.episodeCount !== 1 ? 's' : ''}
|
||||
</div>
|
||||
<div className="text-xs text-ctp-overlay2 mt-1">
|
||||
{formatDuration(group.totalActiveMs)} · {formatNumber(group.totalCards)} cards
|
||||
{group.lastWatchedMs > 0
|
||||
? ` · last watched ${formatRelativeDate(group.lastWatchedMs)}`
|
||||
: ''}
|
||||
</div>
|
||||
<p className="text-xs text-ctp-overlay2 mt-3 leading-relaxed">
|
||||
Grouped by AniList's season, movie and side-story links. Open a part to move it to
|
||||
another anime or show it on its own.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-ctp-surface0 border border-ctp-surface1 rounded-lg p-4">
|
||||
<h3 className="text-sm font-semibold text-ctp-text mb-3">Seasons and Movies</h3>
|
||||
<ul className="space-y-1">
|
||||
{group.parts.map((part) => {
|
||||
const kind = describeAnimePart(part.format, part.startDate);
|
||||
return (
|
||||
<li key={part.animeId}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenPart(part.animeId)}
|
||||
className="w-full flex items-center gap-3 p-2.5 rounded-lg hover:bg-ctp-surface1 transition-colors text-left"
|
||||
>
|
||||
<AnimeCoverImage
|
||||
animeId={part.animeId}
|
||||
title={part.canonicalTitle}
|
||||
coverRetryToken={part.anilistId ?? part.tmdbId ?? 0}
|
||||
className="w-10 h-14 rounded shrink-0"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm text-ctp-text truncate">{part.canonicalTitle}</div>
|
||||
<div className="text-xs text-ctp-overlay2 mt-0.5">
|
||||
{kind ? `${kind} · ` : ''}
|
||||
{part.episodeCount} episode{part.episodeCount !== 1 ? 's' : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-ctp-overlay2 text-right shrink-0">
|
||||
<div>{formatDuration(part.totalActiveMs)}</div>
|
||||
<div>{formatNumber(part.totalCards)} cards</div>
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { apiClient } from '../../lib/api-client';
|
||||
import type {
|
||||
AnimeDetailData,
|
||||
AnimeLibraryGroup,
|
||||
AnimeLibraryGroupPart,
|
||||
StatsAnimeGroupOverrideRequest,
|
||||
} from '../../types/stats';
|
||||
import { AnimeTab } from './AnimeTab';
|
||||
import { installDom } from '../../test-utils/dom';
|
||||
|
||||
function part(
|
||||
animeId: number,
|
||||
title: string,
|
||||
format: string,
|
||||
startDate: number,
|
||||
): AnimeLibraryGroupPart {
|
||||
return {
|
||||
mediaKind: 'anime',
|
||||
animeId,
|
||||
canonicalTitle: title,
|
||||
anilistId: animeId * 100,
|
||||
tmdbId: null,
|
||||
tmdbType: null,
|
||||
totalSessions: 1,
|
||||
totalActiveMs: 60_000,
|
||||
totalCards: 2,
|
||||
totalTokensSeen: 0,
|
||||
episodeCount: format === 'MOVIE' ? 1 : 13,
|
||||
episodesTotal: null,
|
||||
lastWatchedMs: animeId,
|
||||
format,
|
||||
startDate,
|
||||
};
|
||||
}
|
||||
|
||||
const overlord: AnimeLibraryGroup = {
|
||||
groupKey: 20832,
|
||||
title: 'Overlord',
|
||||
mediaKind: 'anime',
|
||||
coverAnimeId: 2,
|
||||
totalSessions: 2,
|
||||
totalActiveMs: 120_000,
|
||||
totalCards: 4,
|
||||
totalTokensSeen: 0,
|
||||
episodeCount: 14,
|
||||
lastWatchedMs: 2,
|
||||
parts: [part(2, 'The Undead King', 'MOVIE', 20170225), part(1, 'Overlord II', 'TV', 20180109)],
|
||||
};
|
||||
|
||||
function detailData(): AnimeDetailData {
|
||||
const {
|
||||
format: _format,
|
||||
startDate: _startDate,
|
||||
episodesTotal: _total,
|
||||
...item
|
||||
} = part(1, 'Overlord II', 'TV', 20180109);
|
||||
return {
|
||||
detail: {
|
||||
...item,
|
||||
titleRomaji: null,
|
||||
titleEnglish: null,
|
||||
titleNative: null,
|
||||
description: null,
|
||||
totalLinesSeen: 0,
|
||||
totalLookupCount: 0,
|
||||
totalLookupHits: 0,
|
||||
totalYomitanLookupCount: 0,
|
||||
},
|
||||
episodes: [],
|
||||
anilistEntries: [],
|
||||
group: { groupKey: 20832, title: 'Overlord', partCount: 2, overrideMode: 'anilist' },
|
||||
};
|
||||
}
|
||||
|
||||
function findButton(container: Element, label: string): HTMLElement {
|
||||
const match = [...container.querySelectorAll('button')].find((button) =>
|
||||
(button.textContent ?? '').includes(label),
|
||||
);
|
||||
assert.ok(match, `expected a "${label}" button`);
|
||||
return match as unknown as HTMLElement;
|
||||
}
|
||||
|
||||
test('a franchise card opens its parts in release order, and a part can stand alone', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = { ...apiClient };
|
||||
const overrides: Array<[number, StatsAnimeGroupOverrideRequest]> = [];
|
||||
let libraryFetches = 0;
|
||||
apiClient.getAnimeLibraryGroups = async () => {
|
||||
libraryFetches += 1;
|
||||
return [overlord];
|
||||
};
|
||||
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
|
||||
apiClient.getAnimeDetail = async () => detailData();
|
||||
apiClient.getAnimeWords = async () => [];
|
||||
apiClient.getAnimeRollups = async () => [];
|
||||
apiClient.getAnimeKnownWordsSummary = async () => ({ totalUniqueWords: 0, knownWordCount: 0 });
|
||||
apiClient.setAnimeGroupOverride = async (animeId, request) => {
|
||||
overrides.push([animeId, request]);
|
||||
};
|
||||
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(<AnimeTab />));
|
||||
// One card for the franchise, counted once, with the first-released part's cover.
|
||||
assert.match(container.textContent ?? '', /1 title/);
|
||||
assert.match(findButton(container, 'Overlord').textContent ?? '', /2 parts/);
|
||||
assert.match(container.querySelector('img')?.getAttribute('src') ?? '', /anime\/2\/cover/);
|
||||
|
||||
await act(async () => findButton(container, 'Overlord').click());
|
||||
const rows = [...container.querySelectorAll('li button')].map((row) => row.textContent ?? '');
|
||||
assert.equal(rows.length, 2);
|
||||
assert.match(rows[0]!, /The Undead King.*Movie · 2017/);
|
||||
assert.match(rows[1]!, /Overlord II.*TV · 2018/);
|
||||
|
||||
await act(async () => findButton(container, 'Overlord II').click());
|
||||
assert.match(container.textContent ?? '', /Listed under Overlord with 1 other part/);
|
||||
await act(async () => findButton(container, 'Show On Its Own').click());
|
||||
assert.deepEqual(overrides, [[1, { mode: 'standalone' }]]);
|
||||
assert.equal(libraryFetches, 2);
|
||||
|
||||
await act(async () => findButton(container, 'Back to Overlord').click());
|
||||
assert.match(container.textContent ?? '', /Seasons and Movies/);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
Object.assign(apiClient, original);
|
||||
uninstallDom();
|
||||
}
|
||||
});
|
||||
|
||||
test('a franchise left with one part closes and does not reopen on a later refresh', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = { ...apiClient };
|
||||
const [movie, season] = overlord.parts as [AnimeLibraryGroupPart, AnimeLibraryGroupPart];
|
||||
const split: AnimeLibraryGroup[] = [
|
||||
{ ...overlord, parts: [movie], coverAnimeId: movie.animeId },
|
||||
{ ...overlord, groupKey: 1, title: season.canonicalTitle, parts: [season], coverAnimeId: 1 },
|
||||
];
|
||||
let library: AnimeLibraryGroup[] = [overlord];
|
||||
apiClient.getAnimeLibraryGroups = async () => library;
|
||||
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
|
||||
apiClient.getAnimeDetail = async () => detailData();
|
||||
apiClient.getAnimeWords = async () => [];
|
||||
apiClient.getAnimeRollups = async () => [];
|
||||
apiClient.getAnimeKnownWordsSummary = async () => ({ totalUniqueWords: 0, knownWordCount: 0 });
|
||||
apiClient.setAnimeGroupOverride = async () => {
|
||||
library = split;
|
||||
};
|
||||
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(<AnimeTab />));
|
||||
await act(async () => findButton(container, 'Overlord').click());
|
||||
await act(async () => findButton(container, 'Overlord II').click());
|
||||
await act(async () => findButton(container, 'Show On Its Own').click());
|
||||
await act(async () => findButton(container, 'Back to Overlord').click());
|
||||
assert.doesNotMatch(container.textContent ?? '', /Seasons and Movies/);
|
||||
|
||||
// The franchise gets its second part back; the library must stay where it is.
|
||||
library = [overlord];
|
||||
await act(async () => {
|
||||
window.dispatchEvent(new window.Event('focus'));
|
||||
});
|
||||
assert.match(findButton(container, 'Overlord').textContent ?? '', /2 parts/);
|
||||
assert.doesNotMatch(container.textContent ?? '', /Seasons and Movies/);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
Object.assign(apiClient, original);
|
||||
uninstallDom();
|
||||
}
|
||||
});
|
||||
@@ -1,17 +1,9 @@
|
||||
import { AnimeCoverImage } from './AnimeCoverImage';
|
||||
import type { AnimeDetailData, AnimeGroupPlacement, AnilistEntry } from '../../types/stats';
|
||||
|
||||
const SECONDARY_BUTTON_CLASS =
|
||||
'inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-ctp-surface1 text-ctp-overlay2 hover:bg-ctp-surface2 hover:text-ctp-subtext0 transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
|
||||
import type { AnimeDetailData, AnilistEntry } from '../../types/stats';
|
||||
|
||||
interface AnimeHeaderProps {
|
||||
detail: AnimeDetailData['detail'];
|
||||
anilistEntries: AnilistEntry[];
|
||||
/** The franchise card this entry is listed under; null hides the grouping actions. */
|
||||
group?: AnimeGroupPlacement | null;
|
||||
onMoveToGroup?: () => void;
|
||||
onSetGroupMode?: (mode: 'standalone' | 'anilist') => void;
|
||||
groupBusy?: boolean;
|
||||
coverRetryToken?: number;
|
||||
onChangeAnilist?: () => void;
|
||||
onChangeTmdb?: () => void;
|
||||
@@ -41,10 +33,6 @@ function AnilistButton({ entry }: { entry: AnilistEntry }) {
|
||||
export function AnimeHeader({
|
||||
detail,
|
||||
anilistEntries,
|
||||
group = null,
|
||||
onMoveToGroup,
|
||||
onSetGroupMode,
|
||||
groupBusy = false,
|
||||
coverRetryToken = 0,
|
||||
onChangeAnilist,
|
||||
onChangeTmdb,
|
||||
@@ -64,9 +52,6 @@ export function AnimeHeader({
|
||||
? `https://www.themoviedb.org/${detail.tmdbType}/${detail.tmdbId}`
|
||||
: null;
|
||||
const coverCacheToken = (detail.anilistId ?? detail.tmdbId ?? 0) * 1_000_000 + coverRetryToken;
|
||||
// Only anime entries are grouped by AniList relations.
|
||||
const placement = detail.mediaKind === 'anime' ? group : null;
|
||||
const otherParts = placement ? placement.partCount - 1 : 0;
|
||||
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
@@ -95,11 +80,6 @@ export function AnimeHeader({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{placement && otherParts > 0 && (
|
||||
<div className="text-xs text-ctp-overlay2 mt-1">
|
||||
Listed under {placement.title} with {otherParts} other part{otherParts !== 1 ? 's' : ''}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-1.5 mt-2">
|
||||
{tmdbUrl && (
|
||||
<a
|
||||
@@ -158,42 +138,6 @@ export function AnimeHeader({
|
||||
{tmdbUrl ? 'Change TMDB Title' : 'Link to TMDB'}
|
||||
</button>
|
||||
)}
|
||||
{placement && onMoveToGroup && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onMoveToGroup}
|
||||
disabled={groupBusy}
|
||||
title="List this entry with another anime's seasons and movies"
|
||||
className={SECONDARY_BUTTON_CLASS}
|
||||
>
|
||||
{'Move to Another Anime\u2026'}
|
||||
</button>
|
||||
)}
|
||||
{placement && onSetGroupMode && placement.overrideMode !== 'anilist' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSetGroupMode('anilist')}
|
||||
disabled={groupBusy}
|
||||
title="Undo a manual move and group this entry by its AniList relations"
|
||||
className={SECONDARY_BUTTON_CLASS}
|
||||
>
|
||||
Put Back Where AniList Has It
|
||||
</button>
|
||||
)}
|
||||
{placement &&
|
||||
onSetGroupMode &&
|
||||
placement.overrideMode === 'anilist' &&
|
||||
otherParts > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSetGroupMode('standalone')}
|
||||
disabled={groupBusy}
|
||||
title="List this entry as its own card instead of with its franchise"
|
||||
className={SECONDARY_BUTTON_CLASS}
|
||||
>
|
||||
Show On Its Own
|
||||
</button>
|
||||
)}
|
||||
{onDeleteAnime && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -7,7 +7,6 @@ import type { AnimeLibraryItem, StatsMergeAnimeResponse } from '../../types/stat
|
||||
import { AnimeMergeDialog } from './AnimeMergeDialog';
|
||||
import { AnimeTab } from './AnimeTab';
|
||||
import { installDom } from '../../test-utils/dom';
|
||||
import { singleGroupLibrary } from '../../test-utils/library';
|
||||
|
||||
function libraryItem(animeId: number, title: string, episodeCount: number): AnimeLibraryItem {
|
||||
return {
|
||||
@@ -53,7 +52,7 @@ function mergeButton(container: Element): HTMLButtonElement {
|
||||
test('AnimeTab merges the selected duplicate entries into the chosen keeper', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
mergeAnime: apiClient.mergeAnime,
|
||||
};
|
||||
|
||||
@@ -62,10 +61,10 @@ test('AnimeTab merges the selected duplicate entries into the chosen keeper', as
|
||||
let libraryFetches = 0;
|
||||
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
|
||||
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
|
||||
apiClient.getAnimeLibrary = (async () => {
|
||||
libraryFetches += 1;
|
||||
return entries;
|
||||
});
|
||||
}) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.mergeAnime = (async (targetAnimeId: number, sourceAnimeIds: number[]) => {
|
||||
mergeCall = { targetAnimeId, sourceAnimeIds };
|
||||
entries = [libraryItem(1, 'Show', 3)];
|
||||
@@ -182,7 +181,7 @@ test('AnimeMergeDialog refuses to merge an AniList entry with a TMDB entry', asy
|
||||
test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merged', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
|
||||
mergeAnime: apiClient.mergeAnime,
|
||||
@@ -192,7 +191,7 @@ test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merg
|
||||
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] }];
|
||||
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
|
||||
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => entries);
|
||||
apiClient.getAnimeLibrary = (async () => entries) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeMergeRecommendations = (async () => ({
|
||||
recommendations,
|
||||
})) as typeof apiClient.getAnimeMergeRecommendations;
|
||||
@@ -253,16 +252,16 @@ test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merg
|
||||
test('AnimeTab dismisses a false-positive duplicate recommendation', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
|
||||
};
|
||||
let dismissedId: number | null = null;
|
||||
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
|
||||
apiClient.getAnimeLibrary = (async () => [
|
||||
libraryItem(1, 'Show', 2),
|
||||
libraryItem(2, 'Different Show', 1),
|
||||
]);
|
||||
]) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeMergeRecommendations = (async () => ({
|
||||
recommendations: [{ recommendationId: 73, animeIds: [1, 2] }],
|
||||
})) as typeof apiClient.getAnimeMergeRecommendations;
|
||||
@@ -292,16 +291,16 @@ test('AnimeTab dismisses a false-positive duplicate recommendation', async () =>
|
||||
test('AnimeTab refreshes the library and recommendations when the window regains focus', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
};
|
||||
let entries = [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
|
||||
let libraryFetches = 0;
|
||||
let recommendationFetches = 0;
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
|
||||
apiClient.getAnimeLibrary = (async () => {
|
||||
libraryFetches += 1;
|
||||
return entries;
|
||||
});
|
||||
}) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeMergeRecommendations = (async () => {
|
||||
recommendationFetches += 1;
|
||||
return { recommendations: [] };
|
||||
@@ -331,14 +330,14 @@ test('AnimeTab refreshes the library and recommendations when the window regains
|
||||
test('AnimeTab keeps a recommendation visible through a transient refresh failure', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
};
|
||||
let failRecommendations = false;
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
|
||||
apiClient.getAnimeLibrary = (async () => [
|
||||
libraryItem(1, 'Show', 2),
|
||||
libraryItem(2, 'Show Season 1', 1),
|
||||
]);
|
||||
]) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeMergeRecommendations = (async () => {
|
||||
if (failRecommendations) throw new Error('temporary failure');
|
||||
return { recommendations: [{ recommendationId: 41, animeIds: [1, 2] }] };
|
||||
@@ -365,14 +364,14 @@ test('AnimeTab keeps a recommendation visible through a transient refresh failur
|
||||
test('AnimeTab retains a recommendation and reports a failed dismissal', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
|
||||
};
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
|
||||
apiClient.getAnimeLibrary = (async () => [
|
||||
libraryItem(1, 'Show', 2),
|
||||
libraryItem(2, 'Show Season 1', 1),
|
||||
]);
|
||||
]) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeMergeRecommendations = (async () => ({
|
||||
recommendations: [{ recommendationId: 41, animeIds: [1, 2] }],
|
||||
})) as typeof apiClient.getAnimeMergeRecommendations;
|
||||
@@ -400,14 +399,14 @@ test('AnimeTab retains a recommendation and reports a failed dismissal', async (
|
||||
test('AnimeTab keeps an open recommendation review stable during background refresh', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
};
|
||||
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] as [number, number] }];
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
|
||||
apiClient.getAnimeLibrary = (async () => [
|
||||
libraryItem(1, 'Show', 2),
|
||||
libraryItem(2, 'Show Season 1', 1),
|
||||
]);
|
||||
]) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeMergeRecommendations = (async () => ({
|
||||
recommendations,
|
||||
})) as typeof apiClient.getAnimeMergeRecommendations;
|
||||
@@ -435,14 +434,14 @@ test('AnimeTab keeps an open recommendation review stable during background refr
|
||||
test('AnimeTab keeps the library visible through a transient background refresh failure', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
};
|
||||
let failLibrary = false;
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
|
||||
apiClient.getAnimeLibrary = (async () => {
|
||||
if (failLibrary) throw new Error('temporary failure');
|
||||
return [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
|
||||
});
|
||||
}) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeMergeRecommendations = (async () => ({
|
||||
recommendations: [],
|
||||
})) as typeof apiClient.getAnimeMergeRecommendations;
|
||||
@@ -471,7 +470,7 @@ test('AnimeTab keeps the library visible through a transient background refresh
|
||||
test('AnimeTab does not resurrect a dismissed recommendation from a stale in-flight refresh', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
|
||||
};
|
||||
@@ -480,10 +479,10 @@ test('AnimeTab does not resurrect a dismissed recommendation from a stale in-fli
|
||||
};
|
||||
let holdNextFetch = false;
|
||||
let releaseHeldFetch: (() => void) | null = null;
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
|
||||
apiClient.getAnimeLibrary = (async () => [
|
||||
libraryItem(1, 'Show', 2),
|
||||
libraryItem(2, 'Show Season 1', 1),
|
||||
]);
|
||||
]) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeMergeRecommendations = ((): Promise<typeof payload> => {
|
||||
if (!holdNextFetch) return Promise.resolve(payload);
|
||||
holdNextFetch = false;
|
||||
|
||||
@@ -6,7 +6,6 @@ import { apiClient } from '../../lib/api-client';
|
||||
import type { AnimeDetailData, AnimeLibraryItem } from '../../types/stats';
|
||||
import { AnimeTab } from './AnimeTab';
|
||||
import { installDom } from '../../test-utils/dom';
|
||||
import { singleGroupLibrary } from '../../test-utils/library';
|
||||
|
||||
function libraryItem(anilistId: number | null): AnimeLibraryItem {
|
||||
return {
|
||||
@@ -52,7 +51,6 @@ function detailData(anilistId: number | null): AnimeDetailData {
|
||||
},
|
||||
episodes: [],
|
||||
anilistEntries: [],
|
||||
group: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -67,7 +65,7 @@ function findButton(container: Element, label: string): HTMLElement {
|
||||
test('AnimeTab refetches the library after the AniList entry is relinked', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeDetail: apiClient.getAnimeDetail,
|
||||
getAnimeWords: apiClient.getAnimeWords,
|
||||
getAnimeRollups: apiClient.getAnimeRollups,
|
||||
@@ -81,10 +79,10 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
|
||||
let anilistId: number | null = 14813;
|
||||
let libraryFetches = 0;
|
||||
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
|
||||
apiClient.getAnimeLibrary = (async () => {
|
||||
libraryFetches += 1;
|
||||
return [libraryItem(anilistId)];
|
||||
});
|
||||
}) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeDetail = (async () => detailData(anilistId)) as typeof apiClient.getAnimeDetail;
|
||||
apiClient.getAnimeWords = (async () => []) as typeof apiClient.getAnimeWords;
|
||||
apiClient.getAnimeRollups = (async () => []) as typeof apiClient.getAnimeRollups;
|
||||
@@ -152,8 +150,8 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
|
||||
|
||||
test('AnimeTab watch time follows the displayed kind filter', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = apiClient.getAnimeLibraryGroups;
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
|
||||
const original = apiClient.getAnimeLibrary;
|
||||
apiClient.getAnimeLibrary = async () => [
|
||||
{ ...libraryItem(42), totalActiveMs: 3600000 },
|
||||
{
|
||||
...libraryItem(null),
|
||||
@@ -164,7 +162,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
|
||||
tmdbType: 'tv',
|
||||
totalActiveMs: 7200000,
|
||||
},
|
||||
]);
|
||||
];
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
@@ -182,7 +180,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
apiClient.getAnimeLibraryGroups = original;
|
||||
apiClient.getAnimeLibrary = original;
|
||||
uninstallDom();
|
||||
}
|
||||
});
|
||||
@@ -190,10 +188,10 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
|
||||
test('Library kind filter separates YouTube channels from anime and updates totals', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
|
||||
};
|
||||
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
|
||||
apiClient.getAnimeLibrary = async () => [
|
||||
{ ...libraryItem(null), totalActiveMs: 60_000 },
|
||||
{
|
||||
...libraryItem(null),
|
||||
@@ -202,7 +200,7 @@ test('Library kind filter separates YouTube channels from anime and updates tota
|
||||
canonicalTitle: 'Language Channel',
|
||||
totalActiveMs: 120_000,
|
||||
},
|
||||
]);
|
||||
];
|
||||
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
} from '../../../../src/shared/media-kind';
|
||||
import { useState, useMemo, useEffect } from 'react';
|
||||
import { useAnimeLibrary } from '../../hooks/useAnimeLibrary';
|
||||
import { groupCardData, groupMatchesSearch } from '../../lib/anime-groups';
|
||||
import { formatDuration } from '../../lib/formatters';
|
||||
import {
|
||||
getLibraryCardSizeStorage,
|
||||
@@ -15,7 +14,6 @@ import {
|
||||
} from '../../lib/library-card-size';
|
||||
import { AnimeCard } from './AnimeCard';
|
||||
import { AnimeDetailView } from './AnimeDetailView';
|
||||
import { AnimeGroupView } from './AnimeGroupView';
|
||||
import { AnimeMergeDialog } from './AnimeMergeDialog';
|
||||
import { DuplicateReviewStrip } from './DuplicateReviewStrip';
|
||||
|
||||
@@ -41,14 +39,7 @@ const SORT_OPTIONS: { key: SortKey; label: string }[] = [
|
||||
{ key: 'episodes', label: 'Episodes' },
|
||||
];
|
||||
|
||||
interface SortableEntry {
|
||||
lastWatchedMs: number;
|
||||
totalActiveMs: number;
|
||||
totalCards: number;
|
||||
episodeCount: number;
|
||||
}
|
||||
|
||||
function sortAnime<T extends SortableEntry>(list: T[], key: SortKey): T[] {
|
||||
function sortAnime(list: ReturnType<typeof useAnimeLibrary>['anime'], key: SortKey) {
|
||||
return [...list].sort((a, b) => {
|
||||
switch (key) {
|
||||
case 'lastWatched':
|
||||
@@ -77,7 +68,6 @@ export function AnimeTab({
|
||||
onOpenEpisodeDetail,
|
||||
}: AnimeTabProps) {
|
||||
const {
|
||||
groups,
|
||||
anime,
|
||||
loading,
|
||||
error,
|
||||
@@ -97,8 +87,6 @@ export function AnimeTab({
|
||||
),
|
||||
);
|
||||
const [selectedAnimeId, setSelectedAnimeId] = useState<number | null>(null);
|
||||
// Franchise card that is open, and stays the back target while one of its parts is open.
|
||||
const [selectedGroupKey, setSelectedGroupKey] = useState<number | null>(null);
|
||||
const [selectionMode, setSelectionMode] = useState(false);
|
||||
const [checkedAnimeIds, setCheckedAnimeIds] = useState<number[]>([]);
|
||||
const [showMergeDialog, setShowMergeDialog] = useState(false);
|
||||
@@ -127,14 +115,11 @@ export function AnimeTab({
|
||||
|
||||
useEffect(() => {
|
||||
if (initialAnimeId != null) {
|
||||
setSelectedGroupKey(null);
|
||||
setSelectedAnimeId(initialAnimeId);
|
||||
onClearInitialAnime?.();
|
||||
}
|
||||
}, [initialAnimeId, onClearInitialAnime]);
|
||||
|
||||
// Merging works on individual entries, so selection mode lists every entry
|
||||
// on its own; browsing lists one card per franchise.
|
||||
const filtered = useMemo(() => {
|
||||
const entries = anime.filter((entry) => mediaKind === 'all' || entry.mediaKind === mediaKind);
|
||||
const base = search.trim()
|
||||
@@ -142,32 +127,8 @@ export function AnimeTab({
|
||||
: entries;
|
||||
return sortAnime(base, sortKey);
|
||||
}, [anime, search, sortKey, mediaKind]);
|
||||
const filteredGroups = useMemo(
|
||||
() =>
|
||||
sortAnime(
|
||||
groups.filter(
|
||||
(group) =>
|
||||
(mediaKind === 'all' || group.mediaKind === mediaKind) &&
|
||||
groupMatchesSearch(group, search),
|
||||
),
|
||||
sortKey,
|
||||
),
|
||||
[groups, search, sortKey, mediaKind],
|
||||
);
|
||||
const shownCount = selectionMode ? filtered.length : filteredGroups.length;
|
||||
|
||||
const totalMs = (selectionMode ? filtered : filteredGroups).reduce(
|
||||
(sum, entry) => sum + entry.totalActiveMs,
|
||||
0,
|
||||
);
|
||||
const selectedGroup = groups.find((group) => group.groupKey === selectedGroupKey) ?? null;
|
||||
// A franchise that no longer has several parts closes, so a later refresh
|
||||
// cannot reopen it on its own. Only loaded results count; while a part is
|
||||
// open, the franchise stays its back target.
|
||||
useEffect(() => {
|
||||
if (loading || selectedGroupKey === null || selectedAnimeId !== null) return;
|
||||
if (!selectedGroup || selectedGroup.parts.length < 2) setSelectedGroupKey(null);
|
||||
}, [loading, selectedGroupKey, selectedAnimeId, selectedGroup]);
|
||||
const totalMs = filtered.reduce((sum, a) => sum + a.totalActiveMs, 0);
|
||||
const checkedEntries = checkedAnimeIds
|
||||
.map((animeId) => anime.find((entry) => entry.animeId === animeId))
|
||||
.filter((entry): entry is (typeof anime)[number] => entry !== undefined);
|
||||
@@ -199,7 +160,6 @@ export function AnimeTab({
|
||||
return (
|
||||
<AnimeDetailView
|
||||
animeId={selectedAnimeId}
|
||||
backLabel={selectedGroup ? `Back to ${selectedGroup.title}` : undefined}
|
||||
onBack={() => setSelectedAnimeId(null)}
|
||||
onNavigateToWord={onNavigateToWord}
|
||||
onOpenEpisodeDetail={
|
||||
@@ -210,17 +170,6 @@ export function AnimeTab({
|
||||
onAnimeDeleted={reload}
|
||||
onProviderRelinked={reload}
|
||||
onEpisodeMoved={reload}
|
||||
onGroupChanged={reload}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedGroup && selectedGroup.parts.length > 1) {
|
||||
return (
|
||||
<AnimeGroupView
|
||||
group={selectedGroup}
|
||||
onBack={() => setSelectedGroupKey(null)}
|
||||
onOpenPart={setSelectedAnimeId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -301,12 +250,12 @@ export function AnimeTab({
|
||||
{selectionMode ? 'Cancel' : 'Select'}
|
||||
</button>
|
||||
<div className="text-xs text-ctp-overlay2 shrink-0">
|
||||
{shownCount}{' '}
|
||||
{filtered.length}{' '}
|
||||
{mediaKind === 'youtube'
|
||||
? shownCount === 1
|
||||
? filtered.length === 1
|
||||
? 'channel'
|
||||
: 'channels'
|
||||
: shownCount === 1
|
||||
: filtered.length === 1
|
||||
? 'title'
|
||||
: 'titles'}{' '}
|
||||
· {formatDuration(totalMs)}
|
||||
@@ -349,30 +298,18 @@ export function AnimeTab({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{shownCount === 0 ? (
|
||||
{filtered.length === 0 ? (
|
||||
<div className="text-sm text-ctp-overlay2 p-4">No titles found</div>
|
||||
) : selectionMode ? (
|
||||
) : (
|
||||
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
|
||||
{filtered.map((item) => (
|
||||
<AnimeCard
|
||||
key={item.animeId}
|
||||
anime={item}
|
||||
selectable
|
||||
selectable={selectionMode}
|
||||
selected={checkedAnimeIds.includes(item.animeId)}
|
||||
onClick={() => toggleChecked(item.animeId)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
|
||||
{filteredGroups.map((group) => (
|
||||
<AnimeCard
|
||||
key={group.groupKey}
|
||||
anime={groupCardData(group)}
|
||||
onClick={() =>
|
||||
group.parts.length > 1
|
||||
? setSelectedGroupKey(group.groupKey)
|
||||
: setSelectedAnimeId(group.parts[0]!.animeId)
|
||||
selectionMode ? toggleChecked(item.animeId) : setSelectedAnimeId(item.animeId)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -12,8 +12,6 @@ interface LibraryEntryPickerProps {
|
||||
excludeAnimeIds?: number[];
|
||||
/** When set, only entries of this kind are offered. */
|
||||
mediaKind?: MediaKind;
|
||||
/** Further narrows the entries offered. */
|
||||
filter?: (entry: AnimeLibraryItem) => boolean;
|
||||
initialQuery?: string;
|
||||
busyAnimeId?: number | null;
|
||||
error?: string | null;
|
||||
@@ -25,7 +23,6 @@ export function LibraryEntryPicker({
|
||||
heading,
|
||||
excludeAnimeIds = [],
|
||||
mediaKind,
|
||||
filter,
|
||||
initialQuery = '',
|
||||
busyAnimeId = null,
|
||||
error = null,
|
||||
@@ -77,10 +74,9 @@ export function LibraryEntryPicker({
|
||||
return (entries ?? [])
|
||||
.filter((entry) => !excluded.has(entry.animeId))
|
||||
.filter((entry) => mediaKind === undefined || shareTitleNamespace(entry.mediaKind, mediaKind))
|
||||
.filter((entry) => filter === undefined || filter(entry))
|
||||
.filter((entry) => !term || entry.canonicalTitle.toLowerCase().includes(term))
|
||||
.sort((a, b) => b.lastWatchedMs - a.lastWatchedMs);
|
||||
}, [entries, excluded, mediaKind, filter, query]);
|
||||
}, [entries, excluded, mediaKind, query]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
import { useCallback, useMemo, useState, useEffect, useRef } from 'react';
|
||||
import { useCallback, useState, useEffect, useRef } from 'react';
|
||||
import { getStatsClient } from './useStatsApi';
|
||||
import type { AnimeLibraryGroup, StatsAnimeMergeRecommendation } from '../types/stats';
|
||||
import type { AnimeLibraryItem, StatsAnimeMergeRecommendation } from '../types/stats';
|
||||
|
||||
const BACKGROUND_REFRESH_MS = 30_000;
|
||||
|
||||
/**
|
||||
* The library as franchise cards (`groups`) plus every entry on its own
|
||||
* (`anime`), which merging and duplicate review work on.
|
||||
*/
|
||||
export function useAnimeLibrary() {
|
||||
const [groups, setGroups] = useState<AnimeLibraryGroup[]>([]);
|
||||
const anime = useMemo(() => groups.flatMap((group) => group.parts), [groups]);
|
||||
const [anime, setAnime] = useState<AnimeLibraryItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [recommendations, setRecommendations] = useState<StatsAnimeMergeRecommendation[]>([]);
|
||||
@@ -34,11 +29,11 @@ export function useAnimeLibrary() {
|
||||
let cancelled = false;
|
||||
const client = getStatsClient();
|
||||
client
|
||||
.getAnimeLibraryGroups()
|
||||
.getAnimeLibrary()
|
||||
.then((data) => {
|
||||
if (!cancelled) {
|
||||
hasLoadedRef.current = true;
|
||||
setGroups(data);
|
||||
setAnime(data);
|
||||
setError(null);
|
||||
}
|
||||
})
|
||||
@@ -108,7 +103,6 @@ export function useAnimeLibrary() {
|
||||
}, []);
|
||||
|
||||
return {
|
||||
groups,
|
||||
anime,
|
||||
loading,
|
||||
error,
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import type { AnimeLibraryGroup, AnimeLibraryItem } from '../types/stats';
|
||||
|
||||
/** What a library card shows; a single entry or a whole franchise. */
|
||||
export type AnimeCardData = Pick<
|
||||
AnimeLibraryItem,
|
||||
| 'animeId'
|
||||
| 'canonicalTitle'
|
||||
| 'anilistId'
|
||||
| 'tmdbId'
|
||||
| 'mediaKind'
|
||||
| 'episodeCount'
|
||||
| 'totalActiveMs'
|
||||
| 'totalCards'
|
||||
> & {
|
||||
/** Set for franchise cards with more than one part. */
|
||||
partCount?: number;
|
||||
};
|
||||
|
||||
/** A one-part card is exactly that entry; a franchise card shows the first part's cover. */
|
||||
export function groupCardData(group: AnimeLibraryGroup): AnimeCardData {
|
||||
const cover = group.parts.find((part) => part.animeId === group.coverAnimeId) ?? group.parts[0]!;
|
||||
if (group.parts.length === 1) return cover;
|
||||
return {
|
||||
animeId: cover.animeId,
|
||||
canonicalTitle: group.title,
|
||||
anilistId: cover.anilistId,
|
||||
tmdbId: cover.tmdbId,
|
||||
mediaKind: group.mediaKind,
|
||||
episodeCount: group.episodeCount,
|
||||
totalActiveMs: group.totalActiveMs,
|
||||
totalCards: group.totalCards,
|
||||
partCount: group.parts.length,
|
||||
};
|
||||
}
|
||||
|
||||
/** Matches the franchise name or any part's title, so "Undead King" finds Overlord. */
|
||||
export function groupMatchesSearch(group: AnimeLibraryGroup, search: string): boolean {
|
||||
const term = search.trim().toLowerCase();
|
||||
if (!term) return true;
|
||||
return (
|
||||
group.title.toLowerCase().includes(term) ||
|
||||
group.parts.some((part) => part.canonicalTitle.toLowerCase().includes(term))
|
||||
);
|
||||
}
|
||||
|
||||
const FORMAT_LABELS: Record<string, string> = {
|
||||
TV: 'TV',
|
||||
TV_SHORT: 'TV Short',
|
||||
MOVIE: 'Movie',
|
||||
SPECIAL: 'Special',
|
||||
OVA: 'OVA',
|
||||
ONA: 'ONA',
|
||||
MUSIC: 'Music',
|
||||
};
|
||||
|
||||
/** "Movie · 2017" from AniList's format and yyyymmdd start date; null when neither is known. */
|
||||
export function describeAnimePart(format: string | null, startDate: number | null): string | null {
|
||||
const label = format ? (FORMAT_LABELS[format] ?? format) : null;
|
||||
const year = startDate ? String(Math.floor(startDate / 10_000)) : null;
|
||||
const parts = [label, year].filter((value): value is string => value !== null);
|
||||
return parts.length > 0 ? parts.join(' · ') : null;
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
StatsExcludedWord,
|
||||
StatsCoverImagesData,
|
||||
StatsAnilistAssignment,
|
||||
StatsAnimeGroupOverrideRequest,
|
||||
StatsAnkiNotesInfoRequest,
|
||||
StatsCoverImagesRequest,
|
||||
StatsDeleteSessionsRequest,
|
||||
@@ -164,7 +163,6 @@ export const apiClient = {
|
||||
getMediaLibrary: () => fetchJson('mediaLibrary', '/api/stats/media'),
|
||||
getMediaDetail: (videoId: number) => fetchJson('mediaDetail', `/api/stats/media/${videoId}`),
|
||||
getAnimeLibrary: () => fetchJson('animeLibrary', '/api/stats/anime'),
|
||||
getAnimeLibraryGroups: () => fetchJson('animeLibraryGroups', '/api/stats/anime/groups'),
|
||||
getAnimeMergeRecommendations: () =>
|
||||
fetchJson('animeMergeRecommendations', '/api/stats/anime/merge-recommendations'),
|
||||
getAnimeDetail: (animeId: number) => fetchJson('animeDetail', `/api/stats/anime/${animeId}`),
|
||||
@@ -270,16 +268,6 @@ export const apiClient = {
|
||||
});
|
||||
return res.json() as Promise<StatsMoveVideoResponse>;
|
||||
},
|
||||
setAnimeGroupOverride: async (
|
||||
animeId: number,
|
||||
request: StatsAnimeGroupOverrideRequest,
|
||||
): Promise<void> => {
|
||||
await fetchResponse(`/api/stats/anime/${animeId}/group`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request satisfies StatsAnimeGroupOverrideRequest),
|
||||
});
|
||||
},
|
||||
dismissAnimeMergeRecommendation: async (recommendationId: number): Promise<void> => {
|
||||
await fetchResponse(`/api/stats/anime/merge-recommendations/${recommendationId}`, {
|
||||
method: 'DELETE',
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { apiClient } from '../lib/api-client';
|
||||
import type { AnimeLibraryGroup, AnimeLibraryItem } from '../types/stats';
|
||||
|
||||
/** Wraps each entry in a one-part card, as the server does for entries without AniList relations. */
|
||||
export function asSingleGroups(items: AnimeLibraryItem[]): AnimeLibraryGroup[] {
|
||||
return items.map((item) => ({
|
||||
groupKey: -item.animeId,
|
||||
title: item.canonicalTitle,
|
||||
mediaKind: item.mediaKind,
|
||||
coverAnimeId: item.animeId,
|
||||
totalSessions: item.totalSessions,
|
||||
totalActiveMs: item.totalActiveMs,
|
||||
totalCards: item.totalCards,
|
||||
totalTokensSeen: item.totalTokensSeen,
|
||||
episodeCount: item.episodeCount,
|
||||
lastWatchedMs: item.lastWatchedMs,
|
||||
parts: [{ ...item, format: null, startDate: null }],
|
||||
}));
|
||||
}
|
||||
|
||||
/** A `getAnimeLibraryGroups` mock serving `load()`'s entries as one-part cards. */
|
||||
export function singleGroupLibrary(
|
||||
load: () => Promise<AnimeLibraryItem[]>,
|
||||
): typeof apiClient.getAnimeLibraryGroups {
|
||||
return async () => asSingleGroups(await load());
|
||||
}
|
||||
Reference in new issue
Block a user