Compare commits

..
Author SHA1 Message Date
sudacode 93045ebf9f fix(build): extract Yomitan on Windows without the Archive module
PowerShell 7's PSModulePath makes powershell.exe load the PS7 Archive
module, whose ExtractToDirectory overload is missing on .NET Framework,
so Expand-Archive silently extracted nothing on the windows-latest runner.
2026-11-23 00:20:03 -08:00
sudacode 18490c9d4f chore(release): prepare v0.22.1-beta.2 2026-11-23 00:02:21 -08:00
sudacode 78809094d2 fix(jimaku): keep the series name for stream titles containing slashes (#337) 2026-11-22 23:59:19 -08:00
sudacode 71251b8d7b feat(stats): group library seasons, movies and OVAs into franchise cards (#336) 2026-11-22 21:03:23 -08:00
sudacode 9d2057cc30 fix(anilist): resolve later seasons past split-cour halves and specials (#335) 2026-11-22 21:03:11 -08:00
sudacode ac3ceab856 feat(aniskip): detect intros and outros from file chapters and AniSkip v2 (#334) 2026-11-22 21:02:54 -08:00
sudacode ee52664655 feat(setup): download FFmpeg from first-run setup when none is usable (#333) 2026-11-22 02:09:06 -08:00
sudacode 0ae70b4ab2 fix(overlay): keep forwarding mpv keys after a Yomitan popup closes (#332)
Decide whether the Yomitan popup is open from the popup host in the DOM
instead of the cached yomitanPopupVisible flag, which can lag a close and
kept input.conf keys from reaching mpv.

Keep the imported mpv key list in place while a refresh is in flight, so a
key pressed right after the overlay regains focus is not dropped. A failed
reload still clears the list.

At --log-level debug, log why the overlay kept an mpv-bound key
(config-loading, modal, lookup-popup, interactive-target or
no-imported-bindings) over a validated IPC channel.

Refs #331
2026-11-20 18:27:11 -08:00
sudacode 0c1865f4a6 chore(release): prepare v0.22.1-beta.1 2026-11-06 19:07:54 -08:00
sudacode 6fd55053d4 fix(overlay): identify Windows mpv windows through IPC PID (#330) 2026-11-06 18:37:44 -08:00
118 changed files with 6950 additions and 947 deletions

No files matched your search

+3
View File
@@ -32,6 +32,9 @@ jobs:
- name: Verify native mpv process launch - name: Verify native mpv process launch
run: bun test src/main/runtime/mpv-process.test.ts run: bun test src/main/runtime/mpv-process.test.ts
- name: Verify mpv PID lookup and Windows tracker
run: bun test src/window-trackers/mpv-process-id.test.ts src/window-trackers/windows-tracker.test.ts
- name: Verify POSIX launcher bootstrap - name: Verify POSIX launcher bootstrap
run: bun test src/main/runtime/posix-launcher-bootstrap.test.ts run: bun test src/main/runtime/posix-launcher-bootstrap.test.ts
+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 | Audio clips and screenshots on cards | | ffmpeg | Recommended | Card audio and screenshots (first-run setup can download it) |
| 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.
+7
View File
@@ -0,0 +1,7 @@
type: added
area: aniskip
- Added outro skipping: the AniSkip key now also skips the ending, with its own prompt and chapter markers.
- Intro and outro detection now reads the file's own chapters first (named OP/ED chapters, or song-length chapters near the start and end) and only asks AniSkip for what is missing, so it also works for Jellyfin and other streams.
- AniSkip lookups now send the episode length so the times match your TV or Blu-ray cut.
- Fixed AniSkip rate limits, server errors, and network failures being remembered as "no intro" until restart; they are now retried on the next load.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: jimaku
- The Jimaku modal fills in the series name again for Jellyfin episodes whose name contains a "/" (for example "Under the Cherry Tree / For Now, Let's Try Stripping"). It used to show only the last part of the episode name with no season or episode. The AniList fallback guess had the same problem and is fixed too.
+5
View File
@@ -0,0 +1,5 @@
type: added
area: stats
- Library lists each anime once: seasons, movies, and OVAs that AniList links as sequels, prequels, side stories, summaries, or compilations share one card, named after the first TV series. Opening it lists the parts in release order with their own stats. Spin-offs and alternative versions keep their own cards.
- A title's page has **Move to Another Anime…**, **Show On Its Own**, and **Put Back Where AniList Has It** to correct the grouping. `subminer sync` keeps the most recent choice.
+6
View File
@@ -0,0 +1,6 @@
type: fixed
area: overlay
- mpv keys from `input.conf` (for example arrow keys bound to `sub-seek`) are no longer sent to a Yomitan popup that has already closed. The overlay decided whether the popup was open from a cached flag that could lag behind a close.
- mpv keys no longer get dropped while the overlay reloads mpv's bindings after it regains focus.
- With `--log-level debug`, the log names why the overlay kept an mpv-bound key instead of forwarding it.
+4
View File
@@ -0,0 +1,4 @@
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.
@@ -0,0 +1,4 @@
type: docs
area: overlay
- Explain how to collect and interpret Windows overlay attachment and readiness warnings without enabling debug logging.
@@ -0,0 +1,6 @@
type: fixed
area: overlay
- Windows overlay attachment now identifies mpv through its IPC process ID, removing the dependency on PowerShell command-line lookups and allowing the IPC socket to be configured in `mpv.conf`.
- Revalidate cached Windows mpv process IDs and expire them after sustained IPC failures so PID reuse cannot keep the overlay attached to an unrelated window.
- Diagnose stalled Windows overlays at the default warn log level, including tracking/PID state, renderer readiness, opacity, native binding errors, and recovery, with repeated warnings rate limited.
+2 -2
View File
@@ -1080,8 +1080,8 @@
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false "autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false "pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path. "subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false "aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible. "aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
}, // SubMiner-managed mpv launch and bundled plugin options. }, // SubMiner-managed mpv launch and bundled plugin options.
// ========================================== // ==========================================
+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
+11 -4
View File
@@ -1,6 +1,6 @@
# AniSkip integration # AniSkip integration
SubMiner looks up opening timestamps on [AniSkip](https://aniskip.com) so you can skip an anime's intro with one key. SubMiner finds an anime's opening and ending so you can skip either with one key. It reads the file's own chapters first and asks [AniSkip](https://aniskip.com) for anything they lack.
## Setup ## Setup
@@ -23,17 +23,24 @@ python3 -m pip install --user guessit
## Usage ## Usage
When a local file loads, SubMiner reads the title and episode from the file name, finds the show on MyAnimeList, and asks AniSkip for the intro's timestamps. Streams and URLs are skipped. Once a file's duration is known, SubMiner looks for the opening and ending in the file's chapters:
If AniSkip has an intro, SubMiner adds `AniSkip Intro Start` and `AniSkip Intro End` chapters. When the intro starts, mpv shows "You can skip by pressing TAB" (with your key) for 3 seconds. Press the key any time during the intro to jump to its end. - By name: chapters called `Opening`, `OP`, `OP ...` or `オープニング`; and `Ending`, `ED`, `ED ...`, `Outro`, `End Credits`, `Closing Credits`, `エンディング`, or `Credits` in the second half of the episode.
- By length, in files with at least three chapters: a 55 to 150 second chapter in the first 30% of the episode (the one closest to 90 seconds) is the opening, and the first one after 70% is the ending.
If the chapters don't give both, SubMiner reads the title and episode from the file name, finds the show on MyAnimeList, and asks AniSkip for the rest, sending the file's length so the times match your cut (TV or Blu-ray). AniSkip lookups run for local files only; streams such as Jellyfin use their chapters alone.
For times that came from AniSkip, SubMiner adds `AniSkip Intro Start`/`End` and `AniSkip Outro Start`/`End` chapters. When the intro or outro starts, SubMiner shows "You can skip the intro by pressing TAB" (or "the outro", with your key) for 3 seconds. Press the key any time during either one to jump to its end. Nothing is skipped automatically.
With a custom key other than `TAB` or `y-k`, `y-k` also skips. With a custom key other than `TAB` or `y-k`, `y-k` also skips.
A failed lookup (AniSkip or MyAnimeList down, rate limited, or offline) is retried the next time the file loads. A show or episode AniSkip has no times for is remembered until SubMiner restarts.
## Triggering from mpv ## Triggering from mpv
| Command | What it does | | Command | What it does |
| ----------------------------------------- | ------------------------------------------------------- | | ----------------------------------------- | ------------------------------------------------------- |
| `script-message subminer-skip-intro` | Skip to the end of the intro | | `script-message subminer-skip-intro` | Skip to the end of the intro or outro that is playing |
| `script-message subminer-aniskip-refresh` | Look up the current file again, ignoring cached results | | `script-message subminer-aniskip-refresh` | Look up the current file again, ignoring cached results |
Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show. Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show.
+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`. SubMiner uses it for audio and images. 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.
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.
+1 -1
View File
@@ -46,7 +46,7 @@ A few ownership notes that are hard to guess from file names:
- mpv access is split into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and property modules under `src/core/services/`. - mpv access is split into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and property modules under `src/core/services/`.
- The renderer keeps `renderer.ts` to orchestration. Keyboard, mouse, and gamepad input live in `renderer/handlers/`, and each modal flow has its own file in `renderer/modals/`. - The renderer keeps `renderer.ts` to orchestration. Keyboard, mouse, and gamepad input live in `renderer/handlers/`, and each modal flow has its own file in `renderer/modals/`.
- AniSkip intro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it. - Intro/outro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which reads the file's chapters, asks AniSkip for what they lack, and drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it.
## Component diagram ## Component diagram
+2 -2
View File
@@ -634,8 +634,8 @@ Settings for mpv instances that SubMiner starts, and for the bundled mpv plugin.
| `mpv.autoStartSubMiner` | `true` | Start SubMiner in the background when mpv loads a file | | `mpv.autoStartSubMiner` | `true` | Start SubMiner in the background when mpv loads a file |
| `mpv.pauseUntilOverlayReady` | `true` | Keep mpv paused until subtitles are ready, up to 30 seconds | | `mpv.pauseUntilOverlayReady` | `true` | Keep mpv paused until subtitles are ready, up to 30 seconds |
| `mpv.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path | | `mpv.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path |
| `mpv.aniskipEnabled` | `true` | Detect intros with AniSkip and show a skip prompt | | `mpv.aniskipEnabled` | `true` | Detect intros and outros (file chapters, then AniSkip) and show a skip prompt |
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro while the prompt is shown | | `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro or outro while it plays |
### YouTube playback settings ### YouTube playback settings
+6 -2
View File
@@ -50,11 +50,15 @@ Deleting a session or session group refreshes the Overview totals, charts, calen
Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel. Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel.
Seasons get separate cards when a season number is detected. Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand. Seasons, movies, and OVAs of one anime share a card. SubMiner follows AniList's sequel, prequel, parent, side-story, summary, and compilation links, including through entries you have not watched, so two films can meet at a TV series you never played. Spin-offs and alternative versions keep their own cards. A shared card is named after the anime's first TV series, shows the cover of the earliest part you have, and opens to a list of its parts in release order. Relations come from AniList in the background and refresh weekly, so a newly linked show can take a minute to join its card.
If a part lands on the wrong card, open it and choose **Move to Another Anime…** (the target must be linked to AniList) or **Show On Its Own**. **Put Back Where AniList Has It** undoes either. This only changes how the library is listed; duplicate entries for the same season still need a merge.
Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
The same show can end up on several cards when release names disagree. To fix that: The same show can end up on several cards when release names disagree. To fix that:
- Merge: click **Select**, tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry. - Merge: click **Select** (the grid then lists every entry on its own), tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction. - Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction.
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**. - Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
+5 -4
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. 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.
| 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. 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. 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`).
<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,8 +262,9 @@ 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. **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`. 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.
4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached. 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`.
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
@@ -145,7 +145,7 @@ subminer sync macbook --remote-cmd ~/Apps/SubMiner.AppImage # SubMiner in a cu
subminer sync --ui # open the sync window subminer sync --ui # open the sync window
``` ```
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. `--push` and `--pull` do not delete anything on the receiving side. Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. The one setting it carries is a library title's anime card choice (**Move to Another Anime…**), where the most recent change wins. `--push` and `--pull` do not delete anything on the receiving side.
Before a command-line sync, close SubMiner on both machines and stop the stats server with `subminer stats -s`, or pass `--force`. The sync window does not need this. It syncs while SubMiner and playback are running, and skips the session in progress until it finishes. Before a command-line sync, close SubMiner on both machines and stop the stats server with `subminer stats -s`, or pass `--force`. The sync window does not need this. It syncs while SubMiner and playback are running, and skips the session in progress until it finishes.
+1 -1
View File
@@ -47,7 +47,7 @@ Most plugin keys are chords: press `y`, then the second key.
`v` replaces mpv's own subtitle visibility toggle. `v` replaces mpv's own subtitle visibility toggle.
The skip-intro key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration). The intro/outro skip key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration).
The `y-y` menu lists Start overlay, Stop overlay, Toggle overlay, Open options, Restart overlay, Check status, and Stats. Press an item's number to run it. Stats only reminds you to press `` ` `` in the overlay. The `y-y` menu lists Start overlay, Stop overlay, Toggle overlay, Open options, Restart overlay, Check status, and Stats. Press an item's number to run it. Stats only reminds you to press `` ` `` in the overlay.
+2 -2
View File
@@ -1080,8 +1080,8 @@
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false "autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false "pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path. "subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false "aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible. "aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
}, // SubMiner-managed mpv launch and bundled plugin options. }, // SubMiner-managed mpv launch and bundled plugin options.
// ========================================== // ==========================================
+15
View File
@@ -51,6 +51,17 @@ When `connect ENOENT /tmp/subminer-socket` follows a cast in the app log, SubMin
- Confirm SubMiner is running (`SubMiner.AppImage --start`, or check for the process). - Confirm SubMiner is running (`SubMiner.AppImage --start`, or check for the process).
- Linux: Hyprland and Sway work natively. Any other compositor needs mpv and SubMiner under X11 or Xwayland, with `xdotool`, `xprop`, and `xwininfo` installed. See [KDE Plasma and other Wayland compositors](#kde-plasma-and-other-wayland-compositors). - Linux: Hyprland and Sway work natively. Any other compositor needs mpv and SubMiner under X11 or Xwayland, with `xdotool`, `xprop`, and `xwininfo` installed. See [KDE Plasma and other Wayland compositors](#kde-plasma-and-other-wayland-compositors).
- macOS: grant Accessibility permission. See [macOS](#macos). - macOS: grant Accessibility permission. See [macOS](#macos).
- Windows: leave the affected mpv window open for at least five seconds, then collect the daily
app log from the directory above. No debug setting is required: a stalled overlay logs
`Windows overlay is not visible after startup or tracking loss` with its PID, native window
handle, tracking state, geometry, opacity, and renderer readiness. The `reason` distinguishes
a missing mpv window, an unready renderer, a hidden window, and a transparent window.
This warning waits until mpv has answered on its IPC socket, so a requested overlay with no
mpv running stays quiet. PID lookup failures and native ownership or transparency errors also
appear at `warn`, and a PID lookup failure is the only trace if mpv never answers.
Repeated visibility/native-operation warnings are limited to one every 30 seconds; recovery
is recorded too. These logs diagnose attachment and readiness, but cannot prove that pixels
were drawn correctly by the graphics driver.
## Overlay is on the wrong monitor or position ## Overlay is on the wrong monitor or position
@@ -179,6 +190,10 @@ Another app or your desktop already uses `Alt+Shift+Y` (Yomitan settings). Free
Overlay shortcuts only work while the overlay has focus. Click the overlay, or press `Alt+Shift+O` with mpv or the overlay focused. Overlay shortcuts only work while the overlay has focus. Click the overlay, or press `Alt+Shift+O` with mpv or the overlay focused.
## An mpv key does nothing over the overlay
Keys from `input.conf` reach mpv through the overlay only in some cases (see [automatic mpv bindings](/shortcuts#automatic-mpv-bindings)). Run with `--log-level debug` and press the key: an `Overlay kept an mpv-bound key` line names the reason. To make a key work everywhere, add it to [`keybindings`](/configuration#keybindings) instead.
## Update checks ## Update checks
**"Update check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`. **"Update check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`.
+1 -1
View File
@@ -229,7 +229,7 @@ script-message subminer-start backend=hyprland socket=/custom/path texthooker=no
The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts. The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts.
While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro, and `subminer-aniskip-refresh` reloads intro data, for example after your script changes title or episode metadata. While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro or outro that is playing, and `subminer-aniskip-refresh` reloads intro and outro data, for example after your script changes title or episode metadata.
## Related pages ## Related pages
+13 -1
View File
@@ -27,6 +27,16 @@ Read when: you need to find the owner module for a behavior or test surface
subtitle suppression while the overlay shows, and the overlay-window IPC handlers (modal subtitle suppression while the overlay shows, and the overlay-window IPC handlers (modal
open/close, pointer interaction, content measurement): `src/main/assemblies/overlay.ts` open/close, pointer interaction, content measurement): `src/main/assemblies/overlay.ts`
Overlay-hosted modal openers: `src/main/assemblies/overlay-modals.ts` Overlay-hosted modal openers: `src/main/assemblies/overlay-modals.ts`
Windows window tracking: `src/window-trackers/windows-tracker.ts` queries the target mpv IPC
socket for its PID through `mpv-process-id.ts`, then `win32.ts` matches native windows by PID.
Visible matches are revalidated every 10 seconds; a PID expires after 30 seconds without a
successful IPC response. Missing windows retry at one-second intervals. Custom executable
names remain supported because matching uses the IPC PID.
`src/core/services/overlay-visibility-diagnostics.ts` watches requested Windows overlays:
after five seconds hidden or transparent it logs a warn-level snapshot, repeating at most
every 30 seconds. Intentional hiding, minimization and having no mpv answer on the socket
yet suppress these warnings; an identified mpv whose window never matches does not. PID lookup
failures and native ownership/transparency failures also log at warn, including recovery.
- MPV runtime and protocol: `src/core/services/mpv*.ts` - MPV runtime and protocol: `src/core/services/mpv*.ts`
mpv client creation, mpv event wiring, AniSkip, the autoplay-ready gate that releases mpv's mpv client creation, mpv event wiring, AniSkip, the autoplay-ready gate that releases mpv's
startup pause, managed local subtitle selection, subtitle prefetch, and subtitle sidebar state: startup pause, managed local subtitle selection, subtitle prefetch, and subtitle sidebar state:
@@ -54,10 +64,12 @@ Read when: you need to find the owner module for a behavior or test surface
the stats overlay window options, and the `--stats` command are assembled by `src/main/assemblies/stats.ts` the stats overlay window options, and the `--stats` command are assembled by `src/main/assemblies/stats.ts`
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata. Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions. Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
Franchise grouping is a view over `imm_anime`, never a merge: `query-library-groups.ts` groups library rows by union-find over the AniList relation cache (`imm_anilist_media` + `imm_anilist_relations`, written by `anilist-relation-cache.ts`; pure graph and walk in `anilist/franchise-graph.ts`, where `FRANCHISE_RELATION_TYPES` is the joining set). `franchise-relation-refresher.ts` walks from owned AniList ids (bounded depth and fetches per run, 7-day staleness, shared AniList rate limiter) when the grouped library is read, after cover art links an id, and after manual AniList or group changes; a failed fetch leaves cached rows untouched. `imm_anime.group_override` (NULL = AniList, 0 = on its own, positive = join the franchise containing that AniList id) is the only user state; `/api/stats/anime/groups` and `PUT /api/stats/anime/:id/group` expose it.
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window. `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`.
`imm_anime.group_override` merges last-writer-wins on `group_override_updated_at` (clears carry a timestamp too); its values are AniList ids, so no id remapping. The AniList relation cache is not merged: each machine rebuilds it, and stale or partial remote cache rows would otherwise outlive the 7-day refresh.
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it. `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`
+39
View File
@@ -114,6 +114,45 @@ test(
}, },
); );
// The other tests read the renderer over CDP, which works even if the window never appears.
// Windows keeps the overlay hidden until the tracker identifies mpv's window.
// Bun's node:test ignores the `skip` option, so this picks `test.skip` instead.
const testOnWindows = process.platform === 'win32' ? test : test.skip;
testOnWindows('visible overlay window appears over mpv', { timeout: TEST_TIMEOUT_MS }, async () => {
const { session } = await useSession();
await session.runAppCommand('--show-visible-overlay');
const mpvPid = await session.mpv.command('get_property', 'pid');
assert.equal(typeof mpvPid, 'number');
const main = await session.mainProcess();
await waitUntil(
() =>
main.evaluate<boolean>(
`(() => {
const electron = process.mainModule.require('electron');
const overlay = electron.BrowserWindow.getAllWindows().find(
(w) => w.webContents.getURL().includes(${JSON.stringify(OVERLAY_PAGE)}));
if (!overlay?.isVisible() || overlay.getOpacity() !== 1 ||
overlay.__subminerOverlayContentReady !== true) return false;
// The inspector's mainModule can be Electron's bootstrap module. Resolve app
// dependencies from the repository instead of that module's search paths.
const appRequire = process.mainModule.require('node:module').createRequire(
process.mainModule.require('node:path').resolve('package.json'));
const koffi = appRequire('koffi');
const getWindow = koffi.load('user32.dll').func(
'intptr __stdcall GetWindow(intptr hwnd, uint uCmd)');
const handle = overlay.getNativeWindowHandle();
const hwnd = handle.length >= 8 ? Number(handle.readBigUInt64LE(0)) : handle.readUInt32LE(0);
const owner = getWindow(hwnd, 4); // GW_OWNER
const win32 = appRequire(
process.mainModule.require('node:path').resolve('dist/window-trackers/win32.js'));
return win32.findMpvWindows(${JSON.stringify(mpvPid)}).matches.some(
(match) => match.hwnd === owner);
})()`,
),
{ description: 'the visible overlay to be fully revealed and owned by the target mpv window' },
);
});
test( test(
'seeking to another cue replaces the line and deinflects verbs to their headword', 'seeking to another cue replaces the line and deinflects verbs to their headword',
{ timeout: TEST_TIMEOUT_MS }, { timeout: TEST_TIMEOUT_MS },
+7
View File
@@ -1,6 +1,11 @@
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,
@@ -65,6 +70,8 @@ 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();
+3 -1
View File
@@ -25,7 +25,9 @@ export const IMMERSION_DB_FIXTURE_DDL = `
tmdb_type TEXT, tmdb_type TEXT,
metadata_json TEXT, metadata_json TEXT,
CREATED_DATE TEXT, CREATED_DATE TEXT,
LAST_UPDATE_DATE TEXT LAST_UPDATE_DATE TEXT,
group_override INTEGER,
group_override_updated_at TEXT
); );
CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key); CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key);
CREATE TABLE imm_videos( CREATE TABLE imm_videos(
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "subminer", "name": "subminer",
"productName": "SubMiner", "productName": "SubMiner",
"desktopName": "SubMiner.desktop", "desktopName": "SubMiner.desktop",
"version": "0.22.0", "version": "0.22.1-beta.2",
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration", "description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
"packageManager": "bun@1.3.5", "packageManager": "bun@1.3.5",
"main": "dist/main-entry.js", "main": "dist/main-entry.js",
+40 -71
View File
@@ -1,88 +1,57 @@
> This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release. > This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release.
<!-- prerelease-version: 0.20.1-beta.2; since: v0.20.1-beta.1 --> <!-- prerelease-version: 0.22.1-beta.2; since: v0.22.1-beta.1 -->
## Changes since v0.20.1-beta.1 ## Changes since v0.22.1-beta.1
- Upgraded the desktop runtime to Electron 43.7.7. - Later seasons now land on the right AniList entry even when the sequel chain includes split-season halves, specials, or movies (for example Mushoku Tensei S3, Re:ZERO S4, and Attack on Titan S4).
- SubMiner now refuses to start on an unsupported Electron runtime, or after an Electron major or minor downgrade, so your Yomitan profile data stays safe; patch downgrades are still allowed. - Entries whose title names the season ("Season 3", "III", "第3期") are now preferred over counting sequels.
- Automatic character-dictionary updates now stop if a Yomitan profile that had dictionaries suddenly reports none. - Episodes in the second half of a split season now update that half's AniList entry at the correct episode number.
- Development launches now use a separate `SubMiner-dev` profile unless you explicitly ask for the production profile. - Character dictionary AniList matches cached by older versions are re-resolved once.
- Sentence mining (single and multi-line) no longer counts each card twice in session and lifetime stats. - Added outro skipping: the AniSkip key now also skips endings, with its own prompt and chapter markers.
- Deleting sessions now updates word and kanji "first seen" and "last seen" dates correctly, and retention pruning keeps historical discovery dates and counts. - Intro and outro detection now reads the file's own chapters first and only asks AniSkip for what is missing, so it also works for Jellyfin and other streams.
- Words hidden by the vocabulary filter are no longer counted in the new-words charts, so the charts now match the vocabulary summary. - AniSkip lookups now send the episode length, so skip times match your TV or Blu-ray cut.
- A one-time background repair on next launch fixes stale "last seen" dates and existing chart mismatches. - AniSkip rate limits, server errors, and network failures are no longer remembered as "no intro" until restart; the lookup is retried on the next load.
- Overview totals, charts, the activity calendar, and the vocabulary summary now refresh after you delete sessions, and a failed refresh keeps the dashboard visible with a retry option. - The Jimaku modal fills in the series name again for Jellyfin episodes whose name contains a "/", and the AniList fallback guess is fixed for the same case.
- Subtitle generation now works during Windows YouTube playback and loads the generated subtitles into the playing video. - The stats Library now shows each anime once, with its linked seasons, movies, and OVAs grouped into one card that lists the parts in release order.
- On Windows, moving on to a video queued from the YouTube browser window no longer drops the rest of mpv's queue. - A title's page now has options to move it to another anime, show it on its own, or restore AniList's grouping, and `subminer sync` keeps the most recent choice.
- The stats docs now cover the automatic Overview refresh after deletions and how discovery dates are kept through retention pruning. - mpv keys from `input.conf` are no longer sent to a Yomitan popup that has already closed.
- mpv keys are no longer dropped while the overlay reloads mpv's bindings after it regains focus.
- With `--log-level debug`, the log now says why the overlay kept an mpv-bound key instead of forwarding it.
- First-run setup now shows whether FFmpeg and FFprobe are usable, and a **Download FFmpeg** button saves a verified build that SubMiner and the `subminer` command use when no system FFmpeg is found.
## Highlights ## Highlights
### Added ### Added
- **Intro and Outro Skipping**:
- **YouTube Browser Window**: - The AniSkip key now skips endings too, with its own prompt and chapter markers.
- Open it with `subminer youtube` (or `subminer yt`), or pick **Browse YouTube** from the tray. It stays logged in across restarts. - Intros and outros are detected from the file's own chapters first, so skipping also works for Jellyfin and other streams.
- Clicking a video plays it in mpv. Middle-click, Shift-click, Ctrl-click, or the right-click menu adds it to mpv's playlist. - AniSkip times now match your TV or Blu-ray cut.
- Queued videos get the same Japanese subtitle setup when they start. - **Library Franchise Cards**: Seasons, movies, and OVAs of the same anime now share one library card, with each part's own stats listed inside. To fix the grouping, use **Move to Another Anime…**, **Show On Its Own**, or **Put Back Where AniList Has It** on a title's page.
- Closing the window quits SubMiner if you started it with `subminer youtube`. If a video is still playing, SubMiner waits until mpv closes. - **FFmpeg Download in Setup**: First-run setup now shows whether FFmpeg and FFprobe are usable. If they are missing, click **Download FFmpeg** to install a verified build that SubMiner and the `subminer` command can use.
- **Whisper Subtitles for YouTube**:
- Set `youtube.subtitleSource` to `whisper` to make subtitles with Whisper instead of downloading YouTube's captions.
- The video stays paused while Whisper works, and progress shows in the subtitle generation modal. You can close the modal to keep watching, or cancel.
- The subtitle generation modal (`Ctrl+Shift+G`) now works on YouTube videos, including on Windows.
- **Mouse and Scroll Wheel Bindings**:
- You can now use scroll wheel keys (`WHEEL_UP`, `WHEEL_DOWN`, `WHEEL_LEFT`, `WHEEL_RIGHT`) in `keybindings` and record them in the settings key editor.
- mpv's mouse button and wheel bindings now work while the cursor is over the overlay. This matters most on Hyprland, where these bindings did nothing before.
- When a binding conflicts, SubMiner's own bindings and right-click pause take priority over mpv's.
- **Session Help Commands**: During playback, press `Enter` or double-click a row in session help to run that command. Hovering over a row makes it the target for `Enter`.
### Changed
- **Release Assets**: Releases no longer include package-size JSON reports.
### Fixed ### Fixed
- **AniList Seasons**: Later seasons now match the right AniList entry when the series has split-season halves, specials, or movies. Episodes in the second half of a split season now update the right entry.
- **Jellyfin Subtitles**: - **AniSkip**: Rate limits, server errors, and network failures are no longer remembered as "no intro" until restart. SubMiner retries them on the next load.
- The Japanese track is selected, and annotations start, as soon as it downloads. SubMiner no longer waits for the other tracks. - **Jimaku**: The modal fills in the series name again for Jellyfin episodes whose name contains a "/".
- Japanese and English tracks are now picked automatically on episodes with image-based subtitles (PGS, DVD, DVB). - **Windows Overlay**:
- If one track fails to download, the other tracks are still selected. - The overlay now finds mpv more reliably, without relying on PowerShell lookups.
- **Jellyfin Audio Track**: On direct-play streams, timing review previews and mined card audio now use the audio track you're playing. - You can now configure the IPC socket in `mpv.conf`.
- **Media Timing Review**: - The overlay no longer stays attached to an unrelated window after mpv's process ID is reused.
- Trim handles are now thin lines centered on the clip edges. - Stalled overlays now log diagnostic warnings without debug logging enabled.
- Original subtitle boundaries are now plain orange bars with no labels. - **mpv Keys in the Overlay**: Keys bound in `input.conf` are no longer sent to a Yomitan popup that has already closed. They also no longer get dropped while the overlay reloads mpv's bindings after it regains focus.
- The preview cursor no longer stutters on macOS with Bluetooth headphones such as AirPods.
- **Hyprland Fullscreen**: The overlay stays visible when mpv enters or leaves fullscreen. With `mpv.backend: x11`, subtitles and the sidebar stay clickable after going fullscreen.
- **mpv Key Bindings in the Overlay**: mpv key bindings, such as `9`/`0` for volume, now work while the overlay has focus, even when the overlay loaded before mpv connected.
- **YouTube Japanese Subtitles**: Some videos also list a machine-translated Japanese track. On those, Japanese subtitles no longer fail with "HTTP 429". If YouTube refuses a direct download, SubMiner retries with yt-dlp.
- **Stats Accuracy**:
- Sentence mining no longer counts each card twice in session and lifetime stats.
- Overview totals, charts, the activity calendar, and the vocabulary summary now update after you delete sessions.
- Word and kanji dates stay correct after deleting sessions. New-word charts now match the vocabulary summary.
- **Dictionary Safety**: Automatic character dictionary changes now stop if a Yomitan profile that had dictionaries suddenly reports none. SubMiner also refuses to load Yomitan data after a downgrade to an older Electron version.
- **AppImage in Sandboxes**: The AppImage now opens its window in sandboxes that mount the image themselves, such as `firejail --appimage`.
- **Ctrl+C Crash**: Stopping the terminal command that started SubMiner with Ctrl+C no longer crashes it with a "write EPIPE" error.
- **Security Updates**: Electron is updated to 43.7.7 and undici to 7.29.1, which fixes known security advisories.
### Docs ### Docs
- **Windows Overlay Troubleshooting**: New guide to collecting and reading overlay attachment and readiness warnings without debug logging.
- **Docs Site Rewrite**: Pages are shorter and easier to scan. The configuration reference now has a short explanation and a table of keys and defaults for each config block. Pages that no longer matched current behavior are fixed.
- **Arch Linux Install**: The MeCab install command now uses the AUR package `mecab-git`. The README now matches the installation guide.
- **Stats**: The docs now cover the Overview refreshing after you delete sessions, and how first-seen dates are kept when old sessions are cleaned up.
## What's Changed ## What's Changed
- fix(storage): protect Yomitan profiles across Electron runtime changes by @ksyasuda in #211 - fix(overlay): identify Windows mpv windows through IPC PID by @ksyasuda in #330
- fix(jellyfin): select subtitles faster and survive failed track downloads by @ksyasuda in #270 - fix(overlay): keep forwarding mpv keys after a Yomitan popup closes by @ksyasuda in #332
- fix(jellyfin): use the current audio track for media generation by @ksyasuda in #271 - feat(setup): download FFmpeg from first-run setup when none is usable by @ksyasuda in #333
- feat(youtube): add YouTube browser window and Whisper subtitle source by @ksyasuda in #273 - feat(aniskip): detect intros and outros from file chapters and AniSkip v2 by @ksyasuda in #334
- fix(overlay): thin centered trim handles and label-free subtitle boundaries in timing review by @ksyasuda in #274 - fix(anilist): resolve later seasons past split-cour halves and specials by @ksyasuda in #335
- feat(overlay): run session help commands with Enter or double-click by @ksyasuda in #275 - feat(stats): group library seasons, movies and OVAs into franchise cards by @ksyasuda in #336
- fix(overlay): keep overlay mapped during Hyprland/Sway fullscreen by @ksyasuda in #276 - fix(jimaku): keep the series name for stream titles containing slashes by @ksyasuda in #337
- fix(linux): skip AppImage mount keepalive on sandbox squashfs mounts by @ksyasuda in #277
- fix(overlay): reload imported mpv keys after mpv connects by @ksyasuda in #278
- feat(overlay): forward mpv mouse button and wheel bindings by @ksyasuda in #279
- fix(stats): count mined cards once and keep lexical stats exact after deletes by @ksyasuda in #280
- fix(youtube): keep mpv queue when advancing to a queued video on Windows by @ksyasuda in #281
- fix(subtitles): allow Whisper generation during Windows YouTube stream playback by @ksyasuda in #282
## Installation ## Installation
+4 -1
View File
@@ -108,6 +108,9 @@ function extractBuild() {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-')); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-'));
try { try {
if (process.platform === 'win32') { if (process.platform === 'win32') {
// Call .NET directly instead of Expand-Archive: under a pwsh CI step, PSModulePath
// makes Windows PowerShell load PowerShell 7's Archive module, whose
// ExtractToDirectory overload does not exist on .NET Framework.
run( run(
'powershell.exe', 'powershell.exe',
[ [
@@ -116,7 +119,7 @@ function extractBuild() {
'-ExecutionPolicy', '-ExecutionPolicy',
'Bypass', 'Bypass',
'-Command', '-Command',
`Expand-Archive -LiteralPath '${escapePowerShellString(zipPath)}' -DestinationPath '${escapePowerShellString(tempDir)}' -Force`, `$ErrorActionPreference = 'Stop'; Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapePowerShellString(zipPath)}', '${escapePowerShellString(tempDir)}')`,
], ],
repoRoot, repoRoot,
); );
@@ -616,13 +616,14 @@ export function buildIntegrationConfigOptionRegistry(
path: 'mpv.aniskipEnabled', path: 'mpv.aniskipEnabled',
kind: 'boolean', kind: 'boolean',
defaultValue: defaultConfig.mpv.aniskipEnabled, defaultValue: defaultConfig.mpv.aniskipEnabled,
description: 'Enable AniSkip intro detection, chapter markers, and the skip-intro key.', description:
'Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key.',
}, },
{ {
path: 'mpv.aniskipButtonKey', path: 'mpv.aniskipButtonKey',
kind: 'string', kind: 'string',
defaultValue: defaultConfig.mpv.aniskipButtonKey, defaultValue: defaultConfig.mpv.aniskipButtonKey,
description: 'mpv key used to skip the detected intro while the skip prompt is visible.', description: 'mpv key that skips the detected intro or outro while it plays.',
}, },
{ {
path: 'jellyfin.enabled', path: 'jellyfin.enabled',
@@ -338,6 +338,7 @@ function createMockTracker(
hasAnime: async (animeId: number) => animeId === 1, hasAnime: async (animeId: number) => animeId === 1,
getAnimeEpisodes: async () => ANIME_EPISODES, getAnimeEpisodes: async () => ANIME_EPISODES,
getAnimeAnilistEntries: async () => [], getAnimeAnilistEntries: async () => [],
getAnimeGroupPlacement: async () => null,
getAnimeWords: async () => ANIME_WORDS, getAnimeWords: async () => ANIME_WORDS,
getAnimeDailyRollups: async () => DAILY_ROLLUPS, getAnimeDailyRollups: async () => DAILY_ROLLUPS,
getEpisodesPerDay: async () => EPISODES_PER_DAY, getEpisodesPerDay: async () => EPISODES_PER_DAY,
@@ -712,7 +713,7 @@ const MALFORMED_IDS = [
/** Every route that takes a positive resource id; `:id` is replaced per request. */ /** Every route that takes a positive resource id; `:id` is replaced per request. */
const ID_ROUTES: Array<{ const ID_ROUTES: Array<{
method: 'GET' | 'DELETE' | 'PATCH' | 'POST'; method: 'GET' | 'DELETE' | 'PATCH' | 'POST' | 'PUT';
path: string; path: string;
body?: unknown; body?: unknown;
}> = [ }> = [
@@ -739,6 +740,7 @@ const ID_ROUTES: Array<{
{ method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } }, { method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } },
{ method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } }, { method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } },
{ method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } }, { method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } },
{ method: 'PUT', path: '/api/stats/anime/:id/group', body: { mode: 'standalone' } },
{ method: 'POST', path: '/api/stats/anki/browse?noteId=:id' }, { method: 'POST', path: '/api/stats/anki/browse?noteId=:id' },
]; ];
@@ -2429,6 +2431,50 @@ describe('stats server API routes', () => {
assert.equal(mergeCalls, 0); assert.equal(mergeCalls, 0);
}); });
it('PUT /api/stats/anime/:animeId/group validates the body and maps refusals', async () => {
const calls: unknown[] = [];
const app = createStatsApp(
createMockTracker({
setAnimeGroupOverride: async (animeId, target) => {
calls.push([animeId, target]);
if (target.mode === 'join' && target.targetAnimeId === 9) {
return { ok: false, reason: 'target-not-grouped' };
}
if (animeId === 404) return { ok: false, reason: 'not-found' };
return { ok: true };
},
}),
);
const put = (path: string, body: unknown) =>
app.request(path, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(body) });
for (const body of [
{},
{ mode: 'join' },
{ mode: 'join', targetAnimeId: 0 },
{ mode: 'join', targetAnimeId: '8' },
{ mode: 'join', targetAnimeId: 3 },
{ mode: 'reset' },
]) {
assert.equal((await put('/api/stats/anime/3/group', body)).status, 400, JSON.stringify(body));
}
assert.deepEqual(calls, []);
assert.equal(
(await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 8 })).status,
200,
);
assert.equal((await put('/api/stats/anime/3/group', { mode: 'anilist' })).status, 200);
assert.equal((await put('/api/stats/anime/404/group', { mode: 'standalone' })).status, 404);
const refused = await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 9 });
assert.equal(refused.status, 409);
assert.match((await refused.json()).error, /no AniList entry/);
assert.deepEqual(calls.slice(0, 2), [
[3, { mode: 'join', targetAnimeId: 8 }],
[3, { mode: 'anilist' }],
]);
});
it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => { it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => {
let moved: { videoId: number; animeId: number } | null = null; let moved: { videoId: number; animeId: number } | null = null;
const app = createStatsApp( const app = createStatsApp(
@@ -0,0 +1,651 @@
// Captured from live AniList responses on 2026-11-22, trimmed to the fields the resolver reads.
// Each chain is in SEQUEL order: entry i's only SEQUEL is entry i + 1.
import type { AnilistSeasonMedia } from '../season-resolver';
/** Mushoku Tensei: S1 -> "Cour 2" -> S2 -> "Season 2 Part 2" -> S3 -> S3 Part 2. */
export const MUSHOKU_CHAIN: AnilistSeasonMedia[] = [
{
id: 108465,
episodes: 11,
format: 'TV',
seasonYear: 2021,
synonyms: [
'Jobless Reincarnation: I Will Seriously Try If I Go To Another World',
'无职转生 ~到了异世界就拿出真本事~',
'เกิดชาตินี้พี่ต้องเทพ',
'Thất nghiệp chuyển sinh',
],
title: {
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu',
english: 'Mushoku Tensei: Jobless Reincarnation',
native: '無職転生 ~異世界行ったら本気だす~',
},
},
{
id: 127720,
episodes: 12,
format: 'TV',
seasonYear: 2021,
synonyms: ['Mushoku Tensei: Jobless Reincarnation Part 2', 'เกิดชาตินี้พี่ต้องเทพ พาร์ท 2'],
title: {
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu Part 2',
english: 'Mushoku Tensei: Jobless Reincarnation Cour 2',
native: '無職転生 ~異世界行ったら本気だす~ 第2クール',
},
},
{
id: 146065,
episodes: 13,
format: 'TV',
seasonYear: 2023,
synonyms: [
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2',
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season',
'Mushoku Tensei II: Jobless Reincarnation',
'Mushoku Tensei II: Reencarnación desde cero',
'无职转生~到了异世界就拿出真本事~第2季',
],
title: {
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu',
english: 'Mushoku Tensei: Jobless Reincarnation Season 2',
native: '無職転生Ⅱ ~異世界行ったら本気だす~',
},
},
{
id: 166873,
episodes: 12,
format: 'TV',
seasonYear: 2024,
synonyms: [
'Mushoku Tensei: Jobless Reincarnation Season 2 Cour 2',
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2 ครึ่งหลัง',
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season Part 2',
'Mushoku Tensei II: Jobless Reincarnation Part 2',
'Mushoku Tensei II: Reencarnación desde cero',
'无职转生~到了异世界就拿出真本事~第2季',
],
title: {
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu Part 2',
english: 'Mushoku Tensei: Jobless Reincarnation Season 2 Part 2',
native: '無職転生Ⅱ ~異世界行ったら本気だす~ 第2クール',
},
},
{
id: 178789,
episodes: 14,
format: 'TV',
seasonYear: 2026,
synonyms: [
'無職転生 ~異世界行ったら本気だす~ 第3期',
'Mushoku Tensei: Isekai Ittara Honki Dasu 3rd Season',
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 3',
],
title: {
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu',
english: 'Mushoku Tensei: Jobless Reincarnation Season 3',
native: '無職転生Ⅲ ~異世界行ったら本気だす~',
},
},
{
id: 217434,
episodes: null,
format: 'TV',
seasonYear: 2027,
synonyms: ['Mushoku Tensei: Jobless Reincarnation Season 3 Part 2'],
title: {
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu Part 2',
english: null,
native: '無職転生Ⅲ ~異世界行ったら本気だす~ 第2クール',
},
},
];
/** Re:ZERO: S1 -> S2 -> "Season 2 Part 2" -> S3 -> S4 -> S5 (unaired). */
export const REZERO_CHAIN: AnilistSeasonMedia[] = [
{
id: 21355,
episodes: 25,
format: 'TV',
seasonYear: 2016,
synonyms: [
'Re: Life in a different world from zero',
'ReZero',
'Re Zero',
'Re:从零开始的异世界生活',
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก',
'Re:Zero — жизнь с нуля в другом мире',
'Re:Zero Empezar de cero en un mundo diferente',
'Re:Zero – Bắt đầu lại ở thế giới khác',
],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu',
english: 'Re:ZERO -Starting Life in Another World-',
native: 'Re:ゼロから始める異世界生活',
},
},
{
id: 108632,
episodes: 13,
format: 'TV',
seasonYear: 2020,
synonyms: [
'Re:Zero kara Hajimeru Isekai Seikatsu (2020)',
'Re: 제로부터 시작하는 이세계 생활 2기',
'Re:从零开始的异世界生活第二季(上半)',
'Re:从零开始的异世界生活 2 上半',
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2',
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season',
english: 'Re:ZERO -Starting Life in Another World- Season 2',
native: 'Re:ゼロから始める異世界生活 2nd Season',
},
},
{
id: 119661,
episodes: 12,
format: 'TV',
seasonYear: 2021,
synonyms: [
'Re:Zero kara Hajimeru Isekai Seikatsu (2021)',
'Re: 제로부터 시작하는 이세계 생활 2기 파트 2',
'Re:从零开始的异世界生活第二季(下半)',
'Re:从零开始的异世界生活 2 下半',
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2 พาร์ท 2',
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season Part 2',
english: 'Re:ZERO -Starting Life in Another World- Season 2 Part 2',
native: 'Re:ゼロから始める異世界生活 2nd Season Part 2',
},
},
{
id: 163134,
episodes: 16,
format: 'TV',
seasonYear: 2024,
synonyms: ['Re:ZERO – Жизнь с нуля в альтернативном мире 3'],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 3rd Season',
english: 'Re:ZERO -Starting Life in Another World- Season 3',
native: 'Re:ゼロから始める異世界生活 3rd season',
},
},
{
id: 189046,
episodes: 19,
format: 'TV',
seasonYear: 2026,
synonyms: [
'Re:ZERO รีเซทชีวิต ฝ่าวิกฤตต่างโลก ซีซั่น 4',
'Re:ZERO – Жизнь с нуля в альтернативном мире 4',
],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 4th Season',
english: 'Re:ZERO -Starting Life in Another World- Season 4',
native: 'Re:ゼロから始める異世界生活 4th season',
},
},
{
id: 219904,
episodes: null,
format: 'TV',
seasonYear: null,
synonyms: ['Re:ZERO -Starting Life in Another World- Season 5'],
title: {
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 5th Season',
english: null,
native: 'Re:ゼロから始める異世界生活 5th season',
},
},
];
/** Dr. STONE: STONE WARS reaches NEW WORLD through a one-episode SPECIAL. */
export const DR_STONE_CHAIN: AnilistSeasonMedia[] = [
{
id: 105333,
episodes: 24,
format: 'TV',
seasonYear: 2019,
synonyms: [
'Dcst',
'石纪元',
'ドクターストーン',
'ดร.สโตน เจ้าแห่งวิทยาศาสตร์กู้คืนอารยธรรมโลก',
'Доктор Стоун',
],
title: {
romaji: 'Dr. STONE',
english: 'Dr. STONE',
native: 'Dr.STONE',
},
},
{
id: 113936,
episodes: 11,
format: 'TV',
seasonYear: 2021,
synonyms: [
'ドクターストーン STONE WARS',
'Dr.STONE第2期',
'Dr. STONE 2',
'닥터 스톤 STONE WARS',
'石纪元第二季',
'DR.STONE ภาค 2',
'Доктор Стоун: Каменные войны',
],
title: {
romaji: 'Dr. STONE: STONE WARS',
english: 'Dr. STONE: STONE WARS',
native: 'Dr.STONE STONE WARS',
},
},
{
id: 142876,
episodes: 1,
format: 'SPECIAL',
seasonYear: 2022,
synonyms: ['Dr. STONE: Ryusui', 'Доктор Стоун: Рюсуй'],
title: {
romaji: 'Dr. STONE: Ryuusui',
english: 'Dr. STONE Special Episode – RYUSUI',
native: 'Dr.STONE 龍水',
},
},
{
id: 131518,
episodes: 11,
format: 'TV',
seasonYear: 2023,
synonyms: [
'石纪元第三季',
'Dr.STONE Season 3',
'DR.STONE ภาค 3',
'Dr.STONE 第3期',
'Dr. STONE 新石紀(第三季)',
'Доктор Стоун: Новый Свет',
],
title: {
romaji: 'Dr. STONE: NEW WORLD',
english: 'Dr. STONE New World',
native: 'Dr.STONE NEW WORLD',
},
},
{
id: 162670,
episodes: 11,
format: 'TV',
seasonYear: 2023,
synonyms: [
'石纪元第三季',
'Dr.STONE Season 3 Part 2',
'DR.STONE ภาค 3',
'Dr.STONE 第3期 第2クール',
],
title: {
romaji: 'Dr. STONE: NEW WORLD Part 2',
english: 'Dr. STONE New World Part 2',
native: 'Dr.STONE NEW WORLD 第2クール',
},
},
{
id: 172019,
episodes: 12,
format: 'TV',
seasonYear: 2025,
synonyms: ['Dr.STONE Season 4', 'Dr.STONE 第4期', 'ドクターストーン'],
title: {
romaji: 'Dr. STONE: SCIENCE FUTURE',
english: 'Dr. STONE SCIENCE FUTURE',
native: 'Dr.STONE SCIENCE FUTURE',
},
},
];
/** Bleach TYBW: cours named after arcs; "Part N" only in synonyms, spelled "Thousand Year". */
export const BLEACH_TYBW_CHAIN: AnilistSeasonMedia[] = [
{
id: 116674,
episodes: 13,
format: 'TV',
seasonYear: 2022,
synonyms: [
'بليتش: حرب الألف سنة الدموية',
'Bleach: La guerre sanglante de mille ans',
'BLEACH TYBW',
],
title: {
romaji: 'BLEACH: Sennen Kessen-hen',
english: 'BLEACH: Thousand-Year Blood War',
native: 'BLEACH 千年血戦篇',
},
},
{
id: 159322,
episodes: 13,
format: 'TV',
seasonYear: 2023,
synonyms: [
'BLEACH: Thousand Year Blood War Part 2',
'BLEACH 千年血戦篇 第2クール',
'BLEACH TYBW',
],
title: {
romaji: 'BLEACH: Sennen Kessen-hen - Ketsubetsu-tan',
english: 'BLEACH: Thousand-Year Blood War - The Separation',
native: 'BLEACH 千年血戦篇-訣別譚-',
},
},
{
id: 169755,
episodes: 14,
format: 'TV',
seasonYear: 2024,
synonyms: [
'BLEACH: Thousand Year Blood War Part 3',
'BLEACH 千年血戦篇 第3クール',
'BLEACH TYBW',
],
title: {
romaji: 'BLEACH: Sennen Kessen-hen - Soukoku-tan',
english: 'BLEACH: Thousand-Year Blood War - The Conflict',
native: 'BLEACH 千年血戦篇-相剋譚-',
},
},
{
id: 185874,
episodes: 10,
format: 'TV',
seasonYear: 2026,
synonyms: [
'BLEACH: Thousand-Year Blood War Part 4',
'BLEACH 千年血戦篇 第4クール',
'BLEACH: Thousand-Year Blood War The Final Season',
'BLEACH TYBW',
],
title: {
romaji: 'BLEACH: Sennen Kessen-hen - Kashin-tan',
english: 'BLEACH: Thousand-Year Blood War - The Calamity',
native: 'BLEACH 千年血戦篇-禍進譚-',
},
},
];
/** Attack on Titan: season 3 carries the Thai synonym "... ภาค 3 Part 1"; the chain ends in SPECIALs. */
export const AOT_CHAIN: AnilistSeasonMedia[] = [
{
id: 16498,
episodes: 25,
format: 'TV',
seasonYear: 2013,
synonyms: [
'SnK',
'AoT',
'Ataque a los Titanes',
'Ataque dos Titãs',
"L'Attacco dei Giganti",
'מתקפת הטיטאנים',
'进击的巨人',
'L’Attaque des Titans',
'الهجوم على العمالقة',
'ผ่าพิภพไททัน',
'حمله به تایتان',
'Ataque de Titãs',
'Atak Tytanów',
'Атака титанов',
'Đại Chiến Titan',
],
title: {
romaji: 'Shingeki no Kyojin',
english: 'Attack on Titan',
native: '進撃の巨人',
},
},
{
id: 20958,
episodes: 12,
format: 'TV',
seasonYear: 2017,
synonyms: [
'SnK 2',
'AoT 2',
'+מתקפת הטיטאנים עונה 2',
"L'Attacco dei Giganti 2",
"L'Attacco dei Giganti - Seconda Stagione",
'ผ่าพิภพไททัน ภาค 2',
'حمله به تایتان فصل 2',
'Атака титанов 2',
],
title: {
romaji: 'Shingeki no Kyojin Season 2',
english: 'Attack on Titan Season 2',
native: '進撃の巨人 Season2',
},
},
{
id: 99147,
episodes: 12,
format: 'TV',
seasonYear: 2018,
synonyms: [
'SnK 3',
'AoT 3',
'מתקפת הטיטאנים עונה 3',
"L'Attacco dei Giganti 3",
"L'Attacco dei Giganti - Terza Stagione",
'ผ่าพิภพไททัน ภาค 3',
'حمله به تایتان فصل 3',
'ผ่าพิภพไททัน ภาค 3 Part 1',
'Атака титанов 3',
],
title: {
romaji: 'Shingeki no Kyojin Season 3',
english: 'Attack on Titan Season 3',
native: '進撃の巨人 Season3',
},
},
{
id: 104578,
episodes: 10,
format: 'TV',
seasonYear: 2019,
synonyms: [
'SnK 3',
'AoT 3',
'Shingeki no Kyojin Season 3 (2019)',
"L'Attaco dei Giganti 3 Parte 2",
"L'Attacco dei Giganti - Terza Stagione Parte 2",
'מתקפת הטיטאנים עונה 3 חלק 2',
"L'Attaque des Titans Saison 3 Partie 2 ",
'ผ่าพิภพไททัน ภาค 3 Part 2',
'ผ่าพิภพไททัน ภาค 3 พาร์ท 2',
'حمله به تایتان فصل 3',
],
title: {
romaji: 'Shingeki no Kyojin Season 3 Part 2',
english: 'Attack on Titan Season 3 Part 2',
native: '進撃の巨人 Season3 Part.2',
},
},
{
id: 110277,
episodes: 16,
format: 'TV',
seasonYear: 2021,
synonyms: [
'SnK 4',
'AoT 4',
'Shingeki no Kyojin 4',
'進撃の巨人4',
'Attack on Titan Season 4',
'진격의 거인 더 파이널 시즌',
'מתקפת הטיטאנים העונה האחרונה',
"L'Attaque des Titans Saison Finale",
"L'Attacco dei Giganti 4",
"L'Attacco dei Giganti - La Stagione Finale",
'حمله به تایتان فصل 4 ',
' ผ่าพิภพไททัน ไฟนอล ซีซั่น',
'ผ่าพิภพไททัน Final Season',
'ผ่าพิภพไททัน ภาค 4',
'هجوم العملاقة الجزء الأخير',
'Атака Титанов: Финал',
],
title: {
romaji: 'Shingeki no Kyojin: The Final Season',
english: 'Attack on Titan Final Season',
native: '進撃の巨人 The Final Season',
},
},
{
id: 131681,
episodes: 12,
format: 'TV',
seasonYear: 2022,
synonyms: [
'SnK 4',
'AoT 4',
"L'attaque des titans Saison Finale Partie 2",
'Shingeki no Kyojin: The Final Season (2022)',
'اتک عن تایتان',
'حمله به غول ها',
'حمله به تایتان فصل 4 ',
' ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 2',
'ผ่าพิภพไททัน ภาค 4',
"L'Attacco dei Giganti 4 Parte 2",
'Атака титанов: Финал. Часть 2',
],
title: {
romaji: 'Shingeki no Kyojin: The Final Season Part 2',
english: 'Attack on Titan Final Season Part 2',
native: '進撃の巨人 The Final Season Part 2',
},
},
{
id: 146984,
episodes: 1,
format: 'SPECIAL',
seasonYear: 2023,
synonyms: [
'Shingeki no Kyojin: The Final Season Final Edition',
'Shingeki no Kyojin: The Final Season Part 3',
'ผ่าพิภพไททัน ภาค 4',
'ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 3',
'Attack on Titan Final Season Part 3 Final Arc Part 1',
'Attack on Titan The Final Season The Final Part Special',
'Attack on Titan The Final Season The Final Part Part 1',
'حمله به تایتان فصل آخر قسمت ویژه 1 ',
'SnK 4',
'AoT 4',
],
title: {
romaji: 'Shingeki no Kyojin: The Final Season - Kanketsu-hen Zenpen',
english: 'Attack on Titan Final Season THE FINAL CHAPTERS Special 1',
native: '進撃の巨人 The Final Season完結編 前編',
},
},
];
/** Overlord: seasons named only by a trailing roman numeral. */
export const OVERLORD_CHAIN: AnilistSeasonMedia[] = [
{
id: 20832,
episodes: 13,
format: 'TV',
seasonYear: 2015,
synonyms: ['Over Lord', 'โอเวอร์ลอร์ด', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก'],
title: {
romaji: 'Overlord',
english: 'Overlord',
native: 'オーバーロード',
},
},
{
id: 98437,
episodes: 13,
format: 'TV',
seasonYear: 2018,
synonyms: ['Over Lord 2', 'โอเวอร์ลอร์ด ภาค 2', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 2'],
title: {
romaji: 'Overlord II',
english: 'Overlord II',
native: 'オーバーロードⅡ',
},
},
{
id: 101474,
episodes: 13,
format: 'TV',
seasonYear: 2018,
synonyms: ['Over Lord 3', 'โอเวอร์ลอร์ด ภาค 3', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 3'],
title: {
romaji: 'Overlord III',
english: 'Overlord III',
native: 'オーバーロードⅢ',
},
},
];
/** JoJo: Golden Wind ends in the synonym "Part 5", Stone Ocean in "Part 6"; both are new seasons. */
export const JOJO_CHAIN: AnilistSeasonMedia[] = [
{
id: 21450,
episodes: 39,
format: 'TV',
seasonYear: 2016,
synonyms: [
'JoJo no Kimyou na Bouken Part 4: Diamond wa Kudakenai',
"JoJo's Bizarre Adventure Part 4: Diamond is Unbreakable",
'مغامرات جوجو العجيبة: الألماس غير قابل للكسر',
'Le bizzarre avventure di JoJo: Diamond is Unbreakable',
'Невероятные приключения ДжоДжо: Diamond is Unbreakable',
],
title: {
romaji: 'JoJo no Kimyou na Bouken: Diamond wa Kudakenai',
english: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
native: 'ジョジョの奇妙な冒険 ダイヤモンドは砕けない',
},
},
{
id: 102883,
episodes: 39,
format: 'TV',
seasonYear: 2018,
synonyms: [
"JoJo's Bizarre Adventure Part 5",
"JoJo's Bizarre Adventure: Vento Aureo",
'Le Bizzarre Avventure Di GioGio: Vento Aureo',
'مغامرات جوجو العجيبة: الرياح الذهبية',
'Невероятные приключения ДжоДжо: Золотой ветер',
],
title: {
romaji: 'JoJo no Kimyou na Bouken: Ougon no Kaze',
english: "JoJo's Bizarre Adventure: Golden Wind",
native: 'ジョジョの奇妙な冒険 黄金の風',
},
},
{
id: 131942,
episodes: 12,
format: 'ONA',
seasonYear: 2021,
synonyms: [
"JoJo's Bizarre Adventure: Stone Ocean",
"JoJo's Bizarre Adventure Part 6",
'JoJo no Kimyou na Bouken Part 6',
'Le bizzarre avventure di JoJo: Stone Ocean',
'โจโจ้ ล่าข้ามศตวรรษ: สโตนโอเชียน ',
'โจโจ้ ล่าข้ามศตวรรษ ภาค 6',
'مغامرات جوجو العجيبة: محيط الأحجار',
"ההרפתקה המוזרה של ג'וג'ו: אוקיינוס האבן",
'Невероятные приключения ДжоДжо: Каменный океан ',
"Химерні пригоди ДжоДжо: Кам'яний океан",
],
title: {
romaji: 'JoJo no Kimyou na Bouken: Stone Ocean',
english: "JoJo's Bizarre Adventure: STONE OCEAN",
native: 'ジョジョの奇妙な冒険 ストーンオーシャン',
},
},
];
@@ -0,0 +1,49 @@
import type { AnilistRateLimiter } from './rate-limiter';
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
export class AnilistRateLimitedError extends Error {
constructor() {
super('Anilist rate limit reached');
this.name = 'AnilistRateLimitedError';
}
}
/**
* Runs one anonymous AniList GraphQL query through the shared rate limiter.
* Throws AnilistRateLimitedError on HTTP 429 (the limiter has already recorded
* the retry window) and a plain Error for other HTTP or GraphQL failures.
*/
export async function executeAnilistQuery<T>(
rateLimiter: AnilistRateLimiter,
query: string,
variables: Record<string, unknown>,
): Promise<T> {
await rateLimiter.acquire();
const res = await fetch(ANILIST_GRAPHQL_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query, variables }),
});
rateLimiter.recordResponse(res.headers);
if (res.status === 429) {
throw new AnilistRateLimitedError();
}
if (!res.ok) {
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
}
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
if (firstError?.message) {
throw new Error(firstError.message);
}
if (!json.data) {
throw new Error('Anilist response missing data');
}
return json.data;
}
@@ -34,6 +34,21 @@ test('guessAnilistMediaInfo fills missing guessit episode from filename parser',
}); });
}); });
test('guessAnilistMediaInfo fallback keeps the series of a stream title with slashes', async () => {
const title = 'Seitokai Yakuindomo S01E01 Under the Cherry Tree / For Now, Lets Try Stripping';
const result = await guessAnilistMediaInfo('jellyfin://host/item/abc', title, {
runGuessit: async () => {
throw new Error('guessit unavailable');
},
});
assert.deepEqual(result, {
title: 'Seitokai Yakuindomo',
season: 1,
episode: 1,
source: 'fallback',
});
});
test('guessAnilistMediaInfo keeps season directory scope when guessit omits details', async () => { test('guessAnilistMediaInfo keeps season directory scope when guessit omits details', async () => {
const result = await guessAnilistMediaInfo('/tmp/Season 2/Guessit Title.mkv', null, { const result = await guessAnilistMediaInfo('/tmp/Season 2/Guessit Title.mkv', null, {
runGuessit: async () => JSON.stringify({ title: 'Guessit Title' }), runGuessit: async () => JSON.stringify({ title: 'Guessit Title' }),
@@ -585,6 +600,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 +628,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;
} }
+21 -14
View File
@@ -1,7 +1,7 @@
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import * as path from 'path'; import * as path from 'path';
import { parseMediaInfo } from '../../../jimaku/utils'; import { parseMediaLookupInfo } from '../../../jimaku/utils';
import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../../../shared/media-identity'; import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../../../shared/media-identity';
import type { AnilistRateLimiter } from './rate-limiter'; import type { AnilistRateLimiter } from './rate-limiter';
import { resolveAnilistSeasonMedia, stripSeasonSuffix } from './season-resolver'; import { resolveAnilistSeasonMedia, stripSeasonSuffix } from './season-resolver';
@@ -231,7 +231,7 @@ export async function guessAnilistMediaInfo(
const season = firstPositiveInteger(parsed.season); const season = firstPositiveInteger(parsed.season);
const year = firstYear(parsed.year); const year = firstYear(parsed.year);
if (title) { if (title) {
const fallback = parseMediaInfo(target); const fallback = parseMediaLookupInfo(mediaPath, mediaTitle);
const canUseFallbackDetails = fallback.confidence !== 'low'; const canUseFallbackDetails = fallback.confidence !== 'low';
return { return {
title: buildGuessitTitle(title, alternativeTitle), title: buildGuessitTitle(title, alternativeTitle),
@@ -247,7 +247,7 @@ export async function guessAnilistMediaInfo(
} }
} }
const parsed = parseMediaInfo(target); const parsed = parseMediaLookupInfo(mediaPath, mediaTitle);
if (!parsed.title.trim()) { if (!parsed.title.trim()) {
return null; return null;
} }
@@ -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}.`,
}; };
} }
+1 -42
View File
@@ -1,4 +1,5 @@
import type { AnilistRateLimiter } from './rate-limiter'; import type { AnilistRateLimiter } from './rate-limiter';
import { AnilistRateLimitedError, executeAnilistQuery } from './anilist-graphql';
import type { DatabaseSync } from '../immersion-tracker/sqlite'; import type { DatabaseSync } from '../immersion-tracker/sqlite';
import { import {
getAnimeCoverArt, getAnimeCoverArt,
@@ -20,7 +21,6 @@ import { getVideoTmdbLink, linkAnimeToTmdbTitle } from '../immersion-tracker/liv
import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver'; import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver';
import type { TmdbTitleDetails } from '../tmdb/tmdb-client'; import type { TmdbTitleDetails } from '../tmdb/tmdb-client';
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
const NO_MATCH_RETRY_MS = 5 * 60 * 1000; const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
export interface CoverArtFetcher { export interface CoverArtFetcher {
@@ -76,47 +76,6 @@ export function stripFilenameTags(raw: string): string {
return title.trim().replace(/\s{2,}/g, ' '); return title.trim().replace(/\s{2,}/g, ' ');
} }
class AnilistRateLimitedError extends Error {
constructor() {
super('Anilist rate limit reached');
this.name = 'AnilistRateLimitedError';
}
}
async function executeAnilistQuery<T>(
rateLimiter: AnilistRateLimiter,
query: string,
variables: Record<string, unknown>,
): Promise<T> {
await rateLimiter.acquire();
const res = await fetch(ANILIST_GRAPHQL_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query, variables }),
});
rateLimiter.recordResponse(res.headers);
if (res.status === 429) {
throw new AnilistRateLimitedError();
}
if (!res.ok) {
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
}
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
if (firstError?.message) {
throw new Error(firstError.message);
}
if (!json.data) {
throw new Error('Anilist response missing data');
}
return json.data;
}
async function downloadImage(url: string): Promise<Buffer | null> { async function downloadImage(url: string): Promise<Buffer | null> {
try { try {
const res = await fetch(url); const res = await fetch(url);
@@ -0,0 +1,261 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildFranchiseGraph,
walkFranchiseRelations,
type AnilistMediaNode,
type FranchiseWalkOptions,
} from './franchise-graph';
function entry(
anilistId: number,
format: string | null,
startDate: number | null,
relations: Array<[string, number]> = [],
): AnilistMediaNode {
return {
anilistId,
format,
titleRomaji: `romaji ${anilistId}`,
titleEnglish: null,
titleNative: null,
startDate,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs: 0,
};
}
// Overlord: two recap films sit between seasons one and two; Isekai Quartet only shares characters.
const overlord = [
entry(20832, 'TV', 20150707, [
['SEQUEL', 98437],
['SUMMARY', 98873],
['CHARACTER', 104454],
]),
entry(98873, 'MOVIE', 20170225, [
['PARENT', 20832],
['SEQUEL', 98874],
]),
entry(98874, 'MOVIE', 20170311, [
['PREQUEL', 98873],
['SEQUEL', 98437],
]),
entry(98437, 'TV', 20180109, [
['PREQUEL', 20832],
['PREQUEL', 98874],
]),
entry(104454, 'TV_SHORT', 20190410, [['CHARACTER', 20832]]),
];
test('seasons, films and recaps share a root named after the first TV series', () => {
const graph = buildFranchiseGraph(overlord);
for (const id of [20832, 98873, 98874, 98437]) assert.equal(graph.rootOf(id), 20832);
assert.equal(graph.rootOf(104454), 104454);
assert.equal(graph.rootOf(1), undefined);
});
test('excluded relation types keep franchises apart even when the other end says PARENT', () => {
const graph = buildFranchiseGraph([
entry(1, 'TV', 20060101, [
['SPIN_OFF', 2],
['ALTERNATIVE', 3],
['ADAPTATION', 4],
['OTHER', 5],
]),
// A spin-off pointing back at its original as PARENT.
entry(2, 'TV', 20130101, [['PARENT', 1]]),
entry(3, 'TV', 20140101, [['ALTERNATIVE', 1]]),
]);
assert.deepEqual(
[1, 2, 3, 4, 5].map((id) => graph.rootOf(id)),
[1, 2, 3, undefined, undefined],
);
});
test('root falls back to episodic formats, then earliest entry, then lowest id', () => {
const ona = buildFranchiseGraph([
entry(10, 'MOVIE', 20000101, [['SEQUEL', 11]]),
entry(11, 'ONA', 20050101, [['PREQUEL', 10]]),
]);
assert.equal(ona.rootOf(10), 11);
const films = buildFranchiseGraph([
entry(20, 'MOVIE', 20100101, [['PREQUEL', 21]]),
entry(21, 'MOVIE', 20090101, [['SEQUEL', 20]]),
entry(22, 'OVA', null, [['PARENT', 20]]),
]);
assert.equal(films.rootOf(22), 21);
});
test('owned films join through an unowned, uncached TV entry they both point at', () => {
const graph = buildFranchiseGraph([
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
entry(1526, 'MOVIE', 20050716, [['PARENT', 527]]),
]);
assert.equal(graph.rootOf(528), graph.rootOf(1526));
});
test('relation cycles terminate and form one franchise', () => {
const graph = buildFranchiseGraph([
entry(1, 'TV', 20000101, [['SEQUEL', 2]]),
entry(2, 'TV', 20010101, [['SEQUEL', 3]]),
entry(3, 'TV', 20020101, [['SEQUEL', 1]]),
]);
assert.deepEqual(
[1, 2, 3].map((id) => graph.rootOf(id)),
[1, 1, 1],
);
});
function walkHarness(all: AnilistMediaNode[], overrides: Partial<FranchiseWalkOptions> = {}) {
const asked: number[][] = [];
const known = new Map<number, AnilistMediaNode>();
const options: FranchiseWalkOptions = {
seeds: [],
known,
isFresh: () => true,
fetchNodes: async (ids) => {
asked.push([...ids].sort((a, b) => a - b));
return all.filter((node) => ids.includes(node.anilistId));
},
onBatch: () => {},
now: () => 5,
maxDepth: 6,
maxFetch: 500,
...overrides,
};
return { asked, known, options };
}
test('walk follows franchise links through entries the user does not own', async () => {
const pokemon = [
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
entry(527, 'TV', 19970401, [
['SIDE_STORY', 528],
['SEQUEL', 1564],
]),
entry(1564, 'TV', 20021121, [
['PREQUEL', 527],
['SIDE_STORY', 1526],
['OTHER', 9],
]),
entry(1526, 'MOVIE', 20050716, [['PARENT', 1564]]),
entry(9, 'TV', 20000101),
];
const { asked, known, options } = walkHarness(pokemon, { seeds: [528, 1526, 404] });
await walkFranchiseRelations(options);
assert.deepEqual(asked, [
[404, 528, 1526],
[527, 1564],
]);
const graph = buildFranchiseGraph(known.values());
assert.equal(graph.rootOf(528), 527);
assert.equal(graph.rootOf(1526), 527);
// Missing ids are remembered so they are not asked about again; OTHER links are not followed.
assert.equal(known.get(404)?.format, null);
assert.equal(known.has(9), false);
});
test('walk does not follow the links of an entry that vetoes how it was reached', async () => {
const { asked, options } = walkHarness(
[
entry(2, 'TV', 20130101, [['PARENT', 1]]),
entry(1, 'TV', 20060101, [
['SPIN_OFF', 2],
['SEQUEL', 3],
]),
entry(3, 'TV', 20070101),
],
{ seeds: [2] },
);
await walkFranchiseRelations(options);
assert.deepEqual(asked, [[2], [1]]);
});
test('walk follows an entry reached through any link it accepts, whatever the seed order', async () => {
const nodes = [
entry(1, 'TV', 20100101, [['SEQUEL', 3]]),
entry(2, 'TV', 20110101, [['SEQUEL', 3]]),
// Rejects seed 1 but accepts seed 2, so its own links are still followed.
entry(3, 'TV', 20120101, [
['SPIN_OFF', 1],
['PREQUEL', 2],
['PARENT', 4],
]),
entry(4, 'TV', 20000101),
];
for (const seeds of [
[1, 2],
[2, 1],
]) {
const { asked, options } = walkHarness(nodes, { seeds });
await walkFranchiseRelations(options);
assert.deepEqual(asked, [[1, 2], [3], [4]]);
}
});
test('a cancelled walk starts no further request and drops the in-flight result', async () => {
const seeds = Array.from({ length: 51 }, (_, index) => index + 1);
let cancelled = false;
const batches: number[] = [];
const { asked, known, options } = walkHarness(
seeds.map((id) => entry(id, 'TV', 20200101)),
{
seeds,
isFresh: () => false,
onBatch: (nodes) => batches.push(nodes.length),
isCancelled: () => cancelled,
},
);
const fetchNodes = options.fetchNodes;
options.fetchNodes = async (ids) => {
cancelled = true;
return fetchNodes(ids);
};
const result = await walkFranchiseRelations(options);
assert.equal(asked.length, 1);
assert.deepEqual(batches, []);
assert.equal(known.size, 0);
assert.equal(result.truncated, true);
});
test('walk respects the depth and fetch bounds', async () => {
const chain = Array.from({ length: 10 }, (_, i) =>
entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []),
);
const deep = walkHarness(chain, { seeds: [1], maxDepth: 3 });
await walkFranchiseRelations(deep.options);
assert.deepEqual([...deep.known.keys()], [1, 2, 3, 4]);
const budget = walkHarness(chain, { seeds: [1], maxFetch: 2 });
const result = await walkFranchiseRelations(budget.options);
assert.deepEqual(result, { fetched: 2, truncated: true });
assert.deepEqual([...budget.known.keys()], [1, 2]);
});
test('walk follows fresh cached entries without asking and keeps old data on a failed fetch', async () => {
const cached = entry(1, 'TV', 20000101, [['SEQUEL', 2]]);
const stale = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
const { known, options } = walkHarness([], {
seeds: [1],
isFresh: (node) => node.fetchedAtMs >= 0,
fetchNodes: async () => {
throw new Error('AniList unavailable');
},
});
known.set(1, cached);
known.set(2, stale);
await assert.rejects(walkFranchiseRelations(options), /AniList unavailable/);
assert.deepEqual(known.get(2), stale);
});
test('an entry AniList stops returning keeps its cached links', async () => {
const previous = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
const { known, options } = walkHarness([], {
seeds: [2],
isFresh: (node) => node.fetchedAtMs >= 0,
});
known.set(2, previous);
await walkFranchiseRelations(options);
assert.deepEqual(known.get(2), { ...previous, fetchedAtMs: 5 });
});
@@ -0,0 +1,250 @@
/**
* Franchise grouping over AniList's relation graph. AniList keeps every
* season, movie and OVA as its own entry and says how entries relate; the
* stats library lists a franchise once by following those links, including
* through entries the user does not own (two movies meet at a TV series that
* is not in the library). Nothing here touches the database or the network.
*/
/**
* Relation types that make two entries parts of one franchise. SPIN_OFF,
* ALTERNATIVE, CHARACTER, OTHER, ADAPTATION and SOURCE are left out on purpose:
* following them collapses Gundam or Fate into a single card.
*/
export const FRANCHISE_RELATION_TYPES: ReadonlySet<string> = new Set([
'PREQUEL',
'SEQUEL',
'PARENT',
'SIDE_STORY',
'SUMMARY',
'COMPILATION',
'CONTAINS',
]);
export interface AnilistRelationEdge {
relationType: string;
targetId: number;
}
/** One cached AniList entry and its links to other anime entries. */
export interface AnilistMediaNode {
anilistId: number;
/** TV, MOVIE, OVA...; null when AniList did not return the entry. */
format: string | null;
titleRomaji: string | null;
titleEnglish: string | null;
titleNative: string | null;
/** First air date as yyyymmdd (month/day 0 when unknown); null when AniList has no year. */
startDate: number | null;
episodes: number | null;
relations: AnilistRelationEdge[];
fetchedAtMs: number;
}
export interface FranchiseGraph {
node(anilistId: number): AnilistMediaNode | undefined;
/** AniList id the franchise containing `anilistId` is named after; undefined when unknown. */
rootOf(anilistId: number): number | undefined;
}
export function anilistNodeTitle(node: AnilistMediaNode): string | null {
return node.titleEnglish ?? node.titleRomaji ?? node.titleNative;
}
/**
* True when `node` names `targetId` only through relations that do not join a
* franchise. AniList records most links from both ends; a spin-off can point
* back at its original as PARENT, so the original's SPIN_OFF edge has to veto
* the join or excluding SPIN_OFF would not keep the two apart.
*/
function vetoes(node: AnilistMediaNode, targetId: number): boolean {
const edges = node.relations.filter((edge) => edge.targetId === targetId);
return edges.length > 0 && !edges.some((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType));
}
function franchiseTargets(node: AnilistMediaNode): number[] {
return node.relations
.filter((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType))
.map((edge) => edge.targetId);
}
// TV first, then other episodic formats, then films/OVAs/specials, then entries with no data.
function formatRank(format: string | null): number {
if (format === 'TV') return 0;
if (format === 'TV_SHORT' || format === 'ONA') return 1;
return format === null ? 3 : 2;
}
export function buildFranchiseGraph(nodes: Iterable<AnilistMediaNode>): FranchiseGraph {
const byId = new Map<number, AnilistMediaNode>();
for (const node of nodes) byId.set(node.anilistId, node);
const parent = new Map<number, number>();
const find = (id: number): number => {
let top = parent.get(id) ?? id;
if (!parent.has(id)) parent.set(id, id);
while (parent.get(top) !== top) top = parent.get(top)!;
// Path compression keeps long sequel chains cheap.
let at = id;
while (at !== top) {
const next = parent.get(at)!;
parent.set(at, top);
at = next;
}
return top;
};
for (const node of byId.values()) {
find(node.anilistId);
for (const targetId of franchiseTargets(node)) {
const target = byId.get(targetId);
if (target && vetoes(target, node.anilistId)) continue;
const a = find(node.anilistId);
const b = find(targetId);
if (a !== b) parent.set(b, a);
}
}
const members = new Map<number, number[]>();
for (const id of parent.keys()) {
const top = find(id);
const list = members.get(top);
if (list) list.push(id);
else members.set(top, [id]);
}
// A franchise is named after its first TV series, else its first episodic
// entry, else its earliest entry; ties go to the lower id.
const compareRoots = (a: number, b: number): number => {
const left = byId.get(a);
const right = byId.get(b);
return (
formatRank(left?.format ?? null) - formatRank(right?.format ?? null) ||
(left?.startDate ?? Number.MAX_SAFE_INTEGER) -
(right?.startDate ?? Number.MAX_SAFE_INTEGER) ||
a - b
);
};
const roots = new Map<number, number>();
for (const ids of members.values()) {
const root = [...ids].sort(compareRoots)[0]!;
for (const id of ids) roots.set(id, root);
}
return {
node: (anilistId) => byId.get(anilistId),
rootOf: (anilistId) => roots.get(anilistId),
};
}
const FETCH_CHUNK_SIZE = 50;
export interface FranchiseWalkOptions {
/** AniList ids the walk starts from (the library's own entries). */
seeds: readonly number[];
/** Cached entries; updated in place with everything fetched. */
known: Map<number, AnilistMediaNode>;
isFresh: (node: AnilistMediaNode) => boolean;
/** Entries AniList returned for `ids` (at most 50). Throws on transport or API failure. */
fetchNodes: (ids: number[]) => Promise<AnilistMediaNode[]>;
/** Called once per fetched batch so progress survives a later failure. */
onBatch: (nodes: AnilistMediaNode[]) => void;
now: () => number;
/** Hops from a seed; entries at this depth are fetched but not followed. */
maxDepth: number;
/** Most entries fetched in one walk; the rest wait for the next walk. */
maxFetch: number;
/** When true, the walk starts no further request and drops an in-flight result. */
isCancelled?: () => boolean;
}
export interface FranchiseWalkResult {
fetched: number;
/** True when the fetch budget ran out before every stale entry was refreshed. */
truncated: boolean;
}
/**
* Breadth-first walk from the seeds along franchise relations, fetching
* entries that are missing or stale. Fresh cached entries are followed without
* a request. An entry AniList does not return keeps its previous data (or gets
* an empty placeholder) so it is not asked about again until it goes stale; a
* thrown fetch error stops the walk and leaves the cache as it was.
*/
export async function walkFranchiseRelations(
options: FranchiseWalkOptions,
): Promise<FranchiseWalkResult> {
const { known } = options;
const visited = new Set<number>();
// `from` lists every entry the walk reached this one through at this depth
// (empty for a seed), so the order seeds are given in cannot change the result.
let frontier: Array<{ id: number; from: number[] }> = [...new Set(options.seeds)].map((id) => ({
id,
from: [],
}));
let fetched = 0;
let truncated = false;
for (let depth = 0; frontier.length > 0; depth += 1) {
for (const step of frontier) visited.add(step.id);
const stale = frontier
.map((step) => step.id)
.filter((id) => {
const node = known.get(id);
return !node || !options.isFresh(node);
});
const allowed = stale.slice(0, Math.max(0, options.maxFetch - fetched));
if (allowed.length < stale.length) truncated = true;
for (let start = 0; start < allowed.length; start += FETCH_CHUNK_SIZE) {
if (options.isCancelled?.()) return { fetched, truncated: true };
const chunk = allowed.slice(start, start + FETCH_CHUNK_SIZE);
const fetchedNodes = await options.fetchNodes(chunk);
if (options.isCancelled?.()) return { fetched, truncated: true };
const found = new Map(fetchedNodes.map((node) => [node.anilistId, node] as const));
const fetchedAtMs = options.now();
const batch = chunk.map((id): AnilistMediaNode => {
const node = found.get(id);
if (node) return node;
const previous = known.get(id);
if (previous) return { ...previous, fetchedAtMs };
return {
anilistId: id,
format: null,
titleRomaji: null,
titleEnglish: null,
titleNative: null,
startDate: null,
episodes: null,
relations: [],
fetchedAtMs,
};
});
for (const node of batch) known.set(node.anilistId, node);
options.onBatch(batch);
fetched += chunk.length;
}
if (depth >= options.maxDepth) break;
const next = new Map<number, number[]>();
for (const step of frontier) {
const node = known.get(step.id);
if (!node) continue;
// Reached only through links the entry itself rejects (a spin-off's
// original): it is not part of the franchise, so its own links are not
// followed. One accepted incoming link is enough.
if (step.from.length > 0 && step.from.every((fromId) => vetoes(node, fromId))) continue;
for (const targetId of franchiseTargets(node)) {
if (visited.has(targetId)) continue;
const from = next.get(targetId);
if (from) from.push(node.anilistId);
else next.set(targetId, [node.anilistId]);
}
}
frontier = [...next].map(([id, from]) => ({ id, from }));
}
return { fetched, truncated };
}
@@ -0,0 +1,83 @@
import { executeAnilistQuery } from './anilist-graphql';
import type { AnilistMediaNode, AnilistRelationEdge } from './franchise-graph';
import type { AnilistRateLimiter } from './rate-limiter';
/** Loads AniList entries with their relations, for the library's franchise grouping. */
export interface AnilistRelationFetcher {
/** Entries AniList returned for `ids` (at most 50); ids it does not know are absent. */
fetchMedia(ids: number[]): Promise<AnilistMediaNode[]>;
}
const RELATIONS_QUERY = `
query ($ids: [Int], $perPage: Int) {
Page(page: 1, perPage: $perPage) {
media(id_in: $ids, type: ANIME) {
id
format
episodes
title { romaji english native }
startDate { year month day }
relations { edges { relationType(version: 2) node { id type } } }
}
}
}`;
interface RelationsMedia {
id: number;
format: string | null;
episodes: number | null;
title: { romaji: string | null; english: string | null; native: string | null } | null;
startDate: { year: number | null; month: number | null; day: number | null } | null;
relations: {
edges: Array<{
relationType: string | null;
node: { id: number; type: string | null } | null;
} | null> | null;
} | null;
}
interface RelationsResponse {
Page: { media: Array<RelationsMedia | null> | null } | null;
}
export function toAnilistMediaNode(media: RelationsMedia, fetchedAtMs: number): AnilistMediaNode {
const start = media.startDate;
const relations: AnilistRelationEdge[] = [];
for (const edge of media.relations?.edges ?? []) {
// Manga and novels are not part of a watch library.
if (!edge?.relationType || edge.node?.type !== 'ANIME') continue;
relations.push({ relationType: edge.relationType, targetId: edge.node.id });
}
return {
anilistId: media.id,
format: media.format,
titleRomaji: media.title?.romaji ?? null,
titleEnglish: media.title?.english ?? null,
titleNative: media.title?.native ?? null,
startDate: start?.year
? start.year * 10_000 + (start.month ?? 0) * 100 + (start.day ?? 0)
: null,
episodes: media.episodes,
relations,
fetchedAtMs,
};
}
export function createAnilistRelationFetcher(
rateLimiter: AnilistRateLimiter,
now: () => number = Date.now,
): AnilistRelationFetcher {
return {
async fetchMedia(ids) {
if (ids.length === 0) return [];
const data = await executeAnilistQuery<RelationsResponse>(rateLimiter, RELATIONS_QUERY, {
ids,
perPage: ids.length,
});
const fetchedAtMs = now();
return (data.Page?.media ?? [])
.filter((media): media is RelationsMedia => media !== null)
.map((media) => toAnilistMediaNode(media, fetchedAtMs));
},
};
}
@@ -4,11 +4,22 @@ import assert from 'node:assert/strict';
import { 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);
} }
@@ -4,6 +4,18 @@ import { createLogger } from '../../logger';
import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity'; import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity';
import { MediaGenerator } from '../../media-generator'; import { MediaGenerator } from '../../media-generator';
import type { CoverArtFetcher } from './anilist/cover-art-fetcher'; import type { CoverArtFetcher } from './anilist/cover-art-fetcher';
import type { AnilistRelationFetcher } from './anilist/franchise-relation-fetcher';
import {
createFranchiseRelationRefresher,
type FranchiseRelationRefresher,
} from './immersion-tracker/franchise-relation-refresher';
import {
getAnimeGroupPlacement,
getAnimeLibraryGroups,
setAnimeGroupOverride,
type AnimeGroupOverrideResult,
type AnimeGroupOverrideTarget,
} from './immersion-tracker/query-library-groups';
import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata'; import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata';
import { import {
pruneRawRetention, pruneRawRetention,
@@ -61,6 +73,7 @@ import type {
StatsTrendGroupBy, StatsTrendGroupBy,
StatsTrendRange, StatsTrendRange,
} from '../../types/stats-http-contract'; } from '../../types/stats-http-contract';
import type { AnimeGroupPlacement, AnimeLibraryGroup } from '../../types/stats-wire';
import { import {
getKanjiAnimeAppearances, getKanjiAnimeAppearances,
getKanjiDetail, getKanjiDetail,
@@ -452,6 +465,7 @@ export class ImmersionTrackerService {
private readonly mediaGenerator = new MediaGenerator(); private readonly mediaGenerator = new MediaGenerator();
private readonly preparedStatements: TrackerPreparedStatements; private readonly preparedStatements: TrackerPreparedStatements;
private coverArtFetcher: CoverArtFetcher | null = null; private coverArtFetcher: CoverArtFetcher | null = null;
private franchiseRelations: FranchiseRelationRefresher | null = null;
private readonly pendingCoverFetches = new Map<number, Promise<boolean>>(); private readonly pendingCoverFetches = new Map<number, Promise<boolean>>();
private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>(); private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>();
private readonly recordedSubtitleKeys = new Set<string>(); private readonly recordedSubtitleKeys = new Set<string>();
@@ -621,6 +635,7 @@ export class ImmersionTrackerService {
} }
this.finalizeActiveSession(); this.finalizeActiveSession();
this.isDestroyed = true; this.isDestroyed = true;
this.franchiseRelations?.stop();
this.deleteMaintenanceScheduler.destroy(); this.deleteMaintenanceScheduler.destroy();
this.destroyDeleteMaintenanceRunner(); this.destroyDeleteMaintenanceRunner();
this.destroyVocabularySummaryRunner(); this.destroyVocabularySummaryRunner();
@@ -833,6 +848,27 @@ export class ImmersionTrackerService {
return getAnimeLibrary(this.db); return getAnimeLibrary(this.db);
} }
/** The library as franchise cards; also schedules a background AniList relation refresh. */
async getAnimeLibraryGroups(): Promise<AnimeLibraryGroup[]> {
this.relinkYoutubeAnimeLibrary();
const groups = getAnimeLibraryGroups(this.db);
this.franchiseRelations?.requestRefresh();
return groups;
}
async getAnimeGroupPlacement(animeId: number): Promise<AnimeGroupPlacement | null> {
return getAnimeGroupPlacement(this.db, animeId);
}
async setAnimeGroupOverride(
animeId: number,
target: AnimeGroupOverrideTarget,
): Promise<AnimeGroupOverrideResult> {
const result = setAnimeGroupOverride(this.db, animeId, target);
if (result.ok) this.franchiseRelations?.requestRefresh({ force: true });
return result;
}
async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> { async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> {
return getAnimeMergeRecommendations(this.db); return getAnimeMergeRecommendations(this.db);
} }
@@ -1122,6 +1158,7 @@ export class ImmersionTrackerService {
this.db.exec('ROLLBACK'); this.db.exec('ROLLBACK');
throw error; throw error;
} }
this.franchiseRelations?.requestRefresh({ force: true });
} }
/** /**
@@ -1248,6 +1285,19 @@ export class ImmersionTrackerService {
this.coverArtFetcher = fetcher; this.coverArtFetcher = fetcher;
} }
/** Enables franchise grouping refreshes; null disables them (tests, offline runs). */
setAnilistRelationFetcher(fetcher: AnilistRelationFetcher | null): void {
this.franchiseRelations?.stop();
this.franchiseRelations = fetcher
? createFranchiseRelationRefresher({
db: this.db,
fetcher,
logger: createLogger('immersion-tracker:franchise-relations'),
})
: null;
this.franchiseRelations?.requestRefresh();
}
async ensureAnimeCoverArt(animeId: number): Promise<boolean> { async ensureAnimeCoverArt(animeId: number): Promise<boolean> {
const existing = await this.getAnimeCoverArt(animeId); const existing = await this.getAnimeCoverArt(animeId);
if (existing?.coverBlob) { if (existing?.coverBlob) {
@@ -1300,6 +1350,8 @@ export class ImmersionTrackerService {
if (!fetched) { if (!fetched) {
return false; return false;
} }
// A fresh AniList link may join this entry to a franchise card.
this.franchiseRelations?.requestRefresh({ force: true });
const cover = await this.getCoverArt(videoId); const cover = await this.getCoverArt(videoId);
return cover?.coverBlob != null; return cover?.coverBlob != null;
})(); })();
@@ -0,0 +1,126 @@
import type { AnilistMediaNode } from '../anilist/franchise-graph';
import type { DatabaseSync } from './sqlite';
import { fromDbTimestamp, toDbTimestamp } from './query-shared';
/**
* Franchise grouping state. `imm_anilist_media` and `imm_anilist_relations`
* cache AniList entries (owned or reached through relations) and every
* anime-to-anime edge, whatever its type, so the grouping rule can change
* without a refetch. The cache is rebuildable from AniList and is not synced.
*
* `imm_anime.group_override` is the user's choice for one library entry:
* NULL follows AniList, 0 keeps the entry on its own, and a positive value is
* an AniList id whose franchise the entry joins. `group_override_updated_at`
* records when it was set (or cleared) so sync can keep the newer choice.
*/
export function ensureAnimeGroupingSchema(db: DatabaseSync): void {
db.exec(`
CREATE TABLE IF NOT EXISTS imm_anilist_media(
anilist_id INTEGER PRIMARY KEY,
format TEXT,
title_romaji TEXT,
title_english TEXT,
title_native TEXT,
start_date INTEGER,
episodes INTEGER,
fetched_at_ms TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS imm_anilist_relations(
anilist_id INTEGER NOT NULL,
relation_type TEXT NOT NULL,
target_anilist_id INTEGER NOT NULL,
PRIMARY KEY(anilist_id, relation_type, target_anilist_id),
FOREIGN KEY(anilist_id) REFERENCES imm_anilist_media(anilist_id) ON DELETE CASCADE
);
`);
const columns = new Set(
(db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>).map(
(column) => column.name,
),
);
if (!columns.has('group_override')) {
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override INTEGER');
}
if (!columns.has('group_override_updated_at')) {
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override_updated_at TEXT');
}
}
export function readAnilistRelationCache(db: DatabaseSync): Map<number, AnilistMediaNode> {
const nodes = new Map<number, AnilistMediaNode>();
const mediaRows = db
.prepare(
`SELECT anilist_id AS anilistId, format, title_romaji AS titleRomaji,
title_english AS titleEnglish, title_native AS titleNative,
start_date AS startDate, episodes, fetched_at_ms AS fetchedAtMs
FROM imm_anilist_media`,
)
.all() as Array<Omit<AnilistMediaNode, 'relations' | 'fetchedAtMs'> & { fetchedAtMs: string }>;
for (const row of mediaRows) {
nodes.set(row.anilistId, {
...row,
relations: [],
fetchedAtMs: fromDbTimestamp(row.fetchedAtMs) ?? 0,
});
}
const edgeRows = db
.prepare(
`SELECT anilist_id AS anilistId, relation_type AS relationType, target_anilist_id AS targetId
FROM imm_anilist_relations
ORDER BY anilist_id, relation_type, target_anilist_id`,
)
.all() as Array<{ anilistId: number; relationType: string; targetId: number }>;
for (const edge of edgeRows) {
nodes.get(edge.anilistId)?.relations.push({
relationType: edge.relationType,
targetId: edge.targetId,
});
}
return nodes;
}
/** Replaces each node's cached row and edges in one transaction. */
export function writeAnilistRelationNodes(db: DatabaseSync, nodes: AnilistMediaNode[]): void {
if (nodes.length === 0) return;
const upsertMedia = db.prepare(`
INSERT INTO imm_anilist_media(anilist_id, format, title_romaji, title_english, title_native,
start_date, episodes, fetched_at_ms)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(anilist_id) DO UPDATE SET
format = excluded.format,
title_romaji = excluded.title_romaji,
title_english = excluded.title_english,
title_native = excluded.title_native,
start_date = excluded.start_date,
episodes = excluded.episodes,
fetched_at_ms = excluded.fetched_at_ms
`);
const deleteEdges = db.prepare('DELETE FROM imm_anilist_relations WHERE anilist_id = ?');
const insertEdge = db.prepare(`
INSERT OR IGNORE INTO imm_anilist_relations(anilist_id, relation_type, target_anilist_id)
VALUES (?, ?, ?)
`);
db.exec('BEGIN IMMEDIATE');
try {
for (const node of nodes) {
upsertMedia.run(
node.anilistId,
node.format,
node.titleRomaji,
node.titleEnglish,
node.titleNative,
node.startDate,
node.episodes,
toDbTimestamp(node.fetchedAtMs),
);
deleteEdges.run(node.anilistId);
for (const edge of node.relations) {
insertEdge.run(node.anilistId, edge.relationType, edge.targetId);
}
}
db.exec('COMMIT');
} catch (error) {
db.exec('ROLLBACK');
throw error;
}
}
@@ -0,0 +1,75 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { AnilistMediaNode } from '../anilist/franchise-graph';
import { readAnilistRelationCache } from './anilist-relation-cache';
import {
createFranchiseRelationRefresher,
FRANCHISE_RELATION_STALE_MS,
} from './franchise-relation-refresher';
import { Database } from './sqlite';
import { ensureSchema } from './storage';
const silent = { info: () => {}, warn: () => {} };
function media(anilistId: number, relations: Array<[string, number]>, fetchedAtMs: number) {
return {
anilistId,
format: 'TV',
titleRomaji: null,
titleEnglish: null,
titleNative: null,
startDate: null,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs,
} satisfies AnilistMediaNode;
}
test('refresh walks from linked entries and override targets, then keeps the cache on failure', async () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
db.exec(`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, media_kind)
VALUES ('a', 'A', 1, 'anime'), ('c', 'C', 77, 'youtube');
INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override)
VALUES ('b', 'B', 50)`);
let clock = 1_000;
let failing = false;
const asked: number[][] = [];
const refresher = createFranchiseRelationRefresher({
db,
logger: silent,
now: () => clock,
fetcher: {
fetchMedia: async (ids) => {
if (failing) throw new Error('AniList down');
asked.push([...ids].sort((a, b) => a - b));
return ids.map((id) => media(id, id === 1 ? [['SEQUEL', 2]] : [], clock));
},
},
});
refresher.requestRefresh();
await refresher.whenIdle();
assert.deepEqual(asked, [[1, 50], [2]]);
assert.deepEqual(
[...readAnilistRelationCache(db).keys()].sort((a, b) => a - b),
[1, 2, 50],
);
// Throttled until forced; everything is fresh, so a forced run asks nothing.
refresher.requestRefresh({ force: true });
await refresher.whenIdle();
assert.equal(asked.length, 2);
clock += FRANCHISE_RELATION_STALE_MS;
failing = true;
refresher.requestRefresh({ force: true });
await refresher.whenIdle();
assert.deepEqual(readAnilistRelationCache(db).get(1)?.relations, [
{ relationType: 'SEQUEL', targetId: 2 },
]);
} finally {
db.close();
}
});
@@ -0,0 +1,121 @@
import { walkFranchiseRelations } from '../anilist/franchise-graph';
import type { AnilistRelationFetcher } from '../anilist/franchise-relation-fetcher';
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
import type { DatabaseSync } from './sqlite';
/** Cached AniList entries are asked about again after a week. */
export const FRANCHISE_RELATION_STALE_MS = 7 * 24 * 60 * 60 * 1000;
/** Hops followed from a library entry; keeps long-running franchises bounded. */
export const FRANCHISE_WALK_MAX_DEPTH = 6;
/** Entries fetched per refresh (five AniList requests); the rest wait for the next refresh. */
export const FRANCHISE_WALK_MAX_FETCH = 250;
/** Unforced refreshes (library polls) run at most this often. */
const MIN_INTERVAL_MS = 10 * 60 * 1000;
interface RefresherLogger {
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
}
export interface FranchiseRelationRefresherDeps {
db: DatabaseSync;
fetcher: AnilistRelationFetcher;
logger: RefresherLogger;
now?: () => number;
}
export interface FranchiseRelationRefresher {
/**
* Starts a background refresh unless one ran recently. `force` skips that
* throttle, for when an entry has just been linked to AniList.
*/
requestRefresh(options?: { force?: boolean }): void;
/** Resolves once no refresh is running; for tests and shutdown. */
whenIdle(): Promise<void>;
/** Stops writing; a running refresh finishes its request and discards the result. */
stop(): void;
}
function readSeeds(db: DatabaseSync): number[] {
return (
db
.prepare(
`SELECT anilist_id AS id FROM imm_anime WHERE media_kind = 'anime' AND anilist_id IS NOT NULL
UNION
SELECT group_override AS id FROM imm_anime WHERE group_override > 0`,
)
.all() as Array<{ id: number }>
).map((row) => row.id);
}
export function createFranchiseRelationRefresher(
deps: FranchiseRelationRefresherDeps,
): FranchiseRelationRefresher {
const now = deps.now ?? Date.now;
let running: Promise<void> | null = null;
let pending = false;
let stopped = false;
let lastStartedAtMs: number | null = null;
const refreshOnce = async (): Promise<void> => {
const known = readAnilistRelationCache(deps.db);
const result = await walkFranchiseRelations({
seeds: readSeeds(deps.db),
known,
isFresh: (node) => now() - node.fetchedAtMs < FRANCHISE_RELATION_STALE_MS,
fetchNodes: (ids) => deps.fetcher.fetchMedia(ids),
onBatch: (nodes) => writeAnilistRelationNodes(deps.db, nodes),
isCancelled: () => stopped,
now,
maxDepth: FRANCHISE_WALK_MAX_DEPTH,
maxFetch: FRANCHISE_WALK_MAX_FETCH,
});
if (result.fetched > 0) {
deps.logger.info(
'franchise-relations: refreshed %d AniList entries%s',
result.fetched,
result.truncated ? ' (more next time)' : '',
);
}
};
const run = (): void => {
lastStartedAtMs = now();
running = (async () => {
try {
do {
pending = false;
await refreshOnce();
} while (pending && !stopped);
} catch (error) {
// Cached rows stay as they were; the next request (after the throttle) retries.
deps.logger.warn(
'franchise-relations: refresh failed: %s',
error instanceof Error ? error.message : String(error),
);
} finally {
running = null;
}
})();
};
return {
requestRefresh(options = {}) {
if (stopped) return;
if (running) {
if (options.force) pending = true;
return;
}
if (!options.force && lastStartedAtMs !== null && now() - lastStartedAtMs < MIN_INTERVAL_MS) {
return;
}
run();
},
async whenIdle() {
while (running) await running;
},
stop() {
stopped = true;
},
};
}
@@ -2,7 +2,7 @@ import crypto from 'node:crypto';
import { spawn as nodeSpawn } from 'node:child_process'; import { spawn as nodeSpawn } from 'node:child_process';
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { parseMediaInfo } from '../../../jimaku/utils'; import { parseMediaLookupInfo } from '../../../jimaku/utils';
import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../../../shared/media-identity'; import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../../../shared/media-identity';
import { import {
guessAnilistMediaInfo, guessAnilistMediaInfo,
@@ -214,7 +214,7 @@ export async function guessAnimeVideoMetadata(
}; };
} }
const fallbackInfo = parseMediaInfo(lookupTarget); const fallbackInfo = parseMediaLookupInfo(mediaPath, mediaTitle);
return { return {
parsedBasename: parsedBasename ?? fallbackInfo.filename ?? null, parsedBasename: parsedBasename ?? fallbackInfo.filename ?? null,
parsedTitle: parsed.title, parsedTitle: parsed.title,
@@ -0,0 +1,226 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildFranchiseGraph, type AnilistMediaNode } from '../anilist/franchise-graph';
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
import {
getAnimeGroupPlacement,
getAnimeLibraryGroups,
groupAnimeLibrary,
setAnimeGroupOverride,
type GroupableLibraryRow,
} from './query-library-groups';
import { Database, type DatabaseSync } from './sqlite';
import { ensureSchema } from './storage';
import { SCHEMA_VERSION } from './types';
function node(
anilistId: number,
format: string,
startDate: number,
relations: Array<[string, number]>,
titleEnglish: string | null = null,
): AnilistMediaNode {
return {
anilistId,
format,
titleRomaji: `romaji ${anilistId}`,
titleEnglish,
titleNative: null,
startDate,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs: 1,
};
}
// Owned: season 2 and a film. The first season (the root) is not in the library.
const overlordNodes = [
node(
20832,
'TV',
20150707,
[
['SEQUEL', 98437],
['SUMMARY', 98873],
],
'Overlord',
),
node(98873, 'MOVIE', 20170225, [['PARENT', 20832]]),
node(98437, 'TV', 20180109, [['PREQUEL', 20832]]),
];
function row(
animeId: number,
anilistId: number | null,
overrides: Partial<GroupableLibraryRow> = {},
): GroupableLibraryRow {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: `Entry ${animeId}`,
anilistId,
tmdbId: null,
tmdbType: null,
totalSessions: 1,
totalActiveMs: 1000 * animeId,
totalCards: animeId,
totalTokensSeen: 10,
episodeCount: 2,
episodesTotal: null,
lastWatchedMs: 100 * animeId,
groupOverride: null,
...overrides,
};
}
test('owned parts join under the unowned root, in release order, with summed totals', () => {
const graph = buildFranchiseGraph(overlordNodes);
const groups = groupAnimeLibrary([row(1, 98437), row(2, 98873), row(3, null)], graph);
assert.equal(groups.length, 2);
const overlord = groups.find((group) => group.groupKey === 20832)!;
assert.equal(overlord.title, 'Overlord');
assert.deepEqual(
overlord.parts.map((part) => [part.animeId, part.format, part.startDate]),
[
[2, 'MOVIE', 20170225],
[1, 'TV', 20180109],
],
);
assert.equal(overlord.coverAnimeId, 2);
assert.deepEqual(
[overlord.totalActiveMs, overlord.totalCards, overlord.episodeCount, overlord.lastWatchedMs],
[3000, 3, 4, 200],
);
});
test('entries without AniList data stay single cards that look like the entry', () => {
const graph = buildFranchiseGraph([]);
const lone = row(7, 555, { canonicalTitle: 'Bocchi the Rock!' });
const [linked, unlinked, channel] = groupAnimeLibrary(
[lone, row(3, null), row(2, null, { mediaKind: 'youtube', groupOverride: 555 })],
graph,
);
assert.deepEqual(
[linked!.groupKey, linked!.title, linked!.coverAnimeId, linked!.parts.length],
[555, 'Bocchi the Rock!', 7, 1],
);
const { groupOverride: _override, ...item } = lone;
assert.deepEqual(linked!.parts[0], { ...item, format: null, startDate: null });
assert.equal(unlinked!.groupKey, -3);
// Overrides never apply to YouTube or live-action entries.
assert.equal(channel!.groupKey, -2);
});
test('overrides move an entry to another franchise or keep it on its own', () => {
const graph = buildFranchiseGraph(overlordNodes);
const groups = groupAnimeLibrary(
[
row(1, 98437),
row(2, 98873, { groupOverride: 0 }),
// Unlinked specials moved in by the user, pointing at any part of the franchise.
row(3, null, { groupOverride: 98437 }),
],
graph,
);
assert.deepEqual(
groups
.map((group) => [group.groupKey, group.parts.map((part) => part.animeId)] as const)
.sort((a, b) => a[0] - b[0]),
[
[-2, [2]],
[20832, [1, 3]],
],
);
});
function seed(db: DatabaseSync, title: string, anilistId: number | null): number {
const animeId = Number(
db
.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id) VALUES (?, ?, ?)`,
)
.run(title.toLowerCase(), title, anilistId).lastInsertRowid,
);
db.prepare(
`INSERT INTO imm_videos(video_key, anime_id, canonical_title, source_type, duration_ms)
VALUES (?, ?, ?, 1, 0)`,
).run(`key:${title}`, animeId, title);
db.prepare(
'INSERT INTO imm_lifetime_anime(anime_id, total_active_ms, total_cards) VALUES (?, 60000, 1)',
).run(animeId);
return animeId;
}
test('library groups and overrides round-trip through the database', () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
const season2 = seed(db, 'Overlord II', 98437);
const film = seed(db, 'The Undead King', 98873);
const specials = seed(db, 'Overlord specials', null);
const other = seed(db, 'Bocchi the Rock!', 130003);
// No cached relations yet: every entry is its own card.
assert.equal(getAnimeLibraryGroups(db).length, 4);
writeAnilistRelationNodes(db, overlordNodes);
assert.deepEqual(readAnilistRelationCache(db).get(20832), overlordNodes[0]);
assert.deepEqual(getAnimeGroupPlacement(db, film), {
groupKey: 20832,
title: 'Overlord',
partCount: 2,
overrideMode: 'anilist',
});
assert.deepEqual(
setAnimeGroupOverride(db, specials, { mode: 'join', targetAnimeId: season2 }),
{
ok: true,
},
);
assert.deepEqual(setAnimeGroupOverride(db, film, { mode: 'standalone' }), { ok: true });
assert.deepEqual(setAnimeGroupOverride(db, other, { mode: 'join', targetAnimeId: film }), {
ok: false,
reason: 'target-not-grouped',
});
assert.deepEqual(setAnimeGroupOverride(db, 999, { mode: 'standalone' }), {
ok: false,
reason: 'not-found',
});
const stored = db
.prepare('SELECT group_override AS value FROM imm_anime WHERE anime_id = ?')
.get(specials) as { value: number };
assert.equal(stored.value, 20832);
assert.deepEqual(getAnimeGroupPlacement(db, specials), {
groupKey: 20832,
title: 'Overlord',
partCount: 2,
overrideMode: 'joined',
});
assert.equal(getAnimeGroupPlacement(db, film)?.overrideMode, 'standalone');
setAnimeGroupOverride(db, film, { mode: 'anilist' });
assert.equal(getAnimeGroupPlacement(db, film)?.partCount, 3);
} finally {
db.close();
}
});
test('schema 27 upgrade adds the relation cache and override columns', () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
db.exec(`DROP TABLE imm_anilist_relations; DROP TABLE imm_anilist_media;
ALTER TABLE imm_anime DROP COLUMN group_override;
ALTER TABLE imm_anime DROP COLUMN group_override_updated_at;`);
db.prepare('UPDATE imm_schema_version SET schema_version = ?').run(SCHEMA_VERSION - 1);
ensureSchema(db);
const columns = (db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>)
.map((column) => column.name)
.filter((name) => name.startsWith('group_override'));
assert.deepEqual(columns, ['group_override', 'group_override_updated_at']);
assert.equal(readAnilistRelationCache(db).size, 0);
} finally {
db.close();
}
});
@@ -0,0 +1,192 @@
import type {
AnimeGroupOverrideMode,
AnimeGroupPlacement,
AnimeLibraryGroup,
AnimeLibraryGroupPart,
} from '../../../types/stats-wire';
import {
anilistNodeTitle,
buildFranchiseGraph,
type FranchiseGraph,
} from '../anilist/franchise-graph';
import { readAnilistRelationCache } from './anilist-relation-cache';
import { toDbTimestamp } from './query-shared';
import { getAnimeLibrary } from './query-library';
import type { DatabaseSync } from './sqlite';
import { nowMs } from './time';
import type { AnimeLibraryRow } from './types';
/** `imm_anime.group_override` value that keeps an entry on its own. */
export const GROUP_OVERRIDE_STANDALONE = 0;
export interface GroupableLibraryRow extends AnimeLibraryRow {
groupOverride: number | null;
}
function overrideMode(row: GroupableLibraryRow): AnimeGroupOverrideMode {
if (row.mediaKind !== 'anime' || row.groupOverride === null || row.groupOverride < 0) {
return 'anilist';
}
return row.groupOverride === GROUP_OVERRIDE_STANDALONE ? 'standalone' : 'joined';
}
/**
* The card an entry belongs to: positive keys are AniList ids (the franchise
* root once its relations are cached, the entry's own id until then), negative
* keys are `-animeId` for entries listed on their own. Overrides only apply to
* anime entries; live-action and YouTube rows always stand alone.
*/
function groupKeyFor(row: GroupableLibraryRow, graph: FranchiseGraph): number {
const mode = overrideMode(row);
if (mode === 'standalone') return -row.animeId;
if (mode === 'joined') return graph.rootOf(row.groupOverride!) ?? row.groupOverride!;
if (row.mediaKind === 'anime' && row.anilistId !== null) {
return graph.rootOf(row.anilistId) ?? row.anilistId;
}
return -row.animeId;
}
function toPart(row: GroupableLibraryRow, graph: FranchiseGraph): AnimeLibraryGroupPart {
const { groupOverride: _groupOverride, ...item } = row;
const node =
row.mediaKind === 'anime' && row.anilistId !== null ? graph.node(row.anilistId) : undefined;
return { ...item, format: node?.format ?? null, startDate: node?.startDate ?? null };
}
// Release order; entries AniList has no date for go last, in library order.
function compareParts(a: AnimeLibraryGroupPart, b: AnimeLibraryGroupPart): number {
return (
(a.startDate ?? Number.MAX_SAFE_INTEGER) - (b.startDate ?? Number.MAX_SAFE_INTEGER) ||
a.animeId - b.animeId
);
}
/**
* Groups library rows into franchise cards. A card with one part keeps that
* entry's own title, so ungrouped entries render exactly as before; a card with
* several parts is named after the franchise root, even when the root itself
* is not in the library.
*/
export function groupAnimeLibrary(
rows: GroupableLibraryRow[],
graph: FranchiseGraph,
): AnimeLibraryGroup[] {
const byKey = new Map<number, GroupableLibraryRow[]>();
for (const row of rows) {
const key = groupKeyFor(row, graph);
const members = byKey.get(key);
if (members) members.push(row);
else byKey.set(key, [row]);
}
const groups: AnimeLibraryGroup[] = [];
for (const [groupKey, members] of byKey) {
const parts = members.map((row) => toPart(row, graph)).sort(compareParts);
const first = parts[0]!;
const rootNode = groupKey > 0 ? graph.node(groupKey) : undefined;
const title =
parts.length === 1
? first.canonicalTitle
: ((rootNode ? anilistNodeTitle(rootNode) : null) ??
parts.find((part) => part.anilistId === groupKey)?.canonicalTitle ??
first.canonicalTitle);
groups.push({
groupKey,
title,
mediaKind: first.mediaKind,
coverAnimeId: first.animeId,
totalSessions: parts.reduce((sum, part) => sum + part.totalSessions, 0),
totalActiveMs: parts.reduce((sum, part) => sum + part.totalActiveMs, 0),
totalCards: parts.reduce((sum, part) => sum + part.totalCards, 0),
totalTokensSeen: parts.reduce((sum, part) => sum + part.totalTokensSeen, 0),
episodeCount: parts.reduce((sum, part) => sum + part.episodeCount, 0),
lastWatchedMs: Math.max(...parts.map((part) => part.lastWatchedMs)),
parts,
});
}
return groups.sort((a, b) => b.totalActiveMs - a.totalActiveMs || a.groupKey - b.groupKey);
}
function readGroupableLibrary(db: DatabaseSync): GroupableLibraryRow[] {
const overrides = new Map(
(
db
.prepare(
'SELECT anime_id AS animeId, group_override AS groupOverride FROM imm_anime WHERE group_override IS NOT NULL',
)
.all() as Array<{ animeId: number; groupOverride: number }>
).map((row) => [row.animeId, row.groupOverride] as const),
);
return getAnimeLibrary(db).map((row) => ({
...row,
groupOverride: overrides.get(row.animeId) ?? null,
}));
}
export function getAnimeLibraryGroups(db: DatabaseSync): AnimeLibraryGroup[] {
return groupAnimeLibrary(
readGroupableLibrary(db),
buildFranchiseGraph(readAnilistRelationCache(db).values()),
);
}
/** The card an entry is listed under, or null when the entry is not in the library list. */
export function getAnimeGroupPlacement(
db: DatabaseSync,
animeId: number,
): AnimeGroupPlacement | null {
const rows = readGroupableLibrary(db);
const row = rows.find((candidate) => candidate.animeId === animeId);
if (!row) return null;
const group = groupAnimeLibrary(
rows,
buildFranchiseGraph(readAnilistRelationCache(db).values()),
).find((candidate) => candidate.parts.some((part) => part.animeId === animeId));
if (!group) return null;
return {
groupKey: group.groupKey,
title: group.title,
partCount: group.parts.length,
overrideMode: overrideMode(row),
};
}
/** Where to put an entry: with another entry's franchise, on its own, or where AniList has it. */
export type AnimeGroupOverrideTarget =
| { mode: 'join'; targetAnimeId: number }
| { mode: 'standalone' }
| { mode: 'anilist' };
export type AnimeGroupOverrideResult =
| { ok: true }
| { ok: false; reason: 'not-found' | 'unsupported-kind' | 'target-not-grouped' };
/**
* Stores the user's grouping choice for one anime entry. Joining stores the
* target's current card key, which is always an AniList id: entries without
* one cannot be joined (merge them instead).
*/
export function setAnimeGroupOverride(
db: DatabaseSync,
animeId: number,
target: AnimeGroupOverrideTarget,
): AnimeGroupOverrideResult {
const row = db
.prepare('SELECT media_kind AS mediaKind FROM imm_anime WHERE anime_id = ?')
.get(animeId) as { mediaKind: string } | undefined;
if (!row) return { ok: false, reason: 'not-found' };
if (row.mediaKind !== 'anime') return { ok: false, reason: 'unsupported-kind' };
let value: number | null = null;
if (target.mode === 'standalone') value = GROUP_OVERRIDE_STANDALONE;
if (target.mode === 'join') {
const placement = getAnimeGroupPlacement(db, target.targetAnimeId);
if (!placement) return { ok: false, reason: 'not-found' };
if (placement.groupKey <= 0) return { ok: false, reason: 'target-not-grouped' };
value = placement.groupKey;
}
db.prepare(
'UPDATE imm_anime SET group_override = ?, group_override_updated_at = ? WHERE anime_id = ?',
).run(value, toDbTimestamp(nowMs()), animeId);
return { ok: true };
}
@@ -1,7 +1,7 @@
import { sameTitleNamespaceSql, type MediaKind } from '../../../shared/media-kind'; import { sameTitleNamespaceSql, type MediaKind } from '../../../shared/media-kind';
import { createHash } from 'node:crypto'; import { createHash } from 'node:crypto';
import path from 'node:path'; import path from 'node:path';
import { parseMediaInfo } from '../../../jimaku/utils'; import { parseMediaInfo, parseMediaTitleInfo } from '../../../jimaku/utils';
import { normalizeTitleIdentity } from '../../utils/title-normalization'; import { normalizeTitleIdentity } from '../../utils/title-normalization';
import type { DatabaseSync } from './sqlite'; import type { DatabaseSync } from './sqlite';
import { nowMs } from './time'; import { nowMs } from './time';
@@ -10,6 +10,7 @@ import { isVocabularyStatsRowVisible, type VocabularyVisibilityRow } from './voc
import { SCHEMA_VERSION } from './types'; import { SCHEMA_VERSION } from './types';
import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types'; import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types';
import { toDbTimestamp } from './query-shared'; import { toDbTimestamp } from './query-shared';
import { ensureAnimeGroupingSchema } from './anilist-relation-cache';
export interface TrackerPreparedStatements { export interface TrackerPreparedStatements {
telemetryInsertStmt: ReturnType<DatabaseSync['prepare']>; telemetryInsertStmt: ReturnType<DatabaseSync['prepare']>;
@@ -404,7 +405,7 @@ function parseLegacyAnimeBackfillCandidate(
const fallbackTitle = canonicalTitle.trim(); const fallbackTitle = canonicalTitle.trim();
if (!fallbackTitle) return null; if (!fallbackTitle) return null;
const fromTitle = parseMediaInfo(fallbackTitle); const fromTitle = parseMediaTitleInfo(fallbackTitle);
if (!fromTitle.title || looksLikeEpisodeOnlyTitle(fromTitle.title)) { if (!fromTitle.title || looksLikeEpisodeOnlyTitle(fromTitle.title)) {
return null; return null;
} }
@@ -998,6 +999,7 @@ export function ensureSchema(db: DatabaseSync): void {
ensureLifetimeSummaryTables(db); ensureLifetimeSummaryTables(db);
ensureStatsExcludedWordsTable(db); ensureStatsExcludedWordsTable(db);
ensureAnimeMergeTables(db); ensureAnimeMergeTables(db);
ensureAnimeGroupingSchema(db);
ensureSubtitleLineEventIndex(db); ensureSubtitleLineEventIndex(db);
return; return;
} }
@@ -1064,6 +1066,8 @@ export function ensureSchema(db: DatabaseSync): void {
'INTEGER NOT NULL DEFAULT 0 CHECK(anime_assignment_locked IN (0, 1))', 'INTEGER NOT NULL DEFAULT 0 CHECK(anime_assignment_locked IN (0, 1))',
); );
ensureAnimeMergeTables(db); ensureAnimeMergeTables(db);
// Schema 27: franchise grouping (AniList relation cache + per-entry override).
ensureAnimeGroupingSchema(db);
db.exec(` db.exec(`
CREATE TABLE IF NOT EXISTS imm_sessions( CREATE TABLE IF NOT EXISTS imm_sessions(
session_id INTEGER PRIMARY KEY AUTOINCREMENT, session_id INTEGER PRIMARY KEY AUTOINCREMENT,
+2 -1
View File
@@ -1,7 +1,8 @@
import type { MediaKind, TmdbMediaType } from '../../../shared/media-kind'; import type { MediaKind, TmdbMediaType } from '../../../shared/media-kind';
// 26: live-action entries (TMDB link) and YouTube channels share the media_kind column. // 26: live-action entries (TMDB link) and YouTube channels share the media_kind column.
export const SCHEMA_VERSION = 26; // 27: AniList relation cache and imm_anime.group_override for franchise grouping.
export const SCHEMA_VERSION = 27;
export const DEFAULT_QUEUE_CAP = 1_000; export const DEFAULT_QUEUE_CAP = 1_000;
export const DEFAULT_BATCH_SIZE = 25; export const DEFAULT_BATCH_SIZE = 25;
export const DEFAULT_FLUSH_INTERVAL_MS = 500; export const DEFAULT_FLUSH_INTERVAL_MS = 500;
+10
View File
@@ -40,10 +40,14 @@ import {
parseSessionActionDispatchRequest, parseSessionActionDispatchRequest,
parseSubtitlePosition, parseSubtitlePosition,
parseSubsyncManualRunRequest, parseSubsyncManualRunRequest,
parseUnforwardedMpvKeyReport,
parseYoutubePickerResolveRequest, parseYoutubePickerResolveRequest,
} from '../../shared/ipc/validators'; } from '../../shared/ipc/validators';
import { createLogger } from '../../logger';
import { applyOverlayClickThrough } from './overlay-click-through'; import { applyOverlayClickThrough } from './overlay-click-through';
const overlayInputLogger = createLogger('overlay:input');
const { ipcMain } = electron; const { ipcMain } = electron;
export interface IpcServiceDeps { export interface IpcServiceDeps {
@@ -640,6 +644,12 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
}, },
); );
// Shows, at --log-level debug, why an mpv input.conf key never reached mpv.
ipc.on(IPC_CHANNELS.command.reportUnforwardedMpvKey, (_event: unknown, payload: unknown) => {
const report = parseUnforwardedMpvKeyReport(payload);
if (report) overlayInputLogger.debug('Overlay kept an mpv-bound key', report);
});
ipc.on(IPC_CHANNELS.command.recordYomitanLookup, (_event: unknown, payload: unknown) => { ipc.on(IPC_CHANNELS.command.recordYomitanLookup, (_event: unknown, payload: unknown) => {
try { try {
deps.recordSubtitleMiningContext?.(parseSubtitleMiningContext(payload)); deps.recordSubtitleMiningContext?.(parseSubtitleMiningContext(payload));
+154
View File
@@ -0,0 +1,154 @@
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
@@ -0,0 +1,222 @@
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 });
}
}
@@ -0,0 +1,176 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createOverlayVisibilityDiagnostics,
readOverlayVisibilitySnapshot,
type OverlayVisibilitySnapshot,
} from './overlay-visibility-diagnostics';
type SnapshotArgs = Parameters<typeof readOverlayVisibilitySnapshot>[0];
function snapshotFor(
options: {
tracking?: boolean;
targetPid?: number | null;
minimized?: boolean;
window?: Record<string, unknown>;
noTracker?: boolean;
} & Pick<SnapshotArgs, 'modalActive' | 'suspendVisibleOverlay'> & {
visibleOverlayVisible?: boolean;
} = {},
) {
const tracker = {
isTracking: () => options.tracking ?? false,
getGeometry: () => null,
isTargetWindowFocused: () => false,
isTargetWindowMinimized: () => options.minimized ?? false,
getDiagnosticState: () => ({ targetPid: options.targetPid ?? null, socketPath: '/tmp/mpv' }),
};
return readOverlayVisibilitySnapshot({
mainWindow: {
isDestroyed: () => false,
isVisible: () => false,
getOpacity: () => 0,
...options.window,
} as unknown as SnapshotArgs['mainWindow'],
windowTracker: options.noTracker ? null : (tracker as unknown as SnapshotArgs['windowTracker']),
visibleOverlayVisible: options.visibleOverlayVisible ?? true,
modalActive: options.modalActive,
suspendVisibleOverlay: options.suspendVisibleOverlay,
});
}
function harness() {
let now = 0;
let callback: (() => void) | null = null;
let delay = 0;
const warnings: Array<{ message: string; details: Record<string, unknown> }> = [];
let snapshot: OverlayVisibilitySnapshot | null = {
expectedVisible: true,
visible: false,
opacity: 0,
contentReady: false,
tracking: false,
targetPid: 4242,
pidLookupPending: false,
};
const diagnostics = createOverlayVisibilityDiagnostics({
now: () => now,
warn: (message, details) => warnings.push({ message, details }),
schedule: (fn, ms) => {
callback = fn;
delay = ms;
return { unref() {} } as ReturnType<typeof setTimeout>;
},
cancel: () => {
callback = null;
},
});
const update = () => diagnostics.update(() => snapshot);
return {
warnings,
update,
setSnapshot: (value: typeof snapshot) => {
snapshot = value;
},
tick: () => {
assert.ok(callback, 'watchdog must be scheduled');
now += delay;
callback();
},
scheduled: () => callback !== null,
};
}
test('visibility watchdog warns without more events and rate limits repeated polls', () => {
const h = harness();
h.update();
assert.equal(h.warnings.length, 0);
for (let i = 0; i < 100; i += 1) h.update();
h.tick();
assert.equal(h.warnings.length, 1);
assert.equal(h.warnings[0]?.details.reason, 'mpv-window-not-tracked');
assert.equal(h.warnings[0]?.details.targetPid, 4242);
assert.equal(h.warnings[0]?.details.elapsedMs, 5_000);
for (let i = 0; i < 100; i += 1) h.update();
assert.equal(h.warnings.length, 1);
h.tick();
assert.equal(h.warnings[1]?.details.elapsedMs, 35_000);
});
test('visibility watchdog distinguishes renderer readiness, hidden windows and opacity', () => {
for (const [contentReady, visible, opacity, reason] of [
[false, false, 0, 'renderer-not-ready'],
[true, false, 0, 'window-hidden'],
[true, true, 0, 'window-transparent'],
] as const) {
const h = harness();
h.setSnapshot({ expectedVisible: true, tracking: true, contentReady, visible, opacity });
h.update();
h.tick();
assert.equal(h.warnings[0]?.details.reason, reason);
}
});
test('visibility watchdog reports recovery only after warning and stops', () => {
const h = harness();
h.update();
h.tick();
h.setSnapshot({
expectedVisible: true,
visible: true,
opacity: 1,
contentReady: true,
tracking: true,
});
h.tick();
assert.match(h.warnings[1]!.message, /recovered/);
assert.equal(h.scheduled(), false);
h.update();
assert.equal(h.warnings.length, 2);
});
test('visibility watchdog stays quiet after fast startup, intentional hide or window destruction', () => {
for (const snapshot of [
{ expectedVisible: true, visible: true, opacity: 1, contentReady: true, tracking: true },
{ expectedVisible: false, visible: false, opacity: 0, contentReady: false, tracking: false },
null,
]) {
const h = harness();
h.update();
h.setSnapshot(snapshot);
h.tick();
assert.deepEqual(h.warnings, []);
assert.equal(h.scheduled(), false);
}
});
test('overlay snapshot expects visibility only once an mpv has been identified', () => {
// Requested before any mpv exists: auto_start_overlay, tray or --show-visible-overlay.
assert.equal(snapshotFor()?.expectedVisible, false);
assert.equal(snapshotFor({ noTracker: true })?.expectedVisible, false);
// mpv answered on the socket but its window never matched, so tracking never started.
assert.equal(snapshotFor({ targetPid: 4242 })?.expectedVisible, true);
// A tracker with no target socket matches windows without ever learning a PID.
assert.equal(snapshotFor({ tracking: true })?.expectedVisible, true);
});
test('overlay snapshot does not expect an intentionally hidden overlay', () => {
const identified = { targetPid: 4242, tracking: true };
assert.equal(snapshotFor(identified)?.expectedVisible, true);
assert.equal(snapshotFor({ ...identified, modalActive: true })?.expectedVisible, false);
assert.equal(snapshotFor({ ...identified, suspendVisibleOverlay: true })?.expectedVisible, false);
assert.equal(snapshotFor({ ...identified, minimized: true })?.expectedVisible, false);
assert.equal(
snapshotFor({ ...identified, visibleOverlayVisible: false })?.expectedVisible,
false,
);
});
test('overlay snapshot carries tracker state, defaults opacity and ends with the window', () => {
const snapshot = snapshotFor({ targetPid: 4242, window: { getOpacity: undefined } });
assert.equal(snapshot?.targetPid, 4242);
assert.equal(snapshot?.socketPath, '/tmp/mpv');
assert.equal(snapshot?.opacity, 1);
assert.equal(snapshotFor({ window: { isDestroyed: () => true } }), null);
});
@@ -0,0 +1,153 @@
import type { BrowserWindow } from 'electron';
import type { BaseWindowTracker } from '../../window-trackers';
import { createLogger } from '../../logger';
import {
OVERLAY_WINDOW_CONTENT_READY_FLAG,
OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG,
} from './overlay-window-flags';
const log = createLogger('overlay:visibility');
export type OverlayVisibilitySnapshot = {
expectedVisible: boolean;
visible: boolean;
opacity: number;
contentReady: boolean;
tracking: boolean;
[key: string]: unknown;
};
// One watchdog per window, independent of further visibility events: a renderer
// that never becomes ready must still leave evidence at the default warn level.
export function createOverlayVisibilityDiagnostics(deps: {
warn: (message: string, details: Record<string, unknown>) => void;
now: () => number;
schedule: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
cancel: (timer: ReturnType<typeof setTimeout>) => void;
}) {
let timer: ReturnType<typeof setTimeout> | null = null;
let readSnapshot: () => OverlayVisibilitySnapshot | null = () => null;
let stalledAtMs: number | null = null;
let warned = false;
let lastWarningAtMs = 0;
const check = () => {
if (timer !== null) deps.cancel(timer);
timer = null;
const snapshot = readSnapshot();
if (!snapshot?.expectedVisible) {
stalledAtMs = null;
warned = false;
return;
}
if (snapshot.visible && snapshot.opacity > 0 && snapshot.contentReady) {
if (warned) {
deps.warn('Windows overlay visibility recovered', {
...snapshot,
elapsedMs: deps.now() - stalledAtMs!,
});
}
stalledAtMs = null;
warned = false;
return;
}
stalledAtMs ??= deps.now();
const elapsedMs = deps.now() - stalledAtMs;
if (elapsedMs >= 5_000 && (!warned || deps.now() - lastWarningAtMs >= 30_000)) {
const reason = !snapshot.tracking
? 'mpv-window-not-tracked'
: !snapshot.contentReady
? 'renderer-not-ready'
: !snapshot.visible
? 'window-hidden'
: 'window-transparent';
deps.warn('Windows overlay is not visible after startup or tracking loss', {
...snapshot,
reason,
elapsedMs,
});
warned = true;
lastWarningAtMs = deps.now();
}
timer = deps.schedule(
check,
warned ? 30_000 - (deps.now() - lastWarningAtMs) : 5_000 - elapsedMs,
);
timer.unref?.();
};
return {
update(reader: () => OverlayVisibilitySnapshot | null) {
readSnapshot = reader;
// Frequent polls must not postpone a warning or bypass its rate limit.
check();
},
};
}
const diagnosticsByWindow = new WeakMap<
BrowserWindow,
ReturnType<typeof createOverlayVisibilityDiagnostics>
>();
type OverlayVisibilityWatchArgs = {
mainWindow: BrowserWindow;
windowTracker: BaseWindowTracker | null;
visibleOverlayVisible: boolean;
modalActive?: boolean;
suspendVisibleOverlay?: boolean;
};
export function readOverlayVisibilitySnapshot(
args: OverlayVisibilityWatchArgs,
): OverlayVisibilitySnapshot | null {
const window = args.mainWindow;
if (window.isDestroyed()) return null;
const tracker = args.windowTracker as
| (BaseWindowTracker & {
getDiagnosticState?: () => { targetPid?: number | null } & Record<string, unknown>;
})
| null;
const trackerState = tracker?.getDiagnosticState?.();
const flags = window as unknown as Record<string, unknown>;
const minimized = tracker?.isTargetWindowMinimized?.() ?? false;
const tracking = tracker?.isTracking() ?? false;
// The overlay may be requested with no mpv to attach to (auto_start_overlay, tray,
// --show-visible-overlay), so it only counts as stalled once an mpv has answered on the
// socket. That still covers an mpv whose window never matches, which never starts tracking.
const mpvIdentified = tracking || (trackerState?.targetPid ?? null) !== null;
return {
...trackerState,
expectedVisible:
args.visibleOverlayVisible &&
mpvIdentified &&
!args.modalActive &&
!args.suspendVisibleOverlay &&
!minimized,
visible: window.isVisible(),
opacity: window.getOpacity?.() ?? 1,
contentReady: flags[OVERLAY_WINDOW_CONTENT_READY_FLAG] === true,
documentLoaded: flags[OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG] === true,
rendererLoading: window.webContents?.isLoading?.() ?? null,
tracking,
trackerInitialized: tracker !== null,
geometry: tracker?.getGeometry() ?? null,
focused: tracker?.isTargetWindowFocused?.() ?? false,
minimized,
};
}
export function watchWindowsOverlayVisibility(args: OverlayVisibilityWatchArgs): void {
const window = args.mainWindow;
let diagnostics = diagnosticsByWindow.get(window);
if (!diagnostics) {
diagnostics = createOverlayVisibilityDiagnostics({
warn: (message, details) => log.warn(message, details),
now: Date.now,
schedule: setTimeout,
cancel: clearTimeout,
});
diagnosticsByWindow.set(window, diagnostics);
}
diagnostics.update(() => readOverlayVisibilitySnapshot(args));
}
@@ -589,6 +589,34 @@ runScenarios([
}, },
]); ]);
test('only a live Windows overlay reads visibility diagnostics', () => {
const diagnosticReads = (platform: Platform, overrides: Partial<VisibilityArgs> = {}): number => {
let reads = 0;
createHarness({ platform, tracker: tracked() }).run({
windowTracker: {
isTracking: () => true,
getGeometry: () => GEOMETRY,
getDiagnosticState: () => {
reads += 1;
return { targetPid: 4242 };
},
} as unknown as VisibilityArgs['windowTracker'],
...overrides,
});
return reads;
};
assert.equal(diagnosticReads('windows'), 1);
assert.equal(diagnosticReads('linux'), 0);
assert.equal(diagnosticReads('macos'), 0);
assert.equal(
diagnosticReads('windows', {
mainWindow: { isDestroyed: () => true } as unknown as VisibilityArgs['mainWindow'],
}),
0,
);
});
test('Windows visible overlay restores opacity and rebinds after the deferred reveal delay', async () => { test('Windows visible overlay restores opacity and rebinds after the deferred reveal delay', async () => {
const h = createHarness({ platform: 'windows', tracker: tracked() }); const h = createHarness({ platform: 'windows', tracker: tracked() });
assertOutcome(h.run(), { opacity: 0, zOrderSyncs: 1 }); assertOutcome(h.run(), { opacity: 0, zOrderSyncs: 1 });
+11 -1
View File
@@ -3,6 +3,7 @@ import { BaseWindowTracker } from '../../window-trackers';
import { WindowGeometry } from '../../types'; import { WindowGeometry } from '../../types';
import { applyOverlayClickThrough } from './overlay-click-through'; import { applyOverlayClickThrough } from './overlay-click-through';
import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags'; import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags';
import { watchWindowsOverlayVisibility } from './overlay-visibility-diagnostics';
const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48; const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48;
const pendingWindowsOverlayRevealTimeoutByWindow = new WeakMap< const pendingWindowsOverlayRevealTimeoutByWindow = new WeakMap<
@@ -65,7 +66,7 @@ function isOverlayWindowContentReady(window: BrowserWindow): boolean {
); );
} }
export function updateVisibleOverlayVisibility(args: { function applyVisibleOverlayVisibility(args: {
visibleOverlayVisible: boolean; visibleOverlayVisible: boolean;
modalActive?: boolean; modalActive?: boolean;
forceMousePassthrough?: boolean; forceMousePassthrough?: boolean;
@@ -453,6 +454,15 @@ export function updateVisibleOverlayVisibility(args: {
args.syncOverlayShortcuts(); args.syncOverlayShortcuts();
} }
export function updateVisibleOverlayVisibility(
args: Parameters<typeof applyVisibleOverlayVisibility>[0],
): void {
applyVisibleOverlayVisibility(args);
if (args.isWindowsPlatform && args.mainWindow && !args.mainWindow.isDestroyed()) {
watchWindowsOverlayVisibility({ ...args, mainWindow: args.mainWindow });
}
}
export function setVisibleOverlayVisible(options: { export function setVisibleOverlayVisible(options: {
visible: boolean; visible: boolean;
setVisibleOverlayVisibleState: (visible: boolean) => void; setVisibleOverlayVisibleState: (visible: boolean) => void;
@@ -11,6 +11,7 @@ import {
enrichSessionsWithKnownWordMetrics, enrichSessionsWithKnownWordMetrics,
isPositiveSafeInteger, isPositiveSafeInteger,
loadKnownWordsSet, loadKnownWordsSet,
parseAnimeGroupOverrideBody,
parseBooleanQuery, parseBooleanQuery,
parseDuplicateLineCleanupBody, parseDuplicateLineCleanupBody,
parseExcludedWordsBody, parseExcludedWordsBody,
@@ -190,6 +191,11 @@ export function registerStatsLibraryRoutes(
return c.json(statsJson('animeLibrary', rows)); return c.json(statsJson('animeLibrary', rows));
}); });
// Registered before `/api/stats/anime/:animeId` so `groups` is not read as an id.
app.get('/api/stats/anime/groups', async (c) => {
return c.json(statsJson('animeLibraryGroups', await tracker.getAnimeLibraryGroups()));
});
app.get('/api/stats/anime/merge-recommendations', async (c) => { app.get('/api/stats/anime/merge-recommendations', async (c) => {
const recommendations = await tracker.getAnimeMergeRecommendations(); const recommendations = await tracker.getAnimeMergeRecommendations();
return c.json(statsJson('animeMergeRecommendations', { recommendations })); return c.json(statsJson('animeMergeRecommendations', { recommendations }));
@@ -208,11 +214,12 @@ export function registerStatsLibraryRoutes(
if (animeId === null) return c.body(null, 400); if (animeId === null) return c.body(null, 400);
const detail = await tracker.getAnimeDetail(animeId); const detail = await tracker.getAnimeDetail(animeId);
if (!detail) return c.body(null, 404); if (!detail) return c.body(null, 404);
const [episodes, anilistEntries] = await Promise.all([ const [episodes, anilistEntries, group] = await Promise.all([
tracker.getAnimeEpisodes(animeId), tracker.getAnimeEpisodes(animeId),
tracker.getAnimeAnilistEntries(animeId), tracker.getAnimeAnilistEntries(animeId),
tracker.getAnimeGroupPlacement(animeId),
]); ]);
return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries })); return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries, group }));
}); });
app.get('/api/stats/anime/:animeId/words', async (c) => { app.get('/api/stats/anime/:animeId/words', async (c) => {
@@ -267,6 +274,22 @@ export function registerStatsLibraryRoutes(
return c.json(statsJson('deleteAnime', { ok: true })); return c.json(statsJson('deleteAnime', { ok: true }));
}); });
app.put('/api/stats/anime/:animeId/group', async (c) => {
const animeId = parsePositiveId(c.req.param('animeId'));
if (animeId === null) return c.body(null, 400);
const request = parseAnimeGroupOverrideBody(await c.req.json().catch(() => null));
if (!request) return c.body(null, 400);
if (request.mode === 'join' && request.targetAnimeId === animeId) return c.body(null, 400);
const result = await tracker.setAnimeGroupOverride(animeId, request);
if (result.ok) return c.json(statsJson('setAnimeGroupOverride', { ok: true }));
if (result.reason === 'not-found') return c.body(null, 404);
const error =
result.reason === 'unsupported-kind'
? 'Only anime entries can be grouped.'
: 'That title has no AniList entry to group with. Link it to AniList or merge the entries instead.';
return c.json(statsJson('error', { error }), 409);
});
app.post('/api/stats/anime/:animeId/merge', async (c) => { app.post('/api/stats/anime/:animeId/merge', async (c) => {
const animeId = parsePositiveId(c.req.param('animeId')); const animeId = parsePositiveId(c.req.param('animeId'));
if (animeId === null) return c.body(null, 400); if (animeId === null) return c.body(null, 400);
@@ -13,6 +13,7 @@ import {
import { createLogger } from '../../../logger.js'; import { createLogger } from '../../../logger.js';
import type { AnkiConnectConfig } from '../../../types.js'; import type { AnkiConnectConfig } from '../../../types.js';
import type { import type {
StatsAnimeGroupOverrideRequest,
StatsDayRange, StatsDayRange,
StatsDictionaryWordQuery, StatsDictionaryWordQuery,
StatsDictionaryWordSort, StatsDictionaryWordSort,
@@ -59,6 +60,15 @@ export function isPositiveSafeInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0; return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
} }
/** Validates a `PUT /api/stats/anime/:animeId/group` body; null for anything malformed. */
export function parseAnimeGroupOverrideBody(body: unknown): StatsAnimeGroupOverrideRequest | null {
if (!body || typeof body !== 'object') return null;
const { mode, targetAnimeId } = body as Record<string, unknown>;
if (mode === 'standalone' || mode === 'anilist') return { mode };
if (mode === 'join' && isPositiveSafeInteger(targetAnimeId)) return { mode, targetAnimeId };
return null;
}
export function parsePositiveId(raw: string | undefined): number | null { export function parsePositiveId(raw: string | undefined): number | null {
if (raw === undefined) return null; if (raw === undefined) return null;
const value = Number(raw); const value = Number(raw);
@@ -58,3 +58,78 @@ for (const [localKind, remoteKind, sameEntry] of [
} }
}); });
} }
test('franchise override follows whichever side set or cleared it last', () => {
const adapt = (db: DatabaseSync) => ({
query: (sql: string) => db.prepare(sql),
exec: (sql: string) => {
db.exec(sql);
},
close: () => {
db.close();
},
});
const cases: Array<{
name: string;
local: [number | null, string | null];
remote: [number | null, string | null];
expected: number | null;
}> = [
{
name: 'newer remote join wins',
local: [null, null],
remote: [20832, '2000'],
expected: 20832,
},
{ name: 'newer remote clear wins', local: [0, '1000'], remote: [null, '2000'], expected: null },
{ name: 'older remote loses', local: [0, '3000'], remote: [20832, '2000'], expected: 0 },
{ name: 'untouched remote keeps local', local: [0, '1000'], remote: [null, null], expected: 0 },
];
for (const c of cases) {
const local = new Database(':memory:');
const remote = new Database(':memory:');
try {
for (const [db, [override, updatedAt]] of [
[local, c.local],
[remote, c.remote],
] as const) {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, group_override, group_override_updated_at)
VALUES ('overlord ii', 'Overlord II', 98437, ?, ?)`,
).run(override, updatedAt);
}
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
const row = local.prepare('SELECT group_override AS value FROM imm_anime').get() as {
value: number | null;
};
assert.equal(row.value, c.expected, c.name);
} finally {
local.close();
remote.close();
}
}
const local = new Database(':memory:');
const remote = new Database(':memory:');
try {
ensureSchema(local);
ensureSchema(remote);
remote
.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override, group_override_updated_at)
VALUES ('specials', 'Specials', 20832, '1000')`,
)
.run();
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
const row = local
.prepare(
'SELECT group_override AS value, group_override_updated_at AS updatedAt FROM imm_anime',
)
.get() as { value: number | null; updatedAt: string | null };
assert.deepEqual([row.value, row.updatedAt], [20832, '1000']);
} finally {
local.close();
remote.close();
}
});
@@ -15,6 +15,8 @@ const ANIME_COPY_COLUMNS = [
'tmdb_id', 'tmdb_id',
'tmdb_type', 'tmdb_type',
'metadata_json', 'metadata_json',
'group_override',
'group_override_updated_at',
'CREATED_DATE', 'CREATED_DATE',
'LAST_UPDATE_DATE', 'LAST_UPDATE_DATE',
] as const; ] as const;
@@ -146,6 +148,13 @@ export function mergeAnime(
END END
WHERE anime_id = ?`, WHERE anime_id = ?`,
); );
// The franchise override holds AniList ids (or 0 / NULL), so it needs no id
// remapping. The side that set or cleared it last wins.
const takeNewerGroupOverride = local.query(
`UPDATE imm_anime SET group_override = ?, group_override_updated_at = ?
WHERE anime_id = ? AND (group_override_updated_at IS NULL
OR CAST(group_override_updated_at AS INTEGER) < CAST(? AS INTEGER))`,
);
for (const row of selectAll( for (const row of selectAll(
remote, remote,
@@ -195,6 +204,14 @@ export function mergeAnime(
row.media_kind, row.media_kind,
localId, localId,
); );
if (row.group_override_updated_at !== null) {
takeNewerGroupOverride.run(
row.group_override,
row.group_override_updated_at,
localId,
row.group_override_updated_at,
);
}
continue; continue;
} }
// Conflicting providers can share a title, but the stored title key is // Conflicting providers can share a title, but the stored title key is
+5
View File
@@ -20,6 +20,11 @@ export type { SyncMergeSummary } from './shared';
* are updated incrementally so history older than the session retention * are updated incrementally so history older than the session retention
* window is preserved on both sides. Idempotent: re-merging the same * window is preserved on both sides. Idempotent: re-merging the same
* snapshot is a no-op. * snapshot is a no-op.
*
* A library entry's franchise override (`group_override`) is last-writer-wins
* by `group_override_updated_at`. The AniList relation cache
* (`imm_anilist_media`, `imm_anilist_relations`) is not merged: each machine
* rebuilds it from AniList.
*/ */
export function mergeSnapshotIntoDb(localDbPath: string, snapshotPath: string): SyncMergeSummary { export function mergeSnapshotIntoDb(localDbPath: string, snapshotPath: string): SyncMergeSummary {
if (!fs.existsSync(localDbPath)) { if (!fs.existsSync(localDbPath)) {
@@ -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, 'model.bin'); const temporaryPath = path.join(temporaryDirectory, 'artifact.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(`Model download failed: HTTP ${response.status}`); throw new Error(`${input.label} 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,7 +36,8 @@ 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) throw new Error('Downloaded model exceeds expected size.'); if (received > input.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));
@@ -50,7 +51,9 @@ 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('Downloaded model failed integrity verification. Try downloading again.'); throw new Error(
`Downloaded ${input.label} failed integrity verification. Try downloading again.`,
);
} }
await file.sync(); await file.sync();
} finally { } finally {
@@ -46,7 +46,11 @@ function executableNames(name: string, env: NodeJS.ProcessEnv): string[] {
return [name, ...extensions.map((extension) => `${name}${extension}`)]; return [name, ...extensions.map((extension) => `${name}${extension}`)];
} }
async function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv): Promise<string> { /** First executable on `env.PATH` matching any of `names` (PATHEXT-aware on Windows), or ''. */
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())
+38
View File
@@ -0,0 +1,38 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { parseMediaInfo, parseMediaLookupInfo, parseMediaTitleInfo } from './utils.js';
const JELLYFIN_TITLE =
"Seitokai Yakuindomo S01E01 Under the Cherry Tree / Will I Get This Feeling Every Time? / For Now, Let's Try Stripping";
test('parseMediaTitleInfo keeps the series when the episode name contains slashes', () => {
const info = parseMediaTitleInfo(JELLYFIN_TITLE);
assert.equal(info.title, 'Seitokai Yakuindomo');
assert.equal(info.season, 1);
assert.equal(info.episode, 1);
assert.equal(info.confidence, 'high');
});
test('parseMediaTitleInfo does not treat a dotted title as a file extension', () => {
// Dots are normalized to spaces; the point is that "Stone S02E03" is not cut off as an extension.
assert.equal(parseMediaTitleInfo('Dr. Stone S02E03').title, 'Dr Stone');
assert.equal(parseMediaTitleInfo('Dr. Stone S02E03.mkv').episode, 3);
});
test('parseMediaInfo still reads the season from the parent directory', () => {
const info = parseMediaInfo('/media/Show/Season 2/Show - 03 - Title.mkv');
assert.equal(info.title, 'Show');
assert.equal(info.season, 2);
assert.equal(info.episode, 3);
});
test('parseMediaLookupInfo parses a stream by its title, not its URL', () => {
const info = parseMediaLookupInfo('jellyfin://host:8096/item/abc', JELLYFIN_TITLE);
assert.equal(info.title, 'Seitokai Yakuindomo');
assert.equal(info.episode, 1);
});
test('parseMediaLookupInfo treats a title already swapped in for the path as a title', () => {
assert.equal(parseMediaLookupInfo(JELLYFIN_TITLE, JELLYFIN_TITLE).title, 'Seitokai Yakuindomo');
});
+52 -14
View File
@@ -4,6 +4,7 @@ import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import { createLogger } from '../logger'; import { createLogger } from '../logger';
import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../shared/media-identity';
import { import {
JimakuApiResponse, JimakuApiResponse,
JimakuConfig, JimakuConfig,
@@ -202,22 +203,60 @@ function cleanupTitle(value: string): string {
.trim(); .trim();
} }
const EMPTY_MEDIA_INFO: JimakuMediaInfo = {
title: '',
season: null,
episode: null,
confidence: 'low',
filename: '',
rawTitle: '',
};
const MEDIA_EXTENSION = /\.(?:mkv|mp4|m4v|webm|avi|mov|wmv|flv|ts|m2ts)$/i;
/** Parses a media file path: the basename carries the title, the parent dir may name the season. */
export function parseMediaInfo(mediaPath: string | null): JimakuMediaInfo { export function parseMediaInfo(mediaPath: string | null): JimakuMediaInfo {
if (!mediaPath) { if (!mediaPath) return { ...EMPTY_MEDIA_INFO };
return {
title: '',
season: null,
episode: null,
confidence: 'low',
filename: '',
rawTitle: '',
};
}
const normalizedMediaPath = normalizeMediaPathForJimaku(mediaPath); const normalizedMediaPath = normalizeMediaPathForJimaku(mediaPath);
const filename = path.basename(normalizedMediaPath); const filename = path.basename(normalizedMediaPath);
let name = filename.replace(/\.[^/.]+$/, ''); return parseMediaName(
name = name.replace(/\[[^\]]*]/g, ' '); filename.replace(/\.[^/.]+$/, ''),
filename,
detectSeasonFromDir(normalizedMediaPath),
);
}
/**
* Parses a display title such as a stream's mpv media-title. A "/" here is part of the title
* (Jellyfin episodes like "Show S01E01 Part A / Part B"), not a directory separator.
*/
export function parseMediaTitleInfo(mediaTitle: string | null): JimakuMediaInfo {
const title = mediaTitle?.trim();
if (!title) return { ...EMPTY_MEDIA_INFO };
return parseMediaName(title.replace(MEDIA_EXTENSION, ''), title, null);
}
/**
* Parses whichever of the path or title `resolveMediaLookupTarget` picks. Callers that already
* swapped a stream URL for its title (`resolveMediaPathForJimaku`) still parse it as a title.
*/
export function parseMediaLookupInfo(
mediaPath: string | null,
mediaTitle: string | null,
): JimakuMediaInfo {
const target = resolveMediaLookupTarget(mediaPath, mediaTitle);
return target !== null && target === sanitizeMediaTitle(mediaTitle)
? parseMediaTitleInfo(target)
: parseMediaInfo(target);
}
function parseMediaName(
baseName: string,
filename: string,
seasonFallback: number | null,
): JimakuMediaInfo {
let name = baseName.replace(/\[[^\]]*]/g, ' ');
name = name.replace(/\(\d{4}\)/g, ' '); name = name.replace(/\(\d{4}\)/g, ' ');
name = name.replace(/[._]/g, ' '); name = name.replace(/[._]/g, ' ');
name = name.replace(/[–—]/g, '-'); name = name.replace(/[–—]/g, '-');
@@ -229,12 +268,11 @@ export function parseMediaInfo(mediaPath: string | null): JimakuMediaInfo {
titlePart = name.slice(0, parsed.index); titlePart = name.slice(0, parsed.index);
} }
const seasonFromDir = parsed.season ?? detectSeasonFromDir(normalizedMediaPath);
const title = cleanupTitle(titlePart || name); const title = cleanupTitle(titlePart || name);
return { return {
title, title,
season: seasonFromDir, season: parsed.season ?? seasonFallback,
episode: parsed.episode, episode: parsed.episode,
confidence: parsed.confidence, confidence: parsed.confidence,
filename, filename,
+6 -2
View File
@@ -71,7 +71,7 @@ import type {
SubtitlePosition, SubtitlePosition,
} from './types'; } from './types';
import { OPEN_ANKI_CARD_ACTION_ID } from './types'; import { OPEN_ANKI_CARD_ACTION_ID } from './types';
import { downloadToFile, isRemoteMediaPath, parseMediaInfo } from './jimaku/utils'; import { downloadToFile, isRemoteMediaPath, parseMediaLookupInfo } from './jimaku/utils';
import { import {
createLogger, createLogger,
setLogFileToggles, setLogFileToggles,
@@ -155,6 +155,7 @@ 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';
@@ -428,6 +429,8 @@ 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({
@@ -688,6 +691,7 @@ 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) =>
@@ -1586,7 +1590,7 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
setFieldGroupingResolver: (resolver: ((choice: KikuFieldGroupingChoice) => void) | null) => setFieldGroupingResolver: (resolver: ((choice: KikuFieldGroupingChoice) => void) | null) =>
mining.setFieldGroupingResolver(resolver), mining.setFieldGroupingResolver(resolver),
parseMediaInfo: (mediaPath: string | null) => parseMediaInfo: (mediaPath: string | null) =>
parseMediaInfo(mediaRuntime.resolveMediaPathForJimaku(mediaPath)), parseMediaLookupInfo(mediaPath, appState.currentMediaTitle),
getCurrentMediaPath: () => appState.currentMediaPath, getCurrentMediaPath: () => appState.currentMediaPath,
jimakuFetchJson: <T>( jimakuFetchJson: <T>(
endpoint: string, endpoint: string,
@@ -30,6 +30,7 @@ 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,6 +1,12 @@
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';
@@ -62,6 +68,8 @@ 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'];
@@ -83,6 +91,23 @@ 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'),
@@ -232,6 +257,9 @@ 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,
}; };
}, },
@@ -304,6 +332,10 @@ 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.`
+3 -1
View File
@@ -1118,7 +1118,8 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
aniskipEnabled: configService.getConfig().mpv.aniskipEnabled, aniskipEnabled: configService.getConfig().mpv.aniskipEnabled,
aniskipButtonKey: configService.getConfig().mpv.aniskipButtonKey, aniskipButtonKey: configService.getConfig().mpv.aniskipButtonKey,
}), }),
resolveMetadataForFile: (mediaPath) => resolveAniSkipMetadataForFile(mediaPath), resolveMetadataForFile: (mediaPath, episodeLength) =>
resolveAniSkipMetadataForFile(mediaPath, { episodeLength }),
sendMpvCommand: (command) => { sendMpvCommand: (command) => {
appState.mpvClient?.send({ command }); appState.mpvClient?.send({ command });
}, },
@@ -1163,6 +1164,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
}); });
client.on('connection-change', aniSkipRuntime.handleConnectionChange); client.on('connection-change', aniSkipRuntime.handleConnectionChange);
client.on('media-path-change', aniSkipRuntime.handleMediaPathChange); client.on('media-path-change', aniSkipRuntime.handleMediaPathChange);
client.on('duration-change', aniSkipRuntime.handleDurationChange);
client.on('time-pos-change', aniSkipRuntime.handleTimePosChange); client.on('time-pos-change', aniSkipRuntime.handleTimePosChange);
client.on('client-message', aniSkipRuntime.handleClientMessage); client.on('client-message', aniSkipRuntime.handleClientMessage);
deps.getPluginHost().attachMpvClient(client); deps.getPluginHost().attachMpvClient(client);
+4
View File
@@ -1,6 +1,7 @@
import path from 'node:path'; import path from 'node:path';
import { ImmersionTrackerService } from '../../core/services'; import { ImmersionTrackerService } from '../../core/services';
import { createCoverArtFetcher } from '../../core/services/anilist/cover-art-fetcher'; import { createCoverArtFetcher } from '../../core/services/anilist/cover-art-fetcher';
import { createAnilistRelationFetcher } from '../../core/services/anilist/franchise-relation-fetcher';
import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter'; import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter';
import { resolveLegacyVocabularyPosFromTokens } from '../../core/services/immersion-tracker/legacy-vocabulary-pos'; import { resolveLegacyVocabularyPosFromTokens } from '../../core/services/immersion-tracker/legacy-vocabulary-pos';
import type { StatsWindowOptions } from '../../core/services/stats-window'; import type { StatsWindowOptions } from '../../core/services/stats-window';
@@ -172,6 +173,8 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
}, },
); );
const anilistRelationFetcher = createAnilistRelationFetcher(deps.anilistRateLimiter);
// One options object serves the overlay's IPC toggle and the session-action toggle. // One options object serves the overlay's IPC toggle and the session-action toggle.
const statsOverlayOptions: StatsWindowOptions = { const statsOverlayOptions: StatsWindowOptions = {
preloadPath: path.join(deps.mainDirname, 'preload-stats.js'), preloadPath: path.join(deps.mainDirname, 'preload-stats.js'),
@@ -235,6 +238,7 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
appState.immersionTracker = tracker as ImmersionTrackerService | null; appState.immersionTracker = tracker as ImmersionTrackerService | null;
appState.immersionTracker?.setCoverArtFetcher(coverArtFetcher); appState.immersionTracker?.setCoverArtFetcher(coverArtFetcher);
appState.immersionTracker?.setAnilistRelationFetcher(anilistRelationFetcher);
if (tracker) { if (tracker) {
// Start HTTP stats server // Start HTTP stats server
if (!appState.statsServer) { if (!appState.statsServer) {
@@ -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',
); );
} }
+116
View File
@@ -0,0 +1,116 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { classifyChapterSkipIntervals } from './aniskip-chapters';
const DURATION = 1440;
function chapters(...entries: Array<[number, string]>) {
return entries.map(([time, title]) => ({ time, title }));
}
test('finds named openings and endings case-insensitively', () => {
const result = classifyChapterSkipIntervals(
chapters([0, 'Prologue'], [95, 'OPENING'], [185, 'Part A'], [1310, 'Ending'], [1400, 'Next']),
DURATION,
);
assert.deepEqual(result, {
intro: { start: 95, end: 185 },
outro: { start: 1310, end: 1400 },
});
});
test('matches short OP/ED titles but not words that merely start with them', () => {
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Op'], [90, 'Episode'], [1350, 'ED']), DURATION),
{ intro: { start: 0, end: 90 }, outro: { start: 1350, end: 1440 } },
);
assert.deepEqual(
classifyChapterSkipIntervals(
chapters([0, 'OP "Song Title"'], [90, 'Episode'], [1350, 'ED "Song Title"']),
DURATION,
),
{ intro: { start: 0, end: 90 }, outro: { start: 1350, end: 1440 } },
);
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Operation'], [500, 'Editing']), DURATION),
{ intro: null, outro: null },
);
});
test('recognises Japanese chapter names', () => {
assert.deepEqual(
classifyChapterSkipIntervals(
chapters([0, 'アバン'], [60, 'オープニング'], [150, '本編'], [1330, 'エンディング']),
DURATION,
),
{ intro: { start: 60, end: 150 }, outro: { start: 1330, end: 1440 } },
);
});
test('accepts outro and credits names, with bare "Credits" only in the second half', () => {
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Outro']), DURATION).outro,
{ start: 1350, end: 1440 },
);
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Closing Credits']), DURATION)
.outro,
{ start: 1350, end: 1440 },
);
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Credits'], [90, 'Episode']), DURATION).outro,
null,
);
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Credits']), DURATION).outro,
{ start: 1350, end: 1440 },
);
});
test('falls back to song-length heuristics when the file has at least three chapters', () => {
const result = classifyChapterSkipIntervals(
chapters(
[0, 'Chapter 1'],
[60, 'Chapter 2'], // 60 s long, in the first 30%
[120, 'Chapter 3'], // 88 s long, nearest 90 s
[208, 'Chapter 4'],
[1100, 'Chapter 5'], // starts after 70% but 230 s long
[1330, 'Chapter 6'], // first song-length chapter after 70%
[1420, 'Chapter 7'],
),
DURATION,
);
assert.deepEqual(result, {
intro: { start: 120, end: 208 },
outro: { start: 1330, end: 1420 },
});
});
test('skips heuristics for files with fewer than three chapters', () => {
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Chapter 1'], [1350, 'Chapter 2']), DURATION),
{ intro: null, outro: null },
);
});
test("ignores SubMiner's own AniSkip marker chapters", () => {
const result = classifyChapterSkipIntervals(
chapters(
[0, 'Episode'],
[10, 'AniSkip Intro Start'],
[100, 'AniSkip Intro End'],
[1330, 'AniSkip Outro Start'],
[1420, 'AniSkip Outro End'],
),
DURATION,
);
assert.deepEqual(result, { intro: null, outro: null });
});
test('returns nothing without a usable duration or chapter list', () => {
assert.deepEqual(classifyChapterSkipIntervals(chapters([0, 'Opening'], [90, 'A']), 0), {
intro: null,
outro: null,
});
assert.deepEqual(classifyChapterSkipIntervals(null, DURATION), { intro: null, outro: null });
});
+124
View File
@@ -0,0 +1,124 @@
/** A skippable time range in seconds. */
export interface SkipInterval {
start: number;
end: number;
}
export interface ChapterSkipIntervals {
intro: SkipInterval | null;
outro: SkipInterval | null;
}
/** Prefix of the marker chapters SubMiner writes; never treated as the file's own chapters. */
export const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
interface Chapter {
title: string;
start: number;
end: number;
}
const MIN_HEURISTIC_CHAPTERS = 3;
const MIN_SONG_SECONDS = 55;
const MAX_SONG_SECONDS = 150;
const TYPICAL_OPENING_SECONDS = 90;
function isSongLength(chapter: Chapter): boolean {
const length = chapter.end - chapter.start;
return length >= MIN_SONG_SECONDS && length <= MAX_SONG_SECONDS;
}
/**
* Turns mpv's `chapter-list` (entries with `time` and `title`) into sorted
* chapters with an end time (the next chapter's start, or the duration),
* dropping SubMiner's own AniSkip marker chapters.
*/
function toChapters(chapterList: unknown, duration: number): Chapter[] {
if (!Array.isArray(chapterList)) return [];
const starts: Array<{ title: string; start: number }> = [];
for (const entry of chapterList) {
if (typeof entry !== 'object' || entry === null) continue;
const { time, title } = entry as { time?: unknown; title?: unknown };
if (typeof time !== 'number' || !Number.isFinite(time) || time < 0 || time >= duration) {
continue;
}
const text = typeof title === 'string' ? title : '';
if (text.startsWith(ANISKIP_CHAPTER_PREFIX)) continue;
starts.push({ title: text, start: time });
}
starts.sort((a, b) => a.start - b.start);
return starts.map((chapter, index) => ({
...chapter,
end: starts[index + 1]?.start ?? duration,
}));
}
function isNamedOpening(chapter: Chapter): boolean {
const title = chapter.title.trim().toLowerCase();
return (
title.includes('opening') ||
title === 'op' ||
title.startsWith('op ') ||
chapter.title.includes('オープニング')
);
}
function isNamedEnding(chapter: Chapter, duration: number): boolean {
const title = chapter.title.trim().toLowerCase();
return (
title.includes('ending') ||
title === 'ed' ||
title === 'outro' ||
title === 'end credits' ||
title === 'closing credits' ||
(title === 'credits' && chapter.start > duration * 0.5) ||
title.startsWith('ed ') ||
chapter.title.includes('エンディング')
);
}
function findOpening(chapters: Chapter[], duration: number): Chapter | null {
const named = chapters.find(isNamedOpening);
if (named) return named;
if (chapters.length < MIN_HEURISTIC_CHAPTERS) return null;
let best: Chapter | null = null;
for (const chapter of chapters) {
if (chapter.start >= duration * 0.3 || !isSongLength(chapter)) continue;
const distance = Math.abs(chapter.end - chapter.start - TYPICAL_OPENING_SECONDS);
if (!best || distance < Math.abs(best.end - best.start - TYPICAL_OPENING_SECONDS)) {
best = chapter;
}
}
return best;
}
function findEnding(chapters: Chapter[], duration: number): Chapter | null {
const named = chapters.find((chapter) => isNamedEnding(chapter, duration));
if (named) return named;
if (chapters.length < MIN_HEURISTIC_CHAPTERS) return null;
return (
chapters.find((chapter) => chapter.start > duration * 0.7 && isSongLength(chapter)) ?? null
);
}
function toInterval(chapter: Chapter | null): SkipInterval | null {
return chapter && chapter.end > chapter.start ? { start: chapter.start, end: chapter.end } : null;
}
/**
* Finds the opening and ending in a file's own chapters: by name first
* ("Opening", "OP", "ED", "Credits", オープニング, ...), else by length and
* position when the file has at least three chapters. Rules follow Telly's
* `media.rs` opening()/ending().
*/
export function classifyChapterSkipIntervals(
chapterList: unknown,
duration: number,
): ChapterSkipIntervals {
if (!Number.isFinite(duration) || duration <= 0) return { intro: null, outro: null };
const chapters = toChapters(chapterList, duration);
return {
intro: toInterval(findOpening(chapters, duration)),
outro: toInterval(findEnding(chapters, duration)),
};
}
+120 -34
View File
@@ -3,17 +3,21 @@ import assert from 'node:assert/strict';
import { import {
inferAniSkipMetadataForFile, inferAniSkipMetadataForFile,
parseAniSkipGuessitJson, parseAniSkipGuessitJson,
parseAniSkipPayload,
resolveAniSkipMetadataForFile, resolveAniSkipMetadataForFile,
} from './aniskip-metadata'; } from './aniskip-metadata';
function makeMockResponse(payload: unknown): Response { const LOOKUP = { episodeLength: 1440 };
return {
ok: true, function makeMockResponse(payload: unknown, status = 200): Response {
status: 200, return new Response(JSON.stringify(payload), {
json: async () => payload, status,
} as Response; headers: { 'Content-Type': 'application/json' },
});
} }
const MAL_MY_SHOW = { categories: [{ items: [{ id: '1234', name: 'My Show' }] }] };
function normalizeFetchInput(input: string | URL | Request): string { function normalizeFetchInput(input: string | URL | Request): string {
if (typeof input === 'string') return input; if (typeof input === 'string') return input;
if (input instanceof URL) return input.toString(); if (input instanceof URL) return input.toString();
@@ -46,8 +50,8 @@ test('parseAniSkipGuessitJson extracts title season and episode', () => {
episode: 7, episode: 7,
source: 'guessit', source: 'guessit',
malId: null, malId: null,
introStart: null, intro: null,
introEnd: null, outro: null,
lookupStatus: 'lookup_failed', lookupStatus: 'lookup_failed',
}); });
}); });
@@ -68,8 +72,8 @@ test('parseAniSkipGuessitJson prefers series over episode title', () => {
episode: 10, episode: 10,
source: 'guessit', source: 'guessit',
malId: null, malId: null,
introStart: null, intro: null,
introEnd: null, outro: null,
lookupStatus: 'lookup_failed', lookupStatus: 'lookup_failed',
}); });
}); });
@@ -111,10 +115,58 @@ test('inferAniSkipMetadataForFile handles release-group filename with trailing q
assert.equal(parsed.source, 'fallback'); assert.equal(parsed.source, 'fallback');
}); });
test('resolveAniSkipMetadataForFile resolves MAL id and intro payload', async () => { test('parseAniSkipPayload reads op and ed from a v2 response', () => {
// Shape captured from api.aniskip.com/v2 on 2026-11-22.
const parsed = parseAniSkipPayload({
found: true,
results: [
{
interval: { startTime: 310.571, endTime: 400.571 },
skipType: 'op',
skipId: 'd4f34b6d-0547-4438-ac93-b25b577eddd5',
episodeLength: 1443.984,
},
{
interval: { startTime: 1396.006, endTime: 1434 },
skipType: 'ed',
skipId: '5751c57a-2bcd-4dd9-be93-58e6af0f8c81',
episodeLength: 1434.985,
},
],
message: 'Successfully found skip times',
statusCode: 200,
});
assert.deepEqual(parsed, {
intro: { start: 310.571, end: 400.571 },
outro: { start: 1396.006, end: 1434 },
});
});
test('parseAniSkipPayload ignores invalid intervals and not-found responses', () => {
assert.deepEqual(
parseAniSkipPayload({
found: true,
results: [
{ skipType: 'op', interval: { startTime: 50, endTime: 20 } },
{ skipType: 'op', interval: { startTime: 0, endTime: 89.5 } },
{ skipType: 'recap', interval: { startTime: 0, endTime: 30 } },
],
}),
{ intro: { start: 0, end: 89.5 }, outro: null },
);
assert.deepEqual(parseAniSkipPayload({ found: false, results: [] }), {
intro: null,
outro: null,
});
assert.deepEqual(parseAniSkipPayload(null), { intro: null, outro: null });
});
test('resolveAniSkipMetadataForFile queries AniSkip v2 with the episode length', async () => {
const requested: string[] = [];
await withMockFetch( await withMockFetch(
async (input) => { async (input) => {
const url = normalizeFetchInput(input); const url = normalizeFetchInput(input);
requested.push(url);
if (url.includes('myanimelist.net/search/prefix.json')) { if (url.includes('myanimelist.net/search/prefix.json')) {
return makeMockResponse({ return makeMockResponse({
categories: [ categories: [
@@ -127,48 +179,82 @@ test('resolveAniSkipMetadataForFile resolves MAL id and intro payload', async ()
], ],
}); });
} }
if (url.includes('api.aniskip.com/v1/skip-times/1234/7')) { if (url.includes('api.aniskip.com/v2/skip-times/1234/7')) {
return makeMockResponse({ return makeMockResponse({
found: true, found: true,
results: [{ skip_type: 'op', interval: { start_time: 12.5, end_time: 54.2 } }], results: [
{ skipType: 'op', interval: { startTime: 12.5, endTime: 54.2 } },
{ skipType: 'ed', interval: { startTime: 1300, endTime: 1390 } },
],
}); });
} }
throw new Error(`unexpected url: ${url}`); throw new Error(`unexpected url: ${url}`);
}, },
async () => { async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/Anime.My.Show.S01E07.mkv'); const resolved = await resolveAniSkipMetadataForFile('/media/Anime.My.Show.S01E07.mkv', {
episodeLength: 1423.4567,
});
assert.equal(resolved.malId, 1234); assert.equal(resolved.malId, 1234);
assert.equal(resolved.introStart, 12.5); assert.deepEqual(resolved.intro, { start: 12.5, end: 54.2 });
assert.equal(resolved.introEnd, 54.2); assert.deepEqual(resolved.outro, { start: 1300, end: 1390 });
assert.equal(resolved.lookupStatus, 'ready'); assert.equal(resolved.lookupStatus, 'ready');
assert.equal(resolved.title, 'Anime My Show'); assert.equal(resolved.title, 'Anime My Show');
}, },
); );
assert.equal(
requested[1],
'https://api.aniskip.com/v2/skip-times/1234/7?types=op&types=ed&episodeLength=1423.457',
);
}); });
test('resolveAniSkipMetadataForFile accepts intro payload starting at zero', async () => { test('resolveAniSkipMetadataForFile treats an AniSkip 404 as a definite miss', async () => {
await withMockFetch( await withMockFetch(
async (input) => { async (input) => {
const url = normalizeFetchInput(input); const url = normalizeFetchInput(input);
if (url.includes('myanimelist.net/search/prefix.json')) { if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
return makeMockResponse({ return makeMockResponse(
categories: [{ items: [{ id: '1234', name: 'My Show' }] }], { found: false, results: [], message: 'No skip times found', statusCode: 404 },
}); 404,
} );
if (url.includes('api.aniskip.com/v1/skip-times/1234/1')) {
return makeMockResponse({
found: true,
results: [{ skip_type: 'op', interval: { start_time: 0, end_time: 89.5 } }],
});
}
throw new Error(`unexpected url: ${url}`);
}, },
async () => { async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E01.mkv'); const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E02.mkv', LOOKUP);
assert.equal(resolved.malId, 1234); assert.equal(resolved.malId, 1234);
assert.equal(resolved.introStart, 0); assert.equal(resolved.lookupStatus, 'missing_payload');
assert.equal(resolved.introEnd, 89.5); },
assert.equal(resolved.lookupStatus, 'ready'); );
});
test('resolveAniSkipMetadataForFile reports transient failures as lookup_failed', async () => {
const failures: Array<[string, () => Promise<Response>]> = [
['AniSkip rate limit', async () => makeMockResponse({ statusCode: 429 }, 429)],
['AniSkip server error', async () => makeMockResponse({ statusCode: 503 }, 503)],
[
'network error',
async () => {
throw new TypeError('fetch failed');
},
],
];
for (const [label, failAniSkip] of failures) {
await withMockFetch(
async (input) => {
const url = normalizeFetchInput(input);
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
return failAniSkip();
},
async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
assert.equal(resolved.lookupStatus, 'lookup_failed', label);
},
);
}
await withMockFetch(
async () => makeMockResponse({}, 429),
async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
assert.equal(resolved.lookupStatus, 'lookup_failed', 'MAL rate limit');
}, },
); );
}); });
@@ -177,7 +263,7 @@ test('resolveAniSkipMetadataForFile emits missing_mal_id when MAL search misses'
await withMockFetch( await withMockFetch(
async () => makeMockResponse({ categories: [] }), async () => makeMockResponse({ categories: [] }),
async () => { async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv'); const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv', LOOKUP);
assert.equal(resolved.malId, null); assert.equal(resolved.malId, null);
assert.equal(resolved.lookupStatus, 'missing_mal_id'); assert.equal(resolved.lookupStatus, 'missing_mal_id');
}, },
+98 -84
View File
@@ -1,6 +1,7 @@
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import type { SkipInterval } from './aniskip-chapters';
export type AniSkipLookupStatus = export type AniSkipLookupStatus =
| 'ready' | 'ready'
@@ -15,11 +16,16 @@ export interface AniSkipMetadata {
episode: number | null; episode: number | null;
source: 'guessit' | 'fallback'; source: 'guessit' | 'fallback';
malId: number | null; malId: number | null;
introStart: number | null; intro: SkipInterval | null;
introEnd: number | null; outro: SkipInterval | null;
lookupStatus?: AniSkipLookupStatus; lookupStatus?: AniSkipLookupStatus;
} }
export interface AniSkipLookupOptions {
/** Length of the playing file in seconds; AniSkip v2 uses it to pick times marked on the same cut. */
episodeLength: number;
}
interface InferAniSkipDeps { interface InferAniSkipDeps {
commandExists: (name: string) => boolean; commandExists: (name: string) => boolean;
runGuessit: (mediaPath: string) => string | null; runGuessit: (mediaPath: string) => string | null;
@@ -39,12 +45,12 @@ interface MalSearchResponse {
} }
interface AniSkipIntervalPayload { interface AniSkipIntervalPayload {
start_time?: unknown; startTime?: unknown;
end_time?: unknown; endTime?: unknown;
} }
interface AniSkipSkipItemPayload { interface AniSkipSkipItemPayload {
skip_type?: unknown; skipType?: unknown;
interval?: unknown; interval?: unknown;
} }
@@ -61,9 +67,12 @@ const ROMAN_SEASON_ALIASES: Record<number, readonly string[]> = {
}; };
const MAL_PREFIX_API = 'https://myanimelist.net/search/prefix.json?type=anime&keyword='; const MAL_PREFIX_API = 'https://myanimelist.net/search/prefix.json?type=anime&keyword=';
const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v1/skip-times/'; const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v2/skip-times/';
const ANISKIP_USER_AGENT = 'SubMiner/ani-skip'; const ANISKIP_USER_AGENT = 'SubMiner/ani-skip';
const ANISKIP_FETCH_TIMEOUT_MS = 8000; const ANISKIP_FETCH_TIMEOUT_MS = 8000;
// AniSkip allows 120 requests a minute; one lookup per file load stays far below that,
// but a gap keeps fast playlist skipping from bursting.
const ANISKIP_MIN_REQUEST_GAP_MS = 1000;
const MAL_MATCH_STOPWORDS = new Set([ const MAL_MATCH_STOPWORDS = new Set([
'the', 'the',
'this', 'this',
@@ -261,49 +270,71 @@ function toMalSearchItems(payload: unknown): MalSearchResult[] {
return items; return items;
} }
function parseAniSkipPayload(payload: unknown): { start: number; end: number } | null { function parseInterval(raw: unknown): SkipInterval | null {
const parsed = payload as AniSkipPayloadResponse; if (typeof raw !== 'object' || raw === null) return null;
const results = Array.isArray(parsed?.results) ? parsed.results : null; const interval = raw as AniSkipIntervalPayload;
if (!results) return null; const start = toNonNegativeNumber(interval.startTime);
const end = toPositiveNumber(interval.endTime);
for (const rawResult of results) { return start !== null && end !== null && end > start ? { start, end } : null;
const result = rawResult as AniSkipSkipItemPayload;
if (
result.skip_type !== 'op' ||
typeof result.interval !== 'object' ||
result.interval === null
) {
continue;
}
const interval = result.interval as AniSkipIntervalPayload;
const start = toNonNegativeNumber(interval?.start_time);
const end = toPositiveNumber(interval?.end_time);
if (start !== null && end !== null && end > start) {
return { start, end };
}
}
return null;
} }
async function fetchJson<T>(url: string): Promise<T | null> { /** Reads the first valid opening (`op`) and ending (`ed`) from an AniSkip v2 response. */
export function parseAniSkipPayload(payload: unknown): {
intro: SkipInterval | null;
outro: SkipInterval | null;
} {
const parsed = payload as AniSkipPayloadResponse | null;
const results = parsed?.found === true && Array.isArray(parsed.results) ? parsed.results : [];
let intro: SkipInterval | null = null;
let outro: SkipInterval | null = null;
for (const rawResult of results) {
const result = rawResult as AniSkipSkipItemPayload;
if (result.skipType === 'op' && !intro) intro = parseInterval(result.interval);
if (result.skipType === 'ed' && !outro) outro = parseInterval(result.interval);
}
return { intro, outro };
}
/**
* Fetches JSON. A 404 is a definite "nothing here" and returns null; any other
* failure (non-OK status, network error, timeout, bad JSON) throws so callers
* report a retryable lookup failure instead of caching a miss.
*/
async function fetchJson(url: string): Promise<unknown> {
const response = await fetch(url, { const response = await fetch(url, {
headers: { headers: {
'User-Agent': ANISKIP_USER_AGENT, 'User-Agent': ANISKIP_USER_AGENT,
}, },
signal: AbortSignal.timeout(ANISKIP_FETCH_TIMEOUT_MS), signal: AbortSignal.timeout(ANISKIP_FETCH_TIMEOUT_MS),
}); });
if (!response.ok) return null; if (response.status === 404) return null;
try { if (!response.ok) {
return (await response.json()) as T; throw new Error(`HTTP ${response.status} from ${new URL(url).host}`);
} catch {
return null;
} }
return await response.json();
}
let lastAniSkipRequestAt = 0;
let aniSkipRequestQueue: Promise<void> = Promise.resolve();
/**
* Resolves when the caller may send its AniSkip request. Callers are released
* one at a time, each at least ANISKIP_MIN_REQUEST_GAP_MS after the previous
* release, so timers that fire late cannot release a burst.
*/
function waitForAniSkipRequestSlot(): Promise<void> {
const slot = aniSkipRequestQueue.then(async () => {
const waitMs = lastAniSkipRequestAt + ANISKIP_MIN_REQUEST_GAP_MS - Date.now();
if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs));
lastAniSkipRequestAt = Date.now();
});
aniSkipRequestQueue = slot;
return slot;
} }
async function resolveMalIdFromTitle(title: string, season: number | null): Promise<number | null> { async function resolveMalIdFromTitle(title: string, season: number | null): Promise<number | null> {
const lookup = season && season > 1 ? `${title} Season ${season}` : title; const lookup = season && season > 1 ? `${title} Season ${season}` : title;
const payload = await fetchJson<unknown>(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`); const payload = await fetchJson(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
const items = toMalSearchItems(payload); const items = toMalSearchItems(payload);
if (!items.length) return null; if (!items.length) return null;
@@ -326,16 +357,17 @@ async function resolveMalIdFromTitle(title: string, season: number | null): Prom
return bestMalId; return bestMalId;
} }
async function fetchAniSkipPayload( async function fetchAniSkipIntervals(
malId: number, malId: number,
episode: number, episode: number,
): Promise<{ start: number; end: number } | null> { episodeLength: number,
const payload = await fetchJson<unknown>( ): Promise<{ intro: SkipInterval | null; outro: SkipInterval | null }> {
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed`, await waitForAniSkipRequestSlot();
const length = Math.round(episodeLength * 1000) / 1000;
const payload = await fetchJson(
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed&episodeLength=${length}`,
); );
const parsed = payload as AniSkipPayloadResponse; return parseAniSkipPayload(payload);
if (!parsed || parsed.found !== true) return null;
return parseAniSkipPayload(parsed);
} }
function detectEpisodeFromName(baseName: string): number | null { function detectEpisodeFromName(baseName: string): number | null {
@@ -456,8 +488,8 @@ export function parseAniSkipGuessitJson(stdout: string, mediaPath: string): AniS
episode: episodeFromDirect ?? episodeFromList, episode: episodeFromDirect ?? episodeFromList,
source: 'guessit', source: 'guessit',
malId: null, malId: null,
introStart: null, intro: null,
introEnd: null, outro: null,
lookupStatus: 'lookup_failed', lookupStatus: 'lookup_failed',
}; };
} catch { } catch {
@@ -501,13 +533,20 @@ export function inferAniSkipMetadataForFile(
episode: detectEpisodeFromName(baseName), episode: detectEpisodeFromName(baseName),
source: 'fallback', source: 'fallback',
malId: null, malId: null,
introStart: null, intro: null,
introEnd: null, outro: null,
lookupStatus: 'lookup_failed', lookupStatus: 'lookup_failed',
}; };
} }
export async function resolveAniSkipMetadataForFile(mediaPath: string): Promise<AniSkipMetadata> { /**
* Resolves a local file's MAL id and AniSkip opening/ending. Statuses other
* than `lookup_failed` are definite answers that callers may cache.
*/
export async function resolveAniSkipMetadataForFile(
mediaPath: string,
options: AniSkipLookupOptions,
): Promise<AniSkipMetadata> {
const inferred = inferAniSkipMetadataForFile(mediaPath); const inferred = inferAniSkipMetadataForFile(mediaPath);
if (!inferred.title) { if (!inferred.title) {
return { ...inferred, lookupStatus: 'lookup_failed' }; return { ...inferred, lookupStatus: 'lookup_failed' };
@@ -516,50 +555,25 @@ export async function resolveAniSkipMetadataForFile(mediaPath: string): Promise<
try { try {
const malId = await resolveMalIdFromTitle(inferred.title, inferred.season); const malId = await resolveMalIdFromTitle(inferred.title, inferred.season);
if (!malId) { if (!malId) {
return { return { ...inferred, lookupStatus: 'missing_mal_id' };
...inferred,
malId: null,
introStart: null,
introEnd: null,
lookupStatus: 'missing_mal_id',
};
} }
if (!inferred.episode) { if (!inferred.episode) {
return { return { ...inferred, malId, lookupStatus: 'missing_episode' };
...inferred,
malId,
introStart: null,
introEnd: null,
lookupStatus: 'missing_episode',
};
}
const payload = await fetchAniSkipPayload(malId, inferred.episode);
if (!payload) {
return {
...inferred,
malId,
introStart: null,
introEnd: null,
lookupStatus: 'missing_payload',
};
} }
const { intro, outro } = await fetchAniSkipIntervals(
malId,
inferred.episode,
options.episodeLength,
);
return { return {
...inferred, ...inferred,
malId, malId,
introStart: payload.start, intro,
introEnd: payload.end, outro,
lookupStatus: 'ready', lookupStatus: intro || outro ? 'ready' : 'missing_payload',
}; };
} catch { } catch {
return { return { ...inferred, lookupStatus: 'lookup_failed' };
...inferred,
malId: inferred.malId,
introStart: inferred.introStart,
introEnd: inferred.introEnd,
lookupStatus: 'lookup_failed',
};
} }
} }
+310 -30
View File
@@ -10,19 +10,22 @@ function readyMetadata(overrides: Partial<AniSkipMetadata> = {}): AniSkipMetadat
episode: 1, episode: 1,
source: 'fallback', source: 'fallback',
malId: 1234, malId: 1234,
introStart: 10, intro: { start: 10, end: 95.5 },
introEnd: 95.5, outro: null,
lookupStatus: 'ready', lookupStatus: 'ready',
...overrides, ...overrides,
}; };
} }
const NO_SKIP_TIMES = { intro: null, outro: null } as const;
function createHarness(options?: { function createHarness(options?: {
enabled?: boolean; enabled?: boolean;
buttonKey?: string; buttonKey?: string;
metadata?: AniSkipMetadata | (() => Promise<AniSkipMetadata>); metadata?: AniSkipMetadata | (() => Promise<AniSkipMetadata>);
chapterList?: unknown; chapterList?: unknown;
playbackFeedback?: boolean; playbackFeedback?: boolean;
duration?: number | null;
}) { }) {
const state = { const state = {
enabled: options?.enabled ?? true, enabled: options?.enabled ?? true,
@@ -31,9 +34,14 @@ function createHarness(options?: {
osd: [] as string[], osd: [] as string[],
feedback: [] as string[], feedback: [] as string[],
resolveCalls: [] as string[], resolveCalls: [] as string[],
episodeLengths: [] as number[],
connected: true, connected: true,
duration: options?.duration === undefined ? 1440 : options.duration,
timePos: 0, timePos: 0,
chapterList: options?.chapterList ?? [], chapterList: options?.chapterList ?? [],
chapterListFails: false,
// When set, chapter-list reads wait for it before answering.
chapterGate: null as Promise<void> | null,
}; };
const deps = { const deps = {
@@ -41,8 +49,9 @@ function createHarness(options?: {
aniskipEnabled: state.enabled, aniskipEnabled: state.enabled,
aniskipButtonKey: state.buttonKey, aniskipButtonKey: state.buttonKey,
}), }),
resolveMetadataForFile: async (mediaPath) => { resolveMetadataForFile: async (mediaPath, episodeLength) => {
state.resolveCalls.push(mediaPath); state.resolveCalls.push(mediaPath);
state.episodeLengths.push(episodeLength);
const metadata = options?.metadata; const metadata = options?.metadata;
if (typeof metadata === 'function') return metadata(); if (typeof metadata === 'function') return metadata();
return metadata ?? readyMetadata(); return metadata ?? readyMetadata();
@@ -51,7 +60,15 @@ function createHarness(options?: {
state.commands.push(command); state.commands.push(command);
}, },
requestMpvProperty: async (name) => { requestMpvProperty: async (name) => {
if (name === 'chapter-list') return state.chapterList; if (name === 'chapter-list') {
if (state.chapterGate) await state.chapterGate;
if (state.chapterListFails) throw new Error('property unavailable');
return state.chapterList;
}
if (name === 'duration') {
if (state.duration === null) throw new Error('property unavailable');
return state.duration;
}
return null; return null;
}, },
isMpvConnected: () => state.connected, isMpvConnected: () => state.connected,
@@ -84,6 +101,10 @@ async function flushAsync(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0)); await new Promise((resolve) => setTimeout(resolve, 0));
} }
function seekCommands(commands: unknown[][]): unknown[][] {
return commands.filter((command) => command[0] === 'set_property' && command[1] === 'time-pos');
}
test('isRemoteMediaPath detects URLs but not local paths', () => { test('isRemoteMediaPath detects URLs but not local paths', () => {
assert.equal(isRemoteMediaPath('https://example.com/stream.mkv'), true); assert.equal(isRemoteMediaPath('https://example.com/stream.mkv'), true);
assert.equal(isRemoteMediaPath('rtmp://example.com/live'), true); assert.equal(isRemoteMediaPath('rtmp://example.com/live'), true);
@@ -101,6 +122,7 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
await flushAsync(); await flushAsync();
assert.deepEqual(state.resolveCalls, ['/media/anime/My Show/ep1.mkv']); assert.deepEqual(state.resolveCalls, ['/media/anime/My Show/ep1.mkv']);
assert.deepEqual(state.episodeLengths, [1440]);
const chapterCommands = chapterListCommands(state.commands); const chapterCommands = chapterListCommands(state.commands);
assert.equal(chapterCommands.length, 1); assert.equal(chapterCommands.length, 1);
const chapters = chapterCommands[0]![2] as Array<{ time: number; title: string }>; const chapters = chapterCommands[0]![2] as Array<{ time: number; title: string }>;
@@ -109,7 +131,10 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
{ time: 10, title: 'AniSkip Intro Start' }, { time: 10, title: 'AniSkip Intro Start' },
{ time: 95.5, title: 'AniSkip Intro End' }, { time: 95.5, title: 'AniSkip Intro End' },
]); ]);
assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 }); assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 10, end: 95.5, source: 'aniskip' },
outro: null,
});
}); });
test('remote media paths and disabled config never resolve', async () => { test('remote media paths and disabled config never resolve', async () => {
@@ -131,21 +156,18 @@ test('skip intro seeks to intro end only inside the intro window', async () => {
state.timePos = 200; state.timePos = 200;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] }); runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Skip intro only during intro']); assert.deepEqual(state.osd, ['Skip only during intro or outro']);
state.timePos = 30; state.timePos = 30;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] }); runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Skip intro only during intro', 'Skipped intro']); assert.deepEqual(state.osd, ['Skip only during intro or outro', 'Skipped intro']);
const seek = state.commands.find( assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 95.5]]);
(command) => command[0] === 'set_property' && command[1] === 'time-pos',
);
assert.deepEqual(seek, ['set_property', 'time-pos', 95.5]);
}); });
test('skip intro reports unavailable when no window was found', () => { test('skip intro reports unavailable when no window was found', () => {
const { runtime, state } = createHarness(); const { runtime, state } = createHarness();
runtime.handleClientMessage({ args: ['subminer-skip-intro'] }); runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Intro skip unavailable']); assert.deepEqual(state.osd, ['Intro/outro skip unavailable']);
}); });
test('time-pos prompt shows once near intro start', async () => { test('time-pos prompt shows once near intro start', async () => {
@@ -158,7 +180,7 @@ test('time-pos prompt shows once near intro start', async () => {
runtime.handleTimePosChange({ time: 10.5 }); runtime.handleTimePosChange({ time: 10.5 });
runtime.handleTimePosChange({ time: 11 }); runtime.handleTimePosChange({ time: 11 });
assert.deepEqual(state.osd, ['You can skip by pressing TAB']); assert.deepEqual(state.osd, ['You can skip the intro by pressing TAB']);
}); });
test('prompt and skip messages use playback feedback when configured', async () => { test('prompt and skip messages use playback feedback when configured', async () => {
@@ -170,7 +192,7 @@ test('prompt and skip messages use playback feedback when configured', async ()
state.timePos = 30; state.timePos = 30;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] }); runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.feedback, ['You can skip by pressing TAB', 'Skipped intro']); assert.deepEqual(state.feedback, ['You can skip the intro by pressing TAB', 'Skipped intro']);
assert.deepEqual(state.osd, []); assert.deepEqual(state.osd, []);
}); });
@@ -240,18 +262,13 @@ test('aniskip refresh forces a fresh lookup for the current media', async () =>
assert.equal(state.resolveCalls.length, 2); assert.equal(state.resolveCalls.length, 2);
}); });
test('media without an intro window is cached and never re-resolved on reload of another file', async () => { test('definite misses are cached and not looked up again for the same file', async () => {
const { runtime, state } = createHarness({ const { runtime, state } = createHarness({
metadata: readyMetadata({ metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
malId: 1234,
introStart: null,
introEnd: null,
lookupStatus: 'missing_payload',
}),
}); });
runtime.handleMediaPathChange({ path: '/media/show.mkv' }); runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync(); await flushAsync();
assert.equal(runtime.getIntroWindow(), null); assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
assert.equal(chapterListCommands(state.commands).length, 0); assert.equal(chapterListCommands(state.commands).length, 0);
runtime.handleMediaPathChange({ path: '/media/other.mkv' }); runtime.handleMediaPathChange({ path: '/media/other.mkv' });
@@ -261,25 +278,117 @@ test('media without an intro window is cached and never re-resolved on reload of
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/other.mkv']); assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/other.mkv']);
}); });
test('transient lookup failures are retried on the next media load', async () => { test('transient lookup failures are not cached and retry on the next media load', async () => {
let failures = 0; let calls = 0;
const { runtime, state } = createHarness({ const { runtime, state } = createHarness({
metadata: async () => { metadata: async () => {
failures += 1; calls += 1;
return readyMetadata( return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
failures === 1 ? { introStart: null, introEnd: null, lookupStatus: 'lookup_failed' } : {},
);
}, },
}); });
runtime.handleMediaPathChange({ path: '/media/show.mkv' }); runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync(); await flushAsync();
assert.equal(runtime.getIntroWindow(), null); assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
runtime.handleMediaPathChange({ path: '' }); runtime.handleMediaPathChange({ path: '' });
runtime.handleMediaPathChange({ path: '/media/show.mkv' }); runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync(); await flushAsync();
assert.equal(state.resolveCalls.length, 2); assert.equal(state.resolveCalls.length, 2);
assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 }); assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
});
test('resolution waits for a known duration before reading chapters or AniSkip', async () => {
const { runtime, state } = createHarness({ duration: null });
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(state.resolveCalls, []);
runtime.handleDurationChange({ duration: 1425.2 });
await flushAsync();
assert.deepEqual(state.episodeLengths, [1425.2]);
});
test('file chapters with both an opening and an ending skip the AniSkip lookup', async () => {
const { runtime, state } = createHarness({
chapterList: [
{ time: 0, title: 'Prologue' },
{ time: 120, title: 'Opening' },
{ time: 210, title: 'Part A' },
{ time: 1300, title: 'Ending' },
{ time: 1390, title: 'Preview' },
],
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(state.resolveCalls, []);
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 120, end: 210, source: 'chapters' },
outro: { start: 1300, end: 1390, source: 'chapters' },
});
// The file already has chapter boundaries there, so no AniSkip markers are added.
assert.equal(chapterListCommands(state.commands).length, 0);
});
test('AniSkip fills in the window the file chapters lack', async () => {
const { runtime, state } = createHarness({
chapterList: [
{ time: 0, title: 'Opening' },
{ time: 90, title: 'Episode' },
],
metadata: readyMetadata({
intro: { start: 3, end: 93 },
outro: { start: 1330, end: 1420 },
}),
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(state.resolveCalls.length, 1);
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 0, end: 90, source: 'chapters' },
outro: { start: 1330, end: 1420, source: 'aniskip' },
});
assert.deepEqual(chapterListCommands(state.commands)[0]![2], [
{ time: 0, title: 'Opening' },
{ time: 90, title: 'Episode' },
{ time: 1330, title: 'AniSkip Outro Start' },
{ time: 1420, title: 'AniSkip Outro End' },
]);
});
test('remote streams use file chapters without an AniSkip lookup', async () => {
const { runtime, state } = createHarness({
chapterList: [
{ time: 0, title: 'Intro' },
{ time: 30, title: 'OP' },
{ time: 120, title: 'Episode' },
],
});
runtime.handleMediaPathChange({ path: 'https://jellyfin.example/Videos/1/stream.mkv' });
await flushAsync();
assert.deepEqual(state.resolveCalls, []);
assert.deepEqual(runtime.getSkipWindows().intro, { start: 30, end: 120, source: 'chapters' });
});
test('skip key skips the outro inside its window and prompts at its start', async () => {
const { runtime, state } = createHarness({
metadata: readyMetadata({ outro: { start: 1330, end: 1420 } }),
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
runtime.handleTimePosChange({ time: 1331 });
runtime.handleTimePosChange({ time: 1332 });
assert.deepEqual(state.osd, ['You can skip the outro by pressing TAB']);
state.timePos = 1329.8;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
state.timePos = 1425;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 1420]]);
assert.deepEqual(state.osd.slice(1), ['Skipped outro', 'Skip only during intro or outro']);
}); });
test('disconnect clears bindings so reconnect rebinds the skip key', () => { test('disconnect clears bindings so reconnect rebinds the skip key', () => {
@@ -292,3 +401,174 @@ test('disconnect clears bindings so reconnect rebinds the skip key', () => {
['keybind', 'TAB', 'script-message subminer-skip-intro'], ['keybind', 'TAB', 'script-message subminer-skip-intro'],
]); ]);
}); });
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
test('a failed chapter-list read leaves the file chapters untouched', async () => {
const harness = createHarness({
chapterList: [{ time: 0, title: 'Prologue' }],
metadata: async () => {
harness.state.chapterListFails = true;
return readyMetadata();
},
});
harness.runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(harness.runtime.getSkipWindows().intro?.source, 'aniskip');
assert.equal(chapterListCommands(harness.state.commands).length, 0);
});
test('markers are not written into a file that replaced the one being read', async () => {
const gate = deferred<void>();
let calls = 0;
const harness = createHarness({
metadata: async () => {
calls += 1;
if (calls === 1) {
harness.state.chapterGate = gate.promise;
return readyMetadata();
}
return readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' });
},
});
harness.runtime.handleMediaPathChange({ path: '/media/a.mkv' });
await flushAsync();
// The marker write for a.mkv is waiting on its chapter-list read.
harness.runtime.handleMediaPathChange({ path: '/media/b.mkv' });
harness.state.chapterGate = null;
gate.resolve();
await flushAsync();
await flushAsync();
assert.deepEqual(harness.state.resolveCalls, ['/media/a.mkv', '/media/b.mkv']);
assert.equal(chapterListCommands(harness.state.commands).length, 0);
});
test('a file-chapter intro is usable while the AniSkip lookup is still running', async () => {
const lookup = deferred<AniSkipMetadata>();
const { runtime, state } = createHarness({
chapterList: [
{ time: 0, title: 'Opening' },
{ time: 90, title: 'Episode' },
],
metadata: () => lookup.promise,
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 0, end: 90, source: 'chapters' },
outro: null,
});
runtime.handleTimePosChange({ time: 1 });
assert.equal(state.osd.length, 1);
lookup.resolve(
readyMetadata({ intro: { start: 3, end: 93 }, outro: { start: 1330, end: 1420 } }),
);
await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 0, end: 90, source: 'chapters' },
outro: { start: 1330, end: 1420, source: 'aniskip' },
});
// The intro prompt already shown is not shown again.
runtime.handleTimePosChange({ time: 1.5 });
assert.equal(state.osd.length, 1);
});
test('a lookup superseded by a refresh does not overwrite the cache', async () => {
const first = deferred<AniSkipMetadata>();
let calls = 0;
const { runtime, state } = createHarness({
metadata: () => {
calls += 1;
return calls === 1 ? first.promise : Promise.resolve(readyMetadata());
},
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
runtime.handleClientMessage({ args: ['subminer-aniskip-refresh'] });
await flushAsync();
first.resolve(readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }));
await flushAsync();
runtime.handleMediaPathChange({ path: '/media/other.mkv' });
await flushAsync();
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/show.mkv', '/media/other.mkv']);
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
});
test('a same-media reload retries a transient lookup failure', async () => {
let calls = 0;
const { runtime, state } = createHarness({
metadata: async () => {
calls += 1;
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
},
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(state.resolveCalls.length, 2);
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
});
test('a failed chapter-list read is retried on the next duration change or reload', async () => {
const stream = 'https://jellyfin.example/Videos/1/stream.mkv';
const chapters = [
{ time: 0, title: 'OP' },
{ time: 90, title: 'Episode' },
];
for (const retry of ['duration', 'reload'] as const) {
const { runtime, state } = createHarness({ chapterList: chapters });
state.chapterListFails = true;
runtime.handleMediaPathChange({ path: stream });
await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
state.chapterListFails = false;
if (retry === 'duration') runtime.handleDurationChange({ duration: 1440 });
else runtime.handleMediaPathChange({ path: stream });
await flushAsync();
assert.deepEqual(runtime.getSkipWindows().intro, { start: 0, end: 90, source: 'chapters' });
}
});
test('a successful empty chapter list is not read again on a duration change', async () => {
const { runtime, state } = createHarness({
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
runtime.handleDurationChange({ duration: 1441 });
await flushAsync();
assert.equal(state.resolveCalls.length, 1);
});
test('a cached lookup is reused only for the episode length it was fetched for', async () => {
const { runtime, state } = createHarness();
// A failing chapter read keeps resolution retrying on each duration change.
state.chapterListFails = true;
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
runtime.handleDurationChange({ duration: 1440 });
await flushAsync();
assert.deepEqual(state.episodeLengths, [1440]);
runtime.handleDurationChange({ duration: 1500 });
await flushAsync();
assert.deepEqual(state.episodeLengths, [1440, 1500]);
});
+276 -122
View File
@@ -1,11 +1,16 @@
import type { AniSkipMetadata } from './aniskip-metadata'; import type { AniSkipMetadata } from './aniskip-metadata';
import {
ANISKIP_CHAPTER_PREFIX,
classifyChapterSkipIntervals,
type SkipInterval,
} from './aniskip-chapters';
/** mpv script-message that skips whichever of the intro or outro is playing. */
export const ANISKIP_SKIP_INTRO_MESSAGE = 'subminer-skip-intro'; export const ANISKIP_SKIP_INTRO_MESSAGE = 'subminer-skip-intro';
export const ANISKIP_REFRESH_MESSAGE = 'subminer-aniskip-refresh'; export const ANISKIP_REFRESH_MESSAGE = 'subminer-aniskip-refresh';
const DEFAULT_ANISKIP_BUTTON_KEY = 'TAB'; const DEFAULT_ANISKIP_BUTTON_KEY = 'TAB';
const LEGACY_ANISKIP_BUTTON_KEY = 'y-k'; const LEGACY_ANISKIP_BUTTON_KEY = 'y-k';
const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
const SKIP_WINDOW_EPSILON_SECONDS = 0.35; const SKIP_WINDOW_EPSILON_SECONDS = 0.35;
const PROMPT_WINDOW_SECONDS = 3; const PROMPT_WINDOW_SECONDS = 3;
const PROMPT_OSD_DURATION_MS = 3000; const PROMPT_OSD_DURATION_MS = 3000;
@@ -16,7 +21,7 @@ export interface AniSkipRuntimeConfig {
export interface AniSkipRuntimeDeps { export interface AniSkipRuntimeDeps {
getAniSkipConfig: () => AniSkipRuntimeConfig; getAniSkipConfig: () => AniSkipRuntimeConfig;
resolveMetadataForFile: (mediaPath: string) => Promise<AniSkipMetadata>; resolveMetadataForFile: (mediaPath: string, episodeLength: number) => Promise<AniSkipMetadata>;
sendMpvCommand: (command: unknown[]) => void; sendMpvCommand: (command: unknown[]) => void;
requestMpvProperty: (name: string) => Promise<unknown>; requestMpvProperty: (name: string) => Promise<unknown>;
isMpvConnected: () => boolean; isMpvConnected: () => boolean;
@@ -28,26 +33,65 @@ export interface AniSkipRuntimeDeps {
logDebug: (message: string) => void; logDebug: (message: string) => void;
} }
export interface AniSkipIntroWindow { export type SkipWindowKind = 'intro' | 'outro';
start: number;
end: number; export interface AniSkipWindow extends SkipInterval {
/** `chapters` = the file's own chapters; `aniskip` = the AniSkip database. */
source: 'chapters' | 'aniskip';
}
export interface AniSkipWindows {
intro: AniSkipWindow | null;
outro: AniSkipWindow | null;
}
interface AniSkipLookupResult {
intro: SkipInterval | null;
outro: SkipInterval | null;
malId: number | null; malId: number | null;
} }
type MpvChapter = { time?: unknown; title?: unknown }; type MpvChapter = { time?: unknown; title?: unknown };
const KIND_LABEL: Record<SkipWindowKind, { chapter: string; word: string }> = {
intro: { chapter: 'Intro', word: 'intro' },
outro: { chapter: 'Outro', word: 'outro' },
};
export function isRemoteMediaPath(mediaPath: string): boolean { export function isRemoteMediaPath(mediaPath: string): boolean {
return /^[a-zA-Z][\w+.-]*:\/\//.test(mediaPath.trim()); return /^[a-zA-Z][\w+.-]*:\/\//.test(mediaPath.trim());
} }
function isAniSkipChapter(chapter: MpvChapter): boolean {
return typeof chapter?.title === 'string' && chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX);
}
function isUsableDuration(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value) && value > 0;
}
/**
* Finds the intro and outro for each loaded file (file chapters first, then
* AniSkip for whatever the chapters lack), marks them as chapters, prompts when
* one starts, and skips the active one when the skip key is pressed.
*/
export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
let requestGeneration = 0; let requestGeneration = 0;
let currentMediaPath = ''; let currentMediaPath = '';
let introWindow: AniSkipIntroWindow | null = null; let currentDuration: number | null = null;
let promptShown = false; // True once resolution for the current media has started (or finished).
let resolutionStarted = false;
// True when resolution for the current media hit a retryable failure (the
// chapter-list read or the AniSkip lookup), so a reload or duration change
// runs it again.
let retryResolution = false;
let windows: AniSkipWindows = { intro: null, outro: null };
const promptShown: Record<SkipWindowKind, boolean> = { intro: false, outro: false };
let boundButtonKey: string | null = null; let boundButtonKey: string | null = null;
let legacyFallbackBound = false; let legacyFallbackBound = false;
const introWindowCache = new Map<string, AniSkipIntroWindow | null>(); // AniSkip results per media path, with the episode length they were fetched
// for (v2 picks times by length). Only definitive answers are stored.
const lookupCache = new Map<string, { duration: number; result: AniSkipLookupResult }>();
function resolveButtonKey(): string { function resolveButtonKey(): string {
const key = deps.getAniSkipConfig().aniskipButtonKey.trim(); const key = deps.getAniSkipConfig().aniskipButtonKey.trim();
@@ -93,22 +137,39 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
} }
} }
async function setIntroChapters(introStart: number, introEnd: number): Promise<void> { async function readChapterList(): Promise<MpvChapter[] | null> {
let existing: MpvChapter[] = [];
try { try {
const chapterList = await deps.requestMpvProperty('chapter-list'); const chapterList = await deps.requestMpvProperty('chapter-list');
if (Array.isArray(chapterList)) { return Array.isArray(chapterList) ? (chapterList as MpvChapter[]) : [];
existing = chapterList as MpvChapter[];
}
} catch { } catch {
// chapter-list may be unavailable mid-load; fall back to AniSkip chapters only // chapter-list may be unavailable mid-load
return null;
} }
const chapters = existing.filter( }
(chapter) =>
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX), /** True while the given request generation still owns the given media. */
); function ownsPlayback(generation: number, mediaPath: string): boolean {
chapters.push({ time: introStart, title: 'AniSkip Intro Start' }); return generation === requestGeneration && mediaPath === currentMediaPath;
chapters.push({ time: introEnd, title: 'AniSkip Intro End' }); }
/** Replaces SubMiner's marker chapters with ones for the AniSkip-sourced windows. */
async function setSkipChapters(): Promise<void> {
const generation = requestGeneration;
const mediaPath = currentMediaPath;
const markers: MpvChapter[] = [];
for (const kind of ['intro', 'outro'] as const) {
const window = windows[kind];
if (window?.source !== 'aniskip') continue;
const label = KIND_LABEL[kind].chapter;
markers.push({ time: window.start, title: `${ANISKIP_CHAPTER_PREFIX}${label} Start` });
markers.push({ time: window.end, title: `${ANISKIP_CHAPTER_PREFIX}${label} End` });
}
if (markers.length === 0) return;
const existing = await readChapterList();
// A failed read must not wipe the file's chapters, and a read that finished
// after the media changed must not write into the next file.
if (!existing || !ownsPlayback(generation, mediaPath)) return;
const chapters = existing.filter((chapter) => !isAniSkipChapter(chapter)).concat(markers);
chapters.sort((a, b) => { chapters.sort((a, b) => {
const aTime = typeof a.time === 'number' ? a.time : 0; const aTime = typeof a.time === 'number' ? a.time : 0;
const bTime = typeof b.time === 'number' ? b.time : 0; const bTime = typeof b.time === 'number' ? b.time : 0;
@@ -117,21 +178,13 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
deps.sendMpvCommand(['set_property', 'chapter-list', chapters]); deps.sendMpvCommand(['set_property', 'chapter-list', chapters]);
} }
async function removeIntroChapters(): Promise<void> { async function removeSkipChapters(): Promise<void> {
if (!deps.isMpvConnected()) return; if (!deps.isMpvConnected()) return;
let existing: MpvChapter[] = []; const generation = requestGeneration;
try { const mediaPath = currentMediaPath;
const chapterList = await deps.requestMpvProperty('chapter-list'); const existing = await readChapterList();
if (Array.isArray(chapterList)) { if (!existing || !ownsPlayback(generation, mediaPath)) return;
existing = chapterList as MpvChapter[]; const filtered = existing.filter((chapter) => !isAniSkipChapter(chapter));
}
} catch {
return;
}
const filtered = existing.filter(
(chapter) =>
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
);
if (filtered.length !== existing.length) { if (filtered.length !== existing.length) {
deps.sendMpvCommand(['set_property', 'chapter-list', filtered]); deps.sendMpvCommand(['set_property', 'chapter-list', filtered]);
} }
@@ -139,81 +192,162 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
function clearState(): void { function clearState(): void {
requestGeneration += 1; requestGeneration += 1;
introWindow = null; resolutionStarted = false;
promptShown = false; retryResolution = false;
windows = { intro: null, outro: null };
promptShown.intro = false;
promptShown.outro = false;
} }
async function applyIntroWindow(window: AniSkipIntroWindow): Promise<void> { function logWindow(kind: SkipWindowKind, window: AniSkipWindow, malId: number | null): void {
introWindow = window;
promptShown = false;
await setIntroChapters(window.start, window.end);
deps.logInfo( deps.logInfo(
`AniSkip intro window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (MAL ${ `AniSkip ${kind} window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (source=${
window.malId ?? '-' window.source
})`, }, MAL ${malId ?? '-'})`,
); );
} }
async function resolveForMedia(mediaPath: string, options?: { force?: boolean }): Promise<void> { /** Installs the file-chapter windows, resetting the prompts. */
if (!deps.getAniSkipConfig().aniskipEnabled) return; function applyChapterWindows(next: AniSkipWindows): void {
if (!mediaPath || isRemoteMediaPath(mediaPath)) { windows = next;
deps.logDebug('AniSkip lookup skipped: no local media path'); promptShown.intro = false;
return; promptShown.outro = false;
for (const kind of ['intro', 'outro'] as const) {
const window = next[kind];
if (window) logWindow(kind, window, null);
} }
}
if (options?.force) { /**
introWindowCache.delete(mediaPath); * Fills the windows the chapters lacked from AniSkip, leaving the chapter
* windows (and whether their prompt was shown) untouched.
*/
async function mergeAniSkipWindows(lookup: AniSkipLookupResult): Promise<void> {
const added: SkipWindowKind[] = [];
for (const kind of ['intro', 'outro'] as const) {
const interval = lookup[kind];
if (windows[kind] || !interval) continue;
windows = { ...windows, [kind]: { ...interval, source: 'aniskip' } };
promptShown[kind] = false;
added.push(kind);
} }
const generation = requestGeneration; if (added.length === 0) return;
const cached = introWindowCache.get(mediaPath); for (const kind of added) {
if (cached !== undefined) { const window = windows[kind];
if (cached) { if (window) logWindow(kind, window, lookup.malId);
await applyIntroWindow(cached);
}
return;
} }
await setSkipChapters();
}
/**
* Looks up AniSkip, using the cache for definitive answers fetched at the same
* episode length. Null means a retryable failure.
*/
async function lookUpAniSkip(
mediaPath: string,
duration: number,
generation: number,
): Promise<AniSkipLookupResult | null> {
const cached = lookupCache.get(mediaPath);
if (cached?.duration === duration) return cached.result;
let metadata: AniSkipMetadata; let metadata: AniSkipMetadata;
try { try {
metadata = await deps.resolveMetadataForFile(mediaPath); metadata = await deps.resolveMetadataForFile(mediaPath, duration);
} catch (error) { } catch (error) {
deps.logWarn('AniSkip metadata lookup failed', error); deps.logWarn('AniSkip metadata lookup failed', error);
return; return null;
} }
if (generation !== requestGeneration || mediaPath !== currentMediaPath) { const result: AniSkipLookupResult = {
return; intro: metadata.intro,
} outro: metadata.outro,
if (
metadata.lookupStatus !== 'ready' ||
metadata.introStart === null ||
metadata.introEnd === null ||
metadata.introEnd <= metadata.introStart
) {
// Only definitive "no skip window exists" results are cached; transient
// lookup failures stay retryable on the next load or refresh.
if (metadata.lookupStatus !== 'lookup_failed') {
introWindowCache.set(mediaPath, null);
}
deps.logInfo(
`AniSkip: no intro window for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
);
return;
}
const window: AniSkipIntroWindow = {
start: metadata.introStart,
end: metadata.introEnd,
malId: metadata.malId, malId: metadata.malId,
}; };
introWindowCache.set(mediaPath, window); if (metadata.lookupStatus === 'lookup_failed') {
await applyIntroWindow(window); deps.logInfo(`AniSkip lookup failed for "${metadata.title}"; will retry on next load`);
return null;
}
// Every other status is definitive (a 404 or an unmatched title), so cache it,
// unless a refresh or media change superseded this lookup while it ran.
if (generation === requestGeneration) lookupCache.set(mediaPath, { duration, result });
if (metadata.lookupStatus !== 'ready') {
deps.logInfo(
`AniSkip: no skip times for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
);
}
return result;
} }
function skipIntroNow(): void { async function resolveForMedia(mediaPath: string, duration: number): Promise<void> {
if (!deps.getAniSkipConfig().aniskipEnabled) return; if (!deps.getAniSkipConfig().aniskipEnabled) return;
if (!introWindow) { const generation = requestGeneration;
showPlaybackFeedback('Intro skip unavailable'); const isStale = () => generation !== requestGeneration || mediaPath !== currentMediaPath;
const chapterList = await readChapterList();
if (isStale()) return;
// A failed read is retried later; a successful empty list is a final answer.
if (chapterList === null) retryResolution = true;
const fromChapters = classifyChapterSkipIntervals(chapterList ?? [], duration);
const next: AniSkipWindows = {
intro: fromChapters.intro ? { ...fromChapters.intro, source: 'chapters' } : null,
outro: fromChapters.outro ? { ...fromChapters.outro, source: 'chapters' } : null,
};
// Chapter windows work right away; AniSkip only fills what they lack.
applyChapterWindows(next);
if (next.intro && next.outro) return;
if (isRemoteMediaPath(mediaPath)) {
deps.logDebug('AniSkip lookup skipped for remote media; using file chapters only');
return;
}
const lookup = await lookUpAniSkip(mediaPath, duration, generation);
if (isStale()) return;
if (lookup === null) retryResolution = true;
if (lookup) await mergeAniSkipWindows(lookup);
}
/** Starts resolution once the current media has both a path and a known duration. */
function maybeStartResolution(): void {
if (resolutionStarted || !currentMediaPath || currentDuration === null) return;
if (!deps.getAniSkipConfig().aniskipEnabled) return;
resolutionStarted = true;
void resolveForMedia(currentMediaPath, currentDuration).catch((error) => {
deps.logWarn('AniSkip media resolution failed', error);
});
}
function requestCurrentDuration(): void {
const generation = requestGeneration;
void deps
.requestMpvProperty('duration')
.then((value) => {
if (generation !== requestGeneration || !isUsableDuration(value)) return;
currentDuration ??= value;
maybeStartResolution();
})
.catch(() => {
// duration is unavailable until the file is loaded; duration-change will follow
});
}
function getActiveWindow(now: number): SkipWindowKind | null {
for (const kind of ['intro', 'outro'] as const) {
const window = windows[kind];
if (
window &&
now >= window.start - SKIP_WINDOW_EPSILON_SECONDS &&
now <= window.end + SKIP_WINDOW_EPSILON_SECONDS
) {
return kind;
}
}
return null;
}
function skipNow(): void {
if (!deps.getAniSkipConfig().aniskipEnabled) return;
if (!windows.intro && !windows.outro) {
showPlaybackFeedback('Intro/outro skip unavailable');
return; return;
} }
const now = deps.getCurrentTimePos(); const now = deps.getCurrentTimePos();
@@ -221,40 +355,56 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
showPlaybackFeedback('Skip unavailable'); showPlaybackFeedback('Skip unavailable');
return; return;
} }
if ( const kind = getActiveWindow(now);
now < introWindow.start - SKIP_WINDOW_EPSILON_SECONDS || const window = kind ? windows[kind] : null;
now > introWindow.end + SKIP_WINDOW_EPSILON_SECONDS if (!kind || !window) {
) { showPlaybackFeedback('Skip only during intro or outro');
showPlaybackFeedback('Skip intro only during intro');
return; return;
} }
deps.sendMpvCommand(['set_property', 'time-pos', introWindow.end]); deps.sendMpvCommand(['set_property', 'time-pos', window.end]);
showPlaybackFeedback('Skipped intro'); showPlaybackFeedback(`Skipped ${KIND_LABEL[kind].word}`);
} }
function handleTimePosChange({ time }: { time: number }): void { function handleTimePosChange({ time }: { time: number }): void {
if (!introWindow || promptShown) return;
if (!deps.getAniSkipConfig().aniskipEnabled) return; if (!deps.getAniSkipConfig().aniskipEnabled) return;
const promptWindowEnd = Math.min(introWindow.start + PROMPT_WINDOW_SECONDS, introWindow.end); for (const kind of ['intro', 'outro'] as const) {
if (time >= introWindow.start && time < promptWindowEnd) { const window = windows[kind];
promptShown = true; if (!window || promptShown[kind]) continue;
showPlaybackFeedback(`You can skip by pressing ${resolveButtonKey()}`); const promptWindowEnd = Math.min(window.start + PROMPT_WINDOW_SECONDS, window.end);
if (time >= window.start && time < promptWindowEnd) {
promptShown[kind] = true;
showPlaybackFeedback(
`You can skip the ${KIND_LABEL[kind].word} by pressing ${resolveButtonKey()}`,
);
}
} }
} }
function handleDurationChange({ duration }: { duration: number }): void {
if (!isUsableDuration(duration) || !currentMediaPath) return;
currentDuration = duration;
if (retryResolution) clearState();
maybeStartResolution();
}
function handleMediaPathChange({ path }: { path: string }): void { function handleMediaPathChange({ path }: { path: string }): void {
const nextPath = typeof path === 'string' ? path : ''; const nextPath = typeof path === 'string' ? path : '';
if (nextPath === currentMediaPath && introWindow) { if (nextPath === currentMediaPath && resolutionStarted) {
if (retryResolution) {
// The last resolution failed transiently; a reload is the retry.
clearState();
maybeStartResolution();
return;
}
// Same-media reload: mpv rebuilt the chapter list, so re-apply markers. // Same-media reload: mpv rebuilt the chapter list, so re-apply markers.
void setIntroChapters(introWindow.start, introWindow.end).catch(() => {}); void setSkipChapters().catch(() => {});
return; return;
} }
currentMediaPath = nextPath; currentMediaPath = nextPath;
currentDuration = null;
clearState(); clearState();
if (!nextPath) return; if (!nextPath || !deps.getAniSkipConfig().aniskipEnabled) return;
void resolveForMedia(nextPath).catch((error) => { requestCurrentDuration();
deps.logWarn('AniSkip media resolution failed', error);
});
} }
function handleConnectionChange({ connected }: { connected: boolean }): void { function handleConnectionChange({ connected }: { connected: boolean }): void {
@@ -263,6 +413,7 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
legacyFallbackBound = false; legacyFallbackBound = false;
clearState(); clearState();
currentMediaPath = ''; currentMediaPath = '';
currentDuration = null;
return; return;
} }
bindSkipKeys(); bindSkipKeys();
@@ -271,43 +422,46 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
function handleClientMessage({ args }: { args: string[] }): void { function handleClientMessage({ args }: { args: string[] }): void {
const messageName = args[0]; const messageName = args[0];
if (messageName === ANISKIP_SKIP_INTRO_MESSAGE) { if (messageName === ANISKIP_SKIP_INTRO_MESSAGE) {
skipIntroNow(); skipNow();
return; return;
} }
if (messageName === ANISKIP_REFRESH_MESSAGE) { if (messageName === ANISKIP_REFRESH_MESSAGE) {
const mediaPath = currentMediaPath; if (!currentMediaPath) return;
if (!mediaPath) return; lookupCache.delete(currentMediaPath);
clearState(); clearState();
void removeIntroChapters().catch(() => {}); void removeSkipChapters().catch(() => {});
void resolveForMedia(mediaPath, { force: true }).catch((error) => { if (currentDuration === null) {
deps.logWarn('AniSkip refresh failed', error); requestCurrentDuration();
}); return;
}
maybeStartResolution();
} }
} }
function applyConfigChange(): void { function applyConfigChange(): void {
bindSkipKeys(); bindSkipKeys();
const enabled = deps.getAniSkipConfig().aniskipEnabled; if (!deps.getAniSkipConfig().aniskipEnabled) {
if (!enabled) {
clearState(); clearState();
void removeIntroChapters().catch(() => {}); void removeSkipChapters().catch(() => {});
return; return;
} }
if (!introWindow && currentMediaPath) { if (!currentMediaPath || resolutionStarted) return;
void resolveForMedia(currentMediaPath).catch((error) => { if (currentDuration === null) {
deps.logWarn('AniSkip media resolution failed', error); requestCurrentDuration();
}); return;
} }
maybeStartResolution();
} }
return { return {
handleConnectionChange, handleConnectionChange,
handleMediaPathChange, handleMediaPathChange,
handleDurationChange,
handleTimePosChange, handleTimePosChange,
handleClientMessage, handleClientMessage,
applyConfigChange, applyConfigChange,
skipIntroNow, skipNow,
getIntroWindow: () => introWindow, getSkipWindows: (): AniSkipWindows => windows,
}; };
} }
@@ -7,6 +7,14 @@ 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> = {},
@@ -52,6 +60,7 @@ 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,
}); });
@@ -90,6 +99,7 @@ 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,
}); });
@@ -117,6 +127,7 @@ 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,
}); });
@@ -146,6 +157,7 @@ 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,
}); });
@@ -221,6 +233,7 @@ 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',
@@ -275,6 +288,7 @@ 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',
@@ -310,6 +324,7 @@ 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',
@@ -403,6 +418,7 @@ 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,
}), }),
@@ -469,6 +485,7 @@ 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,
}; };
@@ -538,6 +555,7 @@ 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,
}), }),
@@ -620,6 +638,7 @@ 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,
}), }),
@@ -692,6 +711,7 @@ 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,
}), }),
@@ -747,6 +767,7 @@ 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,
}); });
@@ -775,3 +796,55 @@ 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,3 +1,4 @@
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';
@@ -34,6 +35,7 @@ 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'
@@ -63,6 +65,7 @@ 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;
} }
@@ -154,6 +157,56 @@ 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 =
@@ -535,6 +588,7 @@ 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)}
@@ -566,6 +620,7 @@ 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' &&
+5
View File
@@ -19,6 +19,7 @@
import { clipboard, contextBridge, ipcRenderer, IpcRendererEvent, webUtils } from 'electron'; import { clipboard, contextBridge, ipcRenderer, IpcRendererEvent, webUtils } from 'electron';
import { resolveOverlayLayerFromArgv } from './preload-args'; import { resolveOverlayLayerFromArgv } from './preload-args';
import { createIpcListenerFactories } from './preload-ipc-listeners'; import { createIpcListenerFactories } from './preload-ipc-listeners';
import type { UnforwardedMpvKeyReport } from './types/session-bindings';
import { import {
DICTIONARY_EXTERNAL_LINK_CHANNEL, DICTIONARY_EXTERNAL_LINK_CHANNEL,
parseDictionaryExternalUrl, parseDictionaryExternalUrl,
@@ -329,6 +330,10 @@ const electronAPI: ElectronAPI = {
ipcRenderer.send(IPC_CHANNELS.command.recordYomitanLookup, context ?? null); ipcRenderer.send(IPC_CHANNELS.command.recordYomitanLookup, context ?? null);
}, },
reportUnforwardedMpvKey: (report: UnforwardedMpvKeyReport) => {
ipcRenderer.send(IPC_CHANNELS.command.reportUnforwardedMpvKey, report);
},
getSubtitlePosition: (): Promise<SubtitlePosition | null> => getSubtitlePosition: (): Promise<SubtitlePosition | null> =>
ipcRenderer.invoke(IPC_CHANNELS.request.getSubtitlePosition), ipcRenderer.invoke(IPC_CHANNELS.request.getSubtitlePosition),
saveSubtitlePosition: (position: SubtitlePosition) => { saveSubtitlePosition: (position: SubtitlePosition) => {
+26
View File
@@ -150,6 +150,7 @@ function installKeyboardTestGlobals() {
let markActiveVideoWatchedCalls = 0; let markActiveVideoWatchedCalls = 0;
let statsToggleOverlayCalls = 0; let statsToggleOverlayCalls = 0;
const openedModalNotifications: string[] = []; const openedModalNotifications: string[] = [];
const unforwardedMpvKeys: Array<{ key: string; reason: string }> = [];
let selectionClearCount = 0; let selectionClearCount = 0;
let selectionAddCount = 0; let selectionAddCount = 0;
let mutationRecordsTaken = 0; let mutationRecordsTaken = 0;
@@ -252,6 +253,9 @@ function installKeyboardTestGlobals() {
sendMpvCommand: (command: Array<string | number>) => { sendMpvCommand: (command: Array<string | number>) => {
mpvCommands.push(command); mpvCommands.push(command);
}, },
reportUnforwardedMpvKey: (report: { key: string; reason: string }) => {
unforwardedMpvKeys.push(report);
},
dispatchSessionAction: async (actionId: string, payload?: unknown) => { dispatchSessionAction: async (actionId: string, payload?: unknown) => {
sessionActions.push({ actionId, payload }); sessionActions.push({ actionId, payload });
}, },
@@ -518,6 +522,7 @@ function installKeyboardTestGlobals() {
markActiveVideoWatchedCalls: () => markActiveVideoWatchedCalls, markActiveVideoWatchedCalls: () => markActiveVideoWatchedCalls,
statsToggleOverlayCalls: () => statsToggleOverlayCalls, statsToggleOverlayCalls: () => statsToggleOverlayCalls,
openedModalNotifications, openedModalNotifications,
unforwardedMpvKeys,
getPlaybackPaused: async () => playbackPausedResponse, getPlaybackPaused: async () => playbackPausedResponse,
setPlaybackPausedResponse: (value: boolean | null) => { setPlaybackPausedResponse: (value: boolean | null) => {
playbackPausedResponse = value; playbackPausedResponse = value;
@@ -2570,6 +2575,27 @@ test('discovered mpv keys only run after SubMiner controls and stay out of sessi
} }
}); });
test('imported mpv keys forward once the popup closes, even if the cached popup flag lags', async () => {
const { handlers, testGlobals, ctx } = createKeyboardHandlerHarness();
try {
testGlobals.setGetMpvInputBindings(async () => ({ keys: ['r'], blockedKeys: [] }));
await handlers.setupMpvInputForwarding();
await wait(0);
testGlobals.setPopupVisible(true);
testGlobals.dispatchKeydown({ key: 'r', code: 'KeyR' });
assert.deepEqual(testGlobals.mpvCommands, []);
assert.deepEqual(testGlobals.unforwardedMpvKeys, [{ key: 'r', reason: 'lookup-popup' }]);
// #331: the popup closed, but a late popup event left the cached flag set.
testGlobals.setPopupVisible(false);
ctx.state.yomitanPopupVisible = true;
testGlobals.dispatchKeydown({ key: 'r', code: 'KeyR' });
assert.deepEqual(testGlobals.mpvCommands, [['keydown', 'r']]);
} finally {
testGlobals.restore();
}
});
test('stalled mpv discovery does not delay configured overlay controls', async () => { test('stalled mpv discovery does not delay configured overlay controls', async () => {
const { handlers, testGlobals } = createKeyboardHandlerHarness(); const { handlers, testGlobals } = createKeyboardHandlerHarness();
try { try {
+26 -8
View File
@@ -1,4 +1,5 @@
import type { CompiledSessionBinding, PrimarySubMode, ShortcutsConfig } from '../../types'; import type { CompiledSessionBinding, PrimarySubMode, ShortcutsConfig } from '../../types';
import type { MpvKeyForwardBlock } from '../../types/session-bindings';
import type { RendererContext } from '../context'; import type { RendererContext } from '../context';
import { createMpvInputForwarding } from './mpv-input-forwarding'; import { createMpvInputForwarding } from './mpv-input-forwarding';
import { MPV_MOUSE_BUTTON_BY_BUTTON, wheelEventToMpvWheel } from '../../shared/mpv-input-bindings'; import { MPV_MOUSE_BUTTON_BY_BUTTON, wheelEventToMpvWheel } from '../../shared/mpv-input-bindings';
@@ -141,14 +142,24 @@ export function createKeyboardHandlers(
// Imported mpv bindings only run when no SubMiner UI could be the input's target. // Imported mpv bindings only run when no SubMiner UI could be the input's target.
// The subtitle sidebar is a side panel over playback, so only input inside it (a // The subtitle sidebar is a side panel over playback, so only input inside it (a
// `.modal` target) stays with SubMiner. // `.modal` target) stays with SubMiner.
// Why imported mpv input must stay in the overlay right now, or null when it may forward.
// SubMiner's own keybindings never pass through here.
function getMpvForwardBlock(target: EventTarget | null): MpvKeyForwardBlock | null {
if (!keyboardConfigLoaded) return 'config-loading';
if (ctx.state.playlistBrowserModalOpen || ctx.state.youtubePickerModalOpen) return 'modal';
if (isLookupPopupOpen(ctx.state, document)) return 'lookup-popup';
if (isInteractiveTarget(target)) return 'interactive-target';
return null;
}
function canForwardToMpv(target: EventTarget | null): boolean { function canForwardToMpv(target: EventTarget | null): boolean {
return ( return getMpvForwardBlock(target) === null;
keyboardConfigLoaded && }
!ctx.state.playlistBrowserModalOpen &&
!ctx.state.youtubePickerModalOpen && // Debug breadcrumb for "my mpv key does nothing": the main process logs it at debug level.
!isLookupPopupOpen(ctx.state, document) && function reportUnforwardedMpvKey(e: KeyboardEvent, reason: MpvKeyForwardBlock): void {
!isInteractiveTarget(target) const report = importedMpvBindings.unforwardedReport(e, reason);
); if (report) window.electronAPI.reportUnforwardedMpvKey(report);
} }
// Scrolling over subtitles still reaches mpv; only scrollable overlay UI keeps the wheel. // Scrolling over subtitles still reaches mpv; only scrollable overlay UI keeps the wheel.
@@ -1403,6 +1414,7 @@ export function createKeyboardHandlers(
if (isLookupPopupOpen(ctx.state, document)) { if (isLookupPopupOpen(ctx.state, document)) {
if (handleYomitanPopupKeybind(e)) { if (handleYomitanPopupKeybind(e)) {
reportUnforwardedMpvKey(e, 'lookup-popup');
e.preventDefault(); e.preventDefault();
return; return;
} }
@@ -1469,7 +1481,13 @@ export function createKeyboardHandlers(
e.preventDefault(); e.preventDefault();
return; return;
} }
if (canForwardToMpv(e.target)) importedMpvBindings.keydown(e); const forwardBlock = getMpvForwardBlock(e.target);
if (forwardBlock) {
reportUnforwardedMpvKey(e, forwardBlock);
} else if (!importedMpvBindings.keydown(e)) {
// Reports only while nothing is imported; an unbound key is not worth a line.
reportUnforwardedMpvKey(e, 'no-imported-bindings');
}
}); });
document.addEventListener('mousedown', (e: MouseEvent) => { document.addEventListener('mousedown', (e: MouseEvent) => {
@@ -175,3 +175,50 @@ test('focus loss releases held keys and failed refresh clears stale bindings', a
await forwarding.refresh(); await forwarding.refresh();
assert.equal(forwarding.keydown(keyEvent()), false); assert.equal(forwarding.keydown(keyEvent()), false);
}); });
test('a reload keeps forwarding the current keys until it settles', async () => {
let resolveReload: (snapshot: MpvInputBindingsSnapshot) => void = () => {};
let loads = 0;
const forwarding = createMpvInputForwarding({
load: () => {
loads += 1;
if (loads === 1) return Promise.resolve({ keys: ['r'], blockedKeys: [] });
return new Promise((resolve) => {
resolveReload = resolve;
});
},
send: () => {},
});
await forwarding.refresh();
const reload = forwarding.refresh();
assert.equal(forwarding.keydown(keyEvent()), true);
forwarding.keyup(keyEvent());
resolveReload({ keys: ['t'], blockedKeys: [] });
await reload;
assert.equal(forwarding.keydown(keyEvent()), false);
assert.equal(forwarding.keydown(keyEvent({ key: 't', code: 'KeyT' })), true);
});
test('unforwarded reports name keys mpv binds, or any key while nothing is imported', async () => {
let snapshot: MpvInputBindingsSnapshot = { keys: [], blockedKeys: [] };
const forwarding = createMpvInputForwarding({ load: async () => snapshot, send: () => {} });
await forwarding.refresh();
assert.deepEqual(forwarding.unforwardedReport(keyEvent(), 'lookup-popup'), {
key: 'r',
reason: 'no-imported-bindings',
});
assert.equal(
forwarding.unforwardedReport(keyEvent({ key: 'Shift', code: 'ShiftLeft' }), 'lookup-popup'),
null,
);
snapshot = { keys: ['r', 't'], blockedKeys: [{ code: 'KeyT', modifiers: [] }] };
await forwarding.refresh();
assert.deepEqual(forwarding.unforwardedReport(keyEvent(), 'interactive-target'), {
key: 'r',
reason: 'interactive-target',
});
assert.equal(forwarding.unforwardedReport(keyEvent(), 'no-imported-bindings'), null);
assert.equal(forwarding.unforwardedReport(keyEvent({ key: 't', code: 'KeyT' }), 'modal'), null);
assert.equal(forwarding.unforwardedReport(keyEvent({ key: 'z', code: 'KeyZ' }), 'modal'), null);
});
+44 -10
View File
@@ -4,7 +4,13 @@ import {
normalizeMpvInputKey, normalizeMpvInputKey,
wheelEventToMpvWheel, wheelEventToMpvWheel,
} from '../../shared/mpv-input-bindings'; } from '../../shared/mpv-input-bindings';
import type { MpvInputBindingsSnapshot } from '../../types/session-bindings'; import type {
MpvInputBindingsSnapshot,
MpvKeyForwardBlock,
UnforwardedMpvKeyReport,
} from '../../types/session-bindings';
const MODIFIER_ONLY_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph']);
type ModifierState = Pick<KeyboardEvent, 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>; type ModifierState = Pick<KeyboardEvent, 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>;
type ForwardedKeyEvent = Parameters<typeof keyboardEventToMpvKey>[0] & type ForwardedKeyEvent = Parameters<typeof keyboardEventToMpvKey>[0] &
@@ -31,25 +37,26 @@ export function createMpvInputForwarding(deps: {
heldKeys.clear(); heldKeys.clear();
} }
// Every window focus refreshes, so the current list keeps forwarding until the reload
// settles; a key pressed mid-reload would otherwise be dropped.
function refresh(): Promise<void> { function refresh(): Promise<void> {
if (disposed) return Promise.resolve(); if (disposed) return Promise.resolve();
generation += 1; generation += 1;
keys.clear();
blockedKeys = [];
releaseAll(); releaseAll();
if (pending) return pending; if (pending) return pending;
pending = (async () => { pending = (async () => {
let requestedGeneration: number; let requestedGeneration: number;
do { do {
requestedGeneration = generation; requestedGeneration = generation;
let snapshot: MpvInputBindingsSnapshot | null = null;
try { try {
const snapshot = await deps.load(); snapshot = await deps.load();
if (!disposed && requestedGeneration === generation) {
keys = new Set(snapshot.keys);
blockedKeys = snapshot.blockedKeys;
}
} catch { } catch {
// Discovery is optional. Keep the existing overlay controls available. // Discovery is optional: SubMiner's own bindings keep working without it.
}
if (!disposed && requestedGeneration === generation) {
keys = new Set(snapshot?.keys ?? []);
blockedKeys = snapshot?.blockedKeys ?? [];
} }
} while (!disposed && requestedGeneration !== generation); } while (!disposed && requestedGeneration !== generation);
})().finally(() => { })().finally(() => {
@@ -98,6 +105,23 @@ export function createMpvInputForwarding(deps: {
return true; return true;
} }
/**
* The debug report for a key the overlay kept from mpv, or null when mpv does not bind
* it. With nothing imported yet, every nameable key is reported as such.
*/
function unforwardedReport(
event: ForwardedKeyEvent,
reason: MpvKeyForwardBlock,
): UnforwardedMpvKeyReport | null {
if (disposed || event.repeat || MODIFIER_ONLY_KEYS.has(event.key)) return null;
const key = keyboardEventToMpvKey(event);
if (!key) return null;
if (keys.size === 0) return { key, reason: 'no-imported-bindings' };
if (reason === 'no-imported-bindings') return null;
if (isBlocked(event.code, event) || !keys.has(key)) return null;
return { key, reason };
}
function keyup(event: Pick<KeyboardEvent, 'code' | 'preventDefault'>): void { function keyup(event: Pick<KeyboardEvent, 'code' | 'preventDefault'>): void {
const key = heldKeys.get(event.code); const key = heldKeys.get(event.code);
if (!key) return; if (!key) return;
@@ -154,5 +178,15 @@ export function createMpvInputForwarding(deps: {
releaseAll(); releaseAll();
} }
return { refresh, keydown, keyup, wheel, mousedown, mouseup, releaseAll, dispose }; return {
refresh,
keydown,
keyup,
wheel,
mousedown,
mouseup,
releaseAll,
dispose,
unforwardedReport,
};
} }
+4 -2
View File
@@ -125,11 +125,13 @@ export function isHachidoriPopupOpen(root: ParentNode | null | undefined = docum
* (the shown event and the host's visible marker) also covers a plain press. * (the shown event and the host's visible marker) also covers a plain press.
*/ */
export function isLookupPopupOpen( export function isLookupPopupOpen(
state: { yomitanPopupVisible: boolean; hachidoriReaderSeen: boolean }, state: { hachidoriReaderSeen: boolean },
root: ParentNode | null | undefined = document, root: ParentNode | null | undefined = document,
): boolean { ): boolean {
if (state.hachidoriReaderSeen) return isHachidoriPopupOpen(root); if (state.hachidoriReaderSeen) return isHachidoriPopupOpen(root);
return state.yomitanPopupVisible || isYomitanPopupVisible(root); // The fork marks the host before it fires the shown event, so the DOM is authoritative.
// The cached yomitanPopupVisible flag can lag a close (#331) and would keep stealing keys.
return isYomitanPopupVisible(root);
} }
export function isYomitanPopupVisible(root: ParentNode | null | undefined = document): boolean { export function isYomitanPopupVisible(root: ParentNode | null | undefined = document): boolean {
+1
View File
@@ -27,6 +27,7 @@ export const IPC_CHANNELS = {
setIgnoreMouseEvents: 'set-ignore-mouse-events', setIgnoreMouseEvents: 'set-ignore-mouse-events',
overlayModalClosed: 'overlay:modal-closed', overlayModalClosed: 'overlay:modal-closed',
recordYomitanLookup: 'record-yomitan-lookup', recordYomitanLookup: 'record-yomitan-lookup',
reportUnforwardedMpvKey: 'overlay:unforwarded-mpv-key',
youtubePickerResolve: 'youtube:picker-resolve', youtubePickerResolve: 'youtube:picker-resolve',
toggleDevTools: 'toggle-dev-tools', toggleDevTools: 'toggle-dev-tools',
saveSubtitlePosition: 'save-subtitle-position', saveSubtitlePosition: 'save-subtitle-position',
+11 -1
View File
@@ -4,7 +4,7 @@ import test from 'node:test';
import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions'; import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions';
import { compileSessionBindings } from '../../core/services/session-bindings'; import { compileSessionBindings } from '../../core/services/session-bindings';
import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config'; import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config';
import { parseSessionActionDispatchRequest } from './validators'; import { parseSessionActionDispatchRequest, parseUnforwardedMpvKeyReport } from './validators';
// Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the // Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the
// SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to // SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to
@@ -36,3 +36,13 @@ test('every default session-action binding is accepted by parseSessionActionDisp
); );
} }
}); });
test('unforwarded mpv key reports accept known reasons only', () => {
assert.deepEqual(parseUnforwardedMpvKeyReport({ key: 'LEFT', reason: 'lookup-popup' }), {
key: 'LEFT',
reason: 'lookup-popup',
});
assert.equal(parseUnforwardedMpvKeyReport({ key: 'LEFT', reason: 'toString' }), null);
assert.equal(parseUnforwardedMpvKeyReport({ key: '', reason: 'modal' }), null);
assert.equal(parseUnforwardedMpvKeyReport(null), null);
});
+26 -1
View File
@@ -14,7 +14,12 @@ import type {
SubsyncManualRunRequest, SubsyncManualRunRequest,
} from '../../types/runtime'; } from '../../types/runtime';
import type { RuntimeOptionId, RuntimeOptionValue } from '../../types/runtime-options'; import type { RuntimeOptionId, RuntimeOptionValue } from '../../types/runtime-options';
import type { SessionActionId, SessionActionPayload } from '../../types/session-bindings'; import type {
MpvKeyForwardBlock,
SessionActionId,
SessionActionPayload,
UnforwardedMpvKeyReport,
} from '../../types/session-bindings';
import type { SubtitlePosition } from '../../types/subtitle'; import type { SubtitlePosition } from '../../types/subtitle';
import { OVERLAY_HOSTED_MODALS, type OverlayHostedModal } from './contracts'; import { OVERLAY_HOSTED_MODALS, type OverlayHostedModal } from './contracts';
import { isControllerFaceButtonLabels, parseControllerDiscreteBinding } from '../controller-review'; import { isControllerFaceButtonLabels, parseControllerDiscreteBinding } from '../controller-review';
@@ -365,6 +370,26 @@ export function parseMpvCommand(value: unknown): Array<string | number> | null {
: null; : null;
} }
// A Record so a new MpvKeyForwardBlock member fails typecheck until it is listed here.
const MPV_KEY_FORWARD_BLOCKS: Record<MpvKeyForwardBlock, true> = {
'config-loading': true,
modal: true,
'lookup-popup': true,
'interactive-target': true,
'no-imported-bindings': true,
};
function isMpvKeyForwardBlock(value: unknown): value is MpvKeyForwardBlock {
return typeof value === 'string' && Object.hasOwn(MPV_KEY_FORWARD_BLOCKS, value);
}
export function parseUnforwardedMpvKeyReport(value: unknown): UnforwardedMpvKeyReport | null {
if (!isObject(value)) return null;
const { key, reason } = value;
if (typeof key !== 'string' || key.length === 0 || key.length > 64) return null;
return isMpvKeyForwardBlock(reason) ? { key, reason } : null;
}
export function parseOptionalForwardingOptions(value: unknown): { export function parseOptionalForwardingOptions(value: unknown): {
forward?: boolean; forward?: boolean;
} { } {
+5 -1
View File
@@ -6,6 +6,7 @@ import { ConfigService } from './config/service';
import { createLogger, setLogLevel } from './logger'; import { createLogger, setLogLevel } from './logger';
import { ImmersionTrackerService } from './core/services/immersion-tracker-service'; import { ImmersionTrackerService } from './core/services/immersion-tracker-service';
import { createCoverArtFetcher } from './core/services/anilist/cover-art-fetcher'; import { createCoverArtFetcher } from './core/services/anilist/cover-art-fetcher';
import { createAnilistRelationFetcher } from './core/services/anilist/franchise-relation-fetcher';
import { createAnilistRateLimiter } from './core/services/anilist/rate-limiter'; import { createAnilistRateLimiter } from './core/services/anilist/rate-limiter';
import { createLiveActionMetadataResolver } from './core/services/tmdb/live-action-resolver'; import { createLiveActionMetadataResolver } from './core/services/tmdb/live-action-resolver';
import { createTmdbClient, createTmdbApiKeyResolver } from './core/services/tmdb/tmdb-client'; import { createTmdbClient, createTmdbApiKeyResolver } from './core/services/tmdb/tmdb-client';
@@ -212,11 +213,14 @@ async function main(): Promise<void> {
() => bundledTmdbApiKey, () => bundledTmdbApiKey,
), ),
}); });
// Cover art and franchise relations share one AniList request budget.
const anilistRateLimiter = createAnilistRateLimiter();
tracker.setCoverArtFetcher( tracker.setCoverArtFetcher(
createCoverArtFetcher(createAnilistRateLimiter(), createLogger('stats-daemon:cover-art'), { createCoverArtFetcher(anilistRateLimiter, createLogger('stats-daemon:cover-art'), {
liveAction: createLiveActionMetadataResolver(tmdbClient, createLogger('stats-daemon:tmdb')), liveAction: createLiveActionMetadataResolver(tmdbClient, createLogger('stats-daemon:tmdb')),
}), }),
); );
tracker.setAnilistRelationFetcher(createAnilistRelationFetcher(anilistRateLimiter));
statsServer = await startStatsServer({ statsServer = await startStatsServer({
port: config.stats.serverPort, port: config.stats.serverPort,
+3 -1
View File
@@ -1,4 +1,4 @@
import type { MpvInputBindingsSnapshot } from './session-bindings'; import type { MpvInputBindingsSnapshot, UnforwardedMpvKeyReport } from './session-bindings';
import type { import type {
KikuFieldGroupingChoice, KikuFieldGroupingChoice,
KikuFieldGroupingRequestData, KikuFieldGroupingRequestData,
@@ -600,6 +600,8 @@ export interface ElectronAPI {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => void; setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => void;
reportOverlayInteractive: (interactive: boolean) => void; reportOverlayInteractive: (interactive: boolean) => void;
recordYomitanLookup: (context?: SubtitleMiningContext | null) => void; recordYomitanLookup: (context?: SubtitleMiningContext | null) => void;
/** Debug-only: the overlay kept a key that mpv binds. */
reportUnforwardedMpvKey: (report: UnforwardedMpvKeyReport) => void;
getSubtitlePosition: () => Promise<SubtitlePosition | null>; getSubtitlePosition: () => Promise<SubtitlePosition | null>;
saveSubtitlePosition: (position: SubtitlePosition) => void; saveSubtitlePosition: (position: SubtitlePosition) => void;
sendMpvCommand: (command: (string | number)[]) => void; sendMpvCommand: (command: (string | number)[]) => void;
+14
View File
@@ -13,6 +13,20 @@ export interface MpvInputBindingsSnapshot {
blockedKeys: SessionKeySpec[]; blockedKeys: SessionKeySpec[];
} }
/** Why the overlay kept a key that mpv binds instead of forwarding it. */
export type MpvKeyForwardBlock =
| 'config-loading'
| 'modal'
| 'lookup-popup'
| 'interactive-target'
| 'no-imported-bindings';
/** Debug report the overlay sends when it does not forward an mpv-bound key. */
export interface UnforwardedMpvKeyReport {
key: string;
reason: MpvKeyForwardBlock;
}
export interface SessionBindingWarning { export interface SessionBindingWarning {
kind: 'unsupported' | 'conflict' | 'deprecated-config'; kind: 'unsupported' | 'conflict' | 'deprecated-config';
path: string; path: string;
+18
View File
@@ -1,5 +1,6 @@
import type { import type {
AnimeDetailData, AnimeDetailData,
AnimeLibraryGroup,
AnimeLibraryItem, AnimeLibraryItem,
AnimeWord, AnimeWord,
DailyRollup, DailyRollup,
@@ -187,6 +188,16 @@ export interface StatsMoveVideoRequest {
animeId: number; animeId: number;
} }
/**
* Body of `PUT /api/stats/anime/:animeId/group`: list the entry with another
* entry's franchise (`join`), on its own (`standalone`), or where AniList's
* relations put it (`anilist`, which clears the override).
*/
export type StatsAnimeGroupOverrideRequest =
| { mode: 'join'; targetAnimeId: number }
| { mode: 'standalone' }
| { mode: 'anilist' };
export interface StatsAnimeMergeRecommendation { export interface StatsAnimeMergeRecommendation {
recommendationId: number; recommendationId: number;
animeIds: [number, number]; animeIds: [number, number];
@@ -251,6 +262,7 @@ export interface StatsJsonResponseMap {
mediaLibrary: MediaLibraryItem[]; mediaLibrary: MediaLibraryItem[];
mediaDetail: MediaDetailData; mediaDetail: MediaDetailData;
animeLibrary: AnimeLibraryItem[]; animeLibrary: AnimeLibraryItem[];
animeLibraryGroups: AnimeLibraryGroup[];
animeMergeRecommendations: StatsAnimeMergeRecommendationsResponse; animeMergeRecommendations: StatsAnimeMergeRecommendationsResponse;
animeDetail: AnimeDetailData; animeDetail: AnimeDetailData;
animeWords: AnimeWord[]; animeWords: AnimeWord[];
@@ -262,6 +274,7 @@ export interface StatsJsonResponseMap {
deleteAnime: StatsOkResponse; deleteAnime: StatsOkResponse;
mergeAnime: StatsMergeAnimeResponse; mergeAnime: StatsMergeAnimeResponse;
moveVideoToAnime: StatsMoveVideoResponse; moveVideoToAnime: StatsMoveVideoResponse;
setAnimeGroupOverride: StatsOkResponse;
dismissAnimeMergeRecommendation: StatsOkResponse; dismissAnimeMergeRecommendation: StatsOkResponse;
anilistSearch: StatsAnilistSearchResult[]; anilistSearch: StatsAnilistSearchResult[];
tmdbSearch: StatsTmdbSearchResult[]; tmdbSearch: StatsTmdbSearchResult[];
@@ -330,6 +343,7 @@ export interface StatsHttpClient {
getMediaLibrary: () => Promise<MediaLibraryItem[]>; getMediaLibrary: () => Promise<MediaLibraryItem[]>;
getMediaDetail: (videoId: number) => Promise<MediaDetailData>; getMediaDetail: (videoId: number) => Promise<MediaDetailData>;
getAnimeLibrary: () => Promise<AnimeLibraryItem[]>; getAnimeLibrary: () => Promise<AnimeLibraryItem[]>;
getAnimeLibraryGroups: () => Promise<AnimeLibraryGroup[]>;
getAnimeMergeRecommendations: () => Promise<StatsAnimeMergeRecommendationsResponse>; getAnimeMergeRecommendations: () => Promise<StatsAnimeMergeRecommendationsResponse>;
getAnimeDetail: (animeId: number) => Promise<AnimeDetailData>; getAnimeDetail: (animeId: number) => Promise<AnimeDetailData>;
getAnimeWords: (animeId: number, limit?: number) => Promise<AnimeWord[]>; getAnimeWords: (animeId: number, limit?: number) => Promise<AnimeWord[]>;
@@ -356,6 +370,10 @@ export interface StatsHttpClient {
deleteAnime: (animeId: number) => Promise<void>; deleteAnime: (animeId: number) => Promise<void>;
mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<StatsMergeAnimeResponse>; mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<StatsMergeAnimeResponse>;
moveVideoToAnime: (videoId: number, animeId: number) => Promise<StatsMoveVideoResponse>; moveVideoToAnime: (videoId: number, animeId: number) => Promise<StatsMoveVideoResponse>;
setAnimeGroupOverride: (
animeId: number,
request: StatsAnimeGroupOverrideRequest,
) => Promise<void>;
dismissAnimeMergeRecommendation: (recommendationId: number) => Promise<void>; dismissAnimeMergeRecommendation: (recommendationId: number) => Promise<void>;
getKnownWords: () => Promise<string[]>; getKnownWords: () => Promise<string[]>;
getKnownWordsSummary: () => Promise<StatsKnownWordsSummary>; getKnownWordsSummary: () => Promise<StatsKnownWordsSummary>;
+42
View File
@@ -306,6 +306,46 @@ export interface AnimeLibraryItem {
lastWatchedMs: number; lastWatchedMs: number;
} }
/** One library entry inside a franchise group, with its AniList format and start date when cached. */
export interface AnimeLibraryGroupPart extends AnimeLibraryItem {
/** AniList format (TV, MOVIE, OVA...); null without a cached AniList entry. */
format: string | null;
/** AniList start date as yyyymmdd (month/day 0 when unknown); null when unknown. */
startDate: number | null;
}
/**
* A library card: one franchise (seasons, movies and OVAs that AniList links
* together) or a single entry. Totals add up the parts; `lastWatchedMs` is the
* latest part's. Parts are in AniList release order.
*/
export interface AnimeLibraryGroup {
/** AniList id the franchise is named after, or minus the entry's animeId for a card of its own. */
groupKey: number;
title: string;
mediaKind: MediaKind;
/** Entry whose cover the card shows: the first part by release date. */
coverAnimeId: number;
totalSessions: number;
totalActiveMs: number;
totalCards: number;
totalTokensSeen: number;
episodeCount: number;
lastWatchedMs: number;
parts: AnimeLibraryGroupPart[];
}
/** How a library entry's franchise was chosen: by AniList, moved by the user, or kept on its own. */
export type AnimeGroupOverrideMode = 'anilist' | 'joined' | 'standalone';
/** Where one library entry sits in the grouped library. */
export interface AnimeGroupPlacement {
groupKey: number;
title: string;
partCount: number;
overrideMode: AnimeGroupOverrideMode;
}
export interface AnilistEntry { export interface AnilistEntry {
anilistId: number; anilistId: number;
titleRomaji: string | null; titleRomaji: string | null;
@@ -338,6 +378,8 @@ export interface AnimeDetailData {
}; };
episodes: AnimeEpisode[]; episodes: AnimeEpisode[];
anilistEntries: AnilistEntry[]; anilistEntries: AnilistEntry[];
/** Null when the entry has no watch history to list in the library. */
group: AnimeGroupPlacement | null;
} }
export interface AnimeEpisode { export interface AnimeEpisode {
@@ -0,0 +1,93 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { queryMpvProcessId } from './mpv-process-id';
// Runs a stand-in mpv IPC server that hands each request line to `onRequest`.
async function withFakeMpv(
onRequest: (socket: net.Socket, request: string) => void,
run: (socketPath: string) => Promise<void>,
): Promise<void> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mpv-pid-'));
const socketPath =
process.platform === 'win32'
? path.win32.join(String.raw`\\.\pipe`, path.basename(dir))
: path.join(dir, 'mpv.sock');
const server = net.createServer((socket) => {
socket.once('data', (data) => onRequest(socket, data.toString()));
});
try {
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(socketPath, resolve);
});
await run(socketPath);
} finally {
await new Promise((resolve) => server.close(resolve));
fs.rmSync(dir, { recursive: true, force: true });
}
}
test('queryMpvProcessId asks mpv for pid and returns the answer', async () => {
let request = '';
await withFakeMpv(
(socket, line) => {
request = line;
socket.write('{"data":4242,"request_id":1,"error":"success"}\n');
},
async (socketPath) => {
assert.equal(await queryMpvProcessId(socketPath), 4242);
},
);
assert.deepEqual(JSON.parse(request), { command: ['get_property', 'pid'], request_id: 1 });
});
test('queryMpvProcessId skips events and malformed lines, across split chunks', async () => {
await withFakeMpv(
(socket) => {
socket.write('{"event":"idle"}\nnot json\n{"data":42');
setTimeout(() => socket.write('42,"request_id":1,"error":"success"}\n'), 10);
},
async (socketPath) => {
assert.equal(await queryMpvProcessId(socketPath), 4242);
},
);
});
test('queryMpvProcessId rejects when mpv refuses the property', async () => {
await withFakeMpv(
(socket) => socket.write('{"request_id":1,"error":"property unavailable"}\n'),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath), /no process ID/);
},
);
});
test('queryMpvProcessId rejects when nothing is listening', async () => {
const missing =
process.platform === 'win32'
? path.win32.join(String.raw`\\.\pipe`, `mpv-pid-missing-${process.pid}`)
: path.join(os.tmpdir(), `mpv-pid-missing-${process.pid}.sock`);
await assert.rejects(queryMpvProcessId(missing));
});
test('queryMpvProcessId rejects when mpv hangs up or never answers', async () => {
await withFakeMpv(
(socket) => socket.end(),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath), /closed before mpv answered/);
},
);
const held: net.Socket[] = [];
await withFakeMpv(
(socket) => held.push(socket),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath, 20), /no answer within 20ms/);
held.forEach((socket) => socket.destroy());
},
);
});
+67
View File
@@ -0,0 +1,67 @@
import net from 'node:net';
const PID_REQUEST_ID = 1;
const PID_QUERY_TIMEOUT_MS = 5_000;
// This runs inside a socket callback, where a parse error would be an uncaught exception.
function parseIpcLine(line: string): unknown {
try {
return JSON.parse(line);
} catch {
return null;
}
}
// Asks the mpv listening on `socketPath` for its process ID over a short-lived IPC connection.
export function queryMpvProcessId(
socketPath: string,
timeoutMs = PID_QUERY_TIMEOUT_MS,
): Promise<number> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(socketPath);
let buffered = '';
const fail = (message: string): void => {
socket.destroy();
reject(new Error(message));
};
socket.setEncoding('utf8');
socket.setTimeout(timeoutMs, () => fail(`no answer within ${timeoutMs}ms`));
socket.once('error', (error) => fail(error.message));
socket.once('close', () => fail('connection closed before mpv answered'));
socket.once('connect', () => {
socket.write(
`${JSON.stringify({ command: ['get_property', 'pid'], request_id: PID_REQUEST_ID })}\n`,
);
});
socket.on('data', (chunk: string) => {
buffered += chunk;
const lines = buffered.split('\n');
buffered = lines.pop() ?? '';
// mpv also streams events on this connection, so skip to the line answering the request.
for (const line of lines) {
const message = parseIpcLine(line);
if (
typeof message !== 'object' ||
message === null ||
!('request_id' in message) ||
message.request_id !== PID_REQUEST_ID
) {
continue;
}
const pid = 'data' in message ? message.data : undefined;
if (typeof pid === 'number') {
socket.destroy();
resolve(pid);
} else {
fail(`mpv returned no process ID: ${line}`);
}
return;
}
});
});
}
@@ -1,72 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
filterMpvPollResultBySocketPath,
matchesMpvSocketPathInCommandLine,
} from './mpv-socket-match';
import type { MpvPollResult } from './win32';
function createPollResult(commandLines: Array<string | null>): MpvPollResult {
return {
matches: commandLines.map((commandLine, index) => ({
hwnd: index + 1,
bounds: { x: index * 10, y: 0, width: 1280, height: 720 },
area: 1280 * 720,
isForeground: index === 0,
commandLine,
})),
focusState: true,
windowState: 'visible',
};
}
test('matchesMpvSocketPathInCommandLine accepts equals and space-delimited socket flags', () => {
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video.mkv',
'\\\\.\\pipe\\subminer-a',
),
true,
);
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server "\\\\.\\pipe\\subminer-b" video.mkv',
'\\\\.\\pipe\\subminer-b',
),
true,
);
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video.mkv',
'\\\\.\\pipe\\subminer-b',
),
false,
);
});
test('filterMpvPollResultBySocketPath keeps only matches for the requested socket path', () => {
const result = filterMpvPollResultBySocketPath(
createPollResult([
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video-a.mkv',
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-b video-b.mkv',
null,
]),
'\\\\.\\pipe\\subminer-b',
);
assert.deepEqual(
result.matches.map((match) => match.hwnd),
[2],
);
assert.equal(result.windowState, 'visible');
});
test('matchesMpvSocketPathInCommandLine rejects socket-path prefix matches', () => {
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-10 video.mkv',
'\\\\.\\pipe\\subminer-1',
),
false,
);
});
-41
View File
@@ -1,41 +0,0 @@
import type { MpvPollResult } from './win32';
function escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function matchesMpvSocketPathInCommandLine(
commandLine: string,
targetSocketPath: string,
): boolean {
if (!commandLine || !targetSocketPath) {
return false;
}
const escapedSocketPath = escapeRegex(targetSocketPath);
return new RegExp(
`(?:^|\\s)--input-ipc-server(?:=|\\s+)(?:"${escapedSocketPath}"|${escapedSocketPath})(?=\\s|$)`,
'i',
).test(commandLine);
}
export function filterMpvPollResultBySocketPath(
result: MpvPollResult,
targetSocketPath?: string | null,
): MpvPollResult {
if (!targetSocketPath) {
return result;
}
const matches = result.matches.filter(
(match) =>
typeof match.commandLine === 'string' &&
matchesMpvSocketPathInCommandLine(match.commandLine, targetSocketPath),
);
return {
matches,
focusState: matches.some((match) => match.isForeground),
windowState: matches.length > 0 ? 'visible' : 'not-found',
};
}
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more