Compare commits

..
Author SHA1 Message Date
sudacode 2b6e589ab3 fix(anilist): treat the anchor as season 1 in the air-order continuation check
pickByAirOrder skipped the named-season guard for an anchor whose titles name
no season, so a "Season 2" entry with a "Part 2" synonym was dropped as a
back half and season 2 could not be picked.
2026-11-22 15:22:33 -08:00
sudacode 11da02e4e9 fix(anilist): reject part-marker continuations that name another season
- An entry whose titles name a season never counts as the back half of a
  different season, even when a synonym carries a part marker ("Show Season 2"
  with "Show Part 2"). The start season comes from its own titles, else from
  the walk's count or the requested season.
- A season 1 episode past the title match's length no longer switches to a
  longer later season; the episode-count fallback only replaces a title match
  that is not itself a season (a same-titled movie or special).
2026-11-22 14:34:39 -08:00
sudacode 593c7cbc30 fix(character-dictionary): re-resolve AniList matches cached by the old season resolver
Version the anilist-resolution-cache.json file and drop entries written
before version 2, so seasons the old resolver landed one short on stop
being served from the cache.
2026-11-22 02:26:36 -08:00
sudacode b7b9400aae fix(anilist): resolve later seasons past split-cour halves and specials
The sequel-chain walk counted every SEQUEL hop as a season, so a split
cour ("Part 2", "Cour 2", 第2クール) or a special/movie in the chain
landed one season short while reporting seasonResolved: true.

- Only TV/TV_SHORT/long-ONA entries count; specials, movies, OVAs and
  short ONAs are walked through.
- A hop whose title or synonym ends in a part/cour marker matching the
  season's first entry is a continuation, not a season. Part 1 never
  marks a back half, and a season's own marker is stripped only when it
  is Part 1 (keeps JoJo Part 5 -> Part 6 as two seasons).
- An entry whose title names the requested season (Season 3, 3rd
  Season, III, 第3期) wins over the count, with a one-season lookahead;
  bare trailing numbers are trusted on main titles only.
- A transport error mid-walk propagates instead of falling through to
  air order.
- Episodes past a split-cour season entry resolve to the part that airs
  them (episodeEntry); the AniList updater writes progress there.
- Air order matches the franchise on any main title and drops
  continuations.

Ports and corrects the unlanded design from checkpoint 27c0ea67.
2026-11-22 02:26:36 -08:00
24 changed files with 1550 additions and 724 deletions

No files matched your search

+1 -1
View File
@@ -121,7 +121,7 @@ SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to
| mpv | Required | The video player SubMiner draws over | | mpv | Required | The video player SubMiner draws over |
| fuse2 | Required (Linux) | Running the AppImage | | fuse2 | Required (Linux) | Running the AppImage |
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup | | Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
| ffmpeg | Recommended | Card audio and screenshots (first-run setup can download it) | | ffmpeg | Recommended | Audio clips and screenshots on cards |
| MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting | | MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting |
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway | | xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
| yt-dlp | Optional | YouTube playback | | yt-dlp | Optional | YouTube playback |
+7
View File
@@ -0,0 +1,7 @@
type: fixed
area: anilist
- Later seasons now resolve to the right AniList entry when the sequel chain contains split-season halves ("Part 2", "Cour 2"), specials, or movies. Mushoku Tensei S3, Re:ZERO S4, Dr. STONE S3, KonoSuba S3, and Attack on Titan S4 used to land one season short or on a movie.
- An entry whose title names the season ("Season 3", "III", "第3期") is preferred over counting sequels.
- Episodes past the first half of a split season update the second half's AniList entry at the right episode (episode 15 of an 11 + 12 season updates the second entry to episode 4).
- Character dictionary AniList matches cached by older versions are re-resolved once.
-4
View File
@@ -1,4 +0,0 @@
type: added
area: setup
- First-run setup now shows whether FFmpeg and FFprobe are usable. When they are missing from `PATH`, **Download FFmpeg** saves a verified static build next to your config, and SubMiner and the `subminer` command use it whenever no system FFmpeg is found.
+5 -3
View File
@@ -26,8 +26,8 @@ On Linux, the token is stored with `gnome-libsecret` by default. If your keyring
An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then: 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. 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. 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. 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. 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 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 ## Commands
+1 -1
View File
@@ -8,7 +8,7 @@ For the day-to-day flow, see [Mining workflow](/mining-workflow). Every key on t
1. Install [Anki](https://apps.ankiweb.net/). 1. Install [Anki](https://apps.ankiweb.net/).
2. Install AnkiConnect (add-on code `2055492159`). 2. Install AnkiConnect (add-on code `2055492159`).
3. Install FFmpeg and make sure it is on your `PATH`, or download it from first-run setup. SubMiner uses it for audio and images. 3. Install FFmpeg and make sure it is on your `PATH`. SubMiner uses it for audio and images.
4. Keep Anki running while you mine. 4. Keep Anki running while you mine.
If you changed AnkiConnect's port, set `ankiConnect.url` to match. If you changed AnkiConnect's port, set `ankiConnect.url` to match.
+4 -5
View File
@@ -12,7 +12,7 @@ Getting started takes three steps:
## 1. Install requirements ## 1. Install requirements
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. If you skip it, first-run setup can download a copy for SubMiner. Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot.
| Dependency | Needed for | Platforms | | Dependency | Needed for | Platforms |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ | | ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
@@ -124,7 +124,7 @@ mpv --version
ffmpeg -version ffmpeg -version
``` ```
ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. Otherwise, use the FFmpeg download in first-run setup. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`). ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`).
<details> <details>
<summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary> <summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary>
@@ -262,9 +262,8 @@ Setup walks you through:
1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows). 1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows).
2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser. 2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser.
3. **FFmpeg** (optional). If `ffmpeg` and `ffprobe` are on your `PATH` and run, there is nothing to do. Otherwise **Download FFmpeg** saves a static build to `tools/ffmpeg/` next to your config file. SubMiner and the `subminer` command use it only when FFmpeg is missing from `PATH`, so a system install always takes priority. 3. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`.
4. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`. 4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
5. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
**Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`. **Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`.
+1 -1
View File
@@ -67,7 +67,7 @@ Read when: you need to find the owner module for a behavior or test surface
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window. `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`. - 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. `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. - 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-*`, - Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
assembled by `src/main/assemblies/jellyfin.ts` assembled by `src/main/assemblies/jellyfin.ts`
-7
View File
@@ -1,11 +1,6 @@
import path from 'node:path'; import path from 'node:path';
import packageJson from '../package.json'; import packageJson from '../package.json';
import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js'; import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js';
import { getDefaultConfigDir } from '../src/shared/setup-state.js';
import {
appendManagedFfmpegToPath,
getManagedFfmpegDir,
} from '../src/core/services/managed-ffmpeg.js';
import { import {
loadLauncherJellyfinConfig, loadLauncherJellyfinConfig,
loadLauncherLoggingConfig, loadLauncherLoggingConfig,
@@ -70,8 +65,6 @@ function ensureAppPath(context: LauncherCommandContext): string {
async function main(): Promise<void> { async function main(): Promise<void> {
const scriptPath = process.argv[1] || 'subminer'; const scriptPath = process.argv[1] || 'subminer';
const scriptName = path.basename(scriptPath); const scriptName = path.basename(scriptPath);
// Same PATH rule as the app: dependency checks and spawned tools see a setup-page FFmpeg.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(getDefaultConfigDir()));
const launcherConfig = loadLauncherYoutubeSubgenConfig(); const launcherConfig = loadLauncherYoutubeSubgenConfig();
const launcherMpvConfig = loadLauncherMpvConfig(); const launcherMpvConfig = loadLauncherMpvConfig();
const launcherLoggingConfig = loadLauncherLoggingConfig(); const launcherLoggingConfig = loadLauncherLoggingConfig();
@@ -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) { 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); assert.equal(body.variables?.mediaId, 202);
return createJsonResponse({ return createJsonResponse({
data: { data: {
@@ -608,7 +613,68 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
assert.deepEqual(searchTerms, ['Demo Show']); assert.deepEqual(searchTerms, ['Demo Show']);
assert.equal(result.status, 'updated'); assert.equal(result.status, 'updated');
assert.match(result.message, /Demo Show Sequel/); 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 { } finally {
globalThis.fetch = originalFetch; globalThis.fetch = originalFetch;
} }
+18 -11
View File
@@ -273,6 +273,9 @@ export async function updateAnilistPostWatchProgress(
let mediaId = pinnedMediaId; let mediaId = pinnedMediaId;
let resolvedTitle: string | null = null; let resolvedTitle: string | null = null;
let resolvedEpisodes: number | 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 // 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. // search hit would add an unrelated show to the user's list.
let confidentMatch = pinnedMediaId !== null; let confidentMatch = pinnedMediaId !== null;
@@ -312,14 +315,18 @@ export async function updateAnilistPostWatchProgress(
}; };
} }
mediaId = resolution.id; // A split-cour back half is its own AniList entry with its own episode numbering:
resolvedTitle = resolution.title; // "S1E15" of an 11 + 12 season is progress 4 on the second entry.
resolvedEpisodes = resolution.episodes; 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" -> // 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. // "Show") only certifies the season 1 anchor, not the entry being watched.
const seasonMarkerStripped = stripSeasonSuffix(title).trim() !== title.trim(); const seasonMarkerStripped = stripSeasonSuffix(title).trim() !== title.trim();
confidentMatch = confidentMatch =
resolution.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped); target.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
} }
const entryResponse = await anilistGraphQl<AnilistMediaEntryData>( const entryResponse = await anilistGraphQl<AnilistMediaEntryData>(
@@ -376,8 +383,8 @@ export async function updateAnilistPostWatchProgress(
} }
const currentProgress = entry?.progress ?? 0; const currentProgress = entry?.progress ?? 0;
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, episode); const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, progress);
if (typeof currentProgress === 'number' && currentProgress >= episode && !shouldMarkCompleted) { if (typeof currentProgress === 'number' && currentProgress >= progress && !shouldMarkCompleted) {
return { return {
status: 'skipped', status: 'skipped',
message: `AniList already at episode ${currentProgress} (${pickedTitle}).`, message: `AniList already at episode ${currentProgress} (${pickedTitle}).`,
@@ -396,7 +403,7 @@ export async function updateAnilistPostWatchProgress(
`, `,
{ {
mediaId, mediaId,
progress: episode, progress,
status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT', status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT',
}, },
options, options,
@@ -410,15 +417,15 @@ export async function updateAnilistPostWatchProgress(
return { return {
status: 'updated', status: 'updated',
message: shouldMarkCompleted message: shouldMarkCompleted
? `AniList added "${pickedTitle}" at episode ${episode} and marked it completed.` ? `AniList added "${pickedTitle}" at episode ${progress} and marked it completed.`
: `AniList added "${pickedTitle}" to Watching at episode ${episode}.`, : `AniList added "${pickedTitle}" to Watching at episode ${progress}.`,
}; };
} }
return { return {
status: 'updated', status: 'updated',
message: shouldMarkCompleted message: shouldMarkCompleted
? `AniList updated "${pickedTitle}" to episode ${episode} and marked it completed.` ? `AniList updated "${pickedTitle}" to episode ${progress} and marked it completed.`
: `AniList updated "${pickedTitle}" to episode ${episode}.`, : `AniList updated "${pickedTitle}" to episode ${progress}.`,
}; };
} }
@@ -4,11 +4,22 @@ import assert from 'node:assert/strict';
import { import {
ANILIST_SEASON_RELATIONS_QUERY, ANILIST_SEASON_RELATIONS_QUERY,
ANILIST_SEASON_SEARCH_QUERY, ANILIST_SEASON_SEARCH_QUERY,
namedSeasons,
pickByAirOrder, pickByAirOrder,
resolveAnilistSeasonMedia, resolveAnilistSeasonMedia,
splitPartMarker,
stripSeasonSuffix, stripSeasonSuffix,
type AnilistSeasonMedia, type AnilistSeasonMedia,
} from './season-resolver'; } 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. */ /** Real AniList payloads for "My Teen Romantic Comedy SNAFU", trimmed to used fields. */
const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [ const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [
@@ -161,7 +172,8 @@ test('resolves season 3 by walking sequel relations', async () => {
assert.equal(result?.via, 'sequel-chain'); assert.equal(result?.via, 'sequel-chain');
// Searches the bare title only; "Season 3" returns nothing on AniList. // Searches the bare title only; "Season 3" returns nothing on AniList.
assert.deepEqual(searches, ['My Teen Romantic Comedy SNAFU']); 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 () => { 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?.id, 2);
assert.equal(result?.via, 'sequel-chain'); assert.equal(result?.via, 'named-season');
assert.equal(result?.exactTitleMatch, true); 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 }); const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
assert.equal(result?.id, 2); 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', () => { 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?.seasonResolved, false);
assert.equal(result?.via, 'anchor'); assert.equal(result?.via, 'anchor');
}); });
/** Executor over a fixture chain: search returns the whole chain, entry i's SEQUEL is i + 1. */
function createChainExecutor(chain: AnilistSeasonMedia[]) {
const relations: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {};
chain.forEach((entry, index) => {
const next = chain[index + 1];
relations[entry.id] = next ? [{ relationType: 'SEQUEL', node: next }] : [];
});
return createExecutor(chain, relations);
}
async function resolveInChain(
chain: AnilistSeasonMedia[],
input: { title: string; season?: number | null; episode?: number | null },
) {
const executor = createChainExecutor(chain);
const result = await resolveAnilistSeasonMedia(input, { execute: executor.execute });
return { result, relationLookups: executor.relationLookups };
}
test('split-cour back halves do not count as seasons', async () => {
const title = 'Mushoku Tensei: Jobless Reincarnation';
const s2 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 2, episode: 1 });
assert.equal(s2.result?.id, 146065);
assert.equal(s2.result?.seasonResolved, true);
const s3 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 3, episode: 1 });
assert.equal(s3.result?.id, 178789);
// Four hops for two seasons: "Cour 2" and "Season 2 Part 2" were walked through.
assert.deepEqual(s3.relationLookups, [108465, 127720, 146065, 166873]);
const reZeroS3 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 3 });
assert.equal(reZeroS3.result?.id, 163134);
const reZeroS4 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 4 });
assert.equal(reZeroS4.result?.id, 189046);
});
test('a special in the sequel chain is walked through without counting', async () => {
const s3 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 3 });
assert.equal(s3.result?.id, 131518);
const s4 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 4 });
assert.equal(s4.result?.id, 172019);
});
test('season names ignore part and cour numbers, including localized ones', () => {
// "Cour 2" carries the Thai synonym "... พาร์ท 2" ("part 2").
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[1]!)], []);
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[3]!)], [2]);
assert.deepEqual([...namedSeasons(OVERLORD_CHAIN[1]!)], [2]);
assert.deepEqual([...namedSeasons(DR_STONE_CHAIN[1]!)], [2]);
assert.deepEqual([...namedSeasons(AOT_CHAIN[4]!)], [4]);
});
test('an entry naming the requested season beats the hop count', async () => {
// The second cour has no marker anywhere, so counting alone would call it season 2.
const chain: AnilistSeasonMedia[] = [
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show: Arc Two' } },
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
];
const { result } = await resolveInChain(chain, { title: 'Show', season: 2 });
assert.equal(result?.id, 3);
assert.equal(result?.via, 'named-season');
const overlord = await resolveInChain(OVERLORD_CHAIN, { title: 'Overlord', season: 2 });
assert.equal(overlord.result?.id, 98437);
assert.equal(overlord.result?.via, 'named-season');
});
test('a counted entry whose title names another season is not accepted', async () => {
const chain: AnilistSeasonMedia[] = [
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2021, title: { english: 'Show: Arc Two' } },
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
];
// Counting lands on id 3 for season 3, but it says it is season 2.
const { result } = await resolveInChain(chain, { title: 'Show', season: 3 });
assert.equal(result?.seasonResolved, false);
});
test('JoJo parts are seasons, not split-cour continuations', async () => {
assert.equal(splitPartMarker('JoJo no Kimyou na Bouken Part 5: Ougon no Kaze'), null);
assert.deepEqual(splitPartMarker("JoJo's Bizarre Adventure Part 5"), {
base: 'jojo s bizarre adventure',
part: 5,
});
// Golden Wind ends in "Part 5" and Stone Ocean in "Part 6": same base, different
// parts, so Stone Ocean must still count as the next season.
const { result } = await resolveInChain(JOJO_CHAIN, {
title: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
season: 3,
});
assert.equal(result?.id, 131942);
assert.equal(result?.via, 'sequel-chain');
});
test('Attack on Titan resolves its final season past the season 3 back half', async () => {
const { result } = await resolveInChain(AOT_CHAIN, { title: 'Attack on Titan', season: 4 });
assert.equal(result?.id, 110277);
});
test('air-order fallback drops back halves but keeps a season spelled "Part 1"', () => {
// AoT season 3 carries the synonym "ผ่าพิภพไททัน ภาค 3 Part 1".
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 3, AOT_CHAIN)?.id, 99147);
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 4, AOT_CHAIN)?.id, 110277);
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 3, MUSHOKU_CHAIN)?.id, 178789);
// Only three real seasons have aired, so a fourth must not fall out of the list.
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 4, MUSHOKU_CHAIN.slice(0, 5)), null);
});
test('a TYBW cour marked only in a differently spelled synonym is not season 2', async () => {
const { result } = await resolveInChain(BLEACH_TYBW_CHAIN, {
title: 'BLEACH: Thousand-Year Blood War',
season: 2,
});
// Every sequel is a later cour of the same season, so there is no season 2 to find.
assert.equal(result?.seasonResolved, false);
assert.equal(result?.id, 116674);
});
test('an episode past the season entry lands on the split-cour part that airs it', async () => {
const mushoku = await resolveInChain(MUSHOKU_CHAIN, {
title: 'Mushoku Tensei: Jobless Reincarnation',
season: 1,
episode: 15,
});
assert.equal(mushoku.result?.id, 108465);
assert.equal(mushoku.result?.episodeEntry?.id, 127720);
assert.equal(mushoku.result?.episodeEntry?.episode, 4);
const mushokuS2 = await resolveInChain(MUSHOKU_CHAIN, {
title: 'Mushoku Tensei: Jobless Reincarnation',
season: 2,
episode: 20,
});
assert.equal(mushokuS2.result?.id, 146065);
assert.equal(mushokuS2.result?.episodeEntry?.id, 166873);
assert.equal(mushokuS2.result?.episodeEntry?.episode, 7);
// Three cours of 13 + 13 + 14: episode 28 is the third cour's second.
const bleach = await resolveInChain(BLEACH_TYBW_CHAIN, {
title: 'BLEACH: Thousand-Year Blood War',
episode: 28,
});
assert.equal(bleach.result?.id, 116674);
assert.equal(bleach.result?.episodeEntry?.id, 169755);
assert.equal(bleach.result?.episodeEntry?.episode, 2);
});
test('an episode inside the season entry needs no remap or relation lookup', async () => {
const { result, relationLookups } = await resolveInChain(MUSHOKU_CHAIN, {
title: 'Mushoku Tensei: Jobless Reincarnation',
season: 1,
episode: 5,
});
assert.equal(result?.id, 108465);
assert.equal(result?.episodeEntry, null);
assert.deepEqual(relationLookups, []);
});
test('an episode past a season with no continuation is not moved into the next season', async () => {
const { result } = await resolveInChain(OVERLORD_CHAIN, {
title: 'Overlord',
season: 1,
episode: 20,
});
assert.equal(result?.id, 20832);
assert.equal(result?.episodeEntry, null);
});
test('a sequel naming its own season is not a back half, even with a part synonym', async () => {
const sequel: AnilistSeasonMedia = {
id: 2,
episodes: 12,
format: 'TV',
seasonYear: 2022,
title: { english: 'Part Synonym Show Season 2' },
synonyms: ['Part Synonym Show Part 2'],
};
// The anchor names season 1 itself...
const named = await resolveInChain(
[
{
id: 1,
episodes: 12,
format: 'TV',
seasonYear: 2020,
title: { english: 'Part Synonym Show' },
synonyms: ['Part Synonym Show Season 1'],
},
sequel,
],
{ title: 'Part Synonym Show', season: 2 },
);
assert.equal(named.result?.id, 2);
// ...or is season 1 because the walk starts there.
const unnamed = await resolveInChain(
[
{
id: 1,
episodes: 12,
format: 'TV',
seasonYear: 2020,
title: { english: 'Part Synonym Show' },
},
sequel,
],
{ title: 'Part Synonym Show', season: 2 },
);
assert.equal(unnamed.result?.id, 2);
});
test('air order keeps a sequel naming its own season despite a part synonym', () => {
const anchor: AnilistSeasonMedia = {
id: 1,
episodes: 12,
format: 'TV',
seasonYear: 2020,
title: { english: 'Air Order Show' },
};
const sequel: AnilistSeasonMedia = {
id: 2,
episodes: 12,
format: 'TV',
seasonYear: 2022,
title: { english: 'Air Order Show Season 2' },
synonyms: ['Air Order Show Part 2'],
};
assert.equal(pickByAirOrder(anchor, 2, [anchor, sequel])?.id, 2);
});
test('a season 1 episode past its length does not move to a longer later season', async () => {
const { result } = await resolveInChain(
[
{
id: 1,
episodes: 12,
format: 'TV',
seasonYear: 2020,
title: { english: 'Long Later Show' },
},
{
id: 2,
episodes: 24,
format: 'TV',
seasonYear: 2022,
title: { english: 'Long Later Show Season 2' },
},
],
{ title: 'Long Later Show', season: 1, episode: 20 },
);
assert.equal(result?.id, 1);
assert.equal(result?.episodeEntry, null);
});
test('a sequel that repeats its predecessor name is still a new season', async () => {
// No part marker, so the identical title must not be read as a continuation.
const chain: AnilistSeasonMedia[] = [
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Same Name Show' } },
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Same Name Show' } },
];
const { result } = await resolveInChain(chain, { title: 'Same Name Show', season: 2 });
assert.equal(result?.id, 2);
assert.equal(result?.seasonResolved, true);
});
test('a rate limit mid-walk is surfaced instead of answered from air order', async () => {
const { execute } = createChainExecutor(MUSHOKU_CHAIN);
let relationCalls = 0;
const failing = async <T>(query: string, variables: Record<string, unknown>): Promise<T> => {
if (query === ANILIST_SEASON_RELATIONS_QUERY && ++relationCalls === 2) {
throw new Error('AniList rate limited (429)');
}
return execute<T>(query, variables);
};
// Air order alone would answer season 3 correctly from this search result, but it must
// not answer from a franchise picture the failed walk never confirmed.
await assert.rejects(
resolveAnilistSeasonMedia(
{ title: 'Mushoku Tensei: Jobless Reincarnation', season: 3 },
{ execute: failing },
),
/429/,
);
});
+452 -132
View File
@@ -9,6 +9,14 @@ import { sanitizeMediaTitle } from '../../../shared/media-identity';
* season 1 anchor and then walking AniList SEQUEL relations, with an air-order fallback * 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 * 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. * 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'; import { normalizeTitleIdentity } from '../../utils/title-normalization';
@@ -35,9 +43,29 @@ export type AnilistQueryExecutor = <T>(
variables: Record<string, unknown>, variables: Record<string, unknown>,
) => Promise<T>; ) => 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 { 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; id: number;
title: string; title: string;
episodes: number | null; episodes: number | null;
@@ -48,6 +76,8 @@ export interface AnilistSeasonResolution {
via: AnilistSeasonResolutionVia; via: AnilistSeasonResolutionVia;
/** Exact normalized match against an AniList title or synonym. */ /** Exact normalized match against an AniList title or synonym. */
exactTitleMatch: boolean; exactTitleMatch: boolean;
/** Set only when the parsed episode belongs to a later part of the season. */
episodeEntry: AnilistEpisodeEntry | null;
} }
export interface ResolveAnilistSeasonMediaInput { export interface ResolveAnilistSeasonMediaInput {
@@ -119,8 +149,79 @@ interface AnilistSeasonRelationsResponse {
/** Formats that can carry a numbered TV season, best first. */ /** Formats that can carry a numbered TV season, best first. */
const SEASONAL_FORMAT_PRIORITY = ['TV', 'TV_SHORT', 'ONA']; 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; 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, * 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". * 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(); .trim();
} }
function mediaTitles(media: AnilistSeasonMedia): string[] { /**
const synonyms = Array.isArray(media.synonyms) ? media.synonyms : []; * Splits a trailing part/cour marker off a title, or returns null when it has none.
return [media.title?.english, media.title?.romaji, media.title?.native, ...synonyms] *
* "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) .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
.map((value) => normalizeTitleIdentity(value)); .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 { function displayTitle(media: AnilistSeasonMedia, fallback: string): string {
return ( return (
media.title?.english?.trim() || media.title?.english?.trim() ||
@@ -167,29 +320,64 @@ function isSeasonalFormat(media: AnilistSeasonMedia): boolean {
return SEASONAL_FORMAT_PRIORITY.includes(format); return SEASONAL_FORMAT_PRIORITY.includes(format);
} }
function formatRank(media: AnilistSeasonMedia): number { /** Whether an entry can be a season: a TV series, or an ONA long enough not to be a special. */
const index = SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase()); function isSeasonEntry(media: AnilistSeasonMedia): boolean {
return index < 0 ? SEASONAL_FORMAT_PRIORITY.length : index; 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( function formatRank(media: AnilistSeasonMedia): number {
media: AnilistSeasonMedia, if (!isSeasonEntry(media)) return SEASONAL_FORMAT_PRIORITY.length;
fallbackTitle: string, return SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
season: number | null, }
via: AnilistSeasonResolutionVia,
seasonResolved: boolean, /**
exactTitleMatch: boolean, * Whether `next` continues the season `seasonStart` began rather than starting a new one.
): AnilistSeasonResolution { *
return { * Compared against the season's first entry, not the previous hop, so a special between
id: media.id, * a season and its second cour cannot hide the link. The marker is required, not just a
title: displayTitle(media, fallbackTitle), * matching base: a sequel that repeats its predecessor's name exactly is a new season
episodes: episodeCount(media), * AniList did not number. "Part 1" never marks a back half, and a season's own marker is
media, * only stripped when it is "Part 1" (AoT season 3 carries "... ภาค 3 Part 1"); stripping
seasonResolved, * any number would read JoJo's "Part 6" as a continuation of its "Part 5".
requestedSeason: season, *
via, * An entry naming a season never continues a different one: "Show Season 2" with the
exactTitleMatch, * 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; return scored[0]?.entry ?? null;
} }
async function walkSequelChain( /** SEQUEL entries of a media id, minus those already visited, best continuation first. */
anchor: AnilistSeasonMedia, type SequelLookup = (id: number, visited: Set<number>) => Promise<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;
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>( const response = await deps.execute<AnilistSeasonRelationsResponse>(
ANILIST_SEASON_RELATIONS_QUERY, ANILIST_SEASON_RELATIONS_QUERY,
{ id: current.id }, { id },
); );
const sequels: AnilistSeasonMedia[] = [];
const sequels = (response.Media?.relations?.edges ?? []) for (const edge of response.Media?.relations?.edges ?? []) {
.map((edge) => edge ?? null) const node = edge?.node;
.filter( if (!node || typeof node.id !== 'number') continue;
( if ((edge.relationType || '').toUpperCase() !== 'SEQUEL') continue;
edge, if ((node.type || 'ANIME').toUpperCase() !== 'ANIME') continue;
): edge is { sequels.push(node);
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;
} }
return sequels.sort((a, b) => {
// A franchise can branch (a TV sequel plus an ONA spinoff); prefer the TV line.
sequels.sort((a, b) => {
const rankDelta = formatRank(a) - formatRank(b); const rankDelta = formatRank(a) - formatRank(b);
if (rankDelta !== 0) return rankDelta; if (rankDelta !== 0) return rankDelta;
const yearDelta = const yearDelta =
@@ -300,12 +470,121 @@ async function walkSequelChain(
if (yearDelta !== 0) return yearDelta; if (yearDelta !== 0) return yearDelta;
return a.id - b.id; 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]!; type ChainResult = { media: AnilistSeasonMedia; via: 'named-season' | 'sequel-chain' };
visited.add(current.id);
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, season: number,
media: AnilistSeasonMedia[], media: AnilistSeasonMedia[],
): AnilistSeasonMedia | null { ): AnilistSeasonMedia | null {
const anchorTitles = mediaTitles(anchor).map((value) => stripSeasonSuffix(value)); // Any of the anchor's main titles, matched on word boundaries. Synonyms are too short
const anchorBase = anchorTitles.sort((a, b) => a.length - b.length)[0]; // and loose ("SnK", "ReZero") to define a franchise, and a single title misses entries
if (!anchorBase) return null; // 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) => { const franchise = media.filter((entry) => {
if (!isSeasonalFormat(entry)) return false; if (!isSeasonEntry(entry)) return false;
if (entry.id === anchor.id) return true; if (entry.id === anchor.id) return true;
return mediaTitles(entry).some((candidate) => return mediaTitles(entry).some((candidate) => {
stripSeasonSuffix(candidate).includes(anchorBase), 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 // 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. // 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); const yearDelta = (airYear(a) ?? 0) - (airYear(b) ?? 0);
if (yearDelta !== 0) return yearDelta; if (yearDelta !== 0) return yearDelta;
return a.id - b.id; 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. // The anchor has to be the first entry, otherwise this ordering is not a season list.
if (ordered[0]?.id !== anchor.id) return null; 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( export async function resolveAnilistSeasonMedia(
@@ -359,6 +664,10 @@ export async function resolveAnilistSeasonMedia(
typeof input.season === 'number' && Number.isInteger(input.season) && input.season > 0 typeof input.season === 'number' && Number.isInteger(input.season) && input.season > 0
? input.season ? input.season
: null; : 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, { const response = await deps.execute<AnilistSeasonSearchResponse>(ANILIST_SEASON_SEARCH_QUERY, {
search: searchTitle, search: searchTitle,
@@ -368,72 +677,83 @@ export async function resolveAnilistSeasonMedia(
); );
if (media.length === 0) return null; if (media.length === 0) return null;
// Season 1 (or unknown) resolves against the episode count; later seasons must not, // Certifies the media actually returned, never the anchor on its behalf: a hop can land
// because the anchor is season 1 and may be shorter than the requested episode. // on the wrong entry while the anchor title still matches perfectly, and that certainty
const anchor = pickAnchorMedia(searchTitle, media, { // must not carry over to the hopped-to entry.
episode: season === null || season <= 1 ? input.episode : null, const parsedTitles = [searchTitle, input.title];
}); const sequelsOf = createSequelLookup(deps);
if (!anchor) return null;
// Certifies the media actually returned, never the anchor on its behalf: a const finish = (
// sequel-chain hop can land one season short (split-cour entries) while the seasonEntry: AnilistSeasonMedia,
// anchor title still matches perfectly, and that certainty must not carry via: AnilistSeasonResolutionVia,
// over to the hopped-to entry. split: { media: AnilistSeasonMedia; episode: number } | null = null,
const exactMatchFor = (candidate: AnilistSeasonMedia): boolean => { seasonResolved = true,
const titles = mediaTitles(candidate); ): AnilistSeasonResolution => {
return ( if (split) {
titles.includes(normalizeTitleIdentity(searchTitle)) || deps.logInfo?.(
titles.includes(normalizeTitleIdentity(input.title)) `[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) { 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; // Later seasons must not filter by episode, because the anchor is season 1 and may be
let viaChain: AnilistSeasonMedia | null = null; // shorter than the requested episode.
try { const anchor = pickAnchorMedia(searchTitle, media);
viaChain = await walkSequelChain(anchor, season, deps); if (!anchor) return null;
} catch (error) {
chainError = error; // 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
if (viaChain) { // 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?.( 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( const split =
viaChain, episode === null ? null : await findEpisodeEntry(seasonEntry, season, episode, sequelsOf);
searchTitle, return finish(seasonEntry, via, split);
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;
} }
deps.logInfo?.( deps.logInfo?.(
`[anilist] could not resolve season ${season} of "${searchTitle}"; falling back to ${displayTitle(anchor, searchTitle)} (${anchor.id})`, `[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);
} }
-154
View File
@@ -1,154 +0,0 @@
import assert from 'node:assert/strict';
import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
appendManagedFfmpegToPath,
detectFfmpeg,
getManagedFfmpegDir,
installManagedFfmpeg,
} from './managed-ffmpeg';
async function withTempDirs(run: (dirs: { system: string; managed: string }) => Promise<void>) {
const root = await mkdtemp(path.join(tmpdir(), 'managed-ffmpeg-'));
const dirs = { system: path.join(root, 'bin'), managed: getManagedFfmpegDir(root) };
await mkdir(dirs.system, { recursive: true });
await mkdir(dirs.managed, { recursive: true });
try {
await run(dirs);
} finally {
await rm(root, { recursive: true, force: true });
}
}
async function writeExecutable(directory: string, name: string): Promise<void> {
const filePath = path.join(directory, name);
await writeFile(filePath, '#!/bin/sh\n');
await chmod(filePath, 0o755);
}
const passVersionCheck = async () => undefined;
test('managed FFmpeg is appended to PATH once, behind system entries, only when downloaded', async () => {
await withTempDirs(async ({ system, managed }) => {
const env: NodeJS.ProcessEnv = { Path: system };
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), false);
await writeExecutable(managed, 'ffmpeg');
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), true);
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), false);
// Writes the existing key (Windows spells it Path) instead of adding a second one.
assert.deepEqual(env, { Path: [system, managed].join(path.delimiter) });
});
});
test('detectFfmpeg prefers system tools and fills gaps from the managed copy', async () => {
await withTempDirs(async ({ system, managed }) => {
const env = { PATH: [system, managed].join(path.delimiter) };
const detect = () =>
detectFfmpeg({
managedDir: managed,
env,
platform: 'linux',
arch: 'x64',
runVersionCheck: passVersionCheck,
});
assert.deepEqual(await detect(), {
kind: 'missing',
missing: ['ffmpeg', 'ffprobe'],
downloadable: true,
});
await writeExecutable(system, 'ffmpeg');
await writeExecutable(managed, 'ffprobe');
assert.deepEqual(await detect(), {
kind: 'ready',
source: 'managed',
ffmpegPath: path.join(system, 'ffmpeg'),
ffprobePath: path.join(managed, 'ffprobe'),
});
await writeExecutable(system, 'ffprobe');
const status = await detect();
assert.equal(status.kind === 'ready' ? status.source : status.kind, 'system');
});
});
test('detectFfmpeg reports a tool that is found but fails to run', async () => {
await withTempDirs(async ({ managed }) => {
await writeExecutable(managed, 'ffmpeg');
await writeExecutable(managed, 'ffprobe');
const status = await detectFfmpeg({
managedDir: managed,
env: { PATH: managed },
platform: 'freebsd',
arch: 'x64',
runVersionCheck: async () => {
throw new Error('Killed: 9');
},
});
assert.deepEqual(status, {
kind: 'broken',
path: path.join(managed, 'ffmpeg'),
message: 'Killed: 9',
managed: true,
downloadable: false,
});
});
});
test('detectFfmpeg reports a broken system tool before offering a download for its companion', async () => {
await withTempDirs(async ({ system, managed }) => {
await writeExecutable(system, 'ffmpeg');
const detect = (runVersionCheck: (executablePath: string) => Promise<void>) =>
detectFfmpeg({
managedDir: managed,
env: { PATH: system },
platform: 'linux',
arch: 'x64',
runVersionCheck,
});
// A download would only add ffprobe; the broken system ffmpeg would still shadow it.
assert.deepEqual(
await detect(async () => {
throw new Error('exit 127');
}),
{
kind: 'broken',
path: path.join(system, 'ffmpeg'),
message: 'exit 127',
managed: false,
downloadable: true,
},
);
assert.deepEqual(await detect(passVersionCheck), {
kind: 'missing',
missing: ['ffprobe'],
downloadable: true,
});
});
});
test('installManagedFfmpeg rejects unsupported platforms and never publishes a failed download', async () => {
await withTempDirs(async ({ managed }) => {
await assert.rejects(
installManagedFfmpeg({ managedDir: managed, platform: 'freebsd', arch: 'x64' }),
/no FFmpeg download for freebsd-x64/,
);
const originalFetch = globalThis.fetch;
globalThis.fetch = Object.assign(async () => new Response('not ffmpeg'), originalFetch);
try {
await assert.rejects(
installManagedFfmpeg({ managedDir: managed, platform: 'linux', arch: 'x64' }),
/FFmpeg failed integrity verification/,
);
} finally {
globalThis.fetch = originalFetch;
}
assert.deepEqual(await readdir(managed), []);
});
});
-222
View File
@@ -1,222 +0,0 @@
import { execFile } from 'node:child_process';
import { createReadStream, createWriteStream, existsSync } from 'node:fs';
import { chmod, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';
import { createGunzip } from 'node:zlib';
import { downloadSubtitleGenerationArtifact } from './subtitle-generation-download';
import { findOnPath } from './subtitle-generation-tools';
/**
* SubMiner can download its own FFmpeg when none is usable on PATH. The copy lives in
* `<configDir>/tools/ffmpeg` and is appended to PATH at startup, so a system FFmpeg always
* wins and every bare `ffmpeg`/`ffprobe` spawn picks up the download otherwise.
*/
export type FfmpegTool = 'ffmpeg' | 'ffprobe';
const FFMPEG_TOOLS: readonly FfmpegTool[] = ['ffmpeg', 'ffprobe'];
/** Pinned ffmpeg-static release: single gzipped static binaries per platform. */
const MANAGED_FFMPEG_RELEASE_URL =
'https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1';
type ManagedAsset = { size: number; sha256: string };
const MANAGED_FFMPEG_ASSETS = {
'linux-x64': {
ffmpeg: {
size: 29354986,
sha256: 'bfe8a8fc511530457b528c48d77b5737527b504a3797a9bc4866aeca69c2dffa',
},
ffprobe: {
size: 29276839,
sha256: '25d9b6ccb05e3d9de9e04e31e2506d8dd7f9f0418981965ac6df12e8d3afd067',
},
},
'linux-arm64': {
ffmpeg: {
size: 25568691,
sha256: '754a678672298bc68156adff58aa7385a592c2b30b1d0ae8750c45c915c4bac0',
},
ffprobe: {
size: 25493573,
sha256: '2ab6aba60ee84412dff9188720703376cb4e7aaf7e0b5e43aa8249f2acae5bf8',
},
},
'darwin-x64': {
ffmpeg: {
size: 25296431,
sha256: '929b375c1182d956c51f7ac25e0b2b0411fb01f6f407aa15c9758efeb4242106',
},
ffprobe: {
size: 25239438,
sha256: 'd4da574d6e2e197bd259b47d69cf262df9e312af24ad960444f6d806d3d4c186',
},
},
'darwin-arm64': {
ffmpeg: {
size: 19246198,
sha256: '8923876afa8db5585022d7860ec7e589af192f441c56793971276d450ed3bbfa',
},
ffprobe: {
size: 19207077,
sha256: 'd986a8ec7b030899fe66a8a288ed809a3543338705a3ce178cfb85869c5d80be',
},
},
'win32-x64': {
ffmpeg: {
size: 29581307,
sha256: '8883a3dffbd0a16cf4ef95206ea05283f78908dbfb118f73c83f4951dcc06d77',
},
ffprobe: {
size: 29521644,
sha256: 'f309e6223ad89d2fe54bccd420a7709b66fd27540674e92309578ed491a43c8d',
},
},
} as const satisfies Record<string, Record<FfmpegTool, ManagedAsset>>;
type ManagedFfmpegTarget = keyof typeof MANAGED_FFMPEG_ASSETS;
function getManagedFfmpegTarget(
platform: NodeJS.Platform,
arch: string,
): ManagedFfmpegTarget | null {
// Windows on ARM runs the x64 build through emulation; there is no native arm64 build.
const key = platform === 'win32' && arch === 'arm64' ? 'win32-x64' : `${platform}-${arch}`;
return key in MANAGED_FFMPEG_ASSETS ? (key as ManagedFfmpegTarget) : null;
}
export function getManagedFfmpegDir(configDir: string): string {
return path.join(configDir, 'tools', 'ffmpeg');
}
function managedBinaryPath(
managedDir: string,
tool: FfmpegTool,
platform: NodeJS.Platform,
): string {
return path.join(managedDir, platform === 'win32' ? `${tool}.exe` : tool);
}
function pathKey(env: NodeJS.ProcessEnv): string {
return Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'PATH';
}
/**
* Appends the managed FFmpeg directory to `env`'s PATH when a download exists there.
* Appending keeps a system FFmpeg in front. Returns whether PATH changed.
*/
export function appendManagedFfmpegToPath(
env: NodeJS.ProcessEnv,
managedDir: string,
platform: NodeJS.Platform = process.platform,
): boolean {
if (!existsSync(managedBinaryPath(managedDir, 'ffmpeg', platform))) return false;
const key = pathKey(env);
const entries = (env[key] ?? '').split(path.delimiter).filter(Boolean);
if (entries.some((entry) => path.resolve(entry) === path.resolve(managedDir))) return false;
env[key] = [...entries, managedDir].join(path.delimiter);
return true;
}
export type FfmpegSetupStatus =
| { kind: 'ready'; source: 'system' | 'managed'; ffmpegPath: string; ffprobePath: string }
| { kind: 'missing'; missing: FfmpegTool[]; downloadable: boolean }
/** Found on PATH but `-version` failed. Only a broken managed copy is fixed by downloading. */
| { kind: 'broken'; path: string; message: string; managed: boolean; downloadable: boolean };
export type RunVersionCheck = (executablePath: string) => Promise<void>;
const runVersionCheckDefault: RunVersionCheck = (executablePath) =>
new Promise((resolve, reject) => {
// Generous timeout: Windows Defender scans a fresh 80 MB exe on first launch.
execFile(executablePath, ['-version'], { timeout: 15_000 }, (error) =>
error ? reject(error) : resolve(),
);
});
/** Whether SubMiner can run FFmpeg and FFprobe from the current PATH, and where they come from. */
export async function detectFfmpeg(options: {
managedDir: string;
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
arch?: string;
runVersionCheck?: RunVersionCheck;
}): Promise<FfmpegSetupStatus> {
const env = options.env ?? process.env;
const platform = options.platform ?? process.platform;
const runVersionCheck = options.runVersionCheck ?? runVersionCheckDefault;
const downloadable = getManagedFfmpegTarget(platform, options.arch ?? process.arch) !== null;
const isManaged = (filePath: string) =>
path.resolve(path.dirname(filePath)) === path.resolve(options.managedDir);
const found = await Promise.all(FFMPEG_TOOLS.map((tool) => findOnPath([tool], env)));
// Check what was found before reporting gaps: a broken system tool shadows any download.
for (const executablePath of found.filter(Boolean)) {
try {
await runVersionCheck(executablePath);
} catch (error) {
return {
kind: 'broken',
path: executablePath,
message: error instanceof Error ? error.message : String(error),
managed: isManaged(executablePath),
downloadable,
};
}
}
const missing = FFMPEG_TOOLS.filter((_, index) => !found[index]);
if (missing.length > 0) return { kind: 'missing', missing, downloadable };
const [ffmpegPath, ffprobePath] = found as [string, string];
return {
kind: 'ready',
source: isManaged(ffmpegPath) || isManaged(ffprobePath) ? 'managed' : 'system',
ffmpegPath,
ffprobePath,
};
}
/**
* Downloads, verifies, and unpacks FFmpeg and FFprobe into `managedDir`, replacing any
* earlier download. Callers append `managedDir` to PATH afterwards.
*/
export async function installManagedFfmpeg(options: {
managedDir: string;
platform?: NodeJS.Platform;
arch?: string;
}): Promise<void> {
const platform = options.platform ?? process.platform;
const arch = options.arch ?? process.arch;
const target = getManagedFfmpegTarget(platform, arch);
if (!target) {
throw new Error(
`SubMiner has no FFmpeg download for ${platform}-${arch}. Install FFmpeg yourself.`,
);
}
await mkdir(options.managedDir, { recursive: true });
const staging = await mkdtemp(path.join(options.managedDir, '.install-'));
try {
const unpacked: Array<[string, string]> = [];
for (const tool of FFMPEG_TOOLS) {
const asset = MANAGED_FFMPEG_ASSETS[target][tool];
const archivePath = path.join(staging, `${tool}.gz`);
await downloadSubtitleGenerationArtifact({
url: `${MANAGED_FFMPEG_RELEASE_URL}/${tool}-${target}.gz`,
size: asset.size,
sha256: asset.sha256,
destination: archivePath,
label: tool === 'ffmpeg' ? 'FFmpeg' : 'FFprobe',
});
const binaryPath = managedBinaryPath(staging, tool, platform);
await pipeline(createReadStream(archivePath), createGunzip(), createWriteStream(binaryPath));
await chmod(binaryPath, 0o755);
unpacked.push([binaryPath, managedBinaryPath(options.managedDir, tool, platform)]);
}
// Publish only after both tools verified, so a failed download never leaves half a pair.
for (const [from, to] of unpacked) await rename(from, to);
} finally {
await rm(staging, { recursive: true, force: true });
}
}
@@ -18,12 +18,12 @@ export async function downloadSubtitleGenerationArtifact(input: {
const temporaryDirectory = await mkdtemp( const temporaryDirectory = await mkdtemp(
path.join(path.dirname(input.destination), '.download-'), path.join(path.dirname(input.destination), '.download-'),
); );
const temporaryPath = path.join(temporaryDirectory, 'artifact.bin'); const temporaryPath = path.join(temporaryDirectory, 'model.bin');
input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` }); input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` });
try { try {
const response = await fetch(input.url, { signal: input.signal }); const response = await fetch(input.url, { signal: input.signal });
if (!response.ok || !response.body) { if (!response.ok || !response.body) {
throw new Error(`${input.label} download failed: HTTP ${response.status}`); throw new Error(`Model download failed: HTTP ${response.status}`);
} }
const file = await open(temporaryPath, 'wx'); const file = await open(temporaryPath, 'wx');
const reader = response.body.getReader(); const reader = response.body.getReader();
@@ -36,8 +36,7 @@ export async function downloadSubtitleGenerationArtifact(input: {
const { done, value } = await reader.read(); const { done, value } = await reader.read();
if (done) break; if (done) break;
received += value.byteLength; received += value.byteLength;
if (received > input.size) if (received > input.size) throw new Error('Downloaded model exceeds expected size.');
throw new Error(`Downloaded ${input.label} exceeds expected size.`);
digest.update(value); digest.update(value);
await file.writeFile(value); await file.writeFile(value);
const percent = Math.min(99, Math.floor((received / input.size) * 100)); const percent = Math.min(99, Math.floor((received / input.size) * 100));
@@ -51,9 +50,7 @@ export async function downloadSubtitleGenerationArtifact(input: {
} }
} }
if (received !== input.size || digest.digest('hex') !== input.sha256) { if (received !== input.size || digest.digest('hex') !== input.sha256) {
throw new Error( throw new Error('Downloaded model failed integrity verification. Try downloading again.');
`Downloaded ${input.label} failed integrity verification. Try downloading again.`,
);
} }
await file.sync(); await file.sync();
} finally { } finally {
@@ -46,11 +46,7 @@ function executableNames(name: string, env: NodeJS.ProcessEnv): string[] {
return [name, ...extensions.map((extension) => `${name}${extension}`)]; return [name, ...extensions.map((extension) => `${name}${extension}`)];
} }
/** First executable on `env.PATH` matching any of `names` (PATHEXT-aware on Windows), or ''. */ async function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv): Promise<string> {
export async function findOnPath(
names: readonly string[],
env: NodeJS.ProcessEnv,
): Promise<string> {
const directories = (env.PATH ?? '') const directories = (env.PATH ?? '')
.split(path.delimiter) .split(path.delimiter)
.map((entry) => entry.trim()) .map((entry) => entry.trim())
-4
View File
@@ -155,7 +155,6 @@ import { createSyncAssembly } from './main/assemblies/sync';
import { createYoutubeAssembly } from './main/assemblies/youtube'; import { createYoutubeAssembly } from './main/assemblies/youtube';
import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals'; import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals';
import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup'; import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup';
import { appendManagedFfmpegToPath, getManagedFfmpegDir } from './core/services/managed-ffmpeg';
import { createOverlayAssembly } from './main/assemblies/overlay'; import { createOverlayAssembly } from './main/assemblies/overlay';
import { createYomitanAssembly } from './main/assemblies/yomitan'; import { createYomitanAssembly } from './main/assemblies/yomitan';
import { createStatsAssembly } from './main/assemblies/stats'; import { createStatsAssembly } from './main/assemblies/stats';
@@ -429,8 +428,6 @@ const {
appState, appState,
appLifecycleApp, appLifecycleApp,
} = bootServices; } = bootServices;
// Before any ffmpeg/ffprobe spawn: a system FFmpeg stays first, the setup-page download fills in.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(CONFIG_DIR));
// Backend changes take effect on restart; windows and parser must share one session. // Backend changes take effect on restart; windows and parser must share one session.
const activeDictionaryBackend = configService.getConfig().dictionaryBackend; const activeDictionaryBackend = configService.getConfig().dictionaryBackend;
const yomitan = createYomitanAssembly({ const yomitan = createYomitanAssembly({
@@ -691,7 +688,6 @@ const firstRunSetup = createFirstRunSetupAssembly({
ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(), ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(),
getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(), getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(),
createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(), createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(),
waitForLoginShellPath: () => loginShellPathReady,
getAppPath: (name) => app.getPath(name), getAppPath: (name) => app.getPath(name),
trashItem: (targetPath) => shell.trashItem(targetPath), trashItem: (targetPath) => shell.trashItem(targetPath),
writeShortcutLink: (shortcutPath, operation, details) => writeShortcutLink: (shortcutPath, operation, details) =>
@@ -30,7 +30,6 @@ function makeDeps(configDir: string): FirstRunSetupAssemblyDeps {
ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'), ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'),
getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'), getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'),
createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'), createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'),
waitForLoginShellPath: lazy('waitForLoginShellPath'),
getAppPath: lazy('getAppPath'), getAppPath: lazy('getAppPath'),
trashItem: lazy('trashItem'), trashItem: lazy('trashItem'),
writeShortcutLink: lazy('writeShortcutLink'), writeShortcutLink: lazy('writeShortcutLink'),
-32
View File
@@ -1,12 +1,6 @@
import os from 'node:os'; import os from 'node:os';
import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron'; import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron';
import type { ConfigService } from '../../config/service'; import type { ConfigService } from '../../config/service';
import {
appendManagedFfmpegToPath,
detectFfmpeg,
getManagedFfmpegDir,
installManagedFfmpeg,
} from '../../core/services/managed-ffmpeg';
import { getYomitanDictionaryInfo } from '../../core/services'; import { getYomitanDictionaryInfo } from '../../core/services';
import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime'; import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime';
import type { Logger } from '../../logger'; import type { Logger } from '../../logger';
@@ -68,8 +62,6 @@ export interface FirstRunSetupAssemblyDeps {
getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps; getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps;
/** Resolves the launcher options after the login-shell PATH is applied. */ /** Resolves the launcher options after the login-shell PATH is applied. */
createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>; createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>;
/** Resolves once the macOS login-shell PATH is merged, so FFmpeg detection sees it. */
waitForLoginShellPath: () => Promise<void>;
getAppPath: (name: 'appData' | 'desktop') => string; getAppPath: (name: 'appData' | 'desktop') => string;
trashItem: (targetPath: string) => Promise<void>; trashItem: (targetPath: string) => Promise<void>;
writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink']; writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink'];
@@ -91,23 +83,6 @@ export type FirstRunSetupAssembly = ReturnType<typeof createFirstRunSetupAssembl
export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) { export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
const { appState, configService, logger } = deps; const { appState, configService, logger } = deps;
let firstRunSetupMessage: string | null = null; let firstRunSetupMessage: string | null = null;
const managedFfmpegDir = getManagedFfmpegDir(deps.configDir);
// Shared by repeat clicks so a second press never starts a parallel download.
let ffmpegInstall: Promise<string> | null = null;
const installFfmpeg = (): Promise<string> =>
(ffmpegInstall ??= installManagedFfmpeg({ managedDir: managedFfmpegDir })
.then(() => {
appendManagedFfmpegToPath(process.env, managedFfmpegDir);
logger.info(`[ffmpeg] Downloaded FFmpeg to ${managedFfmpegDir}`);
return 'FFmpeg downloaded. SubMiner uses it whenever FFmpeg is not on PATH.';
})
.catch((error: unknown) => {
logger.error('[ffmpeg] FFmpeg download failed', error);
return `FFmpeg download failed: ${error instanceof Error ? error.message : String(error)}`;
})
.finally(() => {
ffmpegInstall = null;
}));
const resolveWindowsMpvShortcutRuntimePaths = () => const resolveWindowsMpvShortcutRuntimePaths = () =>
resolveWindowsMpvShortcutPaths({ resolveWindowsMpvShortcutPaths({
appDataDir: deps.getAppPath('appData'), appDataDir: deps.getAppPath('appData'),
@@ -257,9 +232,6 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath), mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath),
windowsMpvShortcuts: snapshot.windowsMpvShortcuts, windowsMpvShortcuts: snapshot.windowsMpvShortcuts,
commandLineLauncher: snapshot.commandLineLauncher, commandLineLauncher: snapshot.commandLineLauncher,
ffmpeg: await deps
.waitForLoginShellPath()
.then(() => detectFfmpeg({ managedDir: managedFfmpegDir })),
message: firstRunSetupMessage, message: firstRunSetupMessage,
}; };
}, },
@@ -332,10 +304,6 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
firstRunSetupMessage = snapshot.message; firstRunSetupMessage = snapshot.message;
return; return;
} }
if (submission.action === 'install-ffmpeg') {
firstRunSetupMessage = await installFfmpeg();
return;
}
if (submission.action === 'open-yomitan-settings') { if (submission.action === 'open-yomitan-settings') {
firstRunSetupMessage = deps.openDictionarySettings() firstRunSetupMessage = deps.openDictionarySettings()
? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.` ? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.`
@@ -4,7 +4,13 @@ import * as os from 'os';
import * as path from 'path'; import * as path from 'path';
import test from 'node:test'; import test from 'node:test';
import { isDeepStrictEqual } from 'node:util'; 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 { CHARACTER_DICTIONARY_FORMAT_VERSION } from './constants';
import type { CharacterDictionarySnapshot } from './types'; 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); assert.equal(await readSnapshot(snapshotPath), null);
}); });
test('media resolutions cached before the season resolver fix are re-resolved', () => {
const outputDir = makeTempDir();
const cachePath = path.join(outputDir, 'anilist-resolution-cache.json');
// Written by the old resolver, which counted "Season 2 Part 2" as season 3.
fs.writeFileSync(
cachePath,
JSON.stringify({
entries: [{ seriesKey: 'mushoku-tensei-s3', mediaId: 166873, mediaTitle: 'Part 2' }],
}),
);
assert.equal(readCachedMediaResolution(outputDir, 'mushoku-tensei-s3'), null);
const entry = { seriesKey: 'mushoku-tensei-s3', mediaId: 178789, mediaTitle: 'Season 3' };
writeCachedMediaResolution(outputDir, entry);
assert.deepEqual(readCachedMediaResolution(outputDir, 'mushoku-tensei-s3'), entry);
});
+14 -1
View File
@@ -28,9 +28,17 @@ type MediaResolutionCacheEntry = {
}; };
type MediaResolutionCacheFile = { type MediaResolutionCacheFile = {
version?: number;
entries?: MediaResolutionCacheEntry[]; 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 { function getMediaResolutionCachePath(outputDir: string): string {
return path.join(outputDir, 'anilist-resolution-cache.json'); return path.join(outputDir, 'anilist-resolution-cache.json');
} }
@@ -55,6 +63,7 @@ function readMediaResolutionEntries(outputDir: string): MediaResolutionCacheEntr
const parsed = JSON.parse( const parsed = JSON.parse(
fs.readFileSync(getMediaResolutionCachePath(outputDir), 'utf8'), fs.readFileSync(getMediaResolutionCachePath(outputDir), 'utf8'),
) as MediaResolutionCacheFile; ) as MediaResolutionCacheFile;
if (parsed.version !== MEDIA_RESOLUTION_CACHE_VERSION) return [];
if (!Array.isArray(parsed.entries)) return []; if (!Array.isArray(parsed.entries)) return [];
const byKey = new Map<string, MediaResolutionCacheEntry>(); const byKey = new Map<string, MediaResolutionCacheEntry>();
for (const value of parsed.entries) { for (const value of parsed.entries) {
@@ -74,7 +83,11 @@ function writeMediaResolutionEntries(
ensureDir(outputDir); ensureDir(outputDir);
fs.writeFileSync( fs.writeFileSync(
getMediaResolutionCachePath(outputDir), getMediaResolutionCachePath(outputDir),
JSON.stringify({ entries }, null, 2), JSON.stringify(
{ version: MEDIA_RESOLUTION_CACHE_VERSION, entries } satisfies MediaResolutionCacheFile,
null,
2,
),
'utf8', 'utf8',
); );
} }
@@ -7,14 +7,6 @@ import {
parseFirstRunSetupSubmissionUrl, parseFirstRunSetupSubmissionUrl,
} from './first-run-setup-window'; } from './first-run-setup-window';
import type { CommandLineLauncherSnapshot } from './command-line-launcher'; import type { CommandLineLauncherSnapshot } from './command-line-launcher';
import type { FfmpegSetupStatus } from '../../core/services/managed-ffmpeg';
const READY_FFMPEG: FfmpegSetupStatus = {
kind: 'ready',
source: 'system',
ffmpegPath: '/usr/bin/ffmpeg',
ffprobePath: '/usr/bin/ffprobe',
};
function createCommandLineLauncherSnapshot( function createCommandLineLauncherSnapshot(
overrides: Partial<CommandLineLauncherSnapshot> = {}, overrides: Partial<CommandLineLauncherSnapshot> = {},
@@ -60,7 +52,6 @@ test('buildFirstRunSetupHtml shows legacy mpv plugin removal action with confirm
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -99,7 +90,6 @@ test('buildFirstRunSetupHtml marks an invalid configured mpv path as invalid', (
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -127,7 +117,6 @@ test('buildFirstRunSetupHtml explains the config blocker when setup is missing c
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -157,7 +146,6 @@ test('buildFirstRunSetupHtml explains external yomitan mode and keeps finish ena
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -233,7 +221,6 @@ test('buildFirstRunSetupHtml reports a broken included runtime in the optional l
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
bun: { bun: {
status: 'failed', status: 'failed',
@@ -288,7 +275,6 @@ test('buildFirstRunSetupHtml labels a missing launcher without error-message wor
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
bun: { bun: {
status: 'ready', status: 'ready',
@@ -324,7 +310,6 @@ test('buildFirstRunSetupHtml disables launcher install when no target is install
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
launcher: { launcher: {
status: 'not_installable', status: 'not_installable',
@@ -418,7 +403,6 @@ test('opening first-run setup shows and focuses window after content loads', asy
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -485,7 +469,6 @@ test('opening first-run setup skips rendering if window is destroyed after snaps
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}; };
@@ -555,7 +538,6 @@ test('first-run setup action can skip rerender after launching another window',
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -638,7 +620,6 @@ test('closing incomplete first-run setup quits app outside background mode', asy
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -711,7 +692,6 @@ test('closing completed first-run setup quits app when completion policy allows
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -767,7 +747,6 @@ test('Hachidori setup names the active dictionary backend', () => {
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -796,55 +775,3 @@ test('setup parses link and unlink actions without losing the host address', ()
{ action: 'unlink-hachidori-host' }, { action: 'unlink-hachidori-host' },
); );
}); });
test('FFmpeg card offers a download only when one would be used', () => {
const render = (ffmpeg: FfmpegSetupStatus) =>
buildFirstRunSetupHtml({
configReady: true,
dictionaryCount: 1,
canFinish: true,
externalYomitanConfigured: false,
pluginStatus: 'installed',
pluginInstallPathSummary: null,
mpvExecutablePath: '',
mpvExecutablePathStatus: 'blank',
windowsMpvShortcuts: {
supported: false,
startMenuEnabled: false,
desktopEnabled: false,
startMenuInstalled: false,
desktopInstalled: false,
status: 'optional',
},
ffmpeg,
commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null,
});
const system = render(READY_FFMPEG);
assert.match(system, /Found on your system\. Nothing to do\./);
assert.match(system, /\/usr\/bin\/ffprobe/);
assert.doesNotMatch(system, /action=install-ffmpeg/);
const missing = render({ kind: 'missing', missing: ['ffprobe'], downloadable: true });
assert.match(missing, /Not found on PATH: ffprobe\./);
assert.match(missing, /action=install-ffmpeg/);
const unsupported = render({ kind: 'missing', missing: ['ffmpeg'], downloadable: false });
assert.match(unsupported, /No download is available for this platform/);
assert.doesNotMatch(unsupported, /action=install-ffmpeg/);
const broken = {
kind: 'broken',
path: '/x/ffmpeg',
message: 'exit 127',
downloadable: true,
} as const;
assert.doesNotMatch(render({ ...broken, managed: false }), /action=install-ffmpeg/);
assert.match(render({ ...broken, managed: true }), /Download FFmpeg again/);
assert.deepEqual(
parseFirstRunSetupSubmissionUrl('subminer://first-run-setup?action=install-ffmpeg'),
{ action: 'install-ffmpeg' },
);
});
@@ -1,4 +1,3 @@
import type { FfmpegSetupStatus } from '../../core/services/managed-ffmpeg';
import type { HachidoriHostStatus } from '../../shared/hachidori-sharing'; import type { HachidoriHostStatus } from '../../shared/hachidori-sharing';
import type { DictionaryBackend } from '../../types/config'; import type { DictionaryBackend } from '../../types/config';
import { getFirstRunSetupCompletionMessage } from './first-run-setup-service'; import { getFirstRunSetupCompletionMessage } from './first-run-setup-service';
@@ -35,7 +34,6 @@ export type FirstRunSetupSubmission =
| 'remove-legacy-plugin' | 'remove-legacy-plugin'
| 'install-bun' | 'install-bun'
| 'install-command-line-launcher' | 'install-command-line-launcher'
| 'install-ffmpeg'
| 'open-yomitan-settings' | 'open-yomitan-settings'
| 'open-config-settings' | 'open-config-settings'
| 'refresh' | 'refresh'
@@ -65,7 +63,6 @@ export interface FirstRunSetupHtmlModel {
status: 'installed' | 'optional' | 'skipped' | 'failed'; status: 'installed' | 'optional' | 'skipped' | 'failed';
}; };
commandLineLauncher: CommandLineLauncherSnapshot; commandLineLauncher: CommandLineLauncherSnapshot;
ffmpeg: FfmpegSetupStatus;
message: string | null; message: string | null;
} }
@@ -157,56 +154,6 @@ function renderCommandLineLauncherSection(
</section>`; </section>`;
} }
function renderFfmpegCard(ffmpeg: FfmpegSetupStatus): string {
const lines: string[] = [];
let badge: string;
let showDownload = false;
if (ffmpeg.kind === 'ready') {
lines.push(
ffmpeg.source === 'system'
? 'Found on your system. Nothing to do.'
: 'Using the copy SubMiner downloaded. Nothing to do.',
`FFmpeg: ${ffmpeg.ffmpegPath}`,
`FFprobe: ${ffmpeg.ffprobePath}`,
);
badge = renderStatusBadge(ffmpeg.source === 'system' ? 'Detected' : 'Downloaded', 'ready');
} else if (ffmpeg.kind === 'missing') {
lines.push(`Not found on PATH: ${ffmpeg.missing.join(', ')}.`);
lines.push(
ffmpeg.downloadable
? 'Download a copy for SubMiner (under 60 MB), or install FFmpeg yourself and refresh.'
: 'No download is available for this platform. Install FFmpeg, then refresh.',
);
badge = renderStatusBadge('Missing', 'warn');
showDownload = ffmpeg.downloadable;
} else {
lines.push(`${ffmpeg.path} failed to run: ${ffmpeg.message}`);
lines.push(
ffmpeg.managed
? 'Download it again to repair the copy SubMiner downloaded.'
: 'Repair or remove that FFmpeg install, then refresh.',
);
badge = renderStatusBadge('Not working', 'danger');
showDownload = ffmpeg.managed && ffmpeg.downloadable;
}
// The button relabels itself because the page only re-renders once the download finishes.
const downloadButton = showDownload
? `<div class="inline-actions"><button onclick="this.disabled = true; this.textContent = 'Downloading FFmpeg...'; window.location.href='subminer://first-run-setup?action=install-ffmpeg'">${ffmpeg.kind === 'broken' ? 'Download FFmpeg again' : 'Download FFmpeg'}</button></div>`
: '';
return `
<div class="card block">
<div class="card-head">
<div>
<strong>FFmpeg</strong>
<div class="meta">Used for card audio and screenshots, and subtitle generation.</div>
${lines.map((line) => `<div class="meta">${escapeHtml(line)}</div>`).join('')}
</div>
${badge}
</div>
${downloadButton}
</div>`;
}
export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string { export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? []; const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? [];
const finishButtonLabel = const finishButtonLabel =
@@ -588,7 +535,6 @@ export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)} ${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)}
</div> </div>
${hostCard} ${hostCard}
${renderFfmpegCard(model.ffmpeg)}
${mpvExecutablePathCard} ${mpvExecutablePathCard}
${windowsShortcutCard} ${windowsShortcutCard}
${renderCommandLineLauncherSection(model.commandLineLauncher)} ${renderCommandLineLauncherSection(model.commandLineLauncher)}
@@ -620,7 +566,6 @@ export function parseFirstRunSetupSubmissionUrl(rawUrl: string): FirstRunSetupSu
action !== 'configure-windows-mpv-shortcuts' && action !== 'configure-windows-mpv-shortcuts' &&
action !== 'install-bun' && action !== 'install-bun' &&
action !== 'install-command-line-launcher' && action !== 'install-command-line-launcher' &&
action !== 'install-ffmpeg' &&
action !== 'open-yomitan-settings' && action !== 'open-yomitan-settings' &&
action !== 'open-config-settings' && action !== 'open-config-settings' &&
action !== 'refresh' && action !== 'refresh' &&