mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-22 16:46:10 -08:00
Compare commits
4
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,7 +0,0 @@
|
||||
type: added
|
||||
area: aniskip
|
||||
|
||||
- Added outro skipping: the AniSkip key now also skips the ending, with its own prompt and chapter markers.
|
||||
- Intro and outro detection now reads the file's own chapters first (named OP/ED chapters, or song-length chapters near the start and end) and only asks AniSkip for what is missing, so it also works for Jellyfin and other streams.
|
||||
- AniSkip lookups now send the episode length so the times match your TV or Blu-ray cut.
|
||||
- Fixed AniSkip rate limits, server errors, and network failures being remembered as "no intro" until restart; they are now retried on the next load.
|
||||
@@ -1080,8 +1080,8 @@
|
||||
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
|
||||
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
|
||||
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
|
||||
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
|
||||
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
|
||||
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
|
||||
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
|
||||
}, // SubMiner-managed mpv launch and bundled plugin options.
|
||||
|
||||
// ==========================================
|
||||
|
||||
@@ -26,8 +26,8 @@ On Linux, the token is stored with `gnome-libsecret` by default. If your keyring
|
||||
An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then:
|
||||
|
||||
1. Reads the title, season, and episode from the file name and folder. Install [guessit](https://github.com/guessit-io/guessit) for better parsing. A folder named `Season 2` is a strong season hint.
|
||||
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels.
|
||||
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode.
|
||||
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels. Specials, movies, and the second half of a split season ("Part 2", "Cour 2") do not count as seasons, and an entry whose title names the season ("Season 3", "III") wins.
|
||||
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode. AniList lists the second half of a split season as its own entry, so an episode past the first half goes there: episode 15 of a season split 11 + 12 is episode 4 of the second entry.
|
||||
|
||||
If the show is not on your list yet, SubMiner adds it as Watching, but only when the file title exactly matches an AniList title or you pinned the entry with the character dictionary's AniList override. For a looser match, add the show to Planning or Watching yourself. SubMiner never changes entries marked Completed, Paused, Dropped, or Rewatching, and it never lowers your progress.
|
||||
|
||||
@@ -37,7 +37,9 @@ Failed updates are saved and retried in the background, up to 8 times with growi
|
||||
|
||||
If a cover or title in the stats Library is wrong, open the title and use **Change AniList Entry**.
|
||||
|
||||
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary).
|
||||
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary). The override is also the fix when AniList splits a season without marking the second half in any title.
|
||||
|
||||
Library entries matched by older versions keep their match after an update. If one points at the wrong season, use **Change AniList Entry**.
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# AniSkip integration
|
||||
|
||||
SubMiner finds an anime's opening and ending so you can skip either with one key. It reads the file's own chapters first and asks [AniSkip](https://aniskip.com) for anything they lack.
|
||||
SubMiner looks up opening timestamps on [AniSkip](https://aniskip.com) so you can skip an anime's intro with one key.
|
||||
|
||||
## Setup
|
||||
|
||||
@@ -23,24 +23,17 @@ python3 -m pip install --user guessit
|
||||
|
||||
## Usage
|
||||
|
||||
Once a file's duration is known, SubMiner looks for the opening and ending in the file's chapters:
|
||||
When a local file loads, SubMiner reads the title and episode from the file name, finds the show on MyAnimeList, and asks AniSkip for the intro's timestamps. Streams and URLs are skipped.
|
||||
|
||||
- By name: chapters called `Opening`, `OP`, `OP ...` or `オープニング`; and `Ending`, `ED`, `ED ...`, `Outro`, `End Credits`, `Closing Credits`, `エンディング`, or `Credits` in the second half of the episode.
|
||||
- By length, in files with at least three chapters: a 55 to 150 second chapter in the first 30% of the episode (the one closest to 90 seconds) is the opening, and the first one after 70% is the ending.
|
||||
|
||||
If the chapters don't give both, SubMiner reads the title and episode from the file name, finds the show on MyAnimeList, and asks AniSkip for the rest, sending the file's length so the times match your cut (TV or Blu-ray). AniSkip lookups run for local files only; streams such as Jellyfin use their chapters alone.
|
||||
|
||||
For times that came from AniSkip, SubMiner adds `AniSkip Intro Start`/`End` and `AniSkip Outro Start`/`End` chapters. When the intro or outro starts, SubMiner shows "You can skip the intro by pressing TAB" (or "the outro", with your key) for 3 seconds. Press the key any time during either one to jump to its end. Nothing is skipped automatically.
|
||||
If AniSkip has an intro, SubMiner adds `AniSkip Intro Start` and `AniSkip Intro End` chapters. When the intro starts, mpv shows "You can skip by pressing TAB" (with your key) for 3 seconds. Press the key any time during the intro to jump to its end.
|
||||
|
||||
With a custom key other than `TAB` or `y-k`, `y-k` also skips.
|
||||
|
||||
A failed lookup (AniSkip or MyAnimeList down, rate limited, or offline) is retried the next time the file loads. A show or episode AniSkip has no times for is remembered until SubMiner restarts.
|
||||
|
||||
## Triggering from mpv
|
||||
|
||||
| Command | What it does |
|
||||
| ----------------------------------------- | ------------------------------------------------------- |
|
||||
| `script-message subminer-skip-intro` | Skip to the end of the intro or outro that is playing |
|
||||
| `script-message subminer-skip-intro` | Skip to the end of the intro |
|
||||
| `script-message subminer-aniskip-refresh` | Look up the current file again, ignoring cached results |
|
||||
|
||||
Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show.
|
||||
@@ -46,7 +46,7 @@ A few ownership notes that are hard to guess from file names:
|
||||
|
||||
- mpv access is split into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and property modules under `src/core/services/`.
|
||||
- The renderer keeps `renderer.ts` to orchestration. Keyboard, mouse, and gamepad input live in `renderer/handlers/`, and each modal flow has its own file in `renderer/modals/`.
|
||||
- Intro/outro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which reads the file's chapters, asks AniSkip for what they lack, and drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it.
|
||||
- AniSkip intro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it.
|
||||
|
||||
## Component diagram
|
||||
|
||||
|
||||
@@ -634,8 +634,8 @@ Settings for mpv instances that SubMiner starts, and for the bundled mpv plugin.
|
||||
| `mpv.autoStartSubMiner` | `true` | Start SubMiner in the background when mpv loads a file |
|
||||
| `mpv.pauseUntilOverlayReady` | `true` | Keep mpv paused until subtitles are ready, up to 30 seconds |
|
||||
| `mpv.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path |
|
||||
| `mpv.aniskipEnabled` | `true` | Detect intros and outros (file chapters, then AniSkip) and show a skip prompt |
|
||||
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro or outro while it plays |
|
||||
| `mpv.aniskipEnabled` | `true` | Detect intros with AniSkip and show a skip prompt |
|
||||
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro while the prompt is shown |
|
||||
|
||||
### YouTube playback settings
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ Most plugin keys are chords: press `y`, then the second key.
|
||||
|
||||
`v` replaces mpv's own subtitle visibility toggle.
|
||||
|
||||
The intro/outro skip key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration).
|
||||
The skip-intro key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration).
|
||||
|
||||
The `y-y` menu lists Start overlay, Stop overlay, Toggle overlay, Open options, Restart overlay, Check status, and Stats. Press an item's number to run it. Stats only reminds you to press `` ` `` in the overlay.
|
||||
|
||||
|
||||
@@ -1080,8 +1080,8 @@
|
||||
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
|
||||
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
|
||||
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
|
||||
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
|
||||
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
|
||||
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
|
||||
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
|
||||
}, // SubMiner-managed mpv launch and bundled plugin options.
|
||||
|
||||
// ==========================================
|
||||
|
||||
@@ -229,7 +229,7 @@ script-message subminer-start backend=hyprland socket=/custom/path texthooker=no
|
||||
|
||||
The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts.
|
||||
|
||||
While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro or outro that is playing, and `subminer-aniskip-refresh` reloads intro and outro data, for example after your script changes title or episode metadata.
|
||||
While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro, and `subminer-aniskip-refresh` reloads intro data, for example after your script changes title or episode metadata.
|
||||
|
||||
## Related pages
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ Read when: you need to find the owner module for a behavior or test surface
|
||||
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
|
||||
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
|
||||
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
|
||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`
|
||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`. Every consumer maps a parsed title + season to an AniList entry through `anilist/season-resolver.ts` (sequel-chain walk; see its header for what counts as a season). Changing what it returns needs a `MEDIA_RESOLUTION_CACHE_VERSION` bump in `character-dictionary-runtime/cache.ts`, or old matches keep being served from `anilist-resolution-cache.json`.
|
||||
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
|
||||
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
|
||||
assembled by `src/main/assemblies/jellyfin.ts`
|
||||
|
||||
@@ -616,14 +616,13 @@ export function buildIntegrationConfigOptionRegistry(
|
||||
path: 'mpv.aniskipEnabled',
|
||||
kind: 'boolean',
|
||||
defaultValue: defaultConfig.mpv.aniskipEnabled,
|
||||
description:
|
||||
'Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key.',
|
||||
description: 'Enable AniSkip intro detection, chapter markers, and the skip-intro key.',
|
||||
},
|
||||
{
|
||||
path: 'mpv.aniskipButtonKey',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.mpv.aniskipButtonKey,
|
||||
description: 'mpv key that skips the detected intro or outro while it plays.',
|
||||
description: 'mpv key used to skip the detected intro while the skip prompt is visible.',
|
||||
},
|
||||
{
|
||||
path: 'jellyfin.enabled',
|
||||
|
||||
@@ -0,0 +1,651 @@
|
||||
// Captured from live AniList responses on 2026-11-22, trimmed to the fields the resolver reads.
|
||||
// Each chain is in SEQUEL order: entry i's only SEQUEL is entry i + 1.
|
||||
import type { AnilistSeasonMedia } from '../season-resolver';
|
||||
|
||||
/** Mushoku Tensei: S1 -> "Cour 2" -> S2 -> "Season 2 Part 2" -> S3 -> S3 Part 2. */
|
||||
export const MUSHOKU_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 108465,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'Jobless Reincarnation: I Will Seriously Try If I Go To Another World',
|
||||
'无职转生 ~到了异世界就拿出真本事~',
|
||||
'เกิดชาตินี้พี่ต้องเทพ',
|
||||
'Thất nghiệp chuyển sinh',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
native: '無職転生 ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 127720,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: ['Mushoku Tensei: Jobless Reincarnation Part 2', 'เกิดชาตินี้พี่ต้องเทพ พาร์ท 2'],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu Part 2',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Cour 2',
|
||||
native: '無職転生 ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 146065,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season',
|
||||
'Mushoku Tensei II: Jobless Reincarnation',
|
||||
'Mushoku Tensei II: Reencarnación desde cero',
|
||||
'无职转生~到了异世界就拿出真本事~第2季',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 2',
|
||||
native: '無職転生Ⅱ ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 166873,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: [
|
||||
'Mushoku Tensei: Jobless Reincarnation Season 2 Cour 2',
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2 ครึ่งหลัง',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season Part 2',
|
||||
'Mushoku Tensei II: Jobless Reincarnation Part 2',
|
||||
'Mushoku Tensei II: Reencarnación desde cero',
|
||||
'无职转生~到了异世界就拿出真本事~第2季',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu Part 2',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 2 Part 2',
|
||||
native: '無職転生Ⅱ ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 178789,
|
||||
episodes: 14,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'無職転生 ~異世界行ったら本気だす~ 第3期',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 3rd Season',
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 3',
|
||||
native: '無職転生Ⅲ ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 217434,
|
||||
episodes: null,
|
||||
format: 'TV',
|
||||
seasonYear: 2027,
|
||||
synonyms: ['Mushoku Tensei: Jobless Reincarnation Season 3 Part 2'],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu Part 2',
|
||||
english: null,
|
||||
native: '無職転生Ⅲ ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Re:ZERO: S1 -> S2 -> "Season 2 Part 2" -> S3 -> S4 -> S5 (unaired). */
|
||||
export const REZERO_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 21355,
|
||||
episodes: 25,
|
||||
format: 'TV',
|
||||
seasonYear: 2016,
|
||||
synonyms: [
|
||||
'Re: Life in a different world from zero',
|
||||
'ReZero',
|
||||
'Re Zero',
|
||||
'Re:从零开始的异世界生活',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก',
|
||||
'Re:Zero — жизнь с нуля в другом мире',
|
||||
'Re:Zero Empezar de cero en un mundo diferente',
|
||||
'Re:Zero – Bắt đầu lại ở thế giới khác',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu',
|
||||
english: 'Re:ZERO -Starting Life in Another World-',
|
||||
native: 'Re:ゼロから始める異世界生活',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 108632,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
synonyms: [
|
||||
'Re:Zero kara Hajimeru Isekai Seikatsu (2020)',
|
||||
'Re: 제로부터 시작하는 이세계 생활 2기',
|
||||
'Re:从零开始的异世界生活第二季(上半)',
|
||||
'Re:从零开始的异世界生活 2 上半',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2',
|
||||
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 2',
|
||||
native: 'Re:ゼロから始める異世界生活 2nd Season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 119661,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'Re:Zero kara Hajimeru Isekai Seikatsu (2021)',
|
||||
'Re: 제로부터 시작하는 이세계 생활 2기 파트 2',
|
||||
'Re:从零开始的异世界生活第二季(下半)',
|
||||
'Re:从零开始的异世界生活 2 下半',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2 พาร์ท 2',
|
||||
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season Part 2',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 2 Part 2',
|
||||
native: 'Re:ゼロから始める異世界生活 2nd Season Part 2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 163134,
|
||||
episodes: 16,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: ['Re:ZERO – Жизнь с нуля в альтернативном мире 3'],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 3rd Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 3',
|
||||
native: 'Re:ゼロから始める異世界生活 3rd season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 189046,
|
||||
episodes: 19,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'Re:ZERO รีเซทชีวิต ฝ่าวิกฤตต่างโลก ซีซั่น 4',
|
||||
'Re:ZERO – Жизнь с нуля в альтернативном мире 4',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 4th Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 4',
|
||||
native: 'Re:ゼロから始める異世界生活 4th season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 219904,
|
||||
episodes: null,
|
||||
format: 'TV',
|
||||
seasonYear: null,
|
||||
synonyms: ['Re:ZERO -Starting Life in Another World- Season 5'],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 5th Season',
|
||||
english: null,
|
||||
native: 'Re:ゼロから始める異世界生活 5th season',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Dr. STONE: STONE WARS reaches NEW WORLD through a one-episode SPECIAL. */
|
||||
export const DR_STONE_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 105333,
|
||||
episodes: 24,
|
||||
format: 'TV',
|
||||
seasonYear: 2019,
|
||||
synonyms: [
|
||||
'Dcst',
|
||||
'石纪元',
|
||||
'ドクターストーン',
|
||||
'ดร.สโตน เจ้าแห่งวิทยาศาสตร์กู้คืนอารยธรรมโลก',
|
||||
'Доктор Стоун',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE',
|
||||
english: 'Dr. STONE',
|
||||
native: 'Dr.STONE',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 113936,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'ドクターストーン STONE WARS',
|
||||
'Dr.STONE第2期',
|
||||
'Dr. STONE 2',
|
||||
'닥터 스톤 STONE WARS',
|
||||
'石纪元第二季',
|
||||
'DR.STONE ภาค 2',
|
||||
'Доктор Стоун: Каменные войны',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: STONE WARS',
|
||||
english: 'Dr. STONE: STONE WARS',
|
||||
native: 'Dr.STONE STONE WARS',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 142876,
|
||||
episodes: 1,
|
||||
format: 'SPECIAL',
|
||||
seasonYear: 2022,
|
||||
synonyms: ['Dr. STONE: Ryusui', 'Доктор Стоун: Рюсуй'],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: Ryuusui',
|
||||
english: 'Dr. STONE Special Episode – RYUSUI',
|
||||
native: 'Dr.STONE 龍水',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131518,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'石纪元第三季',
|
||||
'Dr.STONE Season 3',
|
||||
'DR.STONE ภาค 3',
|
||||
'Dr.STONE 第3期',
|
||||
'Dr. STONE 新石紀(第三季)',
|
||||
'Доктор Стоун: Новый Свет',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: NEW WORLD',
|
||||
english: 'Dr. STONE New World',
|
||||
native: 'Dr.STONE NEW WORLD',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 162670,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'石纪元第三季',
|
||||
'Dr.STONE Season 3 Part 2',
|
||||
'DR.STONE ภาค 3',
|
||||
'Dr.STONE 第3期 第2クール',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: NEW WORLD Part 2',
|
||||
english: 'Dr. STONE New World Part 2',
|
||||
native: 'Dr.STONE NEW WORLD 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 172019,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2025,
|
||||
synonyms: ['Dr.STONE Season 4', 'Dr.STONE 第4期', 'ドクターストーン'],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: SCIENCE FUTURE',
|
||||
english: 'Dr. STONE SCIENCE FUTURE',
|
||||
native: 'Dr.STONE SCIENCE FUTURE',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Bleach TYBW: cours named after arcs; "Part N" only in synonyms, spelled "Thousand Year". */
|
||||
export const BLEACH_TYBW_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 116674,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
synonyms: [
|
||||
'بليتش: حرب الألف سنة الدموية',
|
||||
'Bleach: La guerre sanglante de mille ans',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen',
|
||||
english: 'BLEACH: Thousand-Year Blood War',
|
||||
native: 'BLEACH 千年血戦篇',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 159322,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand Year Blood War Part 2',
|
||||
'BLEACH 千年血戦篇 第2クール',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Ketsubetsu-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Separation',
|
||||
native: 'BLEACH 千年血戦篇-訣別譚-',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 169755,
|
||||
episodes: 14,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand Year Blood War Part 3',
|
||||
'BLEACH 千年血戦篇 第3クール',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Soukoku-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Conflict',
|
||||
native: 'BLEACH 千年血戦篇-相剋譚-',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 185874,
|
||||
episodes: 10,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand-Year Blood War Part 4',
|
||||
'BLEACH 千年血戦篇 第4クール',
|
||||
'BLEACH: Thousand-Year Blood War The Final Season',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Kashin-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Calamity',
|
||||
native: 'BLEACH 千年血戦篇-禍進譚-',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Attack on Titan: season 3 carries the Thai synonym "... ภาค 3 Part 1"; the chain ends in SPECIALs. */
|
||||
export const AOT_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 16498,
|
||||
episodes: 25,
|
||||
format: 'TV',
|
||||
seasonYear: 2013,
|
||||
synonyms: [
|
||||
'SnK',
|
||||
'AoT',
|
||||
'Ataque a los Titanes',
|
||||
'Ataque dos Titãs',
|
||||
"L'Attacco dei Giganti",
|
||||
'מתקפת הטיטאנים',
|
||||
'进击的巨人',
|
||||
'L’Attaque des Titans',
|
||||
'الهجوم على العمالقة',
|
||||
'ผ่าพิภพไททัน',
|
||||
'حمله به تایتان',
|
||||
'Ataque de Titãs',
|
||||
'Atak Tytanów',
|
||||
'Атака титанов',
|
||||
'Đại Chiến Titan',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin',
|
||||
english: 'Attack on Titan',
|
||||
native: '進撃の巨人',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 20958,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2017,
|
||||
synonyms: [
|
||||
'SnK 2',
|
||||
'AoT 2',
|
||||
'+מתקפת הטיטאנים עונה 2',
|
||||
"L'Attacco dei Giganti 2",
|
||||
"L'Attacco dei Giganti - Seconda Stagione",
|
||||
'ผ่าพิภพไททัน ภาค 2',
|
||||
'حمله به تایتان فصل 2',
|
||||
'Атака титанов 2',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 2',
|
||||
english: 'Attack on Titan Season 2',
|
||||
native: '進撃の巨人 Season2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 99147,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: [
|
||||
'SnK 3',
|
||||
'AoT 3',
|
||||
'מתקפת הטיטאנים עונה 3',
|
||||
"L'Attacco dei Giganti 3",
|
||||
"L'Attacco dei Giganti - Terza Stagione",
|
||||
'ผ่าพิภพไททัน ภาค 3',
|
||||
'حمله به تایتان فصل 3',
|
||||
'ผ่าพิภพไททัน ภาค 3 Part 1',
|
||||
'Атака титанов 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 3',
|
||||
english: 'Attack on Titan Season 3',
|
||||
native: '進撃の巨人 Season3',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 104578,
|
||||
episodes: 10,
|
||||
format: 'TV',
|
||||
seasonYear: 2019,
|
||||
synonyms: [
|
||||
'SnK 3',
|
||||
'AoT 3',
|
||||
'Shingeki no Kyojin Season 3 (2019)',
|
||||
"L'Attaco dei Giganti 3 Parte 2",
|
||||
"L'Attacco dei Giganti - Terza Stagione Parte 2",
|
||||
'מתקפת הטיטאנים עונה 3 חלק 2',
|
||||
"L'Attaque des Titans Saison 3 Partie 2 ",
|
||||
'ผ่าพิภพไททัน ภาค 3 Part 2',
|
||||
'ผ่าพิภพไททัน ภาค 3 พาร์ท 2',
|
||||
'حمله به تایتان فصل 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 3 Part 2',
|
||||
english: 'Attack on Titan Season 3 Part 2',
|
||||
native: '進撃の巨人 Season3 Part.2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 110277,
|
||||
episodes: 16,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
'Shingeki no Kyojin 4',
|
||||
'進撃の巨人4',
|
||||
'Attack on Titan Season 4',
|
||||
'진격의 거인 더 파이널 시즌',
|
||||
'מתקפת הטיטאנים העונה האחרונה',
|
||||
"L'Attaque des Titans Saison Finale",
|
||||
"L'Attacco dei Giganti 4",
|
||||
"L'Attacco dei Giganti - La Stagione Finale",
|
||||
'حمله به تایتان فصل 4 ',
|
||||
' ผ่าพิภพไททัน ไฟนอล ซีซั่น',
|
||||
'ผ่าพิภพไททัน Final Season',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
'هجوم العملاقة الجزء الأخير',
|
||||
'Атака Титанов: Финал',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season',
|
||||
english: 'Attack on Titan Final Season',
|
||||
native: '進撃の巨人 The Final Season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131681,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
synonyms: [
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
"L'attaque des titans Saison Finale Partie 2",
|
||||
'Shingeki no Kyojin: The Final Season (2022)',
|
||||
'اتک عن تایتان',
|
||||
'حمله به غول ها',
|
||||
'حمله به تایتان فصل 4 ',
|
||||
' ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 2',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
"L'Attacco dei Giganti 4 Parte 2",
|
||||
'Атака титанов: Финал. Часть 2',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season Part 2',
|
||||
english: 'Attack on Titan Final Season Part 2',
|
||||
native: '進撃の巨人 The Final Season Part 2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 146984,
|
||||
episodes: 1,
|
||||
format: 'SPECIAL',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'Shingeki no Kyojin: The Final Season Final Edition',
|
||||
'Shingeki no Kyojin: The Final Season Part 3',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
'ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 3',
|
||||
'Attack on Titan Final Season Part 3 Final Arc Part 1',
|
||||
'Attack on Titan The Final Season The Final Part Special',
|
||||
'Attack on Titan The Final Season The Final Part Part 1',
|
||||
'حمله به تایتان فصل آخر قسمت ویژه 1 ',
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season - Kanketsu-hen Zenpen',
|
||||
english: 'Attack on Titan Final Season THE FINAL CHAPTERS Special 1',
|
||||
native: '進撃の巨人 The Final Season完結編 前編',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Overlord: seasons named only by a trailing roman numeral. */
|
||||
export const OVERLORD_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 20832,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2015,
|
||||
synonyms: ['Over Lord', 'โอเวอร์ลอร์ด', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก'],
|
||||
title: {
|
||||
romaji: 'Overlord',
|
||||
english: 'Overlord',
|
||||
native: 'オーバーロード',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 98437,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: ['Over Lord 2', 'โอเวอร์ลอร์ด ภาค 2', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 2'],
|
||||
title: {
|
||||
romaji: 'Overlord II',
|
||||
english: 'Overlord II',
|
||||
native: 'オーバーロードⅡ',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 101474,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: ['Over Lord 3', 'โอเวอร์ลอร์ด ภาค 3', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 3'],
|
||||
title: {
|
||||
romaji: 'Overlord III',
|
||||
english: 'Overlord III',
|
||||
native: 'オーバーロードⅢ',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** JoJo: Golden Wind ends in the synonym "Part 5", Stone Ocean in "Part 6"; both are new seasons. */
|
||||
export const JOJO_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 21450,
|
||||
episodes: 39,
|
||||
format: 'TV',
|
||||
seasonYear: 2016,
|
||||
synonyms: [
|
||||
'JoJo no Kimyou na Bouken Part 4: Diamond wa Kudakenai',
|
||||
"JoJo's Bizarre Adventure Part 4: Diamond is Unbreakable",
|
||||
'مغامرات جوجو العجيبة: الألماس غير قابل للكسر',
|
||||
'Le bizzarre avventure di JoJo: Diamond is Unbreakable',
|
||||
'Невероятные приключения ДжоДжо: Diamond is Unbreakable',
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Diamond wa Kudakenai',
|
||||
english: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
|
||||
native: 'ジョジョの奇妙な冒険 ダイヤモンドは砕けない',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 102883,
|
||||
episodes: 39,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: [
|
||||
"JoJo's Bizarre Adventure Part 5",
|
||||
"JoJo's Bizarre Adventure: Vento Aureo",
|
||||
'Le Bizzarre Avventure Di GioGio: Vento Aureo',
|
||||
'مغامرات جوجو العجيبة: الرياح الذهبية',
|
||||
'Невероятные приключения ДжоДжо: Золотой ветер',
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Ougon no Kaze',
|
||||
english: "JoJo's Bizarre Adventure: Golden Wind",
|
||||
native: 'ジョジョの奇妙な冒険 黄金の風',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131942,
|
||||
episodes: 12,
|
||||
format: 'ONA',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
"JoJo's Bizarre Adventure: Stone Ocean",
|
||||
"JoJo's Bizarre Adventure Part 6",
|
||||
'JoJo no Kimyou na Bouken Part 6',
|
||||
'Le bizzarre avventure di JoJo: Stone Ocean',
|
||||
'โจโจ้ ล่าข้ามศตวรรษ: สโตนโอเชียน ',
|
||||
'โจโจ้ ล่าข้ามศตวรรษ ภาค 6',
|
||||
'مغامرات جوجو العجيبة: محيط الأحجار',
|
||||
"ההרפתקה המוזרה של ג'וג'ו: אוקיינוס האבן",
|
||||
'Невероятные приключения ДжоДжо: Каменный океан ',
|
||||
"Химерні пригоди ДжоДжо: Кам'яний океан",
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Stone Ocean',
|
||||
english: "JoJo's Bizarre Adventure: STONE OCEAN",
|
||||
native: 'ジョジョの奇妙な冒険 ストーンオーシャン',
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -585,6 +585,11 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
|
||||
});
|
||||
}
|
||||
if (call === 3) {
|
||||
// Looks one season past the count for an entry naming season 2; there is none.
|
||||
assert.equal(body.variables?.id, 202);
|
||||
return createJsonResponse({ data: { Media: { relations: { edges: [] } } } });
|
||||
}
|
||||
if (call === 4) {
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
@@ -608,7 +613,68 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
|
||||
assert.deepEqual(searchTerms, ['Demo Show']);
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /Demo Show Sequel/);
|
||||
assert.equal(call, 4);
|
||||
assert.equal(call, 5);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress writes a split-cour episode to the part that airs it', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const saved: Array<Record<string, unknown> | undefined> = [];
|
||||
globalThis.fetch = (async (_input, init) => {
|
||||
const body = JSON.parse(String(init?.body)) as {
|
||||
query: string;
|
||||
variables?: Record<string, unknown>;
|
||||
};
|
||||
if (body.query.includes('Page(')) {
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Page: {
|
||||
media: [{ id: 101, episodes: 11, format: 'TV', title: { english: 'Demo Show' } }],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (body.query.includes('relations')) {
|
||||
assert.equal(body.variables?.id, 101);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Media: {
|
||||
relations: {
|
||||
edges: [
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: {
|
||||
id: 202,
|
||||
type: 'ANIME',
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
title: { english: 'Demo Show Cour 2' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (body.query.includes('SaveMediaListEntry')) {
|
||||
saved.push(body.variables);
|
||||
return createJsonResponse({ data: { SaveMediaListEntry: { progress: 4 } } });
|
||||
}
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
return createJsonResponse({
|
||||
data: { Media: { id: 202, mediaListEntry: { progress: 3, status: 'CURRENT' } } },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
// Episode 15 of an 11 + 12 season is episode 4 of the second cour's entry.
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Demo Show', 15, { season: 1 });
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /Demo Show Cour 2.*episode 4/);
|
||||
assert.deepEqual(saved, [{ mediaId: 202, progress: 4, status: 'CURRENT' }]);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
|
||||
@@ -273,6 +273,9 @@ export async function updateAnilistPostWatchProgress(
|
||||
let mediaId = pinnedMediaId;
|
||||
let resolvedTitle: string | null = null;
|
||||
let resolvedEpisodes: number | null = null;
|
||||
// Episode number within the entry being updated; differs from `episode` only for a
|
||||
// split-cour back half.
|
||||
let progress = episode;
|
||||
// A missing list entry is only created when we trust the match; otherwise a fuzzy
|
||||
// search hit would add an unrelated show to the user's list.
|
||||
let confidentMatch = pinnedMediaId !== null;
|
||||
@@ -312,14 +315,18 @@ export async function updateAnilistPostWatchProgress(
|
||||
};
|
||||
}
|
||||
|
||||
mediaId = resolution.id;
|
||||
resolvedTitle = resolution.title;
|
||||
resolvedEpisodes = resolution.episodes;
|
||||
// A split-cour back half is its own AniList entry with its own episode numbering:
|
||||
// "S1E15" of an 11 + 12 season is progress 4 on the second entry.
|
||||
const target = resolution.episodeEntry ?? resolution;
|
||||
mediaId = target.id;
|
||||
resolvedTitle = target.title;
|
||||
resolvedEpisodes = target.episodes;
|
||||
progress = resolution.episodeEntry?.episode ?? episode;
|
||||
// With no parsed season, an exact match on a season-stripped title ("Show S2" ->
|
||||
// "Show") only certifies the season 1 anchor, not the entry being watched.
|
||||
const seasonMarkerStripped = stripSeasonSuffix(title).trim() !== title.trim();
|
||||
confidentMatch =
|
||||
resolution.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
|
||||
target.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
|
||||
}
|
||||
|
||||
const entryResponse = await anilistGraphQl<AnilistMediaEntryData>(
|
||||
@@ -376,8 +383,8 @@ export async function updateAnilistPostWatchProgress(
|
||||
}
|
||||
|
||||
const currentProgress = entry?.progress ?? 0;
|
||||
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, episode);
|
||||
if (typeof currentProgress === 'number' && currentProgress >= episode && !shouldMarkCompleted) {
|
||||
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, progress);
|
||||
if (typeof currentProgress === 'number' && currentProgress >= progress && !shouldMarkCompleted) {
|
||||
return {
|
||||
status: 'skipped',
|
||||
message: `AniList already at episode ${currentProgress} (${pickedTitle}).`,
|
||||
@@ -396,7 +403,7 @@ export async function updateAnilistPostWatchProgress(
|
||||
`,
|
||||
{
|
||||
mediaId,
|
||||
progress: episode,
|
||||
progress,
|
||||
status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT',
|
||||
},
|
||||
options,
|
||||
@@ -410,15 +417,15 @@ export async function updateAnilistPostWatchProgress(
|
||||
return {
|
||||
status: 'updated',
|
||||
message: shouldMarkCompleted
|
||||
? `AniList added "${pickedTitle}" at episode ${episode} and marked it completed.`
|
||||
: `AniList added "${pickedTitle}" to Watching at episode ${episode}.`,
|
||||
? `AniList added "${pickedTitle}" at episode ${progress} and marked it completed.`
|
||||
: `AniList added "${pickedTitle}" to Watching at episode ${progress}.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'updated',
|
||||
message: shouldMarkCompleted
|
||||
? `AniList updated "${pickedTitle}" to episode ${episode} and marked it completed.`
|
||||
: `AniList updated "${pickedTitle}" to episode ${episode}.`,
|
||||
? `AniList updated "${pickedTitle}" to episode ${progress} and marked it completed.`
|
||||
: `AniList updated "${pickedTitle}" to episode ${progress}.`,
|
||||
};
|
||||
}
|
||||
@@ -4,11 +4,22 @@ import assert from 'node:assert/strict';
|
||||
import {
|
||||
ANILIST_SEASON_RELATIONS_QUERY,
|
||||
ANILIST_SEASON_SEARCH_QUERY,
|
||||
namedSeasons,
|
||||
pickByAirOrder,
|
||||
resolveAnilistSeasonMedia,
|
||||
splitPartMarker,
|
||||
stripSeasonSuffix,
|
||||
type AnilistSeasonMedia,
|
||||
} from './season-resolver';
|
||||
import {
|
||||
AOT_CHAIN,
|
||||
BLEACH_TYBW_CHAIN,
|
||||
DR_STONE_CHAIN,
|
||||
JOJO_CHAIN,
|
||||
MUSHOKU_CHAIN,
|
||||
OVERLORD_CHAIN,
|
||||
REZERO_CHAIN,
|
||||
} from './__fixtures__/anilist-season-chains';
|
||||
|
||||
/** Real AniList payloads for "My Teen Romantic Comedy SNAFU", trimmed to used fields. */
|
||||
const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [
|
||||
@@ -161,7 +172,8 @@ test('resolves season 3 by walking sequel relations', async () => {
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
// Searches the bare title only; "Season 3" returns nothing on AniList.
|
||||
assert.deepEqual(searches, ['My Teen Romantic Comedy SNAFU']);
|
||||
assert.deepEqual(relationLookups, [14813, 20698]);
|
||||
// The last lookup checks one season past the count for an entry naming season 3.
|
||||
assert.deepEqual(relationLookups, [14813, 20698, 108489]);
|
||||
});
|
||||
|
||||
test('season 1 resolves to the anchor without relation lookups', async () => {
|
||||
@@ -215,7 +227,7 @@ test('a sequel resolution whose own title matches the parsed title stays exact',
|
||||
);
|
||||
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
assert.equal(result?.via, 'named-season');
|
||||
assert.equal(result?.exactTitleMatch, true);
|
||||
});
|
||||
|
||||
@@ -325,7 +337,7 @@ test('prefers the TV sequel when a franchise branches into other formats', async
|
||||
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
|
||||
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
assert.equal(result?.via, 'named-season');
|
||||
});
|
||||
|
||||
test('air-order fallback refuses when the anchor is not the earliest entry', () => {
|
||||
@@ -399,3 +411,288 @@ test('air-order fallback declines when a franchise entry has no air year', async
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.via, 'anchor');
|
||||
});
|
||||
|
||||
/** Executor over a fixture chain: search returns the whole chain, entry i's SEQUEL is i + 1. */
|
||||
function createChainExecutor(chain: AnilistSeasonMedia[]) {
|
||||
const relations: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {};
|
||||
chain.forEach((entry, index) => {
|
||||
const next = chain[index + 1];
|
||||
relations[entry.id] = next ? [{ relationType: 'SEQUEL', node: next }] : [];
|
||||
});
|
||||
return createExecutor(chain, relations);
|
||||
}
|
||||
|
||||
async function resolveInChain(
|
||||
chain: AnilistSeasonMedia[],
|
||||
input: { title: string; season?: number | null; episode?: number | null },
|
||||
) {
|
||||
const executor = createChainExecutor(chain);
|
||||
const result = await resolveAnilistSeasonMedia(input, { execute: executor.execute });
|
||||
return { result, relationLookups: executor.relationLookups };
|
||||
}
|
||||
|
||||
test('split-cour back halves do not count as seasons', async () => {
|
||||
const title = 'Mushoku Tensei: Jobless Reincarnation';
|
||||
const s2 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 2, episode: 1 });
|
||||
assert.equal(s2.result?.id, 146065);
|
||||
assert.equal(s2.result?.seasonResolved, true);
|
||||
|
||||
const s3 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 3, episode: 1 });
|
||||
assert.equal(s3.result?.id, 178789);
|
||||
// Four hops for two seasons: "Cour 2" and "Season 2 Part 2" were walked through.
|
||||
assert.deepEqual(s3.relationLookups, [108465, 127720, 146065, 166873]);
|
||||
|
||||
const reZeroS3 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 3 });
|
||||
assert.equal(reZeroS3.result?.id, 163134);
|
||||
const reZeroS4 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 4 });
|
||||
assert.equal(reZeroS4.result?.id, 189046);
|
||||
});
|
||||
|
||||
test('a special in the sequel chain is walked through without counting', async () => {
|
||||
const s3 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 3 });
|
||||
assert.equal(s3.result?.id, 131518);
|
||||
const s4 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 4 });
|
||||
assert.equal(s4.result?.id, 172019);
|
||||
});
|
||||
|
||||
test('season names ignore part and cour numbers, including localized ones', () => {
|
||||
// "Cour 2" carries the Thai synonym "... พาร์ท 2" ("part 2").
|
||||
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[1]!)], []);
|
||||
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[3]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(OVERLORD_CHAIN[1]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(DR_STONE_CHAIN[1]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(AOT_CHAIN[4]!)], [4]);
|
||||
});
|
||||
|
||||
test('an entry naming the requested season beats the hop count', async () => {
|
||||
// The second cour has no marker anywhere, so counting alone would call it season 2.
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show: Arc Two' } },
|
||||
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
|
||||
];
|
||||
const { result } = await resolveInChain(chain, { title: 'Show', season: 2 });
|
||||
assert.equal(result?.id, 3);
|
||||
assert.equal(result?.via, 'named-season');
|
||||
|
||||
const overlord = await resolveInChain(OVERLORD_CHAIN, { title: 'Overlord', season: 2 });
|
||||
assert.equal(overlord.result?.id, 98437);
|
||||
assert.equal(overlord.result?.via, 'named-season');
|
||||
});
|
||||
|
||||
test('a counted entry whose title names another season is not accepted', async () => {
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2021, title: { english: 'Show: Arc Two' } },
|
||||
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
|
||||
];
|
||||
// Counting lands on id 3 for season 3, but it says it is season 2.
|
||||
const { result } = await resolveInChain(chain, { title: 'Show', season: 3 });
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
});
|
||||
|
||||
test('JoJo parts are seasons, not split-cour continuations', async () => {
|
||||
assert.equal(splitPartMarker('JoJo no Kimyou na Bouken Part 5: Ougon no Kaze'), null);
|
||||
assert.deepEqual(splitPartMarker("JoJo's Bizarre Adventure Part 5"), {
|
||||
base: 'jojo s bizarre adventure',
|
||||
part: 5,
|
||||
});
|
||||
// Golden Wind ends in "Part 5" and Stone Ocean in "Part 6": same base, different
|
||||
// parts, so Stone Ocean must still count as the next season.
|
||||
const { result } = await resolveInChain(JOJO_CHAIN, {
|
||||
title: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
|
||||
season: 3,
|
||||
});
|
||||
assert.equal(result?.id, 131942);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
});
|
||||
|
||||
test('Attack on Titan resolves its final season past the season 3 back half', async () => {
|
||||
const { result } = await resolveInChain(AOT_CHAIN, { title: 'Attack on Titan', season: 4 });
|
||||
assert.equal(result?.id, 110277);
|
||||
});
|
||||
|
||||
test('air-order fallback drops back halves but keeps a season spelled "Part 1"', () => {
|
||||
// AoT season 3 carries the synonym "ผ่าพิภพไททัน ภาค 3 Part 1".
|
||||
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 3, AOT_CHAIN)?.id, 99147);
|
||||
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 4, AOT_CHAIN)?.id, 110277);
|
||||
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 3, MUSHOKU_CHAIN)?.id, 178789);
|
||||
// Only three real seasons have aired, so a fourth must not fall out of the list.
|
||||
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 4, MUSHOKU_CHAIN.slice(0, 5)), null);
|
||||
});
|
||||
|
||||
test('a TYBW cour marked only in a differently spelled synonym is not season 2', async () => {
|
||||
const { result } = await resolveInChain(BLEACH_TYBW_CHAIN, {
|
||||
title: 'BLEACH: Thousand-Year Blood War',
|
||||
season: 2,
|
||||
});
|
||||
// Every sequel is a later cour of the same season, so there is no season 2 to find.
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.id, 116674);
|
||||
});
|
||||
|
||||
test('an episode past the season entry lands on the split-cour part that airs it', async () => {
|
||||
const mushoku = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 1,
|
||||
episode: 15,
|
||||
});
|
||||
assert.equal(mushoku.result?.id, 108465);
|
||||
assert.equal(mushoku.result?.episodeEntry?.id, 127720);
|
||||
assert.equal(mushoku.result?.episodeEntry?.episode, 4);
|
||||
|
||||
const mushokuS2 = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 2,
|
||||
episode: 20,
|
||||
});
|
||||
assert.equal(mushokuS2.result?.id, 146065);
|
||||
assert.equal(mushokuS2.result?.episodeEntry?.id, 166873);
|
||||
assert.equal(mushokuS2.result?.episodeEntry?.episode, 7);
|
||||
|
||||
// Three cours of 13 + 13 + 14: episode 28 is the third cour's second.
|
||||
const bleach = await resolveInChain(BLEACH_TYBW_CHAIN, {
|
||||
title: 'BLEACH: Thousand-Year Blood War',
|
||||
episode: 28,
|
||||
});
|
||||
assert.equal(bleach.result?.id, 116674);
|
||||
assert.equal(bleach.result?.episodeEntry?.id, 169755);
|
||||
assert.equal(bleach.result?.episodeEntry?.episode, 2);
|
||||
});
|
||||
|
||||
test('an episode inside the season entry needs no remap or relation lookup', async () => {
|
||||
const { result, relationLookups } = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 1,
|
||||
episode: 5,
|
||||
});
|
||||
assert.equal(result?.id, 108465);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
assert.deepEqual(relationLookups, []);
|
||||
});
|
||||
|
||||
test('an episode past a season with no continuation is not moved into the next season', async () => {
|
||||
const { result } = await resolveInChain(OVERLORD_CHAIN, {
|
||||
title: 'Overlord',
|
||||
season: 1,
|
||||
episode: 20,
|
||||
});
|
||||
assert.equal(result?.id, 20832);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
});
|
||||
|
||||
test('a sequel naming its own season is not a back half, even with a part synonym', async () => {
|
||||
const sequel: AnilistSeasonMedia = {
|
||||
id: 2,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Part Synonym Show Season 2' },
|
||||
synonyms: ['Part Synonym Show Part 2'],
|
||||
};
|
||||
// The anchor names season 1 itself...
|
||||
const named = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Part Synonym Show' },
|
||||
synonyms: ['Part Synonym Show Season 1'],
|
||||
},
|
||||
sequel,
|
||||
],
|
||||
{ title: 'Part Synonym Show', season: 2 },
|
||||
);
|
||||
assert.equal(named.result?.id, 2);
|
||||
// ...or is season 1 because the walk starts there.
|
||||
const unnamed = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Part Synonym Show' },
|
||||
},
|
||||
sequel,
|
||||
],
|
||||
{ title: 'Part Synonym Show', season: 2 },
|
||||
);
|
||||
assert.equal(unnamed.result?.id, 2);
|
||||
});
|
||||
|
||||
test('air order keeps a sequel naming its own season despite a part synonym', () => {
|
||||
const anchor: AnilistSeasonMedia = {
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Air Order Show' },
|
||||
};
|
||||
const sequel: AnilistSeasonMedia = {
|
||||
id: 2,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Air Order Show Season 2' },
|
||||
synonyms: ['Air Order Show Part 2'],
|
||||
};
|
||||
assert.equal(pickByAirOrder(anchor, 2, [anchor, sequel])?.id, 2);
|
||||
});
|
||||
|
||||
test('a season 1 episode past its length does not move to a longer later season', async () => {
|
||||
const { result } = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Long Later Show' },
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
episodes: 24,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Long Later Show Season 2' },
|
||||
},
|
||||
],
|
||||
{ title: 'Long Later Show', season: 1, episode: 20 },
|
||||
);
|
||||
assert.equal(result?.id, 1);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
});
|
||||
|
||||
test('a sequel that repeats its predecessor name is still a new season', async () => {
|
||||
// No part marker, so the identical title must not be read as a continuation.
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Same Name Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Same Name Show' } },
|
||||
];
|
||||
const { result } = await resolveInChain(chain, { title: 'Same Name Show', season: 2 });
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.seasonResolved, true);
|
||||
});
|
||||
|
||||
test('a rate limit mid-walk is surfaced instead of answered from air order', async () => {
|
||||
const { execute } = createChainExecutor(MUSHOKU_CHAIN);
|
||||
let relationCalls = 0;
|
||||
const failing = async <T>(query: string, variables: Record<string, unknown>): Promise<T> => {
|
||||
if (query === ANILIST_SEASON_RELATIONS_QUERY && ++relationCalls === 2) {
|
||||
throw new Error('AniList rate limited (429)');
|
||||
}
|
||||
return execute<T>(query, variables);
|
||||
};
|
||||
// Air order alone would answer season 3 correctly from this search result, but it must
|
||||
// not answer from a franchise picture the failed walk never confirmed.
|
||||
await assert.rejects(
|
||||
resolveAnilistSeasonMedia(
|
||||
{ title: 'Mushoku Tensei: Jobless Reincarnation', season: 3 },
|
||||
{ execute: failing },
|
||||
),
|
||||
/429/,
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1118,8 +1118,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
aniskipEnabled: configService.getConfig().mpv.aniskipEnabled,
|
||||
aniskipButtonKey: configService.getConfig().mpv.aniskipButtonKey,
|
||||
}),
|
||||
resolveMetadataForFile: (mediaPath, episodeLength) =>
|
||||
resolveAniSkipMetadataForFile(mediaPath, { episodeLength }),
|
||||
resolveMetadataForFile: (mediaPath) => resolveAniSkipMetadataForFile(mediaPath),
|
||||
sendMpvCommand: (command) => {
|
||||
appState.mpvClient?.send({ command });
|
||||
},
|
||||
@@ -1164,7 +1163,6 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
});
|
||||
client.on('connection-change', aniSkipRuntime.handleConnectionChange);
|
||||
client.on('media-path-change', aniSkipRuntime.handleMediaPathChange);
|
||||
client.on('duration-change', aniSkipRuntime.handleDurationChange);
|
||||
client.on('time-pos-change', aniSkipRuntime.handleTimePosChange);
|
||||
client.on('client-message', aniSkipRuntime.handleClientMessage);
|
||||
deps.getPluginHost().attachMpvClient(client);
|
||||
|
||||
@@ -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',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { classifyChapterSkipIntervals } from './aniskip-chapters';
|
||||
|
||||
const DURATION = 1440;
|
||||
|
||||
function chapters(...entries: Array<[number, string]>) {
|
||||
return entries.map(([time, title]) => ({ time, title }));
|
||||
}
|
||||
|
||||
test('finds named openings and endings case-insensitively', () => {
|
||||
const result = classifyChapterSkipIntervals(
|
||||
chapters([0, 'Prologue'], [95, 'OPENING'], [185, 'Part A'], [1310, 'Ending'], [1400, 'Next']),
|
||||
DURATION,
|
||||
);
|
||||
assert.deepEqual(result, {
|
||||
intro: { start: 95, end: 185 },
|
||||
outro: { start: 1310, end: 1400 },
|
||||
});
|
||||
});
|
||||
|
||||
test('matches short OP/ED titles but not words that merely start with them', () => {
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Op'], [90, 'Episode'], [1350, 'ED']), DURATION),
|
||||
{ intro: { start: 0, end: 90 }, outro: { start: 1350, end: 1440 } },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(
|
||||
chapters([0, 'OP "Song Title"'], [90, 'Episode'], [1350, 'ED "Song Title"']),
|
||||
DURATION,
|
||||
),
|
||||
{ intro: { start: 0, end: 90 }, outro: { start: 1350, end: 1440 } },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Operation'], [500, 'Editing']), DURATION),
|
||||
{ intro: null, outro: null },
|
||||
);
|
||||
});
|
||||
|
||||
test('recognises Japanese chapter names', () => {
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(
|
||||
chapters([0, 'アバン'], [60, 'オープニング'], [150, '本編'], [1330, 'エンディング']),
|
||||
DURATION,
|
||||
),
|
||||
{ intro: { start: 60, end: 150 }, outro: { start: 1330, end: 1440 } },
|
||||
);
|
||||
});
|
||||
|
||||
test('accepts outro and credits names, with bare "Credits" only in the second half', () => {
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Outro']), DURATION).outro,
|
||||
{ start: 1350, end: 1440 },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Closing Credits']), DURATION)
|
||||
.outro,
|
||||
{ start: 1350, end: 1440 },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Credits'], [90, 'Episode']), DURATION).outro,
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Credits']), DURATION).outro,
|
||||
{ start: 1350, end: 1440 },
|
||||
);
|
||||
});
|
||||
|
||||
test('falls back to song-length heuristics when the file has at least three chapters', () => {
|
||||
const result = classifyChapterSkipIntervals(
|
||||
chapters(
|
||||
[0, 'Chapter 1'],
|
||||
[60, 'Chapter 2'], // 60 s long, in the first 30%
|
||||
[120, 'Chapter 3'], // 88 s long, nearest 90 s
|
||||
[208, 'Chapter 4'],
|
||||
[1100, 'Chapter 5'], // starts after 70% but 230 s long
|
||||
[1330, 'Chapter 6'], // first song-length chapter after 70%
|
||||
[1420, 'Chapter 7'],
|
||||
),
|
||||
DURATION,
|
||||
);
|
||||
assert.deepEqual(result, {
|
||||
intro: { start: 120, end: 208 },
|
||||
outro: { start: 1330, end: 1420 },
|
||||
});
|
||||
});
|
||||
|
||||
test('skips heuristics for files with fewer than three chapters', () => {
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Chapter 1'], [1350, 'Chapter 2']), DURATION),
|
||||
{ intro: null, outro: null },
|
||||
);
|
||||
});
|
||||
|
||||
test("ignores SubMiner's own AniSkip marker chapters", () => {
|
||||
const result = classifyChapterSkipIntervals(
|
||||
chapters(
|
||||
[0, 'Episode'],
|
||||
[10, 'AniSkip Intro Start'],
|
||||
[100, 'AniSkip Intro End'],
|
||||
[1330, 'AniSkip Outro Start'],
|
||||
[1420, 'AniSkip Outro End'],
|
||||
),
|
||||
DURATION,
|
||||
);
|
||||
assert.deepEqual(result, { intro: null, outro: null });
|
||||
});
|
||||
|
||||
test('returns nothing without a usable duration or chapter list', () => {
|
||||
assert.deepEqual(classifyChapterSkipIntervals(chapters([0, 'Opening'], [90, 'A']), 0), {
|
||||
intro: null,
|
||||
outro: null,
|
||||
});
|
||||
assert.deepEqual(classifyChapterSkipIntervals(null, DURATION), { intro: null, outro: null });
|
||||
});
|
||||
@@ -1,124 +0,0 @@
|
||||
/** A skippable time range in seconds. */
|
||||
export interface SkipInterval {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
export interface ChapterSkipIntervals {
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
}
|
||||
|
||||
/** Prefix of the marker chapters SubMiner writes; never treated as the file's own chapters. */
|
||||
export const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
|
||||
|
||||
interface Chapter {
|
||||
title: string;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
const MIN_HEURISTIC_CHAPTERS = 3;
|
||||
const MIN_SONG_SECONDS = 55;
|
||||
const MAX_SONG_SECONDS = 150;
|
||||
const TYPICAL_OPENING_SECONDS = 90;
|
||||
|
||||
function isSongLength(chapter: Chapter): boolean {
|
||||
const length = chapter.end - chapter.start;
|
||||
return length >= MIN_SONG_SECONDS && length <= MAX_SONG_SECONDS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns mpv's `chapter-list` (entries with `time` and `title`) into sorted
|
||||
* chapters with an end time (the next chapter's start, or the duration),
|
||||
* dropping SubMiner's own AniSkip marker chapters.
|
||||
*/
|
||||
function toChapters(chapterList: unknown, duration: number): Chapter[] {
|
||||
if (!Array.isArray(chapterList)) return [];
|
||||
const starts: Array<{ title: string; start: number }> = [];
|
||||
for (const entry of chapterList) {
|
||||
if (typeof entry !== 'object' || entry === null) continue;
|
||||
const { time, title } = entry as { time?: unknown; title?: unknown };
|
||||
if (typeof time !== 'number' || !Number.isFinite(time) || time < 0 || time >= duration) {
|
||||
continue;
|
||||
}
|
||||
const text = typeof title === 'string' ? title : '';
|
||||
if (text.startsWith(ANISKIP_CHAPTER_PREFIX)) continue;
|
||||
starts.push({ title: text, start: time });
|
||||
}
|
||||
starts.sort((a, b) => a.start - b.start);
|
||||
return starts.map((chapter, index) => ({
|
||||
...chapter,
|
||||
end: starts[index + 1]?.start ?? duration,
|
||||
}));
|
||||
}
|
||||
|
||||
function isNamedOpening(chapter: Chapter): boolean {
|
||||
const title = chapter.title.trim().toLowerCase();
|
||||
return (
|
||||
title.includes('opening') ||
|
||||
title === 'op' ||
|
||||
title.startsWith('op ') ||
|
||||
chapter.title.includes('オープニング')
|
||||
);
|
||||
}
|
||||
|
||||
function isNamedEnding(chapter: Chapter, duration: number): boolean {
|
||||
const title = chapter.title.trim().toLowerCase();
|
||||
return (
|
||||
title.includes('ending') ||
|
||||
title === 'ed' ||
|
||||
title === 'outro' ||
|
||||
title === 'end credits' ||
|
||||
title === 'closing credits' ||
|
||||
(title === 'credits' && chapter.start > duration * 0.5) ||
|
||||
title.startsWith('ed ') ||
|
||||
chapter.title.includes('エンディング')
|
||||
);
|
||||
}
|
||||
|
||||
function findOpening(chapters: Chapter[], duration: number): Chapter | null {
|
||||
const named = chapters.find(isNamedOpening);
|
||||
if (named) return named;
|
||||
if (chapters.length < MIN_HEURISTIC_CHAPTERS) return null;
|
||||
let best: Chapter | null = null;
|
||||
for (const chapter of chapters) {
|
||||
if (chapter.start >= duration * 0.3 || !isSongLength(chapter)) continue;
|
||||
const distance = Math.abs(chapter.end - chapter.start - TYPICAL_OPENING_SECONDS);
|
||||
if (!best || distance < Math.abs(best.end - best.start - TYPICAL_OPENING_SECONDS)) {
|
||||
best = chapter;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function findEnding(chapters: Chapter[], duration: number): Chapter | null {
|
||||
const named = chapters.find((chapter) => isNamedEnding(chapter, duration));
|
||||
if (named) return named;
|
||||
if (chapters.length < MIN_HEURISTIC_CHAPTERS) return null;
|
||||
return (
|
||||
chapters.find((chapter) => chapter.start > duration * 0.7 && isSongLength(chapter)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function toInterval(chapter: Chapter | null): SkipInterval | null {
|
||||
return chapter && chapter.end > chapter.start ? { start: chapter.start, end: chapter.end } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the opening and ending in a file's own chapters: by name first
|
||||
* ("Opening", "OP", "ED", "Credits", オープニング, ...), else by length and
|
||||
* position when the file has at least three chapters. Rules follow Telly's
|
||||
* `media.rs` opening()/ending().
|
||||
*/
|
||||
export function classifyChapterSkipIntervals(
|
||||
chapterList: unknown,
|
||||
duration: number,
|
||||
): ChapterSkipIntervals {
|
||||
if (!Number.isFinite(duration) || duration <= 0) return { intro: null, outro: null };
|
||||
const chapters = toChapters(chapterList, duration);
|
||||
return {
|
||||
intro: toInterval(findOpening(chapters, duration)),
|
||||
outro: toInterval(findEnding(chapters, duration)),
|
||||
};
|
||||
}
|
||||
@@ -3,21 +3,17 @@ import assert from 'node:assert/strict';
|
||||
import {
|
||||
inferAniSkipMetadataForFile,
|
||||
parseAniSkipGuessitJson,
|
||||
parseAniSkipPayload,
|
||||
resolveAniSkipMetadataForFile,
|
||||
} from './aniskip-metadata';
|
||||
|
||||
const LOOKUP = { episodeLength: 1440 };
|
||||
|
||||
function makeMockResponse(payload: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
function makeMockResponse(payload: unknown): Response {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => payload,
|
||||
} as Response;
|
||||
}
|
||||
|
||||
const MAL_MY_SHOW = { categories: [{ items: [{ id: '1234', name: 'My Show' }] }] };
|
||||
|
||||
function normalizeFetchInput(input: string | URL | Request): string {
|
||||
if (typeof input === 'string') return input;
|
||||
if (input instanceof URL) return input.toString();
|
||||
@@ -50,8 +46,8 @@ test('parseAniSkipGuessitJson extracts title season and episode', () => {
|
||||
episode: 7,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
});
|
||||
});
|
||||
@@ -72,8 +68,8 @@ test('parseAniSkipGuessitJson prefers series over episode title', () => {
|
||||
episode: 10,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
});
|
||||
});
|
||||
@@ -115,58 +111,10 @@ test('inferAniSkipMetadataForFile handles release-group filename with trailing q
|
||||
assert.equal(parsed.source, 'fallback');
|
||||
});
|
||||
|
||||
test('parseAniSkipPayload reads op and ed from a v2 response', () => {
|
||||
// Shape captured from api.aniskip.com/v2 on 2026-11-22.
|
||||
const parsed = parseAniSkipPayload({
|
||||
found: true,
|
||||
results: [
|
||||
{
|
||||
interval: { startTime: 310.571, endTime: 400.571 },
|
||||
skipType: 'op',
|
||||
skipId: 'd4f34b6d-0547-4438-ac93-b25b577eddd5',
|
||||
episodeLength: 1443.984,
|
||||
},
|
||||
{
|
||||
interval: { startTime: 1396.006, endTime: 1434 },
|
||||
skipType: 'ed',
|
||||
skipId: '5751c57a-2bcd-4dd9-be93-58e6af0f8c81',
|
||||
episodeLength: 1434.985,
|
||||
},
|
||||
],
|
||||
message: 'Successfully found skip times',
|
||||
statusCode: 200,
|
||||
});
|
||||
assert.deepEqual(parsed, {
|
||||
intro: { start: 310.571, end: 400.571 },
|
||||
outro: { start: 1396.006, end: 1434 },
|
||||
});
|
||||
});
|
||||
|
||||
test('parseAniSkipPayload ignores invalid intervals and not-found responses', () => {
|
||||
assert.deepEqual(
|
||||
parseAniSkipPayload({
|
||||
found: true,
|
||||
results: [
|
||||
{ skipType: 'op', interval: { startTime: 50, endTime: 20 } },
|
||||
{ skipType: 'op', interval: { startTime: 0, endTime: 89.5 } },
|
||||
{ skipType: 'recap', interval: { startTime: 0, endTime: 30 } },
|
||||
],
|
||||
}),
|
||||
{ intro: { start: 0, end: 89.5 }, outro: null },
|
||||
);
|
||||
assert.deepEqual(parseAniSkipPayload({ found: false, results: [] }), {
|
||||
intro: null,
|
||||
outro: null,
|
||||
});
|
||||
assert.deepEqual(parseAniSkipPayload(null), { intro: null, outro: null });
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile queries AniSkip v2 with the episode length', async () => {
|
||||
const requested: string[] = [];
|
||||
test('resolveAniSkipMetadataForFile resolves MAL id and intro payload', async () => {
|
||||
await withMockFetch(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
requested.push(url);
|
||||
if (url.includes('myanimelist.net/search/prefix.json')) {
|
||||
return makeMockResponse({
|
||||
categories: [
|
||||
@@ -179,82 +127,48 @@ test('resolveAniSkipMetadataForFile queries AniSkip v2 with the episode length',
|
||||
],
|
||||
});
|
||||
}
|
||||
if (url.includes('api.aniskip.com/v2/skip-times/1234/7')) {
|
||||
if (url.includes('api.aniskip.com/v1/skip-times/1234/7')) {
|
||||
return makeMockResponse({
|
||||
found: true,
|
||||
results: [
|
||||
{ skipType: 'op', interval: { startTime: 12.5, endTime: 54.2 } },
|
||||
{ skipType: 'ed', interval: { startTime: 1300, endTime: 1390 } },
|
||||
],
|
||||
results: [{ skip_type: 'op', interval: { start_time: 12.5, end_time: 54.2 } }],
|
||||
});
|
||||
}
|
||||
throw new Error(`unexpected url: ${url}`);
|
||||
},
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/Anime.My.Show.S01E07.mkv', {
|
||||
episodeLength: 1423.4567,
|
||||
});
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/Anime.My.Show.S01E07.mkv');
|
||||
assert.equal(resolved.malId, 1234);
|
||||
assert.deepEqual(resolved.intro, { start: 12.5, end: 54.2 });
|
||||
assert.deepEqual(resolved.outro, { start: 1300, end: 1390 });
|
||||
assert.equal(resolved.introStart, 12.5);
|
||||
assert.equal(resolved.introEnd, 54.2);
|
||||
assert.equal(resolved.lookupStatus, 'ready');
|
||||
assert.equal(resolved.title, 'Anime My Show');
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
requested[1],
|
||||
'https://api.aniskip.com/v2/skip-times/1234/7?types=op&types=ed&episodeLength=1423.457',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile treats an AniSkip 404 as a definite miss', async () => {
|
||||
test('resolveAniSkipMetadataForFile accepts intro payload starting at zero', async () => {
|
||||
await withMockFetch(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
|
||||
return makeMockResponse(
|
||||
{ found: false, results: [], message: 'No skip times found', statusCode: 404 },
|
||||
404,
|
||||
);
|
||||
if (url.includes('myanimelist.net/search/prefix.json')) {
|
||||
return makeMockResponse({
|
||||
categories: [{ items: [{ id: '1234', name: 'My Show' }] }],
|
||||
});
|
||||
}
|
||||
if (url.includes('api.aniskip.com/v1/skip-times/1234/1')) {
|
||||
return makeMockResponse({
|
||||
found: true,
|
||||
results: [{ skip_type: 'op', interval: { start_time: 0, end_time: 89.5 } }],
|
||||
});
|
||||
}
|
||||
throw new Error(`unexpected url: ${url}`);
|
||||
},
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E02.mkv', LOOKUP);
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E01.mkv');
|
||||
assert.equal(resolved.malId, 1234);
|
||||
assert.equal(resolved.lookupStatus, 'missing_payload');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile reports transient failures as lookup_failed', async () => {
|
||||
const failures: Array<[string, () => Promise<Response>]> = [
|
||||
['AniSkip rate limit', async () => makeMockResponse({ statusCode: 429 }, 429)],
|
||||
['AniSkip server error', async () => makeMockResponse({ statusCode: 503 }, 503)],
|
||||
[
|
||||
'network error',
|
||||
async () => {
|
||||
throw new TypeError('fetch failed');
|
||||
},
|
||||
],
|
||||
];
|
||||
for (const [label, failAniSkip] of failures) {
|
||||
await withMockFetch(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
|
||||
return failAniSkip();
|
||||
},
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
|
||||
assert.equal(resolved.lookupStatus, 'lookup_failed', label);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
await withMockFetch(
|
||||
async () => makeMockResponse({}, 429),
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
|
||||
assert.equal(resolved.lookupStatus, 'lookup_failed', 'MAL rate limit');
|
||||
assert.equal(resolved.introStart, 0);
|
||||
assert.equal(resolved.introEnd, 89.5);
|
||||
assert.equal(resolved.lookupStatus, 'ready');
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -263,7 +177,7 @@ test('resolveAniSkipMetadataForFile emits missing_mal_id when MAL search misses'
|
||||
await withMockFetch(
|
||||
async () => makeMockResponse({ categories: [] }),
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv', LOOKUP);
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv');
|
||||
assert.equal(resolved.malId, null);
|
||||
assert.equal(resolved.lookupStatus, 'missing_mal_id');
|
||||
},
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import type { SkipInterval } from './aniskip-chapters';
|
||||
|
||||
export type AniSkipLookupStatus =
|
||||
| 'ready'
|
||||
@@ -16,16 +15,11 @@ export interface AniSkipMetadata {
|
||||
episode: number | null;
|
||||
source: 'guessit' | 'fallback';
|
||||
malId: number | null;
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
introStart: number | null;
|
||||
introEnd: number | null;
|
||||
lookupStatus?: AniSkipLookupStatus;
|
||||
}
|
||||
|
||||
export interface AniSkipLookupOptions {
|
||||
/** Length of the playing file in seconds; AniSkip v2 uses it to pick times marked on the same cut. */
|
||||
episodeLength: number;
|
||||
}
|
||||
|
||||
interface InferAniSkipDeps {
|
||||
commandExists: (name: string) => boolean;
|
||||
runGuessit: (mediaPath: string) => string | null;
|
||||
@@ -45,12 +39,12 @@ interface MalSearchResponse {
|
||||
}
|
||||
|
||||
interface AniSkipIntervalPayload {
|
||||
startTime?: unknown;
|
||||
endTime?: unknown;
|
||||
start_time?: unknown;
|
||||
end_time?: unknown;
|
||||
}
|
||||
|
||||
interface AniSkipSkipItemPayload {
|
||||
skipType?: unknown;
|
||||
skip_type?: unknown;
|
||||
interval?: unknown;
|
||||
}
|
||||
|
||||
@@ -67,12 +61,9 @@ const ROMAN_SEASON_ALIASES: Record<number, readonly string[]> = {
|
||||
};
|
||||
|
||||
const MAL_PREFIX_API = 'https://myanimelist.net/search/prefix.json?type=anime&keyword=';
|
||||
const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v2/skip-times/';
|
||||
const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v1/skip-times/';
|
||||
const ANISKIP_USER_AGENT = 'SubMiner/ani-skip';
|
||||
const ANISKIP_FETCH_TIMEOUT_MS = 8000;
|
||||
// AniSkip allows 120 requests a minute; one lookup per file load stays far below that,
|
||||
// but a gap keeps fast playlist skipping from bursting.
|
||||
const ANISKIP_MIN_REQUEST_GAP_MS = 1000;
|
||||
const MAL_MATCH_STOPWORDS = new Set([
|
||||
'the',
|
||||
'this',
|
||||
@@ -270,71 +261,49 @@ function toMalSearchItems(payload: unknown): MalSearchResult[] {
|
||||
return items;
|
||||
}
|
||||
|
||||
function parseInterval(raw: unknown): SkipInterval | null {
|
||||
if (typeof raw !== 'object' || raw === null) return null;
|
||||
const interval = raw as AniSkipIntervalPayload;
|
||||
const start = toNonNegativeNumber(interval.startTime);
|
||||
const end = toPositiveNumber(interval.endTime);
|
||||
return start !== null && end !== null && end > start ? { start, end } : null;
|
||||
}
|
||||
function parseAniSkipPayload(payload: unknown): { start: number; end: number } | null {
|
||||
const parsed = payload as AniSkipPayloadResponse;
|
||||
const results = Array.isArray(parsed?.results) ? parsed.results : null;
|
||||
if (!results) return null;
|
||||
|
||||
/** Reads the first valid opening (`op`) and ending (`ed`) from an AniSkip v2 response. */
|
||||
export function parseAniSkipPayload(payload: unknown): {
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
} {
|
||||
const parsed = payload as AniSkipPayloadResponse | null;
|
||||
const results = parsed?.found === true && Array.isArray(parsed.results) ? parsed.results : [];
|
||||
let intro: SkipInterval | null = null;
|
||||
let outro: SkipInterval | null = null;
|
||||
for (const rawResult of results) {
|
||||
const result = rawResult as AniSkipSkipItemPayload;
|
||||
if (result.skipType === 'op' && !intro) intro = parseInterval(result.interval);
|
||||
if (result.skipType === 'ed' && !outro) outro = parseInterval(result.interval);
|
||||
if (
|
||||
result.skip_type !== 'op' ||
|
||||
typeof result.interval !== 'object' ||
|
||||
result.interval === null
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const interval = result.interval as AniSkipIntervalPayload;
|
||||
const start = toNonNegativeNumber(interval?.start_time);
|
||||
const end = toPositiveNumber(interval?.end_time);
|
||||
if (start !== null && end !== null && end > start) {
|
||||
return { start, end };
|
||||
}
|
||||
}
|
||||
return { intro, outro };
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches JSON. A 404 is a definite "nothing here" and returns null; any other
|
||||
* failure (non-OK status, network error, timeout, bad JSON) throws so callers
|
||||
* report a retryable lookup failure instead of caching a miss.
|
||||
*/
|
||||
async function fetchJson(url: string): Promise<unknown> {
|
||||
async function fetchJson<T>(url: string): Promise<T | null> {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'User-Agent': ANISKIP_USER_AGENT,
|
||||
},
|
||||
signal: AbortSignal.timeout(ANISKIP_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status} from ${new URL(url).host}`);
|
||||
if (!response.ok) return null;
|
||||
try {
|
||||
return (await response.json()) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
let lastAniSkipRequestAt = 0;
|
||||
let aniSkipRequestQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
/**
|
||||
* Resolves when the caller may send its AniSkip request. Callers are released
|
||||
* one at a time, each at least ANISKIP_MIN_REQUEST_GAP_MS after the previous
|
||||
* release, so timers that fire late cannot release a burst.
|
||||
*/
|
||||
function waitForAniSkipRequestSlot(): Promise<void> {
|
||||
const slot = aniSkipRequestQueue.then(async () => {
|
||||
const waitMs = lastAniSkipRequestAt + ANISKIP_MIN_REQUEST_GAP_MS - Date.now();
|
||||
if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs));
|
||||
lastAniSkipRequestAt = Date.now();
|
||||
});
|
||||
aniSkipRequestQueue = slot;
|
||||
return slot;
|
||||
}
|
||||
|
||||
async function resolveMalIdFromTitle(title: string, season: number | null): Promise<number | null> {
|
||||
const lookup = season && season > 1 ? `${title} Season ${season}` : title;
|
||||
const payload = await fetchJson(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
|
||||
const payload = await fetchJson<unknown>(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
|
||||
const items = toMalSearchItems(payload);
|
||||
if (!items.length) return null;
|
||||
|
||||
@@ -357,17 +326,16 @@ async function resolveMalIdFromTitle(title: string, season: number | null): Prom
|
||||
return bestMalId;
|
||||
}
|
||||
|
||||
async function fetchAniSkipIntervals(
|
||||
async function fetchAniSkipPayload(
|
||||
malId: number,
|
||||
episode: number,
|
||||
episodeLength: number,
|
||||
): Promise<{ intro: SkipInterval | null; outro: SkipInterval | null }> {
|
||||
await waitForAniSkipRequestSlot();
|
||||
const length = Math.round(episodeLength * 1000) / 1000;
|
||||
const payload = await fetchJson(
|
||||
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed&episodeLength=${length}`,
|
||||
): Promise<{ start: number; end: number } | null> {
|
||||
const payload = await fetchJson<unknown>(
|
||||
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed`,
|
||||
);
|
||||
return parseAniSkipPayload(payload);
|
||||
const parsed = payload as AniSkipPayloadResponse;
|
||||
if (!parsed || parsed.found !== true) return null;
|
||||
return parseAniSkipPayload(parsed);
|
||||
}
|
||||
|
||||
function detectEpisodeFromName(baseName: string): number | null {
|
||||
@@ -488,8 +456,8 @@ export function parseAniSkipGuessitJson(stdout: string, mediaPath: string): AniS
|
||||
episode: episodeFromDirect ?? episodeFromList,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
};
|
||||
} catch {
|
||||
@@ -533,20 +501,13 @@ export function inferAniSkipMetadataForFile(
|
||||
episode: detectEpisodeFromName(baseName),
|
||||
source: 'fallback',
|
||||
malId: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a local file's MAL id and AniSkip opening/ending. Statuses other
|
||||
* than `lookup_failed` are definite answers that callers may cache.
|
||||
*/
|
||||
export async function resolveAniSkipMetadataForFile(
|
||||
mediaPath: string,
|
||||
options: AniSkipLookupOptions,
|
||||
): Promise<AniSkipMetadata> {
|
||||
export async function resolveAniSkipMetadataForFile(mediaPath: string): Promise<AniSkipMetadata> {
|
||||
const inferred = inferAniSkipMetadataForFile(mediaPath);
|
||||
if (!inferred.title) {
|
||||
return { ...inferred, lookupStatus: 'lookup_failed' };
|
||||
@@ -555,25 +516,50 @@ export async function resolveAniSkipMetadataForFile(
|
||||
try {
|
||||
const malId = await resolveMalIdFromTitle(inferred.title, inferred.season);
|
||||
if (!malId) {
|
||||
return { ...inferred, lookupStatus: 'missing_mal_id' };
|
||||
return {
|
||||
...inferred,
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_mal_id',
|
||||
};
|
||||
}
|
||||
|
||||
if (!inferred.episode) {
|
||||
return { ...inferred, malId, lookupStatus: 'missing_episode' };
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_episode',
|
||||
};
|
||||
}
|
||||
|
||||
const payload = await fetchAniSkipPayload(malId, inferred.episode);
|
||||
if (!payload) {
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_payload',
|
||||
};
|
||||
}
|
||||
|
||||
const { intro, outro } = await fetchAniSkipIntervals(
|
||||
malId,
|
||||
inferred.episode,
|
||||
options.episodeLength,
|
||||
);
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
intro,
|
||||
outro,
|
||||
lookupStatus: intro || outro ? 'ready' : 'missing_payload',
|
||||
introStart: payload.start,
|
||||
introEnd: payload.end,
|
||||
lookupStatus: 'ready',
|
||||
};
|
||||
} catch {
|
||||
return { ...inferred, lookupStatus: 'lookup_failed' };
|
||||
return {
|
||||
...inferred,
|
||||
malId: inferred.malId,
|
||||
introStart: inferred.introStart,
|
||||
introEnd: inferred.introEnd,
|
||||
lookupStatus: 'lookup_failed',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -10,22 +10,19 @@ function readyMetadata(overrides: Partial<AniSkipMetadata> = {}): AniSkipMetadat
|
||||
episode: 1,
|
||||
source: 'fallback',
|
||||
malId: 1234,
|
||||
intro: { start: 10, end: 95.5 },
|
||||
outro: null,
|
||||
introStart: 10,
|
||||
introEnd: 95.5,
|
||||
lookupStatus: 'ready',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const NO_SKIP_TIMES = { intro: null, outro: null } as const;
|
||||
|
||||
function createHarness(options?: {
|
||||
enabled?: boolean;
|
||||
buttonKey?: string;
|
||||
metadata?: AniSkipMetadata | (() => Promise<AniSkipMetadata>);
|
||||
chapterList?: unknown;
|
||||
playbackFeedback?: boolean;
|
||||
duration?: number | null;
|
||||
}) {
|
||||
const state = {
|
||||
enabled: options?.enabled ?? true,
|
||||
@@ -34,14 +31,9 @@ function createHarness(options?: {
|
||||
osd: [] as string[],
|
||||
feedback: [] as string[],
|
||||
resolveCalls: [] as string[],
|
||||
episodeLengths: [] as number[],
|
||||
connected: true,
|
||||
duration: options?.duration === undefined ? 1440 : options.duration,
|
||||
timePos: 0,
|
||||
chapterList: options?.chapterList ?? [],
|
||||
chapterListFails: false,
|
||||
// When set, chapter-list reads wait for it before answering.
|
||||
chapterGate: null as Promise<void> | null,
|
||||
};
|
||||
|
||||
const deps = {
|
||||
@@ -49,9 +41,8 @@ function createHarness(options?: {
|
||||
aniskipEnabled: state.enabled,
|
||||
aniskipButtonKey: state.buttonKey,
|
||||
}),
|
||||
resolveMetadataForFile: async (mediaPath, episodeLength) => {
|
||||
resolveMetadataForFile: async (mediaPath) => {
|
||||
state.resolveCalls.push(mediaPath);
|
||||
state.episodeLengths.push(episodeLength);
|
||||
const metadata = options?.metadata;
|
||||
if (typeof metadata === 'function') return metadata();
|
||||
return metadata ?? readyMetadata();
|
||||
@@ -60,15 +51,7 @@ function createHarness(options?: {
|
||||
state.commands.push(command);
|
||||
},
|
||||
requestMpvProperty: async (name) => {
|
||||
if (name === 'chapter-list') {
|
||||
if (state.chapterGate) await state.chapterGate;
|
||||
if (state.chapterListFails) throw new Error('property unavailable');
|
||||
return state.chapterList;
|
||||
}
|
||||
if (name === 'duration') {
|
||||
if (state.duration === null) throw new Error('property unavailable');
|
||||
return state.duration;
|
||||
}
|
||||
if (name === 'chapter-list') return state.chapterList;
|
||||
return null;
|
||||
},
|
||||
isMpvConnected: () => state.connected,
|
||||
@@ -101,10 +84,6 @@ async function flushAsync(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function seekCommands(commands: unknown[][]): unknown[][] {
|
||||
return commands.filter((command) => command[0] === 'set_property' && command[1] === 'time-pos');
|
||||
}
|
||||
|
||||
test('isRemoteMediaPath detects URLs but not local paths', () => {
|
||||
assert.equal(isRemoteMediaPath('https://example.com/stream.mkv'), true);
|
||||
assert.equal(isRemoteMediaPath('rtmp://example.com/live'), true);
|
||||
@@ -122,7 +101,6 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(state.resolveCalls, ['/media/anime/My Show/ep1.mkv']);
|
||||
assert.deepEqual(state.episodeLengths, [1440]);
|
||||
const chapterCommands = chapterListCommands(state.commands);
|
||||
assert.equal(chapterCommands.length, 1);
|
||||
const chapters = chapterCommands[0]![2] as Array<{ time: number; title: string }>;
|
||||
@@ -131,10 +109,7 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
|
||||
{ time: 10, title: 'AniSkip Intro Start' },
|
||||
{ time: 95.5, title: 'AniSkip Intro End' },
|
||||
]);
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 10, end: 95.5, source: 'aniskip' },
|
||||
outro: null,
|
||||
});
|
||||
assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 });
|
||||
});
|
||||
|
||||
test('remote media paths and disabled config never resolve', async () => {
|
||||
@@ -156,18 +131,21 @@ test('skip intro seeks to intro end only inside the intro window', async () => {
|
||||
|
||||
state.timePos = 200;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Skip only during intro or outro']);
|
||||
assert.deepEqual(state.osd, ['Skip intro only during intro']);
|
||||
|
||||
state.timePos = 30;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Skip only during intro or outro', 'Skipped intro']);
|
||||
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 95.5]]);
|
||||
assert.deepEqual(state.osd, ['Skip intro only during intro', 'Skipped intro']);
|
||||
const seek = state.commands.find(
|
||||
(command) => command[0] === 'set_property' && command[1] === 'time-pos',
|
||||
);
|
||||
assert.deepEqual(seek, ['set_property', 'time-pos', 95.5]);
|
||||
});
|
||||
|
||||
test('skip intro reports unavailable when no window was found', () => {
|
||||
const { runtime, state } = createHarness();
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Intro/outro skip unavailable']);
|
||||
assert.deepEqual(state.osd, ['Intro skip unavailable']);
|
||||
});
|
||||
|
||||
test('time-pos prompt shows once near intro start', async () => {
|
||||
@@ -180,7 +158,7 @@ test('time-pos prompt shows once near intro start', async () => {
|
||||
|
||||
runtime.handleTimePosChange({ time: 10.5 });
|
||||
runtime.handleTimePosChange({ time: 11 });
|
||||
assert.deepEqual(state.osd, ['You can skip the intro by pressing TAB']);
|
||||
assert.deepEqual(state.osd, ['You can skip by pressing TAB']);
|
||||
});
|
||||
|
||||
test('prompt and skip messages use playback feedback when configured', async () => {
|
||||
@@ -192,7 +170,7 @@ test('prompt and skip messages use playback feedback when configured', async ()
|
||||
state.timePos = 30;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
|
||||
assert.deepEqual(state.feedback, ['You can skip the intro by pressing TAB', 'Skipped intro']);
|
||||
assert.deepEqual(state.feedback, ['You can skip by pressing TAB', 'Skipped intro']);
|
||||
assert.deepEqual(state.osd, []);
|
||||
});
|
||||
|
||||
@@ -262,13 +240,18 @@ test('aniskip refresh forces a fresh lookup for the current media', async () =>
|
||||
assert.equal(state.resolveCalls.length, 2);
|
||||
});
|
||||
|
||||
test('definite misses are cached and not looked up again for the same file', async () => {
|
||||
test('media without an intro window is cached and never re-resolved on reload of another file', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
|
||||
metadata: readyMetadata({
|
||||
malId: 1234,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_payload',
|
||||
}),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
assert.equal(runtime.getIntroWindow(), null);
|
||||
assert.equal(chapterListCommands(state.commands).length, 0);
|
||||
|
||||
runtime.handleMediaPathChange({ path: '/media/other.mkv' });
|
||||
@@ -278,117 +261,25 @@ test('definite misses are cached and not looked up again for the same file', asy
|
||||
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/other.mkv']);
|
||||
});
|
||||
|
||||
test('transient lookup failures are not cached and retry on the next media load', async () => {
|
||||
let calls = 0;
|
||||
test('transient lookup failures are retried on the next media load', async () => {
|
||||
let failures = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: async () => {
|
||||
calls += 1;
|
||||
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
|
||||
failures += 1;
|
||||
return readyMetadata(
|
||||
failures === 1 ? { introStart: null, introEnd: null, lookupStatus: 'lookup_failed' } : {},
|
||||
);
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
assert.equal(runtime.getIntroWindow(), null);
|
||||
|
||||
runtime.handleMediaPathChange({ path: '' });
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(state.resolveCalls.length, 2);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
|
||||
});
|
||||
|
||||
test('resolution waits for a known duration before reading chapters or AniSkip', async () => {
|
||||
const { runtime, state } = createHarness({ duration: null });
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.resolveCalls, []);
|
||||
|
||||
runtime.handleDurationChange({ duration: 1425.2 });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.episodeLengths, [1425.2]);
|
||||
});
|
||||
|
||||
test('file chapters with both an opening and an ending skip the AniSkip lookup', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Prologue' },
|
||||
{ time: 120, title: 'Opening' },
|
||||
{ time: 210, title: 'Part A' },
|
||||
{ time: 1300, title: 'Ending' },
|
||||
{ time: 1390, title: 'Preview' },
|
||||
],
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(state.resolveCalls, []);
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 120, end: 210, source: 'chapters' },
|
||||
outro: { start: 1300, end: 1390, source: 'chapters' },
|
||||
});
|
||||
// The file already has chapter boundaries there, so no AniSkip markers are added.
|
||||
assert.equal(chapterListCommands(state.commands).length, 0);
|
||||
});
|
||||
|
||||
test('AniSkip fills in the window the file chapters lack', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Opening' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
],
|
||||
metadata: readyMetadata({
|
||||
intro: { start: 3, end: 93 },
|
||||
outro: { start: 1330, end: 1420 },
|
||||
}),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.equal(state.resolveCalls.length, 1);
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 0, end: 90, source: 'chapters' },
|
||||
outro: { start: 1330, end: 1420, source: 'aniskip' },
|
||||
});
|
||||
assert.deepEqual(chapterListCommands(state.commands)[0]![2], [
|
||||
{ time: 0, title: 'Opening' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
{ time: 1330, title: 'AniSkip Outro Start' },
|
||||
{ time: 1420, title: 'AniSkip Outro End' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('remote streams use file chapters without an AniSkip lookup', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Intro' },
|
||||
{ time: 30, title: 'OP' },
|
||||
{ time: 120, title: 'Episode' },
|
||||
],
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: 'https://jellyfin.example/Videos/1/stream.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(state.resolveCalls, []);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 30, end: 120, source: 'chapters' });
|
||||
});
|
||||
|
||||
test('skip key skips the outro inside its window and prompts at its start', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: readyMetadata({ outro: { start: 1330, end: 1420 } }),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
runtime.handleTimePosChange({ time: 1331 });
|
||||
runtime.handleTimePosChange({ time: 1332 });
|
||||
assert.deepEqual(state.osd, ['You can skip the outro by pressing TAB']);
|
||||
|
||||
state.timePos = 1329.8;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
state.timePos = 1425;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 1420]]);
|
||||
assert.deepEqual(state.osd.slice(1), ['Skipped outro', 'Skip only during intro or outro']);
|
||||
assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 });
|
||||
});
|
||||
|
||||
test('disconnect clears bindings so reconnect rebinds the skip key', () => {
|
||||
@@ -401,174 +292,3 @@ test('disconnect clears bindings so reconnect rebinds the skip key', () => {
|
||||
['keybind', 'TAB', 'script-message subminer-skip-intro'],
|
||||
]);
|
||||
});
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
test('a failed chapter-list read leaves the file chapters untouched', async () => {
|
||||
const harness = createHarness({
|
||||
chapterList: [{ time: 0, title: 'Prologue' }],
|
||||
metadata: async () => {
|
||||
harness.state.chapterListFails = true;
|
||||
return readyMetadata();
|
||||
},
|
||||
});
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.equal(harness.runtime.getSkipWindows().intro?.source, 'aniskip');
|
||||
assert.equal(chapterListCommands(harness.state.commands).length, 0);
|
||||
});
|
||||
|
||||
test('markers are not written into a file that replaced the one being read', async () => {
|
||||
const gate = deferred<void>();
|
||||
let calls = 0;
|
||||
const harness = createHarness({
|
||||
metadata: async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
harness.state.chapterGate = gate.promise;
|
||||
return readyMetadata();
|
||||
}
|
||||
return readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' });
|
||||
},
|
||||
});
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/a.mkv' });
|
||||
await flushAsync();
|
||||
// The marker write for a.mkv is waiting on its chapter-list read.
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/b.mkv' });
|
||||
harness.state.chapterGate = null;
|
||||
gate.resolve();
|
||||
await flushAsync();
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(harness.state.resolveCalls, ['/media/a.mkv', '/media/b.mkv']);
|
||||
assert.equal(chapterListCommands(harness.state.commands).length, 0);
|
||||
});
|
||||
|
||||
test('a file-chapter intro is usable while the AniSkip lookup is still running', async () => {
|
||||
const lookup = deferred<AniSkipMetadata>();
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Opening' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
],
|
||||
metadata: () => lookup.promise,
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 0, end: 90, source: 'chapters' },
|
||||
outro: null,
|
||||
});
|
||||
runtime.handleTimePosChange({ time: 1 });
|
||||
assert.equal(state.osd.length, 1);
|
||||
|
||||
lookup.resolve(
|
||||
readyMetadata({ intro: { start: 3, end: 93 }, outro: { start: 1330, end: 1420 } }),
|
||||
);
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 0, end: 90, source: 'chapters' },
|
||||
outro: { start: 1330, end: 1420, source: 'aniskip' },
|
||||
});
|
||||
// The intro prompt already shown is not shown again.
|
||||
runtime.handleTimePosChange({ time: 1.5 });
|
||||
assert.equal(state.osd.length, 1);
|
||||
});
|
||||
|
||||
test('a lookup superseded by a refresh does not overwrite the cache', async () => {
|
||||
const first = deferred<AniSkipMetadata>();
|
||||
let calls = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: () => {
|
||||
calls += 1;
|
||||
return calls === 1 ? first.promise : Promise.resolve(readyMetadata());
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleClientMessage({ args: ['subminer-aniskip-refresh'] });
|
||||
await flushAsync();
|
||||
first.resolve(readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }));
|
||||
await flushAsync();
|
||||
|
||||
runtime.handleMediaPathChange({ path: '/media/other.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/show.mkv', '/media/other.mkv']);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
|
||||
});
|
||||
|
||||
test('a same-media reload retries a transient lookup failure', async () => {
|
||||
let calls = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: async () => {
|
||||
calls += 1;
|
||||
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(state.resolveCalls.length, 2);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
|
||||
});
|
||||
|
||||
test('a failed chapter-list read is retried on the next duration change or reload', async () => {
|
||||
const stream = 'https://jellyfin.example/Videos/1/stream.mkv';
|
||||
const chapters = [
|
||||
{ time: 0, title: 'OP' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
];
|
||||
for (const retry of ['duration', 'reload'] as const) {
|
||||
const { runtime, state } = createHarness({ chapterList: chapters });
|
||||
state.chapterListFails = true;
|
||||
runtime.handleMediaPathChange({ path: stream });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
|
||||
state.chapterListFails = false;
|
||||
if (retry === 'duration') runtime.handleDurationChange({ duration: 1440 });
|
||||
else runtime.handleMediaPathChange({ path: stream });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 0, end: 90, source: 'chapters' });
|
||||
}
|
||||
});
|
||||
|
||||
test('a successful empty chapter list is not read again on a duration change', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleDurationChange({ duration: 1441 });
|
||||
await flushAsync();
|
||||
assert.equal(state.resolveCalls.length, 1);
|
||||
});
|
||||
|
||||
test('a cached lookup is reused only for the episode length it was fetched for', async () => {
|
||||
const { runtime, state } = createHarness();
|
||||
// A failing chapter read keeps resolution retrying on each duration change.
|
||||
state.chapterListFails = true;
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleDurationChange({ duration: 1440 });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.episodeLengths, [1440]);
|
||||
|
||||
runtime.handleDurationChange({ duration: 1500 });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.episodeLengths, [1440, 1500]);
|
||||
});
|
||||
+129
-283
@@ -1,16 +1,11 @@
|
||||
import type { AniSkipMetadata } from './aniskip-metadata';
|
||||
import {
|
||||
ANISKIP_CHAPTER_PREFIX,
|
||||
classifyChapterSkipIntervals,
|
||||
type SkipInterval,
|
||||
} from './aniskip-chapters';
|
||||
|
||||
/** mpv script-message that skips whichever of the intro or outro is playing. */
|
||||
export const ANISKIP_SKIP_INTRO_MESSAGE = 'subminer-skip-intro';
|
||||
export const ANISKIP_REFRESH_MESSAGE = 'subminer-aniskip-refresh';
|
||||
|
||||
const DEFAULT_ANISKIP_BUTTON_KEY = 'TAB';
|
||||
const LEGACY_ANISKIP_BUTTON_KEY = 'y-k';
|
||||
const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
|
||||
const SKIP_WINDOW_EPSILON_SECONDS = 0.35;
|
||||
const PROMPT_WINDOW_SECONDS = 3;
|
||||
const PROMPT_OSD_DURATION_MS = 3000;
|
||||
@@ -21,7 +16,7 @@ export interface AniSkipRuntimeConfig {
|
||||
|
||||
export interface AniSkipRuntimeDeps {
|
||||
getAniSkipConfig: () => AniSkipRuntimeConfig;
|
||||
resolveMetadataForFile: (mediaPath: string, episodeLength: number) => Promise<AniSkipMetadata>;
|
||||
resolveMetadataForFile: (mediaPath: string) => Promise<AniSkipMetadata>;
|
||||
sendMpvCommand: (command: unknown[]) => void;
|
||||
requestMpvProperty: (name: string) => Promise<unknown>;
|
||||
isMpvConnected: () => boolean;
|
||||
@@ -33,65 +28,26 @@ export interface AniSkipRuntimeDeps {
|
||||
logDebug: (message: string) => void;
|
||||
}
|
||||
|
||||
export type SkipWindowKind = 'intro' | 'outro';
|
||||
|
||||
export interface AniSkipWindow extends SkipInterval {
|
||||
/** `chapters` = the file's own chapters; `aniskip` = the AniSkip database. */
|
||||
source: 'chapters' | 'aniskip';
|
||||
}
|
||||
|
||||
export interface AniSkipWindows {
|
||||
intro: AniSkipWindow | null;
|
||||
outro: AniSkipWindow | null;
|
||||
}
|
||||
|
||||
interface AniSkipLookupResult {
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
export interface AniSkipIntroWindow {
|
||||
start: number;
|
||||
end: number;
|
||||
malId: number | null;
|
||||
}
|
||||
|
||||
type MpvChapter = { time?: unknown; title?: unknown };
|
||||
|
||||
const KIND_LABEL: Record<SkipWindowKind, { chapter: string; word: string }> = {
|
||||
intro: { chapter: 'Intro', word: 'intro' },
|
||||
outro: { chapter: 'Outro', word: 'outro' },
|
||||
};
|
||||
|
||||
export function isRemoteMediaPath(mediaPath: string): boolean {
|
||||
return /^[a-zA-Z][\w+.-]*:\/\//.test(mediaPath.trim());
|
||||
}
|
||||
|
||||
function isAniSkipChapter(chapter: MpvChapter): boolean {
|
||||
return typeof chapter?.title === 'string' && chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX);
|
||||
}
|
||||
|
||||
function isUsableDuration(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the intro and outro for each loaded file (file chapters first, then
|
||||
* AniSkip for whatever the chapters lack), marks them as chapters, prompts when
|
||||
* one starts, and skips the active one when the skip key is pressed.
|
||||
*/
|
||||
export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
let requestGeneration = 0;
|
||||
let currentMediaPath = '';
|
||||
let currentDuration: number | null = null;
|
||||
// True once resolution for the current media has started (or finished).
|
||||
let resolutionStarted = false;
|
||||
// True when resolution for the current media hit a retryable failure (the
|
||||
// chapter-list read or the AniSkip lookup), so a reload or duration change
|
||||
// runs it again.
|
||||
let retryResolution = false;
|
||||
let windows: AniSkipWindows = { intro: null, outro: null };
|
||||
const promptShown: Record<SkipWindowKind, boolean> = { intro: false, outro: false };
|
||||
let introWindow: AniSkipIntroWindow | null = null;
|
||||
let promptShown = false;
|
||||
let boundButtonKey: string | null = null;
|
||||
let legacyFallbackBound = false;
|
||||
// AniSkip results per media path, with the episode length they were fetched
|
||||
// for (v2 picks times by length). Only definitive answers are stored.
|
||||
const lookupCache = new Map<string, { duration: number; result: AniSkipLookupResult }>();
|
||||
const introWindowCache = new Map<string, AniSkipIntroWindow | null>();
|
||||
|
||||
function resolveButtonKey(): string {
|
||||
const key = deps.getAniSkipConfig().aniskipButtonKey.trim();
|
||||
@@ -137,39 +93,22 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
}
|
||||
}
|
||||
|
||||
async function readChapterList(): Promise<MpvChapter[] | null> {
|
||||
async function setIntroChapters(introStart: number, introEnd: number): Promise<void> {
|
||||
let existing: MpvChapter[] = [];
|
||||
try {
|
||||
const chapterList = await deps.requestMpvProperty('chapter-list');
|
||||
return Array.isArray(chapterList) ? (chapterList as MpvChapter[]) : [];
|
||||
if (Array.isArray(chapterList)) {
|
||||
existing = chapterList as MpvChapter[];
|
||||
}
|
||||
} catch {
|
||||
// chapter-list may be unavailable mid-load
|
||||
return null;
|
||||
// chapter-list may be unavailable mid-load; fall back to AniSkip chapters only
|
||||
}
|
||||
}
|
||||
|
||||
/** True while the given request generation still owns the given media. */
|
||||
function ownsPlayback(generation: number, mediaPath: string): boolean {
|
||||
return generation === requestGeneration && mediaPath === currentMediaPath;
|
||||
}
|
||||
|
||||
/** Replaces SubMiner's marker chapters with ones for the AniSkip-sourced windows. */
|
||||
async function setSkipChapters(): Promise<void> {
|
||||
const generation = requestGeneration;
|
||||
const mediaPath = currentMediaPath;
|
||||
const markers: MpvChapter[] = [];
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = windows[kind];
|
||||
if (window?.source !== 'aniskip') continue;
|
||||
const label = KIND_LABEL[kind].chapter;
|
||||
markers.push({ time: window.start, title: `${ANISKIP_CHAPTER_PREFIX}${label} Start` });
|
||||
markers.push({ time: window.end, title: `${ANISKIP_CHAPTER_PREFIX}${label} End` });
|
||||
}
|
||||
if (markers.length === 0) return;
|
||||
const existing = await readChapterList();
|
||||
// A failed read must not wipe the file's chapters, and a read that finished
|
||||
// after the media changed must not write into the next file.
|
||||
if (!existing || !ownsPlayback(generation, mediaPath)) return;
|
||||
const chapters = existing.filter((chapter) => !isAniSkipChapter(chapter)).concat(markers);
|
||||
const chapters = existing.filter(
|
||||
(chapter) =>
|
||||
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
|
||||
);
|
||||
chapters.push({ time: introStart, title: 'AniSkip Intro Start' });
|
||||
chapters.push({ time: introEnd, title: 'AniSkip Intro End' });
|
||||
chapters.sort((a, b) => {
|
||||
const aTime = typeof a.time === 'number' ? a.time : 0;
|
||||
const bTime = typeof b.time === 'number' ? b.time : 0;
|
||||
@@ -178,13 +117,21 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
deps.sendMpvCommand(['set_property', 'chapter-list', chapters]);
|
||||
}
|
||||
|
||||
async function removeSkipChapters(): Promise<void> {
|
||||
async function removeIntroChapters(): Promise<void> {
|
||||
if (!deps.isMpvConnected()) return;
|
||||
const generation = requestGeneration;
|
||||
const mediaPath = currentMediaPath;
|
||||
const existing = await readChapterList();
|
||||
if (!existing || !ownsPlayback(generation, mediaPath)) return;
|
||||
const filtered = existing.filter((chapter) => !isAniSkipChapter(chapter));
|
||||
let existing: MpvChapter[] = [];
|
||||
try {
|
||||
const chapterList = await deps.requestMpvProperty('chapter-list');
|
||||
if (Array.isArray(chapterList)) {
|
||||
existing = chapterList as MpvChapter[];
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const filtered = existing.filter(
|
||||
(chapter) =>
|
||||
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
|
||||
);
|
||||
if (filtered.length !== existing.length) {
|
||||
deps.sendMpvCommand(['set_property', 'chapter-list', filtered]);
|
||||
}
|
||||
@@ -192,162 +139,81 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
|
||||
function clearState(): void {
|
||||
requestGeneration += 1;
|
||||
resolutionStarted = false;
|
||||
retryResolution = false;
|
||||
windows = { intro: null, outro: null };
|
||||
promptShown.intro = false;
|
||||
promptShown.outro = false;
|
||||
introWindow = null;
|
||||
promptShown = false;
|
||||
}
|
||||
|
||||
function logWindow(kind: SkipWindowKind, window: AniSkipWindow, malId: number | null): void {
|
||||
async function applyIntroWindow(window: AniSkipIntroWindow): Promise<void> {
|
||||
introWindow = window;
|
||||
promptShown = false;
|
||||
await setIntroChapters(window.start, window.end);
|
||||
deps.logInfo(
|
||||
`AniSkip ${kind} window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (source=${
|
||||
window.source
|
||||
}, MAL ${malId ?? '-'})`,
|
||||
`AniSkip intro window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (MAL ${
|
||||
window.malId ?? '-'
|
||||
})`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Installs the file-chapter windows, resetting the prompts. */
|
||||
function applyChapterWindows(next: AniSkipWindows): void {
|
||||
windows = next;
|
||||
promptShown.intro = false;
|
||||
promptShown.outro = false;
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = next[kind];
|
||||
if (window) logWindow(kind, window, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills the windows the chapters lacked from AniSkip, leaving the chapter
|
||||
* windows (and whether their prompt was shown) untouched.
|
||||
*/
|
||||
async function mergeAniSkipWindows(lookup: AniSkipLookupResult): Promise<void> {
|
||||
const added: SkipWindowKind[] = [];
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const interval = lookup[kind];
|
||||
if (windows[kind] || !interval) continue;
|
||||
windows = { ...windows, [kind]: { ...interval, source: 'aniskip' } };
|
||||
promptShown[kind] = false;
|
||||
added.push(kind);
|
||||
}
|
||||
if (added.length === 0) return;
|
||||
for (const kind of added) {
|
||||
const window = windows[kind];
|
||||
if (window) logWindow(kind, window, lookup.malId);
|
||||
}
|
||||
await setSkipChapters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up AniSkip, using the cache for definitive answers fetched at the same
|
||||
* episode length. Null means a retryable failure.
|
||||
*/
|
||||
async function lookUpAniSkip(
|
||||
mediaPath: string,
|
||||
duration: number,
|
||||
generation: number,
|
||||
): Promise<AniSkipLookupResult | null> {
|
||||
const cached = lookupCache.get(mediaPath);
|
||||
if (cached?.duration === duration) return cached.result;
|
||||
|
||||
let metadata: AniSkipMetadata;
|
||||
try {
|
||||
metadata = await deps.resolveMetadataForFile(mediaPath, duration);
|
||||
} catch (error) {
|
||||
deps.logWarn('AniSkip metadata lookup failed', error);
|
||||
return null;
|
||||
}
|
||||
const result: AniSkipLookupResult = {
|
||||
intro: metadata.intro,
|
||||
outro: metadata.outro,
|
||||
malId: metadata.malId,
|
||||
};
|
||||
if (metadata.lookupStatus === 'lookup_failed') {
|
||||
deps.logInfo(`AniSkip lookup failed for "${metadata.title}"; will retry on next load`);
|
||||
return null;
|
||||
}
|
||||
// Every other status is definitive (a 404 or an unmatched title), so cache it,
|
||||
// unless a refresh or media change superseded this lookup while it ran.
|
||||
if (generation === requestGeneration) lookupCache.set(mediaPath, { duration, result });
|
||||
if (metadata.lookupStatus !== 'ready') {
|
||||
deps.logInfo(
|
||||
`AniSkip: no skip times for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function resolveForMedia(mediaPath: string, duration: number): Promise<void> {
|
||||
async function resolveForMedia(mediaPath: string, options?: { force?: boolean }): Promise<void> {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
const generation = requestGeneration;
|
||||
const isStale = () => generation !== requestGeneration || mediaPath !== currentMediaPath;
|
||||
|
||||
const chapterList = await readChapterList();
|
||||
if (isStale()) return;
|
||||
// A failed read is retried later; a successful empty list is a final answer.
|
||||
if (chapterList === null) retryResolution = true;
|
||||
const fromChapters = classifyChapterSkipIntervals(chapterList ?? [], duration);
|
||||
const next: AniSkipWindows = {
|
||||
intro: fromChapters.intro ? { ...fromChapters.intro, source: 'chapters' } : null,
|
||||
outro: fromChapters.outro ? { ...fromChapters.outro, source: 'chapters' } : null,
|
||||
};
|
||||
// Chapter windows work right away; AniSkip only fills what they lack.
|
||||
applyChapterWindows(next);
|
||||
if (next.intro && next.outro) return;
|
||||
if (isRemoteMediaPath(mediaPath)) {
|
||||
deps.logDebug('AniSkip lookup skipped for remote media; using file chapters only');
|
||||
if (!mediaPath || isRemoteMediaPath(mediaPath)) {
|
||||
deps.logDebug('AniSkip lookup skipped: no local media path');
|
||||
return;
|
||||
}
|
||||
|
||||
const lookup = await lookUpAniSkip(mediaPath, duration, generation);
|
||||
if (isStale()) return;
|
||||
if (lookup === null) retryResolution = true;
|
||||
if (lookup) await mergeAniSkipWindows(lookup);
|
||||
}
|
||||
|
||||
/** Starts resolution once the current media has both a path and a known duration. */
|
||||
function maybeStartResolution(): void {
|
||||
if (resolutionStarted || !currentMediaPath || currentDuration === null) return;
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
resolutionStarted = true;
|
||||
void resolveForMedia(currentMediaPath, currentDuration).catch((error) => {
|
||||
deps.logWarn('AniSkip media resolution failed', error);
|
||||
});
|
||||
}
|
||||
|
||||
function requestCurrentDuration(): void {
|
||||
const generation = requestGeneration;
|
||||
void deps
|
||||
.requestMpvProperty('duration')
|
||||
.then((value) => {
|
||||
if (generation !== requestGeneration || !isUsableDuration(value)) return;
|
||||
currentDuration ??= value;
|
||||
maybeStartResolution();
|
||||
})
|
||||
.catch(() => {
|
||||
// duration is unavailable until the file is loaded; duration-change will follow
|
||||
});
|
||||
}
|
||||
|
||||
function getActiveWindow(now: number): SkipWindowKind | null {
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = windows[kind];
|
||||
if (
|
||||
window &&
|
||||
now >= window.start - SKIP_WINDOW_EPSILON_SECONDS &&
|
||||
now <= window.end + SKIP_WINDOW_EPSILON_SECONDS
|
||||
) {
|
||||
return kind;
|
||||
}
|
||||
if (options?.force) {
|
||||
introWindowCache.delete(mediaPath);
|
||||
}
|
||||
return null;
|
||||
const generation = requestGeneration;
|
||||
const cached = introWindowCache.get(mediaPath);
|
||||
if (cached !== undefined) {
|
||||
if (cached) {
|
||||
await applyIntroWindow(cached);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let metadata: AniSkipMetadata;
|
||||
try {
|
||||
metadata = await deps.resolveMetadataForFile(mediaPath);
|
||||
} catch (error) {
|
||||
deps.logWarn('AniSkip metadata lookup failed', error);
|
||||
return;
|
||||
}
|
||||
if (generation !== requestGeneration || mediaPath !== currentMediaPath) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
metadata.lookupStatus !== 'ready' ||
|
||||
metadata.introStart === null ||
|
||||
metadata.introEnd === null ||
|
||||
metadata.introEnd <= metadata.introStart
|
||||
) {
|
||||
// Only definitive "no skip window exists" results are cached; transient
|
||||
// lookup failures stay retryable on the next load or refresh.
|
||||
if (metadata.lookupStatus !== 'lookup_failed') {
|
||||
introWindowCache.set(mediaPath, null);
|
||||
}
|
||||
deps.logInfo(
|
||||
`AniSkip: no intro window for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const window: AniSkipIntroWindow = {
|
||||
start: metadata.introStart,
|
||||
end: metadata.introEnd,
|
||||
malId: metadata.malId,
|
||||
};
|
||||
introWindowCache.set(mediaPath, window);
|
||||
await applyIntroWindow(window);
|
||||
}
|
||||
|
||||
function skipNow(): void {
|
||||
function skipIntroNow(): void {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
if (!windows.intro && !windows.outro) {
|
||||
showPlaybackFeedback('Intro/outro skip unavailable');
|
||||
if (!introWindow) {
|
||||
showPlaybackFeedback('Intro skip unavailable');
|
||||
return;
|
||||
}
|
||||
const now = deps.getCurrentTimePos();
|
||||
@@ -355,56 +221,40 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
showPlaybackFeedback('Skip unavailable');
|
||||
return;
|
||||
}
|
||||
const kind = getActiveWindow(now);
|
||||
const window = kind ? windows[kind] : null;
|
||||
if (!kind || !window) {
|
||||
showPlaybackFeedback('Skip only during intro or outro');
|
||||
if (
|
||||
now < introWindow.start - SKIP_WINDOW_EPSILON_SECONDS ||
|
||||
now > introWindow.end + SKIP_WINDOW_EPSILON_SECONDS
|
||||
) {
|
||||
showPlaybackFeedback('Skip intro only during intro');
|
||||
return;
|
||||
}
|
||||
deps.sendMpvCommand(['set_property', 'time-pos', window.end]);
|
||||
showPlaybackFeedback(`Skipped ${KIND_LABEL[kind].word}`);
|
||||
deps.sendMpvCommand(['set_property', 'time-pos', introWindow.end]);
|
||||
showPlaybackFeedback('Skipped intro');
|
||||
}
|
||||
|
||||
function handleTimePosChange({ time }: { time: number }): void {
|
||||
if (!introWindow || promptShown) return;
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = windows[kind];
|
||||
if (!window || promptShown[kind]) continue;
|
||||
const promptWindowEnd = Math.min(window.start + PROMPT_WINDOW_SECONDS, window.end);
|
||||
if (time >= window.start && time < promptWindowEnd) {
|
||||
promptShown[kind] = true;
|
||||
showPlaybackFeedback(
|
||||
`You can skip the ${KIND_LABEL[kind].word} by pressing ${resolveButtonKey()}`,
|
||||
);
|
||||
}
|
||||
const promptWindowEnd = Math.min(introWindow.start + PROMPT_WINDOW_SECONDS, introWindow.end);
|
||||
if (time >= introWindow.start && time < promptWindowEnd) {
|
||||
promptShown = true;
|
||||
showPlaybackFeedback(`You can skip by pressing ${resolveButtonKey()}`);
|
||||
}
|
||||
}
|
||||
|
||||
function handleDurationChange({ duration }: { duration: number }): void {
|
||||
if (!isUsableDuration(duration) || !currentMediaPath) return;
|
||||
currentDuration = duration;
|
||||
if (retryResolution) clearState();
|
||||
maybeStartResolution();
|
||||
}
|
||||
|
||||
function handleMediaPathChange({ path }: { path: string }): void {
|
||||
const nextPath = typeof path === 'string' ? path : '';
|
||||
if (nextPath === currentMediaPath && resolutionStarted) {
|
||||
if (retryResolution) {
|
||||
// The last resolution failed transiently; a reload is the retry.
|
||||
clearState();
|
||||
maybeStartResolution();
|
||||
return;
|
||||
}
|
||||
if (nextPath === currentMediaPath && introWindow) {
|
||||
// Same-media reload: mpv rebuilt the chapter list, so re-apply markers.
|
||||
void setSkipChapters().catch(() => {});
|
||||
void setIntroChapters(introWindow.start, introWindow.end).catch(() => {});
|
||||
return;
|
||||
}
|
||||
currentMediaPath = nextPath;
|
||||
currentDuration = null;
|
||||
clearState();
|
||||
if (!nextPath || !deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
requestCurrentDuration();
|
||||
if (!nextPath) return;
|
||||
void resolveForMedia(nextPath).catch((error) => {
|
||||
deps.logWarn('AniSkip media resolution failed', error);
|
||||
});
|
||||
}
|
||||
|
||||
function handleConnectionChange({ connected }: { connected: boolean }): void {
|
||||
@@ -413,7 +263,6 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
legacyFallbackBound = false;
|
||||
clearState();
|
||||
currentMediaPath = '';
|
||||
currentDuration = null;
|
||||
return;
|
||||
}
|
||||
bindSkipKeys();
|
||||
@@ -422,46 +271,43 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
function handleClientMessage({ args }: { args: string[] }): void {
|
||||
const messageName = args[0];
|
||||
if (messageName === ANISKIP_SKIP_INTRO_MESSAGE) {
|
||||
skipNow();
|
||||
skipIntroNow();
|
||||
return;
|
||||
}
|
||||
if (messageName === ANISKIP_REFRESH_MESSAGE) {
|
||||
if (!currentMediaPath) return;
|
||||
lookupCache.delete(currentMediaPath);
|
||||
const mediaPath = currentMediaPath;
|
||||
if (!mediaPath) return;
|
||||
clearState();
|
||||
void removeSkipChapters().catch(() => {});
|
||||
if (currentDuration === null) {
|
||||
requestCurrentDuration();
|
||||
return;
|
||||
}
|
||||
maybeStartResolution();
|
||||
void removeIntroChapters().catch(() => {});
|
||||
void resolveForMedia(mediaPath, { force: true }).catch((error) => {
|
||||
deps.logWarn('AniSkip refresh failed', error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function applyConfigChange(): void {
|
||||
bindSkipKeys();
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) {
|
||||
const enabled = deps.getAniSkipConfig().aniskipEnabled;
|
||||
if (!enabled) {
|
||||
clearState();
|
||||
void removeSkipChapters().catch(() => {});
|
||||
void removeIntroChapters().catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (!currentMediaPath || resolutionStarted) return;
|
||||
if (currentDuration === null) {
|
||||
requestCurrentDuration();
|
||||
return;
|
||||
if (!introWindow && currentMediaPath) {
|
||||
void resolveForMedia(currentMediaPath).catch((error) => {
|
||||
deps.logWarn('AniSkip media resolution failed', error);
|
||||
});
|
||||
}
|
||||
maybeStartResolution();
|
||||
}
|
||||
|
||||
return {
|
||||
handleConnectionChange,
|
||||
handleMediaPathChange,
|
||||
handleDurationChange,
|
||||
handleTimePosChange,
|
||||
handleClientMessage,
|
||||
applyConfigChange,
|
||||
skipNow,
|
||||
getSkipWindows: (): AniSkipWindows => windows,
|
||||
skipIntroNow,
|
||||
getIntroWindow: () => introWindow,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user