mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-23 04:46:08 -08:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
935af26cca
|
||
|
|
24cd8cae88
|
||
|
|
0cae6b96fb
|
||
|
|
172c771d97
|
||
|
|
b0446833e6
|
||
|
|
86823aebe9
|
||
|
|
93d95538ae
|
||
|
|
ec98118006
|
||
|
|
c742e9541c
|
||
|
|
8076f3faae
|
||
|
|
93045ebf9f
|
||
|
|
18490c9d4f
|
||
|
|
78809094d2 | ||
|
|
71251b8d7b | ||
|
|
9d2057cc30 | ||
|
|
ac3ceab856 | ||
|
|
ee52664655 | ||
|
|
0ae70b4ab2 |
No files matched your search
@@ -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 |
|
||||
| fuse2 | Required (Linux) | Running the AppImage |
|
||||
| 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 |
|
||||
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
|
||||
| yt-dlp | Optional | YouTube playback |
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,5 @@
|
||||
type: added
|
||||
area: jellyfin
|
||||
|
||||
- Jellyfin playback now adds the episodes around the playing one to mpv's playlist, so mpv's playlist keys and end-of-file advance move through the series (across seasons) in the same session, with resume, progress reporting, stats, and subtitles handled per episode.
|
||||
- New `jellyfin.episodePlaylist.enabled` (on by default) and `jellyfin.episodePlaylist.maxEpisodes` settings, under Settings > Integrations > Jellyfin > Episode Playlist.
|
||||
@@ -0,0 +1,4 @@
|
||||
type: fixed
|
||||
area: jellyfin
|
||||
|
||||
- Starting Jellyfin playback while another file was playing could drop the new item's playback tracking, so Jellyfin never received its progress or stop reports. mpv's unload of the previous file no longer cancels the new playback.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -1080,8 +1080,8 @@
|
||||
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
|
||||
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
|
||||
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
|
||||
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
|
||||
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
|
||||
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
|
||||
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
|
||||
}, // SubMiner-managed mpv launch and bundled plugin options.
|
||||
|
||||
// ==========================================
|
||||
@@ -1111,7 +1111,11 @@
|
||||
"mp3",
|
||||
"aac"
|
||||
], // Container allowlist for direct play decisions.
|
||||
"transcodeVideoCodec": "h264" // Preferred transcode video codec when direct play is unavailable.
|
||||
"transcodeVideoCodec": "h264", // Preferred transcode video codec when direct play is unavailable.
|
||||
"episodePlaylist": {
|
||||
"enabled": true, // Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes. Values: true | false
|
||||
"maxEpisodes": 5 // Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).
|
||||
} // Episode playlist setting.
|
||||
}, // Optional Jellyfin integration for auth, browsing, and playback launch.
|
||||
|
||||
// ==========================================
|
||||
|
||||
@@ -26,8 +26,8 @@ On Linux, the token is stored with `gnome-libsecret` by default. If your keyring
|
||||
An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then:
|
||||
|
||||
1. Reads the title, season, and episode from the file name and folder. Install [guessit](https://github.com/guessit-io/guessit) for better parsing. A folder named `Season 2` is a strong season hint.
|
||||
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels.
|
||||
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode.
|
||||
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels. Specials, movies, and the second half of a split season ("Part 2", "Cour 2") do not count as seasons, and an entry whose title names the season ("Season 3", "III") wins.
|
||||
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode. AniList lists the second half of a split season as its own entry, so an episode past the first half goes there: episode 15 of a season split 11 + 12 is episode 4 of the second entry.
|
||||
|
||||
If the show is not on your list yet, SubMiner adds it as Watching, but only when the file title exactly matches an AniList title or you pinned the entry with the character dictionary's AniList override. For a looser match, add the show to Planning or Watching yourself. SubMiner never changes entries marked Completed, Paused, Dropped, or Rewatching, and it never lowers your progress.
|
||||
|
||||
@@ -37,7 +37,9 @@ Failed updates are saved and retried in the background, up to 8 times with growi
|
||||
|
||||
If a cover or title in the stats Library is wrong, open the title and use **Change AniList Entry**.
|
||||
|
||||
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary).
|
||||
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary). The override is also the fix when AniList splits a season without marking the second half in any title.
|
||||
|
||||
Library entries matched by older versions keep their match after an update. If one points at the wrong season, use **Change AniList Entry**.
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# AniSkip integration
|
||||
|
||||
SubMiner 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
|
||||
|
||||
@@ -23,17 +23,24 @@ python3 -m pip install --user guessit
|
||||
|
||||
## 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.
|
||||
|
||||
A failed lookup (AniSkip or MyAnimeList down, rate limited, or offline) is retried the next time the file loads. A show or episode AniSkip has no times for is remembered until SubMiner restarts.
|
||||
|
||||
## Triggering from mpv
|
||||
|
||||
| Command | What it does |
|
||||
| ----------------------------------------- | ------------------------------------------------------- |
|
||||
| `script-message subminer-skip-intro` | Skip to the end of the intro |
|
||||
| `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 |
|
||||
|
||||
Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show.
|
||||
@@ -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/).
|
||||
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.
|
||||
|
||||
If you changed AnkiConnect's port, set `ankiConnect.url` to match.
|
||||
|
||||
@@ -46,7 +46,7 @@ A few ownership notes that are hard to guess from file names:
|
||||
|
||||
- mpv access is split into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and property modules under `src/core/services/`.
|
||||
- The renderer keeps `renderer.ts` to orchestration. Keyboard, mouse, and gamepad input live in `renderer/handlers/`, and each modal flow has its own file in `renderer/modals/`.
|
||||
- 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
|
||||
|
||||
|
||||
+16
-14
@@ -559,18 +559,20 @@ In external-profile mode, SubMiner only reads the profile. It does not open its
|
||||
|
||||
Log in to a Jellyfin server, browse libraries, and play or cast to SubMiner. Login tokens are stored encrypted, not in this file. See [Jellyfin integration](/jellyfin-integration).
|
||||
|
||||
| Key | Default | What it does |
|
||||
| ----------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------- |
|
||||
| `jellyfin.enabled` | `false` | Enable Jellyfin |
|
||||
| `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` |
|
||||
| `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` |
|
||||
| `jellyfin.remoteControlEnabled` | `true` | Let Jellyfin apps cast to SubMiner |
|
||||
| `jellyfin.remoteControlAutoConnect` | `true` | Connect the cast session on startup (also needs `startupWarmups.jellyfinRemoteSession`) |
|
||||
| `jellyfin.autoAnnounce` | `false` | Announce SubMiner as a cast target on connect |
|
||||
| `jellyfin.pullPictures` | `false` | Fetch posters for launcher pickers |
|
||||
| `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder |
|
||||
| `jellyfin.directPlayPreferred` | `true` | Try direct play before transcoding |
|
||||
| `jellyfin.transcodeVideoCodec` | `"h264"` | Codec requested when transcoding |
|
||||
| Key | Default | What it does |
|
||||
| -------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `jellyfin.enabled` | `false` | Enable Jellyfin |
|
||||
| `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` |
|
||||
| `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` |
|
||||
| `jellyfin.remoteControlEnabled` | `true` | Let Jellyfin apps cast to SubMiner |
|
||||
| `jellyfin.remoteControlAutoConnect` | `true` | Connect the cast session on startup (also needs `startupWarmups.jellyfinRemoteSession`) |
|
||||
| `jellyfin.autoAnnounce` | `false` | Announce SubMiner as a cast target on connect |
|
||||
| `jellyfin.pullPictures` | `false` | Fetch posters for launcher pickers |
|
||||
| `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder |
|
||||
| `jellyfin.directPlayPreferred` | `true` | Try direct play before transcoding |
|
||||
| `jellyfin.transcodeVideoCodec` | `"h264"` | Codec requested when transcoding |
|
||||
| `jellyfin.episodePlaylist.enabled` | `true` | Queue the episodes around the playing one in mpv's playlist ([episode playlist](/jellyfin-integration#episode-playlist)) |
|
||||
| `jellyfin.episodePlaylist.maxEpisodes` | `5` | Most episodes in that playlist, the playing one included (3-25) |
|
||||
|
||||
### Discord rich presence
|
||||
|
||||
@@ -634,8 +636,8 @@ Settings for mpv instances that SubMiner starts, and for the bundled mpv plugin.
|
||||
| `mpv.autoStartSubMiner` | `true` | Start SubMiner in the background when mpv loads a file |
|
||||
| `mpv.pauseUntilOverlayReady` | `true` | Keep mpv paused until subtitles are ready, up to 30 seconds |
|
||||
| `mpv.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path |
|
||||
| `mpv.aniskipEnabled` | `true` | Detect intros with AniSkip and show a skip prompt |
|
||||
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro while the prompt is shown |
|
||||
| `mpv.aniskipEnabled` | `true` | Detect intros and outros (file chapters, then AniSkip) and show a skip prompt |
|
||||
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro or outro while it plays |
|
||||
|
||||
### YouTube playback settings
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
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:
|
||||
|
||||
- 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.
|
||||
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ Getting started takes three steps:
|
||||
|
||||
## 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 |
|
||||
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
|
||||
@@ -124,7 +124,7 @@ mpv --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>
|
||||
<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).
|
||||
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`.
|
||||
4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
|
||||
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. **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`.
|
||||
|
||||
|
||||
@@ -27,6 +27,14 @@ If an episode has no Japanese subtitles, you can [generate them with Whisper](/s
|
||||
|
||||
Casting finds mpv through `mpv.executablePath`, then `SUBMINER_MPV_PATH`, then `PATH`. On macOS it then checks `/opt/homebrew/bin/mpv`, `/usr/local/bin/mpv`, and `/Applications/mpv.app`, because an app opened from Finder, the Dock, or Spotlight does not get your shell's `PATH`. If mpv lives somewhere else, set `mpv.executablePath` to its full path (`command -v mpv` prints it). An invalid `mpv.executablePath` stops mpv from starting.
|
||||
|
||||
## Episode playlist
|
||||
|
||||
When you play an episode, by casting or from the terminal, SubMiner adds the episodes around it from the same series to mpv's playlist. Move between them with mpv's playlist keys (`<` and `>` by default) or your playlist UI, and mpv moves on to the next episode when one ends. The series order runs across seasons. Each switch happens in the running mpv and overlay; nothing restarts.
|
||||
|
||||
SubMiner waits until the first episode is playing before it looks up the others, so startup is no slower. Every episode you switch to reports progress like one you picked yourself, and resumes from the position Jellyfin had saved when it was added to the playlist. Its subtitles load the same way. With mpv 0.42 or newer, the playlist lists the queued episodes by title; older mpv versions show their stream URLs.
|
||||
|
||||
`episodePlaylist.maxEpisodes` caps how many episodes the playlist holds, centered on the playing one. Turn `episodePlaylist.enabled` off to play one episode at a time. Changes apply from the next episode switch.
|
||||
|
||||
## Playing from the terminal
|
||||
|
||||
The launcher can browse your libraries and play an item without a Jellyfin client:
|
||||
@@ -42,14 +50,16 @@ Sign in first. Playback resumes from Jellyfin's saved position, and watch progre
|
||||
|
||||
All options are under **Settings > Integrations > Jellyfin**, or `jellyfin` in `config.jsonc`. See [Configuration](/configuration#jellyfin) for the full list and defaults.
|
||||
|
||||
| Key | What it does |
|
||||
| -------------------------- | ---------------------------------------------------------------------- |
|
||||
| `enabled` | Turns the integration on. Set for you when you sign in. |
|
||||
| `serverUrl` | Your Jellyfin server. Filled in when you sign in. |
|
||||
| `remoteControlEnabled` | Lets SubMiner act as a cast target. |
|
||||
| `remoteControlAutoConnect` | Connects at startup when `startupWarmups.jellyfinRemoteSession` is on. |
|
||||
| `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. |
|
||||
| `transcodeVideoCodec` | Video codec requested when Jellyfin transcodes. |
|
||||
| Key | What it does |
|
||||
| ----------------------------- | ---------------------------------------------------------------------- |
|
||||
| `enabled` | Turns the integration on. Set for you when you sign in. |
|
||||
| `serverUrl` | Your Jellyfin server. Filled in when you sign in. |
|
||||
| `remoteControlEnabled` | Lets SubMiner act as a cast target. |
|
||||
| `remoteControlAutoConnect` | Connects at startup when `startupWarmups.jellyfinRemoteSession` is on. |
|
||||
| `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. |
|
||||
| `transcodeVideoCodec` | Video codec requested when Jellyfin transcodes. |
|
||||
| `episodePlaylist.enabled` | Adds the surrounding episodes to mpv's playlist. |
|
||||
| `episodePlaylist.maxEpisodes` | Most episodes in that playlist, the playing one included. |
|
||||
|
||||
For headless setups, `SUBMINER_JELLYFIN_ACCESS_TOKEN` and `SUBMINER_JELLYFIN_USER_ID` supply a session without the sign-in window. Treat the token store and `config.jsonc` as secrets.
|
||||
|
||||
|
||||
@@ -145,7 +145,7 @@ subminer sync macbook --remote-cmd ~/Apps/SubMiner.AppImage # SubMiner in a cu
|
||||
subminer sync --ui # open the sync window
|
||||
```
|
||||
|
||||
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. `--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.
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ Most plugin keys are chords: press `y`, then the second key.
|
||||
|
||||
`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.
|
||||
|
||||
@@ -124,7 +124,7 @@ script-message subminer-start backend=hyprland socket=/custom/path texthooker=no
|
||||
|
||||
`log-level` sets SubMiner's log verbosity. Do not use `--debug` for this; it turns on the app's dev mode.
|
||||
|
||||
The plugin also handles messages the SubMiner app sends it (`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`, `subminer-reload-session-bindings`). You do not need to send these yourself. The AniSkip messages are listed on the [AniSkip page](/aniskip-integration#triggering-from-mpv).
|
||||
The plugin also handles messages the SubMiner app sends it (`subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-managed-playlist-entries`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, `subminer-reload-session-bindings`). You do not need to send these yourself. The AniSkip messages are listed on the [AniSkip page](/aniskip-integration#triggering-from-mpv).
|
||||
|
||||
## Auto-start behavior
|
||||
|
||||
|
||||
@@ -1080,8 +1080,8 @@
|
||||
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
|
||||
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
|
||||
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
|
||||
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
|
||||
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
|
||||
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
|
||||
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
|
||||
}, // SubMiner-managed mpv launch and bundled plugin options.
|
||||
|
||||
// ==========================================
|
||||
@@ -1111,7 +1111,11 @@
|
||||
"mp3",
|
||||
"aac"
|
||||
], // Container allowlist for direct play decisions.
|
||||
"transcodeVideoCodec": "h264" // Preferred transcode video codec when direct play is unavailable.
|
||||
"transcodeVideoCodec": "h264", // Preferred transcode video codec when direct play is unavailable.
|
||||
"episodePlaylist": {
|
||||
"enabled": true, // Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes. Values: true | false
|
||||
"maxEpisodes": 5 // Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).
|
||||
} // Episode playlist setting.
|
||||
}, // Optional Jellyfin integration for auth, browsing, and playback launch.
|
||||
|
||||
// ==========================================
|
||||
|
||||
@@ -190,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.
|
||||
|
||||
## 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 check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`.
|
||||
|
||||
@@ -227,9 +227,9 @@ The mpv plugin accepts these script messages:
|
||||
script-message subminer-start backend=hyprland socket=/custom/path texthooker=no log-level=debug
|
||||
```
|
||||
|
||||
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-managed-playlist-entries`, `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
|
||||
|
||||
|
||||
@@ -64,13 +64,16 @@ Read when: you need to find the owner module for a behavior or test surface
|
||||
the stats overlay window options, and the `--stats` command are assembled by `src/main/assemblies/stats.ts`
|
||||
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
|
||||
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
|
||||
Franchise grouping is a view over `imm_anime`, never a merge: `query-library-groups.ts` groups library rows by union-find over the AniList relation cache (`imm_anilist_media` + `imm_anilist_relations`, written by `anilist-relation-cache.ts`; pure graph and walk in `anilist/franchise-graph.ts`, where `FRANCHISE_RELATION_TYPES` is the joining set). `franchise-relation-refresher.ts` walks from owned AniList ids (bounded depth and fetches per run, 7-day staleness, shared AniList rate limiter) when the grouped library is read, after cover art links an id, and after manual AniList or group changes; a failed fetch leaves cached rows untouched. `imm_anime.group_override` (NULL = AniList, 0 = on its own, positive = join the franchise containing that AniList id) is the only user state; `/api/stats/anime/groups` and `PUT /api/stats/anime/:id/group` expose it.
|
||||
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
|
||||
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
|
||||
`imm_anime.group_override` merges last-writer-wins on `group_override_updated_at` (clears carry a timestamp too); its values are AniList ids, so no id remapping. The AniList relation cache is not merged: each machine rebuilds it, and stale or partial remote cache rows would otherwise outlive the 7-day refresh.
|
||||
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
|
||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`
|
||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`. Every consumer maps a parsed title + season to an AniList entry through `anilist/season-resolver.ts` (sequel-chain walk; see its header for what counts as a season). Changing what it returns needs a `MEDIA_RESOLUTION_CACHE_VERSION` bump in `character-dictionary-runtime/cache.ts`, or old matches keep being served from `anilist-resolution-cache.json`.
|
||||
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
|
||||
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
|
||||
assembled by `src/main/assemblies/jellyfin.ts`
|
||||
The episode playlist (`jellyfin-episode-playlist.ts`) inserts the playing episode's series neighbors into mpv's playlist after the item's first time-pos, so it never delays startup. mpv starts those entries itself; `adoptQueuedEpisode` in `jellyfin-playback-launch.ts` recognizes them from mpv's `path` and switches Jellyfin reporting, stats metadata, and subtitles without a `loadfile`. It runs from the media-path handler before the immersion sync, because stats metadata must exist before the session starts. The `subminer-managed-playlist-entries` script message tells the plugin which paths the app manages, so its start-file handling skips subtitle rearm and overlay auto-start for them.
|
||||
- YouTube playback, subtitles, media cache, and in-app browser: `src/core/services/youtube/`,
|
||||
`src/main/runtime/youtube-*`, assembled by `src/main/assemblies/youtube.ts`
|
||||
- User plugins: `src/core/services/plugins/` (host, `ctx`, `exec`), `src/main/runtime/plugin-panel-runtime.ts` (panel modal), `src/main/runtime/plugin-window-runtime.ts` (plugin windows), assembled by `src/main/assemblies/plugins.ts`; `src/renderer/modals/plugin-panel*.ts`; examples in `assets/plugins/`
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { once } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
|
||||
export type FakeJellyfinEpisode = { id: string; name: string; mediaPath: string };
|
||||
|
||||
export type FakeJellyfinReport = {
|
||||
kind: 'playing' | 'progress' | 'stopped';
|
||||
itemId: string;
|
||||
positionTicks: number;
|
||||
};
|
||||
|
||||
export type FakeJellyfin = {
|
||||
url: string;
|
||||
userId: string;
|
||||
accessToken: string;
|
||||
/** Every playback report the app sent, in arrival order. */
|
||||
reports: FakeJellyfinReport[];
|
||||
stop: () => Promise<void>;
|
||||
};
|
||||
|
||||
const SERIES_ID = 'e2e-series';
|
||||
const REPORT_KINDS: Record<string, FakeJellyfinReport['kind']> = {
|
||||
'/Sessions/Playing': 'playing',
|
||||
'/Sessions/Playing/Progress': 'progress',
|
||||
'/Sessions/Playing/Stopped': 'stopped',
|
||||
};
|
||||
|
||||
// Serves one file with Range support, since mpv probes and seeks over HTTP.
|
||||
function serveFile(request: http.IncomingMessage, response: http.ServerResponse, file: string) {
|
||||
const size = fs.statSync(file).size;
|
||||
const range = /^bytes=(\d+)-(\d*)$/.exec(request.headers.range ?? '');
|
||||
const start = range ? Number(range[1]) : 0;
|
||||
const end = Math.min(range?.[2] ? Number(range[2]) : size - 1, size - 1);
|
||||
response.writeHead(range ? 206 : 200, {
|
||||
'content-type': 'video/x-matroska',
|
||||
'accept-ranges': 'bytes',
|
||||
'content-length': end - start + 1,
|
||||
...(range ? { 'content-range': `bytes ${start}-${end}/${size}` } : {}),
|
||||
});
|
||||
fs.createReadStream(file, { start, end }).pipe(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* A Jellyfin stand-in holding one series of `episodes`, in order. It answers the item, episode
|
||||
* list, PlaybackInfo, and stream requests direct play needs, and records playback reports.
|
||||
*/
|
||||
export async function startFakeJellyfin(episodes: FakeJellyfinEpisode[]): Promise<FakeJellyfin> {
|
||||
const reports: FakeJellyfinReport[] = [];
|
||||
const byId = new Map(episodes.map((episode, index) => [episode.id, { episode, index }]));
|
||||
|
||||
const itemJson = (id: string) => {
|
||||
const found = byId.get(id);
|
||||
if (!found) return null;
|
||||
return {
|
||||
Id: id,
|
||||
Name: found.episode.name,
|
||||
Type: 'Episode',
|
||||
SeriesName: 'E2E Show',
|
||||
SeriesId: SERIES_ID,
|
||||
ParentIndexNumber: 1,
|
||||
IndexNumber: found.index + 1,
|
||||
LocationType: 'FileSystem',
|
||||
UserData: { PlaybackPositionTicks: 0 },
|
||||
MediaSources: [
|
||||
{
|
||||
Id: id,
|
||||
Container: 'mkv',
|
||||
SupportsDirectStream: true,
|
||||
SupportsTranscoding: false,
|
||||
MediaStreams: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const server = http.createServer((request, response) => {
|
||||
const url = new URL(request.url ?? '/', 'http://fake-jellyfin');
|
||||
const json = (status: number, body: unknown) => {
|
||||
response.writeHead(status, { 'content-type': 'application/json' });
|
||||
response.end(JSON.stringify(body));
|
||||
};
|
||||
|
||||
const stream = /^\/Videos\/([^/]+)\/stream$/.exec(url.pathname);
|
||||
if (request.method === 'GET' && stream) {
|
||||
const found = byId.get(stream[1]!);
|
||||
if (!found) return json(404, {});
|
||||
return serveFile(request, response, found.episode.mediaPath);
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
request.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
request.on('end', () => {
|
||||
const reportKind = REPORT_KINDS[url.pathname];
|
||||
if (request.method === 'POST' && reportKind) {
|
||||
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||||
reports.push({
|
||||
kind: reportKind,
|
||||
itemId: String(body.ItemId ?? ''),
|
||||
positionTicks: Number(body.PositionTicks ?? 0),
|
||||
});
|
||||
response.writeHead(204);
|
||||
return response.end();
|
||||
}
|
||||
const item = /^\/Users\/[^/]+\/Items\/([^/]+)$/.exec(url.pathname);
|
||||
if (request.method === 'GET' && item) {
|
||||
const body = itemJson(item[1]!);
|
||||
return body ? json(200, body) : json(404, {});
|
||||
}
|
||||
const playbackInfo = /^\/Items\/([^/]+)\/PlaybackInfo$/.exec(url.pathname);
|
||||
if (request.method === 'POST' && playbackInfo) {
|
||||
return json(200, { MediaSources: itemJson(playbackInfo[1]!)?.MediaSources ?? [] });
|
||||
}
|
||||
if (request.method === 'GET' && url.pathname === `/Shows/${SERIES_ID}/Episodes`) {
|
||||
return json(200, { Items: episodes.map((episode) => itemJson(episode.id)) });
|
||||
}
|
||||
json(404, {});
|
||||
});
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const { port } = server.address() as AddressInfo;
|
||||
|
||||
return {
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
userId: 'e2e-user',
|
||||
accessToken: 'e2e-token',
|
||||
reports,
|
||||
stop: async () => {
|
||||
server.closeAllConnections();
|
||||
server.close();
|
||||
await once(server, 'close');
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -30,6 +30,8 @@ export type E2eSessionOptions = {
|
||||
config?: JsonObject;
|
||||
/** Files written before launch, keyed by path relative to the config dir (e.g. plugins). */
|
||||
files?: Record<string, string>;
|
||||
/** Extra environment for every app launch, e.g. a Jellyfin session. */
|
||||
env?: Record<string, string>;
|
||||
};
|
||||
|
||||
export type AppTarget = {
|
||||
@@ -241,6 +243,7 @@ export async function startE2eSession(options: E2eSessionOptions = {}): Promise<
|
||||
SUBMINER_APP_LOG: path.join(root, 'app.log'),
|
||||
// Stay attached instead of re-spawning detached, so the harness owns the process.
|
||||
SUBMINER_BACKGROUND_CHILD: '1',
|
||||
...options.env,
|
||||
},
|
||||
unset: [...display.env.unset, 'ELECTRON_RUN_AS_NODE'],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test, { after } from 'node:test';
|
||||
import { startFakeJellyfin, type FakeJellyfin } from './harness/fake-jellyfin';
|
||||
import { generateFixtureClip } from './harness/fixtures';
|
||||
import { startE2eSession, type E2eSession } from './harness/session';
|
||||
import { waitUntil } from './harness/wait';
|
||||
|
||||
const TEST_TIMEOUT_MS = 180_000;
|
||||
const EPISODE_IDS = ['ep1', 'ep2', 'ep3'];
|
||||
|
||||
let clipsDir: string | undefined;
|
||||
let jellyfin: FakeJellyfin | undefined;
|
||||
let session: E2eSession | undefined;
|
||||
|
||||
after(async () => {
|
||||
await session?.dispose();
|
||||
await jellyfin?.stop();
|
||||
if (clipsDir) fs.rmSync(clipsDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
type PlaylistEntry = { filename: string; current?: boolean; title?: string };
|
||||
|
||||
// The episode ids in mpv's playlist, the current one marked with `*`.
|
||||
async function playlistIds(mpv: E2eSession['mpv']): Promise<string[]> {
|
||||
const playlist = (await mpv.command('get_property', 'playlist')) as PlaylistEntry[];
|
||||
return playlist.map((entry) => {
|
||||
const id = /\/Videos\/([^/]+)\/stream/.exec(entry.filename)?.[1] ?? entry.filename;
|
||||
return entry.current ? `${id}*` : id;
|
||||
});
|
||||
}
|
||||
|
||||
// `playlist/N/title` is writable from mpv 0.42.
|
||||
async function supportsPlaylistTitles(mpv: E2eSession['mpv']): Promise<boolean> {
|
||||
const version = String(await mpv.command('get_property', 'mpv-version'));
|
||||
const [major = 0, minor = 0] = (/v?(\d+)\.(\d+)/.exec(version) ?? []).slice(1).map(Number);
|
||||
return major > 0 || minor >= 42;
|
||||
}
|
||||
|
||||
async function mainPid(started: E2eSession): Promise<number> {
|
||||
const main = await started.mainProcess();
|
||||
try {
|
||||
return await main.evaluate<number>('process.pid');
|
||||
} finally {
|
||||
main.close();
|
||||
}
|
||||
}
|
||||
|
||||
test(
|
||||
'Jellyfin playback moves through queued series episodes in the same session',
|
||||
{ timeout: TEST_TIMEOUT_MS },
|
||||
async () => {
|
||||
clipsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-e2e-jellyfin-'));
|
||||
const episodes = EPISODE_IDS.map((id, index) => ({
|
||||
id,
|
||||
name: `Episode ${index + 1}`,
|
||||
mediaPath: path.join(clipsDir!, `${id}.mkv`),
|
||||
}));
|
||||
await Promise.all(episodes.map((episode) => generateFixtureClip(episode.mediaPath)));
|
||||
jellyfin = await startFakeJellyfin(episodes);
|
||||
session = await startE2eSession({
|
||||
config: {
|
||||
jellyfin: {
|
||||
enabled: true,
|
||||
serverUrl: jellyfin.url,
|
||||
remoteControlEnabled: false,
|
||||
episodePlaylist: { enabled: true, maxEpisodes: 3 },
|
||||
},
|
||||
},
|
||||
env: {
|
||||
SUBMINER_JELLYFIN_ACCESS_TOKEN: jellyfin.accessToken,
|
||||
SUBMINER_JELLYFIN_USER_ID: jellyfin.userId,
|
||||
},
|
||||
});
|
||||
const { mpv } = session;
|
||||
const pid = await mainPid(session);
|
||||
const reports = jellyfin.reports;
|
||||
const reported = (kind: string, itemId: string) =>
|
||||
reports.findIndex((report) => report.kind === kind && report.itemId === itemId);
|
||||
|
||||
await session.runAppCommand('--jellyfin-play', '--jellyfin-item-id=ep2');
|
||||
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2*,ep3', {
|
||||
description: 'the episodes around ep2 queued in the mpv playlist',
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
// The start report is fire-and-forget, so it can land after the playlist fills.
|
||||
await waitUntil(() => reported('playing', 'ep2') >= 0, {
|
||||
description: 'Jellyfin to hear ep2 start',
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
// mpv's playlist lists entry titles, not stream URLs carrying the API key. Entry titles
|
||||
// became writable in mpv 0.42; older players keep listing URLs.
|
||||
const titles = [
|
||||
'E2E Show S01E01 Episode 1',
|
||||
'E2E Show S01E02 Episode 2',
|
||||
'E2E Show S01E03 Episode 3',
|
||||
];
|
||||
if (await supportsPlaylistTitles(mpv)) {
|
||||
await waitUntil(
|
||||
async () => {
|
||||
const playlist = (await mpv.command('get_property', 'playlist')) as PlaylistEntry[];
|
||||
return playlist.map((entry) => entry.title).join('|') === titles.join('|');
|
||||
},
|
||||
{
|
||||
description: 'queued playlist entries titled like the playing episode',
|
||||
timeoutMs: 10_000,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
await mpv.command('playlist-next');
|
||||
await waitUntil(() => reported('playing', 'ep3') >= 0, {
|
||||
description: 'Jellyfin to hear ep3 start after playlist-next',
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
const stoppedEp2 = reported('stopped', 'ep2');
|
||||
assert.ok(stoppedEp2 >= 0, 'Jellyfin hears ep2 stop');
|
||||
assert.ok(stoppedEp2 < reported('playing', 'ep3'), 'ep2 stops before ep3 starts');
|
||||
assert.equal(await mpv.command('get_property', 'media-title'), 'E2E Show S01E03 Episode 3');
|
||||
// At the end of the series the window shifts back so it stays full.
|
||||
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2,ep3*', {
|
||||
description: 'the playlist window re-centered on ep3',
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
|
||||
await mpv.command('playlist-prev');
|
||||
await waitUntil(
|
||||
() =>
|
||||
reports.filter((report) => report.kind === 'playing' && report.itemId === 'ep2').length ===
|
||||
2,
|
||||
{ description: 'Jellyfin to hear ep2 start again after playlist-prev', timeoutMs: 30_000 },
|
||||
);
|
||||
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2*,ep3', {
|
||||
description: 'the playlist window re-centered on ep2',
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
|
||||
assert.equal(await mainPid(session), pid, 'the app keeps running across episode switches');
|
||||
},
|
||||
);
|
||||
@@ -1,6 +1,11 @@
|
||||
import path from 'node:path';
|
||||
import packageJson from '../package.json';
|
||||
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 {
|
||||
loadLauncherJellyfinConfig,
|
||||
loadLauncherLoggingConfig,
|
||||
@@ -65,6 +70,8 @@ function ensureAppPath(context: LauncherCommandContext): string {
|
||||
async function main(): Promise<void> {
|
||||
const scriptPath = process.argv[1] || 'subminer';
|
||||
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 launcherMpvConfig = loadLauncherMpvConfig();
|
||||
const launcherLoggingConfig = loadLauncherLoggingConfig();
|
||||
|
||||
@@ -25,7 +25,9 @@ export const IMMERSION_DB_FIXTURE_DDL = `
|
||||
tmdb_type TEXT,
|
||||
metadata_json 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 TABLE imm_videos(
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "subminer",
|
||||
"productName": "SubMiner",
|
||||
"desktopName": "SubMiner.desktop",
|
||||
"version": "0.22.1-beta.1",
|
||||
"version": "0.22.1-beta.2",
|
||||
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
||||
"packageManager": "bun@1.3.5",
|
||||
"main": "dist/main-entry.js",
|
||||
|
||||
@@ -1,21 +1,57 @@
|
||||
> This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release.
|
||||
|
||||
<!-- prerelease-version: 0.22.1-beta.1 -->
|
||||
<!-- prerelease-version: 0.22.1-beta.2; since: v0.22.1-beta.1 -->
|
||||
|
||||
## Changes since v0.22.1-beta.1
|
||||
|
||||
- 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).
|
||||
- Entries whose title names the season ("Season 3", "III", "第3期") are now preferred over counting sequels.
|
||||
- Episodes in the second half of a split season now update that half's AniList entry at the correct episode number.
|
||||
- Character dictionary AniList matches cached by older versions are re-resolved once.
|
||||
- Added outro skipping: the AniSkip key now also skips endings, with its own prompt and chapter markers.
|
||||
- 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.
|
||||
- AniSkip lookups now send the episode length, so skip times match your TV or Blu-ray cut.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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
|
||||
### Added
|
||||
- **Intro and Outro Skipping**:
|
||||
- The AniSkip key now skips endings too, with its own prompt and chapter markers.
|
||||
- Intros and outros are detected from the file's own chapters first, so skipping also works for Jellyfin and other streams.
|
||||
- AniSkip times now match your TV or Blu-ray cut.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
### 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.
|
||||
- **AniSkip**: Rate limits, server errors, and network failures are no longer remembered as "no intro" until restart. SubMiner retries them on the next load.
|
||||
- **Jimaku**: The modal fills in the series name again for Jellyfin episodes whose name contains a "/".
|
||||
- **Windows Overlay**:
|
||||
- The overlay now finds mpv more reliably, without relying on PowerShell lookups.
|
||||
- You can now configure the IPC socket in `mpv.conf`.
|
||||
- The overlay no longer stays attached to an unrelated window after mpv's process ID is reused.
|
||||
- Stalled overlays now log diagnostic warnings without debug logging enabled.
|
||||
- **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.
|
||||
|
||||
### Docs
|
||||
- **Windows Overlay Troubleshooting**: Added a guide to collecting and interpreting overlay attachment and readiness warnings without debug logging.
|
||||
- **Windows Overlay Troubleshooting**: New guide to collecting and reading overlay attachment and readiness warnings without debug logging.
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix(overlay): identify Windows mpv windows through IPC PID by @ksyasuda in #330
|
||||
- fix(overlay): keep forwarding mpv keys after a Yomitan popup closes by @ksyasuda in #332
|
||||
- feat(setup): download FFmpeg from first-run setup when none is usable by @ksyasuda in #333
|
||||
- feat(aniskip): detect intros and outros from file chapters and AniSkip v2 by @ksyasuda in #334
|
||||
- fix(anilist): resolve later seasons past split-cour halves and specials by @ksyasuda in #335
|
||||
- feat(stats): group library seasons, movies and OVAs into franchise cards by @ksyasuda in #336
|
||||
- fix(jimaku): keep the series name for stream titles containing slashes by @ksyasuda in #337
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -210,8 +210,17 @@ function M.create(ctx)
|
||||
})
|
||||
end
|
||||
|
||||
local function is_app_managed_playlist_entry()
|
||||
local path = mp.get_property("path")
|
||||
local managed_paths = state.app_managed_playlist_paths or {}
|
||||
return type(path) == "string" and managed_paths[path] == true
|
||||
end
|
||||
|
||||
local function on_start_file()
|
||||
if should_show_overlay_loading_osd() then
|
||||
if is_app_managed_playlist_entry() then
|
||||
state.skip_managed_subtitle_rearm_once = true
|
||||
state.app_managed_playback_pending = true
|
||||
elseif should_show_overlay_loading_osd() then
|
||||
process.start_overlay_loading_osd()
|
||||
end
|
||||
if state.pending_reload_media_identity ~= nil then
|
||||
@@ -322,6 +331,7 @@ function M.create(ctx)
|
||||
state.pending_reload_reason = nil
|
||||
state.app_managed_playback_pending = false
|
||||
state.app_managed_playback_active = false
|
||||
state.app_managed_playlist_paths = {}
|
||||
end
|
||||
|
||||
local function register_lifecycle_hooks()
|
||||
|
||||
@@ -27,6 +27,15 @@ function M.create(ctx)
|
||||
state.skip_managed_subtitle_rearm_once = true
|
||||
state.app_managed_playback_pending = true
|
||||
end)
|
||||
-- Playlist entries the app queued (Jellyfin neighbor episodes). mpv starts them on its own,
|
||||
-- so start-file recognizes them by path instead of waiting for subminer-managed-subtitles-loading.
|
||||
mp.register_script_message("subminer-managed-playlist-entries", function(...)
|
||||
local paths = {}
|
||||
for _, path in ipairs({ ... }) do
|
||||
paths[path] = true
|
||||
end
|
||||
state.app_managed_playlist_paths = paths
|
||||
end)
|
||||
mp.register_script_message("subminer-menu", function()
|
||||
ui.show_menu()
|
||||
end)
|
||||
|
||||
@@ -34,6 +34,7 @@ function M.new()
|
||||
pending_reload_reason = nil,
|
||||
app_managed_playback_pending = false,
|
||||
app_managed_playback_active = false,
|
||||
app_managed_playlist_paths = {},
|
||||
auto_start_retry_generation = 0,
|
||||
session_binding_generation = 0,
|
||||
session_binding_names = {},
|
||||
|
||||
@@ -108,6 +108,9 @@ function extractBuild() {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-'));
|
||||
try {
|
||||
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(
|
||||
'powershell.exe',
|
||||
[
|
||||
@@ -116,7 +119,7 @@ function extractBuild() {
|
||||
'-ExecutionPolicy',
|
||||
'Bypass',
|
||||
'-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,
|
||||
);
|
||||
|
||||
@@ -1042,6 +1042,65 @@ do
|
||||
)
|
||||
end
|
||||
|
||||
do
|
||||
local scenario = {
|
||||
process_list = "",
|
||||
option_overrides = {
|
||||
binary_path = binary_path,
|
||||
auto_start = "yes",
|
||||
auto_start_visible_overlay = "yes",
|
||||
auto_start_pause_until_ready = "yes",
|
||||
socket_path = "/tmp/subminer-socket",
|
||||
},
|
||||
input_ipc_server = "/tmp/subminer-socket",
|
||||
path = "https://jellyfin.example/Videos/ep1/stream",
|
||||
media_title = "Jellyfin Episode 1",
|
||||
files = {
|
||||
[binary_path] = true,
|
||||
},
|
||||
}
|
||||
local recorded, err = run_plugin_scenario(scenario)
|
||||
assert_true(recorded ~= nil, "plugin failed to load for managed playlist entry scenario: " .. tostring(err))
|
||||
recorded.script_messages["subminer-managed-playlist-entries"](
|
||||
"https://jellyfin.example/Videos/ep1/stream",
|
||||
"https://jellyfin.example/Videos/ep2/stream"
|
||||
)
|
||||
fire_event(recorded, "end-file", { reason = "eof" })
|
||||
scenario.path = "https://jellyfin.example/Videos/ep2/stream"
|
||||
scenario.media_title = "Jellyfin Episode 2"
|
||||
fire_event(recorded, "start-file")
|
||||
fire_event(recorded, "file-loaded")
|
||||
assert_true(
|
||||
not has_property_set(recorded.property_sets, "sid", "auto"),
|
||||
"an app-queued playlist entry should keep the app's subtitle selection"
|
||||
)
|
||||
assert_true(
|
||||
count_start_calls(recorded.async_calls) == 0,
|
||||
"an app-queued playlist entry should not auto-start the overlay"
|
||||
)
|
||||
assert_true(
|
||||
count_property_set(recorded.property_sets, "pause", true) == 0,
|
||||
"an app-queued playlist entry should not arm the plugin pause gate"
|
||||
)
|
||||
assert_true(
|
||||
not has_osd_message(recorded.osd, "SubMiner: Overlay loading |"),
|
||||
"an app-queued playlist entry should not show the overlay loading spinner"
|
||||
)
|
||||
fire_event(recorded, "end-file", { reason = "stop" })
|
||||
scenario.path = "/media/local-episode.mkv"
|
||||
scenario.media_title = "Local Episode"
|
||||
fire_event(recorded, "start-file")
|
||||
fire_event(recorded, "file-loaded")
|
||||
assert_true(
|
||||
count_property_set(recorded.property_sets, "sid", "auto") == 1,
|
||||
"a path the app did not queue should get the normal subtitle rearm"
|
||||
)
|
||||
assert_true(
|
||||
count_start_calls(recorded.async_calls) == 1,
|
||||
"a path the app did not queue should auto-start the overlay"
|
||||
)
|
||||
end
|
||||
|
||||
do
|
||||
local recorded, err = run_plugin_scenario({
|
||||
process_list = "",
|
||||
|
||||
@@ -160,6 +160,10 @@ export const INTEGRATIONS_DEFAULT_CONFIG: Pick<
|
||||
directPlayPreferred: true,
|
||||
directPlayContainers: ['mkv', 'mp4', 'webm', 'mov', 'flac', 'mp3', 'aac'],
|
||||
transcodeVideoCodec: 'h264',
|
||||
episodePlaylist: {
|
||||
enabled: true,
|
||||
maxEpisodes: 5,
|
||||
},
|
||||
},
|
||||
discordPresence: {
|
||||
enabled: true,
|
||||
|
||||
@@ -616,13 +616,14 @@ export function buildIntegrationConfigOptionRegistry(
|
||||
path: 'mpv.aniskipEnabled',
|
||||
kind: 'boolean',
|
||||
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',
|
||||
kind: 'string',
|
||||
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',
|
||||
@@ -703,6 +704,20 @@ export function buildIntegrationConfigOptionRegistry(
|
||||
defaultValue: defaultConfig.jellyfin.transcodeVideoCodec,
|
||||
description: 'Preferred transcode video codec when direct play is unavailable.',
|
||||
},
|
||||
{
|
||||
path: 'jellyfin.episodePlaylist.enabled',
|
||||
kind: 'boolean',
|
||||
defaultValue: defaultConfig.jellyfin.episodePlaylist.enabled,
|
||||
description:
|
||||
"Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes.",
|
||||
},
|
||||
{
|
||||
path: 'jellyfin.episodePlaylist.maxEpisodes',
|
||||
kind: 'number',
|
||||
defaultValue: defaultConfig.jellyfin.episodePlaylist.maxEpisodes,
|
||||
description:
|
||||
'Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).',
|
||||
},
|
||||
{
|
||||
path: 'discordPresence.enabled',
|
||||
kind: 'boolean',
|
||||
|
||||
@@ -62,9 +62,14 @@ export function getConfigHotReloadField(path: string): string | null {
|
||||
|
||||
// These consumers read the current config when the next operation starts.
|
||||
if (
|
||||
['jimaku', 'tmdb', 'subsync', 'notifications', 'subtitleGeneration'].some((root) =>
|
||||
pathStartsWith(path, root),
|
||||
)
|
||||
[
|
||||
'jimaku',
|
||||
'tmdb',
|
||||
'subsync',
|
||||
'notifications',
|
||||
'subtitleGeneration',
|
||||
'jellyfin.episodePlaylist',
|
||||
].some((root) => pathStartsWith(path, root))
|
||||
) {
|
||||
return path;
|
||||
}
|
||||
|
||||
@@ -372,6 +372,49 @@ export function applyIntegrationConfig(context: ResolveContext): void {
|
||||
);
|
||||
}
|
||||
|
||||
if (isObject(src.jellyfin.episodePlaylist)) {
|
||||
const episodePlaylist = src.jellyfin.episodePlaylist;
|
||||
const playlistEnabled = asBoolean(episodePlaylist.enabled);
|
||||
if (playlistEnabled !== undefined) {
|
||||
resolved.jellyfin.episodePlaylist.enabled = playlistEnabled;
|
||||
} else if (episodePlaylist.enabled !== undefined) {
|
||||
warn(
|
||||
'jellyfin.episodePlaylist.enabled',
|
||||
episodePlaylist.enabled,
|
||||
resolved.jellyfin.episodePlaylist.enabled,
|
||||
'Expected boolean.',
|
||||
);
|
||||
}
|
||||
|
||||
const maxEpisodes = asNumber(episodePlaylist.maxEpisodes);
|
||||
if (maxEpisodes !== undefined) {
|
||||
const normalized = Math.min(25, Math.max(3, Math.floor(maxEpisodes)));
|
||||
if (normalized !== maxEpisodes) {
|
||||
warn(
|
||||
'jellyfin.episodePlaylist.maxEpisodes',
|
||||
episodePlaylist.maxEpisodes,
|
||||
normalized,
|
||||
'Out of range; clamped to 3..25.',
|
||||
);
|
||||
}
|
||||
resolved.jellyfin.episodePlaylist.maxEpisodes = normalized;
|
||||
} else if (episodePlaylist.maxEpisodes !== undefined) {
|
||||
warn(
|
||||
'jellyfin.episodePlaylist.maxEpisodes',
|
||||
episodePlaylist.maxEpisodes,
|
||||
resolved.jellyfin.episodePlaylist.maxEpisodes,
|
||||
'Expected number.',
|
||||
);
|
||||
}
|
||||
} else if (src.jellyfin.episodePlaylist !== undefined) {
|
||||
warn(
|
||||
'jellyfin.episodePlaylist',
|
||||
src.jellyfin.episodePlaylist,
|
||||
resolved.jellyfin.episodePlaylist,
|
||||
'Expected object.',
|
||||
);
|
||||
}
|
||||
|
||||
if (Array.isArray(src.jellyfin.recentServers)) {
|
||||
const seenRecentServers = new Set<string>();
|
||||
resolved.jellyfin.recentServers = src.jellyfin.recentServers
|
||||
|
||||
@@ -165,3 +165,26 @@ test('yomitan externalProfilePath expands leading tilde to the current home dire
|
||||
path.join(homeDir, '.config', 'gsm_overlay'),
|
||||
);
|
||||
});
|
||||
|
||||
test('jellyfin episodePlaylist resolves the toggle and clamps the episode cap', () => {
|
||||
const { context, warnings } = createResolveContext({
|
||||
jellyfin: {
|
||||
episodePlaylist: { enabled: false, maxEpisodes: 400 },
|
||||
},
|
||||
});
|
||||
|
||||
applyIntegrationConfig(context);
|
||||
|
||||
assert.deepEqual(context.resolved.jellyfin.episodePlaylist, { enabled: false, maxEpisodes: 25 });
|
||||
assert.ok(warnings.some((warning) => warning.path === 'jellyfin.episodePlaylist.maxEpisodes'));
|
||||
});
|
||||
|
||||
test('jellyfin episodePlaylist raises an episode cap below 3', () => {
|
||||
const { context } = createResolveContext({
|
||||
jellyfin: { episodePlaylist: { maxEpisodes: 2 } },
|
||||
});
|
||||
|
||||
applyIntegrationConfig(context);
|
||||
|
||||
assert.equal(context.resolved.jellyfin.episodePlaylist.maxEpisodes, 3);
|
||||
});
|
||||
@@ -223,6 +223,7 @@ const SUBSECTION_ORDER = new Map<string, number>(
|
||||
'Toggle & Visibility',
|
||||
'Open Panels',
|
||||
'Playback',
|
||||
'Episode Playlist',
|
||||
'Default Fold State',
|
||||
].map((subsection, index) => [subsection, index]),
|
||||
);
|
||||
@@ -629,6 +630,9 @@ function subsectionForPath(path: string): string | undefined {
|
||||
if (path === 'mpv.aniskipButtonKey') {
|
||||
return 'Playback';
|
||||
}
|
||||
if (path.startsWith('jellyfin.episodePlaylist.')) {
|
||||
return 'Episode Playlist';
|
||||
}
|
||||
if (path.startsWith('shortcuts.')) {
|
||||
const leaf = path.split('.').at(-1) ?? '';
|
||||
if (
|
||||
|
||||
@@ -338,6 +338,7 @@ function createMockTracker(
|
||||
hasAnime: async (animeId: number) => animeId === 1,
|
||||
getAnimeEpisodes: async () => ANIME_EPISODES,
|
||||
getAnimeAnilistEntries: async () => [],
|
||||
getAnimeGroupPlacement: async () => null,
|
||||
getAnimeWords: async () => ANIME_WORDS,
|
||||
getAnimeDailyRollups: async () => DAILY_ROLLUPS,
|
||||
getEpisodesPerDay: async () => EPISODES_PER_DAY,
|
||||
@@ -712,7 +713,7 @@ const MALFORMED_IDS = [
|
||||
|
||||
/** Every route that takes a positive resource id; `:id` is replaced per request. */
|
||||
const ID_ROUTES: Array<{
|
||||
method: 'GET' | 'DELETE' | 'PATCH' | 'POST';
|
||||
method: 'GET' | 'DELETE' | 'PATCH' | 'POST' | 'PUT';
|
||||
path: string;
|
||||
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/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } },
|
||||
{ method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } },
|
||||
{ method: 'PUT', path: '/api/stats/anime/:id/group', body: { mode: 'standalone' } },
|
||||
{ method: 'POST', path: '/api/stats/anki/browse?noteId=:id' },
|
||||
];
|
||||
|
||||
@@ -2429,6 +2431,50 @@ describe('stats server API routes', () => {
|
||||
assert.equal(mergeCalls, 0);
|
||||
});
|
||||
|
||||
it('PUT /api/stats/anime/:animeId/group validates the body and maps refusals', async () => {
|
||||
const calls: unknown[] = [];
|
||||
const app = createStatsApp(
|
||||
createMockTracker({
|
||||
setAnimeGroupOverride: async (animeId, target) => {
|
||||
calls.push([animeId, target]);
|
||||
if (target.mode === 'join' && target.targetAnimeId === 9) {
|
||||
return { ok: false, reason: 'target-not-grouped' };
|
||||
}
|
||||
if (animeId === 404) return { ok: false, reason: 'not-found' };
|
||||
return { ok: true };
|
||||
},
|
||||
}),
|
||||
);
|
||||
const put = (path: string, body: unknown) =>
|
||||
app.request(path, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(body) });
|
||||
|
||||
for (const body of [
|
||||
{},
|
||||
{ mode: 'join' },
|
||||
{ mode: 'join', targetAnimeId: 0 },
|
||||
{ mode: 'join', targetAnimeId: '8' },
|
||||
{ mode: 'join', targetAnimeId: 3 },
|
||||
{ mode: 'reset' },
|
||||
]) {
|
||||
assert.equal((await put('/api/stats/anime/3/group', body)).status, 400, JSON.stringify(body));
|
||||
}
|
||||
assert.deepEqual(calls, []);
|
||||
|
||||
assert.equal(
|
||||
(await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 8 })).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await put('/api/stats/anime/3/group', { mode: 'anilist' })).status, 200);
|
||||
assert.equal((await put('/api/stats/anime/404/group', { mode: 'standalone' })).status, 404);
|
||||
const refused = await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 9 });
|
||||
assert.equal(refused.status, 409);
|
||||
assert.match((await refused.json()).error, /no AniList entry/);
|
||||
assert.deepEqual(calls.slice(0, 2), [
|
||||
[3, { mode: 'join', targetAnimeId: 8 }],
|
||||
[3, { mode: 'anilist' }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => {
|
||||
let moved: { videoId: number; animeId: number } | null = null;
|
||||
const app = createStatsApp(
|
||||
|
||||
@@ -0,0 +1,651 @@
|
||||
// Captured from live AniList responses on 2026-11-22, trimmed to the fields the resolver reads.
|
||||
// Each chain is in SEQUEL order: entry i's only SEQUEL is entry i + 1.
|
||||
import type { AnilistSeasonMedia } from '../season-resolver';
|
||||
|
||||
/** Mushoku Tensei: S1 -> "Cour 2" -> S2 -> "Season 2 Part 2" -> S3 -> S3 Part 2. */
|
||||
export const MUSHOKU_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 108465,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'Jobless Reincarnation: I Will Seriously Try If I Go To Another World',
|
||||
'无职转生 ~到了异世界就拿出真本事~',
|
||||
'เกิดชาตินี้พี่ต้องเทพ',
|
||||
'Thất nghiệp chuyển sinh',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
native: '無職転生 ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 127720,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: ['Mushoku Tensei: Jobless Reincarnation Part 2', 'เกิดชาตินี้พี่ต้องเทพ พาร์ท 2'],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu Part 2',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Cour 2',
|
||||
native: '無職転生 ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 146065,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season',
|
||||
'Mushoku Tensei II: Jobless Reincarnation',
|
||||
'Mushoku Tensei II: Reencarnación desde cero',
|
||||
'无职转生~到了异世界就拿出真本事~第2季',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 2',
|
||||
native: '無職転生Ⅱ ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 166873,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: [
|
||||
'Mushoku Tensei: Jobless Reincarnation Season 2 Cour 2',
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2 ครึ่งหลัง',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season Part 2',
|
||||
'Mushoku Tensei II: Jobless Reincarnation Part 2',
|
||||
'Mushoku Tensei II: Reencarnación desde cero',
|
||||
'无职转生~到了异世界就拿出真本事~第2季',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu Part 2',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 2 Part 2',
|
||||
native: '無職転生Ⅱ ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 178789,
|
||||
episodes: 14,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'無職転生 ~異世界行ったら本気だす~ 第3期',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 3rd Season',
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 3',
|
||||
native: '無職転生Ⅲ ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 217434,
|
||||
episodes: null,
|
||||
format: 'TV',
|
||||
seasonYear: 2027,
|
||||
synonyms: ['Mushoku Tensei: Jobless Reincarnation Season 3 Part 2'],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu Part 2',
|
||||
english: null,
|
||||
native: '無職転生Ⅲ ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Re:ZERO: S1 -> S2 -> "Season 2 Part 2" -> S3 -> S4 -> S5 (unaired). */
|
||||
export const REZERO_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 21355,
|
||||
episodes: 25,
|
||||
format: 'TV',
|
||||
seasonYear: 2016,
|
||||
synonyms: [
|
||||
'Re: Life in a different world from zero',
|
||||
'ReZero',
|
||||
'Re Zero',
|
||||
'Re:从零开始的异世界生活',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก',
|
||||
'Re:Zero — жизнь с нуля в другом мире',
|
||||
'Re:Zero Empezar de cero en un mundo diferente',
|
||||
'Re:Zero – Bắt đầu lại ở thế giới khác',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu',
|
||||
english: 'Re:ZERO -Starting Life in Another World-',
|
||||
native: 'Re:ゼロから始める異世界生活',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 108632,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
synonyms: [
|
||||
'Re:Zero kara Hajimeru Isekai Seikatsu (2020)',
|
||||
'Re: 제로부터 시작하는 이세계 생활 2기',
|
||||
'Re:从零开始的异世界生活第二季(上半)',
|
||||
'Re:从零开始的异世界生活 2 上半',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2',
|
||||
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 2',
|
||||
native: 'Re:ゼロから始める異世界生活 2nd Season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 119661,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'Re:Zero kara Hajimeru Isekai Seikatsu (2021)',
|
||||
'Re: 제로부터 시작하는 이세계 생활 2기 파트 2',
|
||||
'Re:从零开始的异世界生活第二季(下半)',
|
||||
'Re:从零开始的异世界生活 2 下半',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2 พาร์ท 2',
|
||||
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season Part 2',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 2 Part 2',
|
||||
native: 'Re:ゼロから始める異世界生活 2nd Season Part 2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 163134,
|
||||
episodes: 16,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: ['Re:ZERO – Жизнь с нуля в альтернативном мире 3'],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 3rd Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 3',
|
||||
native: 'Re:ゼロから始める異世界生活 3rd season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 189046,
|
||||
episodes: 19,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'Re:ZERO รีเซทชีวิต ฝ่าวิกฤตต่างโลก ซีซั่น 4',
|
||||
'Re:ZERO – Жизнь с нуля в альтернативном мире 4',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 4th Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 4',
|
||||
native: 'Re:ゼロから始める異世界生活 4th season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 219904,
|
||||
episodes: null,
|
||||
format: 'TV',
|
||||
seasonYear: null,
|
||||
synonyms: ['Re:ZERO -Starting Life in Another World- Season 5'],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 5th Season',
|
||||
english: null,
|
||||
native: 'Re:ゼロから始める異世界生活 5th season',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Dr. STONE: STONE WARS reaches NEW WORLD through a one-episode SPECIAL. */
|
||||
export const DR_STONE_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 105333,
|
||||
episodes: 24,
|
||||
format: 'TV',
|
||||
seasonYear: 2019,
|
||||
synonyms: [
|
||||
'Dcst',
|
||||
'石纪元',
|
||||
'ドクターストーン',
|
||||
'ดร.สโตน เจ้าแห่งวิทยาศาสตร์กู้คืนอารยธรรมโลก',
|
||||
'Доктор Стоун',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE',
|
||||
english: 'Dr. STONE',
|
||||
native: 'Dr.STONE',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 113936,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'ドクターストーン STONE WARS',
|
||||
'Dr.STONE第2期',
|
||||
'Dr. STONE 2',
|
||||
'닥터 스톤 STONE WARS',
|
||||
'石纪元第二季',
|
||||
'DR.STONE ภาค 2',
|
||||
'Доктор Стоун: Каменные войны',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: STONE WARS',
|
||||
english: 'Dr. STONE: STONE WARS',
|
||||
native: 'Dr.STONE STONE WARS',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 142876,
|
||||
episodes: 1,
|
||||
format: 'SPECIAL',
|
||||
seasonYear: 2022,
|
||||
synonyms: ['Dr. STONE: Ryusui', 'Доктор Стоун: Рюсуй'],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: Ryuusui',
|
||||
english: 'Dr. STONE Special Episode – RYUSUI',
|
||||
native: 'Dr.STONE 龍水',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131518,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'石纪元第三季',
|
||||
'Dr.STONE Season 3',
|
||||
'DR.STONE ภาค 3',
|
||||
'Dr.STONE 第3期',
|
||||
'Dr. STONE 新石紀(第三季)',
|
||||
'Доктор Стоун: Новый Свет',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: NEW WORLD',
|
||||
english: 'Dr. STONE New World',
|
||||
native: 'Dr.STONE NEW WORLD',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 162670,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'石纪元第三季',
|
||||
'Dr.STONE Season 3 Part 2',
|
||||
'DR.STONE ภาค 3',
|
||||
'Dr.STONE 第3期 第2クール',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: NEW WORLD Part 2',
|
||||
english: 'Dr. STONE New World Part 2',
|
||||
native: 'Dr.STONE NEW WORLD 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 172019,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2025,
|
||||
synonyms: ['Dr.STONE Season 4', 'Dr.STONE 第4期', 'ドクターストーン'],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: SCIENCE FUTURE',
|
||||
english: 'Dr. STONE SCIENCE FUTURE',
|
||||
native: 'Dr.STONE SCIENCE FUTURE',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Bleach TYBW: cours named after arcs; "Part N" only in synonyms, spelled "Thousand Year". */
|
||||
export const BLEACH_TYBW_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 116674,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
synonyms: [
|
||||
'بليتش: حرب الألف سنة الدموية',
|
||||
'Bleach: La guerre sanglante de mille ans',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen',
|
||||
english: 'BLEACH: Thousand-Year Blood War',
|
||||
native: 'BLEACH 千年血戦篇',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 159322,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand Year Blood War Part 2',
|
||||
'BLEACH 千年血戦篇 第2クール',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Ketsubetsu-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Separation',
|
||||
native: 'BLEACH 千年血戦篇-訣別譚-',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 169755,
|
||||
episodes: 14,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand Year Blood War Part 3',
|
||||
'BLEACH 千年血戦篇 第3クール',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Soukoku-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Conflict',
|
||||
native: 'BLEACH 千年血戦篇-相剋譚-',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 185874,
|
||||
episodes: 10,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand-Year Blood War Part 4',
|
||||
'BLEACH 千年血戦篇 第4クール',
|
||||
'BLEACH: Thousand-Year Blood War The Final Season',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Kashin-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Calamity',
|
||||
native: 'BLEACH 千年血戦篇-禍進譚-',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Attack on Titan: season 3 carries the Thai synonym "... ภาค 3 Part 1"; the chain ends in SPECIALs. */
|
||||
export const AOT_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 16498,
|
||||
episodes: 25,
|
||||
format: 'TV',
|
||||
seasonYear: 2013,
|
||||
synonyms: [
|
||||
'SnK',
|
||||
'AoT',
|
||||
'Ataque a los Titanes',
|
||||
'Ataque dos Titãs',
|
||||
"L'Attacco dei Giganti",
|
||||
'מתקפת הטיטאנים',
|
||||
'进击的巨人',
|
||||
'L’Attaque des Titans',
|
||||
'الهجوم على العمالقة',
|
||||
'ผ่าพิภพไททัน',
|
||||
'حمله به تایتان',
|
||||
'Ataque de Titãs',
|
||||
'Atak Tytanów',
|
||||
'Атака титанов',
|
||||
'Đại Chiến Titan',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin',
|
||||
english: 'Attack on Titan',
|
||||
native: '進撃の巨人',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 20958,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2017,
|
||||
synonyms: [
|
||||
'SnK 2',
|
||||
'AoT 2',
|
||||
'+מתקפת הטיטאנים עונה 2',
|
||||
"L'Attacco dei Giganti 2",
|
||||
"L'Attacco dei Giganti - Seconda Stagione",
|
||||
'ผ่าพิภพไททัน ภาค 2',
|
||||
'حمله به تایتان فصل 2',
|
||||
'Атака титанов 2',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 2',
|
||||
english: 'Attack on Titan Season 2',
|
||||
native: '進撃の巨人 Season2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 99147,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: [
|
||||
'SnK 3',
|
||||
'AoT 3',
|
||||
'מתקפת הטיטאנים עונה 3',
|
||||
"L'Attacco dei Giganti 3",
|
||||
"L'Attacco dei Giganti - Terza Stagione",
|
||||
'ผ่าพิภพไททัน ภาค 3',
|
||||
'حمله به تایتان فصل 3',
|
||||
'ผ่าพิภพไททัน ภาค 3 Part 1',
|
||||
'Атака титанов 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 3',
|
||||
english: 'Attack on Titan Season 3',
|
||||
native: '進撃の巨人 Season3',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 104578,
|
||||
episodes: 10,
|
||||
format: 'TV',
|
||||
seasonYear: 2019,
|
||||
synonyms: [
|
||||
'SnK 3',
|
||||
'AoT 3',
|
||||
'Shingeki no Kyojin Season 3 (2019)',
|
||||
"L'Attaco dei Giganti 3 Parte 2",
|
||||
"L'Attacco dei Giganti - Terza Stagione Parte 2",
|
||||
'מתקפת הטיטאנים עונה 3 חלק 2',
|
||||
"L'Attaque des Titans Saison 3 Partie 2 ",
|
||||
'ผ่าพิภพไททัน ภาค 3 Part 2',
|
||||
'ผ่าพิภพไททัน ภาค 3 พาร์ท 2',
|
||||
'حمله به تایتان فصل 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 3 Part 2',
|
||||
english: 'Attack on Titan Season 3 Part 2',
|
||||
native: '進撃の巨人 Season3 Part.2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 110277,
|
||||
episodes: 16,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
'Shingeki no Kyojin 4',
|
||||
'進撃の巨人4',
|
||||
'Attack on Titan Season 4',
|
||||
'진격의 거인 더 파이널 시즌',
|
||||
'מתקפת הטיטאנים העונה האחרונה',
|
||||
"L'Attaque des Titans Saison Finale",
|
||||
"L'Attacco dei Giganti 4",
|
||||
"L'Attacco dei Giganti - La Stagione Finale",
|
||||
'حمله به تایتان فصل 4 ',
|
||||
' ผ่าพิภพไททัน ไฟนอล ซีซั่น',
|
||||
'ผ่าพิภพไททัน Final Season',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
'هجوم العملاقة الجزء الأخير',
|
||||
'Атака Титанов: Финал',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season',
|
||||
english: 'Attack on Titan Final Season',
|
||||
native: '進撃の巨人 The Final Season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131681,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
synonyms: [
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
"L'attaque des titans Saison Finale Partie 2",
|
||||
'Shingeki no Kyojin: The Final Season (2022)',
|
||||
'اتک عن تایتان',
|
||||
'حمله به غول ها',
|
||||
'حمله به تایتان فصل 4 ',
|
||||
' ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 2',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
"L'Attacco dei Giganti 4 Parte 2",
|
||||
'Атака титанов: Финал. Часть 2',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season Part 2',
|
||||
english: 'Attack on Titan Final Season Part 2',
|
||||
native: '進撃の巨人 The Final Season Part 2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 146984,
|
||||
episodes: 1,
|
||||
format: 'SPECIAL',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'Shingeki no Kyojin: The Final Season Final Edition',
|
||||
'Shingeki no Kyojin: The Final Season Part 3',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
'ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 3',
|
||||
'Attack on Titan Final Season Part 3 Final Arc Part 1',
|
||||
'Attack on Titan The Final Season The Final Part Special',
|
||||
'Attack on Titan The Final Season The Final Part Part 1',
|
||||
'حمله به تایتان فصل آخر قسمت ویژه 1 ',
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season - Kanketsu-hen Zenpen',
|
||||
english: 'Attack on Titan Final Season THE FINAL CHAPTERS Special 1',
|
||||
native: '進撃の巨人 The Final Season完結編 前編',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Overlord: seasons named only by a trailing roman numeral. */
|
||||
export const OVERLORD_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 20832,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2015,
|
||||
synonyms: ['Over Lord', 'โอเวอร์ลอร์ด', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก'],
|
||||
title: {
|
||||
romaji: 'Overlord',
|
||||
english: 'Overlord',
|
||||
native: 'オーバーロード',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 98437,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: ['Over Lord 2', 'โอเวอร์ลอร์ด ภาค 2', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 2'],
|
||||
title: {
|
||||
romaji: 'Overlord II',
|
||||
english: 'Overlord II',
|
||||
native: 'オーバーロードⅡ',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 101474,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: ['Over Lord 3', 'โอเวอร์ลอร์ด ภาค 3', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 3'],
|
||||
title: {
|
||||
romaji: 'Overlord III',
|
||||
english: 'Overlord III',
|
||||
native: 'オーバーロードⅢ',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** JoJo: Golden Wind ends in the synonym "Part 5", Stone Ocean in "Part 6"; both are new seasons. */
|
||||
export const JOJO_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 21450,
|
||||
episodes: 39,
|
||||
format: 'TV',
|
||||
seasonYear: 2016,
|
||||
synonyms: [
|
||||
'JoJo no Kimyou na Bouken Part 4: Diamond wa Kudakenai',
|
||||
"JoJo's Bizarre Adventure Part 4: Diamond is Unbreakable",
|
||||
'مغامرات جوجو العجيبة: الألماس غير قابل للكسر',
|
||||
'Le bizzarre avventure di JoJo: Diamond is Unbreakable',
|
||||
'Невероятные приключения ДжоДжо: Diamond is Unbreakable',
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Diamond wa Kudakenai',
|
||||
english: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
|
||||
native: 'ジョジョの奇妙な冒険 ダイヤモンドは砕けない',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 102883,
|
||||
episodes: 39,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: [
|
||||
"JoJo's Bizarre Adventure Part 5",
|
||||
"JoJo's Bizarre Adventure: Vento Aureo",
|
||||
'Le Bizzarre Avventure Di GioGio: Vento Aureo',
|
||||
'مغامرات جوجو العجيبة: الرياح الذهبية',
|
||||
'Невероятные приключения ДжоДжо: Золотой ветер',
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Ougon no Kaze',
|
||||
english: "JoJo's Bizarre Adventure: Golden Wind",
|
||||
native: 'ジョジョの奇妙な冒険 黄金の風',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131942,
|
||||
episodes: 12,
|
||||
format: 'ONA',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
"JoJo's Bizarre Adventure: Stone Ocean",
|
||||
"JoJo's Bizarre Adventure Part 6",
|
||||
'JoJo no Kimyou na Bouken Part 6',
|
||||
'Le bizzarre avventure di JoJo: Stone Ocean',
|
||||
'โจโจ้ ล่าข้ามศตวรรษ: สโตนโอเชียน ',
|
||||
'โจโจ้ ล่าข้ามศตวรรษ ภาค 6',
|
||||
'مغامرات جوجو العجيبة: محيط الأحجار',
|
||||
"ההרפתקה המוזרה של ג'וג'ו: אוקיינוס האבן",
|
||||
'Невероятные приключения ДжоДжо: Каменный океан ',
|
||||
"Химерні пригоди ДжоДжо: Кам'яний океан",
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Stone Ocean',
|
||||
english: "JoJo's Bizarre Adventure: STONE OCEAN",
|
||||
native: 'ジョジョの奇妙な冒険 ストーンオーシャン',
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -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 () => {
|
||||
const result = await guessAnilistMediaInfo('/tmp/Season 2/Guessit Title.mkv', null, {
|
||||
runGuessit: async () => JSON.stringify({ title: 'Guessit Title' }),
|
||||
@@ -585,6 +600,11 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
|
||||
});
|
||||
}
|
||||
if (call === 3) {
|
||||
// Looks one season past the count for an entry naming season 2; there is none.
|
||||
assert.equal(body.variables?.id, 202);
|
||||
return createJsonResponse({ data: { Media: { relations: { edges: [] } } } });
|
||||
}
|
||||
if (call === 4) {
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
@@ -608,7 +628,68 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
|
||||
assert.deepEqual(searchTerms, ['Demo Show']);
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /Demo Show Sequel/);
|
||||
assert.equal(call, 4);
|
||||
assert.equal(call, 5);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress writes a split-cour episode to the part that airs it', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const saved: Array<Record<string, unknown> | undefined> = [];
|
||||
globalThis.fetch = (async (_input, init) => {
|
||||
const body = JSON.parse(String(init?.body)) as {
|
||||
query: string;
|
||||
variables?: Record<string, unknown>;
|
||||
};
|
||||
if (body.query.includes('Page(')) {
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Page: {
|
||||
media: [{ id: 101, episodes: 11, format: 'TV', title: { english: 'Demo Show' } }],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (body.query.includes('relations')) {
|
||||
assert.equal(body.variables?.id, 101);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Media: {
|
||||
relations: {
|
||||
edges: [
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: {
|
||||
id: 202,
|
||||
type: 'ANIME',
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
title: { english: 'Demo Show Cour 2' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (body.query.includes('SaveMediaListEntry')) {
|
||||
saved.push(body.variables);
|
||||
return createJsonResponse({ data: { SaveMediaListEntry: { progress: 4 } } });
|
||||
}
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
return createJsonResponse({
|
||||
data: { Media: { id: 202, mediaListEntry: { progress: 3, status: 'CURRENT' } } },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
// Episode 15 of an 11 + 12 season is episode 4 of the second cour's entry.
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Demo Show', 15, { season: 1 });
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /Demo Show Cour 2.*episode 4/);
|
||||
assert.deepEqual(saved, [{ mediaId: 202, progress: 4, status: 'CURRENT' }]);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as childProcess from 'child_process';
|
||||
import * as path from 'path';
|
||||
|
||||
import { parseMediaInfo } from '../../../jimaku/utils';
|
||||
import { parseMediaLookupInfo } from '../../../jimaku/utils';
|
||||
import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../../../shared/media-identity';
|
||||
import type { AnilistRateLimiter } from './rate-limiter';
|
||||
import { resolveAnilistSeasonMedia, stripSeasonSuffix } from './season-resolver';
|
||||
@@ -231,7 +231,7 @@ export async function guessAnilistMediaInfo(
|
||||
const season = firstPositiveInteger(parsed.season);
|
||||
const year = firstYear(parsed.year);
|
||||
if (title) {
|
||||
const fallback = parseMediaInfo(target);
|
||||
const fallback = parseMediaLookupInfo(mediaPath, mediaTitle);
|
||||
const canUseFallbackDetails = fallback.confidence !== 'low';
|
||||
return {
|
||||
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()) {
|
||||
return null;
|
||||
}
|
||||
@@ -273,6 +273,9 @@ export async function updateAnilistPostWatchProgress(
|
||||
let mediaId = pinnedMediaId;
|
||||
let resolvedTitle: string | null = null;
|
||||
let resolvedEpisodes: number | null = null;
|
||||
// Episode number within the entry being updated; differs from `episode` only for a
|
||||
// split-cour back half.
|
||||
let progress = episode;
|
||||
// A missing list entry is only created when we trust the match; otherwise a fuzzy
|
||||
// search hit would add an unrelated show to the user's list.
|
||||
let confidentMatch = pinnedMediaId !== null;
|
||||
@@ -312,14 +315,18 @@ export async function updateAnilistPostWatchProgress(
|
||||
};
|
||||
}
|
||||
|
||||
mediaId = resolution.id;
|
||||
resolvedTitle = resolution.title;
|
||||
resolvedEpisodes = resolution.episodes;
|
||||
// A split-cour back half is its own AniList entry with its own episode numbering:
|
||||
// "S1E15" of an 11 + 12 season is progress 4 on the second entry.
|
||||
const target = resolution.episodeEntry ?? resolution;
|
||||
mediaId = target.id;
|
||||
resolvedTitle = target.title;
|
||||
resolvedEpisodes = target.episodes;
|
||||
progress = resolution.episodeEntry?.episode ?? episode;
|
||||
// With no parsed season, an exact match on a season-stripped title ("Show S2" ->
|
||||
// "Show") only certifies the season 1 anchor, not the entry being watched.
|
||||
const seasonMarkerStripped = stripSeasonSuffix(title).trim() !== title.trim();
|
||||
confidentMatch =
|
||||
resolution.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
|
||||
target.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
|
||||
}
|
||||
|
||||
const entryResponse = await anilistGraphQl<AnilistMediaEntryData>(
|
||||
@@ -376,8 +383,8 @@ export async function updateAnilistPostWatchProgress(
|
||||
}
|
||||
|
||||
const currentProgress = entry?.progress ?? 0;
|
||||
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, episode);
|
||||
if (typeof currentProgress === 'number' && currentProgress >= episode && !shouldMarkCompleted) {
|
||||
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, progress);
|
||||
if (typeof currentProgress === 'number' && currentProgress >= progress && !shouldMarkCompleted) {
|
||||
return {
|
||||
status: 'skipped',
|
||||
message: `AniList already at episode ${currentProgress} (${pickedTitle}).`,
|
||||
@@ -396,7 +403,7 @@ export async function updateAnilistPostWatchProgress(
|
||||
`,
|
||||
{
|
||||
mediaId,
|
||||
progress: episode,
|
||||
progress,
|
||||
status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT',
|
||||
},
|
||||
options,
|
||||
@@ -410,15 +417,15 @@ export async function updateAnilistPostWatchProgress(
|
||||
return {
|
||||
status: 'updated',
|
||||
message: shouldMarkCompleted
|
||||
? `AniList added "${pickedTitle}" at episode ${episode} and marked it completed.`
|
||||
: `AniList added "${pickedTitle}" to Watching at episode ${episode}.`,
|
||||
? `AniList added "${pickedTitle}" at episode ${progress} and marked it completed.`
|
||||
: `AniList added "${pickedTitle}" to Watching at episode ${progress}.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'updated',
|
||||
message: shouldMarkCompleted
|
||||
? `AniList updated "${pickedTitle}" to episode ${episode} and marked it completed.`
|
||||
: `AniList updated "${pickedTitle}" to episode ${episode}.`,
|
||||
? `AniList updated "${pickedTitle}" to episode ${progress} and marked it completed.`
|
||||
: `AniList updated "${pickedTitle}" to episode ${progress}.`,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AnilistRateLimiter } from './rate-limiter';
|
||||
import { AnilistRateLimitedError, executeAnilistQuery } from './anilist-graphql';
|
||||
import type { DatabaseSync } from '../immersion-tracker/sqlite';
|
||||
import {
|
||||
getAnimeCoverArt,
|
||||
@@ -20,7 +21,6 @@ import { getVideoTmdbLink, linkAnimeToTmdbTitle } from '../immersion-tracker/liv
|
||||
import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver';
|
||||
import type { TmdbTitleDetails } from '../tmdb/tmdb-client';
|
||||
|
||||
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
|
||||
const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
|
||||
|
||||
export interface CoverArtFetcher {
|
||||
@@ -76,47 +76,6 @@ export function stripFilenameTags(raw: string): string {
|
||||
return title.trim().replace(/\s{2,}/g, ' ');
|
||||
}
|
||||
|
||||
class AnilistRateLimitedError extends Error {
|
||||
constructor() {
|
||||
super('Anilist rate limit reached');
|
||||
this.name = 'AnilistRateLimitedError';
|
||||
}
|
||||
}
|
||||
|
||||
async function executeAnilistQuery<T>(
|
||||
rateLimiter: AnilistRateLimiter,
|
||||
query: string,
|
||||
variables: Record<string, unknown>,
|
||||
): Promise<T> {
|
||||
await rateLimiter.acquire();
|
||||
|
||||
const res = await fetch(ANILIST_GRAPHQL_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ query, variables }),
|
||||
});
|
||||
|
||||
rateLimiter.recordResponse(res.headers);
|
||||
|
||||
if (res.status === 429) {
|
||||
throw new AnilistRateLimitedError();
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
|
||||
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
|
||||
if (firstError?.message) {
|
||||
throw new Error(firstError.message);
|
||||
}
|
||||
if (!json.data) {
|
||||
throw new Error('Anilist response missing data');
|
||||
}
|
||||
return json.data;
|
||||
}
|
||||
|
||||
async function downloadImage(url: string): Promise<Buffer | null> {
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
|
||||
@@ -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 {
|
||||
ANILIST_SEASON_RELATIONS_QUERY,
|
||||
ANILIST_SEASON_SEARCH_QUERY,
|
||||
namedSeasons,
|
||||
pickByAirOrder,
|
||||
resolveAnilistSeasonMedia,
|
||||
splitPartMarker,
|
||||
stripSeasonSuffix,
|
||||
type AnilistSeasonMedia,
|
||||
} from './season-resolver';
|
||||
import {
|
||||
AOT_CHAIN,
|
||||
BLEACH_TYBW_CHAIN,
|
||||
DR_STONE_CHAIN,
|
||||
JOJO_CHAIN,
|
||||
MUSHOKU_CHAIN,
|
||||
OVERLORD_CHAIN,
|
||||
REZERO_CHAIN,
|
||||
} from './__fixtures__/anilist-season-chains';
|
||||
|
||||
/** Real AniList payloads for "My Teen Romantic Comedy SNAFU", trimmed to used fields. */
|
||||
const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [
|
||||
@@ -161,7 +172,8 @@ test('resolves season 3 by walking sequel relations', async () => {
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
// Searches the bare title only; "Season 3" returns nothing on AniList.
|
||||
assert.deepEqual(searches, ['My Teen Romantic Comedy SNAFU']);
|
||||
assert.deepEqual(relationLookups, [14813, 20698]);
|
||||
// The last lookup checks one season past the count for an entry naming season 3.
|
||||
assert.deepEqual(relationLookups, [14813, 20698, 108489]);
|
||||
});
|
||||
|
||||
test('season 1 resolves to the anchor without relation lookups', async () => {
|
||||
@@ -215,7 +227,7 @@ test('a sequel resolution whose own title matches the parsed title stays exact',
|
||||
);
|
||||
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
assert.equal(result?.via, 'named-season');
|
||||
assert.equal(result?.exactTitleMatch, true);
|
||||
});
|
||||
|
||||
@@ -325,7 +337,7 @@ test('prefers the TV sequel when a franchise branches into other formats', async
|
||||
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
|
||||
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
assert.equal(result?.via, 'named-season');
|
||||
});
|
||||
|
||||
test('air-order fallback refuses when the anchor is not the earliest entry', () => {
|
||||
@@ -399,3 +411,288 @@ test('air-order fallback declines when a franchise entry has no air year', async
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.via, 'anchor');
|
||||
});
|
||||
|
||||
/** Executor over a fixture chain: search returns the whole chain, entry i's SEQUEL is i + 1. */
|
||||
function createChainExecutor(chain: AnilistSeasonMedia[]) {
|
||||
const relations: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {};
|
||||
chain.forEach((entry, index) => {
|
||||
const next = chain[index + 1];
|
||||
relations[entry.id] = next ? [{ relationType: 'SEQUEL', node: next }] : [];
|
||||
});
|
||||
return createExecutor(chain, relations);
|
||||
}
|
||||
|
||||
async function resolveInChain(
|
||||
chain: AnilistSeasonMedia[],
|
||||
input: { title: string; season?: number | null; episode?: number | null },
|
||||
) {
|
||||
const executor = createChainExecutor(chain);
|
||||
const result = await resolveAnilistSeasonMedia(input, { execute: executor.execute });
|
||||
return { result, relationLookups: executor.relationLookups };
|
||||
}
|
||||
|
||||
test('split-cour back halves do not count as seasons', async () => {
|
||||
const title = 'Mushoku Tensei: Jobless Reincarnation';
|
||||
const s2 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 2, episode: 1 });
|
||||
assert.equal(s2.result?.id, 146065);
|
||||
assert.equal(s2.result?.seasonResolved, true);
|
||||
|
||||
const s3 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 3, episode: 1 });
|
||||
assert.equal(s3.result?.id, 178789);
|
||||
// Four hops for two seasons: "Cour 2" and "Season 2 Part 2" were walked through.
|
||||
assert.deepEqual(s3.relationLookups, [108465, 127720, 146065, 166873]);
|
||||
|
||||
const reZeroS3 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 3 });
|
||||
assert.equal(reZeroS3.result?.id, 163134);
|
||||
const reZeroS4 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 4 });
|
||||
assert.equal(reZeroS4.result?.id, 189046);
|
||||
});
|
||||
|
||||
test('a special in the sequel chain is walked through without counting', async () => {
|
||||
const s3 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 3 });
|
||||
assert.equal(s3.result?.id, 131518);
|
||||
const s4 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 4 });
|
||||
assert.equal(s4.result?.id, 172019);
|
||||
});
|
||||
|
||||
test('season names ignore part and cour numbers, including localized ones', () => {
|
||||
// "Cour 2" carries the Thai synonym "... พาร์ท 2" ("part 2").
|
||||
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[1]!)], []);
|
||||
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[3]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(OVERLORD_CHAIN[1]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(DR_STONE_CHAIN[1]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(AOT_CHAIN[4]!)], [4]);
|
||||
});
|
||||
|
||||
test('an entry naming the requested season beats the hop count', async () => {
|
||||
// The second cour has no marker anywhere, so counting alone would call it season 2.
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show: Arc Two' } },
|
||||
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
|
||||
];
|
||||
const { result } = await resolveInChain(chain, { title: 'Show', season: 2 });
|
||||
assert.equal(result?.id, 3);
|
||||
assert.equal(result?.via, 'named-season');
|
||||
|
||||
const overlord = await resolveInChain(OVERLORD_CHAIN, { title: 'Overlord', season: 2 });
|
||||
assert.equal(overlord.result?.id, 98437);
|
||||
assert.equal(overlord.result?.via, 'named-season');
|
||||
});
|
||||
|
||||
test('a counted entry whose title names another season is not accepted', async () => {
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2021, title: { english: 'Show: Arc Two' } },
|
||||
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
|
||||
];
|
||||
// Counting lands on id 3 for season 3, but it says it is season 2.
|
||||
const { result } = await resolveInChain(chain, { title: 'Show', season: 3 });
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
});
|
||||
|
||||
test('JoJo parts are seasons, not split-cour continuations', async () => {
|
||||
assert.equal(splitPartMarker('JoJo no Kimyou na Bouken Part 5: Ougon no Kaze'), null);
|
||||
assert.deepEqual(splitPartMarker("JoJo's Bizarre Adventure Part 5"), {
|
||||
base: 'jojo s bizarre adventure',
|
||||
part: 5,
|
||||
});
|
||||
// Golden Wind ends in "Part 5" and Stone Ocean in "Part 6": same base, different
|
||||
// parts, so Stone Ocean must still count as the next season.
|
||||
const { result } = await resolveInChain(JOJO_CHAIN, {
|
||||
title: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
|
||||
season: 3,
|
||||
});
|
||||
assert.equal(result?.id, 131942);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
});
|
||||
|
||||
test('Attack on Titan resolves its final season past the season 3 back half', async () => {
|
||||
const { result } = await resolveInChain(AOT_CHAIN, { title: 'Attack on Titan', season: 4 });
|
||||
assert.equal(result?.id, 110277);
|
||||
});
|
||||
|
||||
test('air-order fallback drops back halves but keeps a season spelled "Part 1"', () => {
|
||||
// AoT season 3 carries the synonym "ผ่าพิภพไททัน ภาค 3 Part 1".
|
||||
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 3, AOT_CHAIN)?.id, 99147);
|
||||
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 4, AOT_CHAIN)?.id, 110277);
|
||||
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 3, MUSHOKU_CHAIN)?.id, 178789);
|
||||
// Only three real seasons have aired, so a fourth must not fall out of the list.
|
||||
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 4, MUSHOKU_CHAIN.slice(0, 5)), null);
|
||||
});
|
||||
|
||||
test('a TYBW cour marked only in a differently spelled synonym is not season 2', async () => {
|
||||
const { result } = await resolveInChain(BLEACH_TYBW_CHAIN, {
|
||||
title: 'BLEACH: Thousand-Year Blood War',
|
||||
season: 2,
|
||||
});
|
||||
// Every sequel is a later cour of the same season, so there is no season 2 to find.
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.id, 116674);
|
||||
});
|
||||
|
||||
test('an episode past the season entry lands on the split-cour part that airs it', async () => {
|
||||
const mushoku = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 1,
|
||||
episode: 15,
|
||||
});
|
||||
assert.equal(mushoku.result?.id, 108465);
|
||||
assert.equal(mushoku.result?.episodeEntry?.id, 127720);
|
||||
assert.equal(mushoku.result?.episodeEntry?.episode, 4);
|
||||
|
||||
const mushokuS2 = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 2,
|
||||
episode: 20,
|
||||
});
|
||||
assert.equal(mushokuS2.result?.id, 146065);
|
||||
assert.equal(mushokuS2.result?.episodeEntry?.id, 166873);
|
||||
assert.equal(mushokuS2.result?.episodeEntry?.episode, 7);
|
||||
|
||||
// Three cours of 13 + 13 + 14: episode 28 is the third cour's second.
|
||||
const bleach = await resolveInChain(BLEACH_TYBW_CHAIN, {
|
||||
title: 'BLEACH: Thousand-Year Blood War',
|
||||
episode: 28,
|
||||
});
|
||||
assert.equal(bleach.result?.id, 116674);
|
||||
assert.equal(bleach.result?.episodeEntry?.id, 169755);
|
||||
assert.equal(bleach.result?.episodeEntry?.episode, 2);
|
||||
});
|
||||
|
||||
test('an episode inside the season entry needs no remap or relation lookup', async () => {
|
||||
const { result, relationLookups } = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 1,
|
||||
episode: 5,
|
||||
});
|
||||
assert.equal(result?.id, 108465);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
assert.deepEqual(relationLookups, []);
|
||||
});
|
||||
|
||||
test('an episode past a season with no continuation is not moved into the next season', async () => {
|
||||
const { result } = await resolveInChain(OVERLORD_CHAIN, {
|
||||
title: 'Overlord',
|
||||
season: 1,
|
||||
episode: 20,
|
||||
});
|
||||
assert.equal(result?.id, 20832);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
});
|
||||
|
||||
test('a sequel naming its own season is not a back half, even with a part synonym', async () => {
|
||||
const sequel: AnilistSeasonMedia = {
|
||||
id: 2,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Part Synonym Show Season 2' },
|
||||
synonyms: ['Part Synonym Show Part 2'],
|
||||
};
|
||||
// The anchor names season 1 itself...
|
||||
const named = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Part Synonym Show' },
|
||||
synonyms: ['Part Synonym Show Season 1'],
|
||||
},
|
||||
sequel,
|
||||
],
|
||||
{ title: 'Part Synonym Show', season: 2 },
|
||||
);
|
||||
assert.equal(named.result?.id, 2);
|
||||
// ...or is season 1 because the walk starts there.
|
||||
const unnamed = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Part Synonym Show' },
|
||||
},
|
||||
sequel,
|
||||
],
|
||||
{ title: 'Part Synonym Show', season: 2 },
|
||||
);
|
||||
assert.equal(unnamed.result?.id, 2);
|
||||
});
|
||||
|
||||
test('air order keeps a sequel naming its own season despite a part synonym', () => {
|
||||
const anchor: AnilistSeasonMedia = {
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Air Order Show' },
|
||||
};
|
||||
const sequel: AnilistSeasonMedia = {
|
||||
id: 2,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Air Order Show Season 2' },
|
||||
synonyms: ['Air Order Show Part 2'],
|
||||
};
|
||||
assert.equal(pickByAirOrder(anchor, 2, [anchor, sequel])?.id, 2);
|
||||
});
|
||||
|
||||
test('a season 1 episode past its length does not move to a longer later season', async () => {
|
||||
const { result } = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Long Later Show' },
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
episodes: 24,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Long Later Show Season 2' },
|
||||
},
|
||||
],
|
||||
{ title: 'Long Later Show', season: 1, episode: 20 },
|
||||
);
|
||||
assert.equal(result?.id, 1);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
});
|
||||
|
||||
test('a sequel that repeats its predecessor name is still a new season', async () => {
|
||||
// No part marker, so the identical title must not be read as a continuation.
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Same Name Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Same Name Show' } },
|
||||
];
|
||||
const { result } = await resolveInChain(chain, { title: 'Same Name Show', season: 2 });
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.seasonResolved, true);
|
||||
});
|
||||
|
||||
test('a rate limit mid-walk is surfaced instead of answered from air order', async () => {
|
||||
const { execute } = createChainExecutor(MUSHOKU_CHAIN);
|
||||
let relationCalls = 0;
|
||||
const failing = async <T>(query: string, variables: Record<string, unknown>): Promise<T> => {
|
||||
if (query === ANILIST_SEASON_RELATIONS_QUERY && ++relationCalls === 2) {
|
||||
throw new Error('AniList rate limited (429)');
|
||||
}
|
||||
return execute<T>(query, variables);
|
||||
};
|
||||
// Air order alone would answer season 3 correctly from this search result, but it must
|
||||
// not answer from a franchise picture the failed walk never confirmed.
|
||||
await assert.rejects(
|
||||
resolveAnilistSeasonMedia(
|
||||
{ title: 'Mushoku Tensei: Jobless Reincarnation', season: 3 },
|
||||
{ execute: failing },
|
||||
),
|
||||
/429/,
|
||||
);
|
||||
});
|
||||
@@ -9,6 +9,14 @@ import { sanitizeMediaTitle } from '../../../shared/media-identity';
|
||||
* season 1 anchor and then walking AniList SEQUEL relations, with an air-order fallback
|
||||
* when the relation chain is incomplete. When the seasonal entry cannot be located it
|
||||
* reports `seasonResolved: false` so callers can refuse to act instead of guessing.
|
||||
*
|
||||
* Not every SEQUEL hop is a new season. Along the chain:
|
||||
* - the back half of a split cour ("Part 2", "Cour 2", "第2クール") is its own entry,
|
||||
* - movies, specials and OVAs sit between seasons,
|
||||
* so the walk only counts entries that start a new TV season, and prefers an entry whose
|
||||
* title names the requested season ("Season 3", "3rd Season", "III", "第3期") over the
|
||||
* count. A continuation with no marker anywhere is indistinguishable from a new season;
|
||||
* the manual AniList override covers those.
|
||||
*/
|
||||
|
||||
import { normalizeTitleIdentity } from '../../utils/title-normalization';
|
||||
@@ -35,9 +43,29 @@ export type AnilistQueryExecutor = <T>(
|
||||
variables: Record<string, unknown>,
|
||||
) => Promise<T>;
|
||||
|
||||
export type AnilistSeasonResolutionVia = 'anchor' | 'sequel-chain' | 'air-order';
|
||||
export type AnilistSeasonResolutionVia = 'anchor' | 'named-season' | 'sequel-chain' | 'air-order';
|
||||
|
||||
/**
|
||||
* The entry that actually airs the parsed episode when it runs past the season entry
|
||||
* into a later part of the same season ("S1E15" of an 11 + 12 split cour is episode 4
|
||||
* of the "Cour 2" entry).
|
||||
*/
|
||||
export interface AnilistEpisodeEntry {
|
||||
id: number;
|
||||
title: string;
|
||||
episodes: number | null;
|
||||
media: AnilistSeasonMedia;
|
||||
/** Episode number within this entry. */
|
||||
episode: number;
|
||||
exactTitleMatch: boolean;
|
||||
}
|
||||
|
||||
export interface AnilistSeasonResolution {
|
||||
/**
|
||||
* The season's own entry (its first part). Season-level consumers (cover art, the
|
||||
* anime row's AniList link, the character dictionary) use this so every episode of a
|
||||
* split-cour season agrees on one id.
|
||||
*/
|
||||
id: number;
|
||||
title: string;
|
||||
episodes: number | null;
|
||||
@@ -48,6 +76,8 @@ export interface AnilistSeasonResolution {
|
||||
via: AnilistSeasonResolutionVia;
|
||||
/** Exact normalized match against an AniList title or synonym. */
|
||||
exactTitleMatch: boolean;
|
||||
/** Set only when the parsed episode belongs to a later part of the season. */
|
||||
episodeEntry: AnilistEpisodeEntry | null;
|
||||
}
|
||||
|
||||
export interface ResolveAnilistSeasonMediaInput {
|
||||
@@ -119,8 +149,79 @@ interface AnilistSeasonRelationsResponse {
|
||||
/** Formats that can carry a numbered TV season, best first. */
|
||||
const SEASONAL_FORMAT_PRIORITY = ['TV', 'TV_SHORT', 'ONA'];
|
||||
|
||||
/** An ONA this short is a special released online, not a season. */
|
||||
const MIN_ONA_SEASON_EPISODES = 3;
|
||||
|
||||
/** Largest season the chain walk will count to. */
|
||||
const MAX_SEQUEL_HOPS = 12;
|
||||
|
||||
/**
|
||||
* Hops the walk may take in total. Continuations and specials add hops without adding
|
||||
* seasons, so this has to leave room beyond the season number.
|
||||
*/
|
||||
const MAX_SEQUEL_STEPS = 24;
|
||||
|
||||
/** Parts a single season can be split into before the episode remap gives up. */
|
||||
const MAX_SEASON_PARTS = 6;
|
||||
|
||||
/**
|
||||
* Markers AniList appends when one broadcast season is listed as several entries,
|
||||
* matched against normalized titles. Anchored to the end so a numbered *work*
|
||||
* ("JoJo no Kimyou na Bouken Part 5: Ougon no Kaze") is not read as a continuation:
|
||||
* those carry a subtitle after the number and really are separate seasons.
|
||||
*/
|
||||
const PART_MARKER_PATTERNS: RegExp[] = [
|
||||
/\bpart\s*(\d{1,2}|i{1,3}|iv|v)$/u,
|
||||
/\bcour\s*(\d{1,2})$/u,
|
||||
/\b(\d{1,2})(?:st|nd|rd|th)\s+(?:part|cour)$/u,
|
||||
/\b(second|final)\s+(?:part|cour)$/u,
|
||||
/第\s*(\d{1,2})\s*(?:部|クール)$/u,
|
||||
];
|
||||
|
||||
const NUMBER_WORDS: Record<string, number> = {
|
||||
i: 1,
|
||||
ii: 2,
|
||||
iii: 3,
|
||||
iv: 4,
|
||||
v: 5,
|
||||
vi: 6,
|
||||
second: 2,
|
||||
third: 3,
|
||||
fourth: 4,
|
||||
fifth: 5,
|
||||
sixth: 6,
|
||||
一: 1,
|
||||
二: 2,
|
||||
三: 3,
|
||||
四: 4,
|
||||
五: 5,
|
||||
六: 6,
|
||||
七: 7,
|
||||
八: 8,
|
||||
九: 9,
|
||||
};
|
||||
|
||||
/**
|
||||
* Patterns that state a season outright. Safe on any title or synonym, because none of
|
||||
* them can be confused with a part or cour number.
|
||||
*/
|
||||
const EXPLICIT_SEASON_PATTERNS: RegExp[] = [
|
||||
/\bseason\s*(\d{1,2})\b/u,
|
||||
/\b(\d{1,2})(?:st|nd|rd|th)\s+season\b/u,
|
||||
/\b(second|third|fourth|fifth|sixth)\s+season\b/u,
|
||||
/\bs(\d{1,2})\b/u,
|
||||
/第\s*(\d{1,2}|[二三四五六七八九])\s*[期季]/u,
|
||||
/(\d{1,2})\s*(?:期|기)/u,
|
||||
];
|
||||
|
||||
/** Words after which a trailing number counts parts, not seasons. */
|
||||
const PART_WORDS = new Set(['part', 'cour', 'parte', 'partie']);
|
||||
|
||||
function parseNumberToken(token: string): number | null {
|
||||
if (/^\d{1,2}$/.test(token)) return Number(token);
|
||||
return NUMBER_WORDS[token] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops season markers a release name carries but AniList titles never do,
|
||||
* so "Some Show Season 3" and "Some Show S3" both search as "Some Show".
|
||||
@@ -134,13 +235,65 @@ export function stripSeasonSuffix(title: string): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
function mediaTitles(media: AnilistSeasonMedia): string[] {
|
||||
const synonyms = Array.isArray(media.synonyms) ? media.synonyms : [];
|
||||
return [media.title?.english, media.title?.romaji, media.title?.native, ...synonyms]
|
||||
/**
|
||||
* Splits a trailing part/cour marker off a title, or returns null when it has none.
|
||||
*
|
||||
* "Mushoku Tensei: Jobless Reincarnation Season 2 Part 2" is the back half of season 2,
|
||||
* not season 3. `part` is null for an unnumbered marker ("Final Cour").
|
||||
*/
|
||||
export function splitPartMarker(title: string): { base: string; part: number | null } | null {
|
||||
const normalized = normalizeTitleIdentity(title);
|
||||
for (const pattern of PART_MARKER_PATTERNS) {
|
||||
const match = normalized.match(pattern);
|
||||
if (!match || match.index === undefined) continue;
|
||||
const base = normalized.slice(0, match.index).trim();
|
||||
if (!base) continue;
|
||||
const token = match[1] ?? '';
|
||||
return { base, part: token === 'final' ? null : parseNumberToken(token) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mainTitles(media: AnilistSeasonMedia): string[] {
|
||||
return [media.title?.english, media.title?.romaji, media.title?.native]
|
||||
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||
.map((value) => normalizeTitleIdentity(value));
|
||||
}
|
||||
|
||||
function mediaTitles(media: AnilistSeasonMedia): string[] {
|
||||
const synonyms = (Array.isArray(media.synonyms) ? media.synonyms : [])
|
||||
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||
.map((value) => normalizeTitleIdentity(value));
|
||||
return [...mainTitles(media), ...synonyms].filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Season numbers an entry's titles name.
|
||||
*
|
||||
* A bare trailing number ("Overlord II", "Konosuba 2") is only trusted on the main
|
||||
* titles: localized synonyms end in part numbers spelled in other scripts (Mushoku
|
||||
* Tensei's "Cour 2" carries the Thai "... พาร์ท 2", "part 2").
|
||||
*/
|
||||
export function namedSeasons(media: AnilistSeasonMedia): Set<number> {
|
||||
const seasons = new Set<number>();
|
||||
for (const title of mediaTitles(media)) {
|
||||
for (const pattern of EXPLICIT_SEASON_PATTERNS) {
|
||||
const token = title.match(pattern)?.[1];
|
||||
const value = token ? parseNumberToken(token) : null;
|
||||
if (value !== null && value > 0) seasons.add(value);
|
||||
}
|
||||
}
|
||||
for (const title of mainTitles(media)) {
|
||||
const words = title.split(' ');
|
||||
const last = words.at(-1) ?? '';
|
||||
const before = words.at(-2) ?? '';
|
||||
if (PART_WORDS.has(before)) continue;
|
||||
const value = parseNumberToken(last);
|
||||
if (value !== null && value > 1) seasons.add(value);
|
||||
}
|
||||
return seasons;
|
||||
}
|
||||
|
||||
function displayTitle(media: AnilistSeasonMedia, fallback: string): string {
|
||||
return (
|
||||
media.title?.english?.trim() ||
|
||||
@@ -167,29 +320,64 @@ function isSeasonalFormat(media: AnilistSeasonMedia): boolean {
|
||||
return SEASONAL_FORMAT_PRIORITY.includes(format);
|
||||
}
|
||||
|
||||
function formatRank(media: AnilistSeasonMedia): number {
|
||||
const index = SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
|
||||
return index < 0 ? SEASONAL_FORMAT_PRIORITY.length : index;
|
||||
/** Whether an entry can be a season: a TV series, or an ONA long enough not to be a special. */
|
||||
function isSeasonEntry(media: AnilistSeasonMedia): boolean {
|
||||
if (!isSeasonalFormat(media)) return false;
|
||||
if ((media.format || '').toUpperCase() !== 'ONA') return true;
|
||||
const episodes = episodeCount(media);
|
||||
return episodes === null || episodes >= MIN_ONA_SEASON_EPISODES;
|
||||
}
|
||||
|
||||
function toResolution(
|
||||
media: AnilistSeasonMedia,
|
||||
fallbackTitle: string,
|
||||
season: number | null,
|
||||
via: AnilistSeasonResolutionVia,
|
||||
seasonResolved: boolean,
|
||||
exactTitleMatch: boolean,
|
||||
): AnilistSeasonResolution {
|
||||
return {
|
||||
id: media.id,
|
||||
title: displayTitle(media, fallbackTitle),
|
||||
episodes: episodeCount(media),
|
||||
media,
|
||||
seasonResolved,
|
||||
requestedSeason: season,
|
||||
via,
|
||||
exactTitleMatch,
|
||||
};
|
||||
function formatRank(media: AnilistSeasonMedia): number {
|
||||
if (!isSeasonEntry(media)) return SEASONAL_FORMAT_PRIORITY.length;
|
||||
return SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `next` continues the season `seasonStart` began rather than starting a new one.
|
||||
*
|
||||
* Compared against the season's first entry, not the previous hop, so a special between
|
||||
* a season and its second cour cannot hide the link. The marker is required, not just a
|
||||
* matching base: a sequel that repeats its predecessor's name exactly is a new season
|
||||
* AniList did not number. "Part 1" never marks a back half, and a season's own marker is
|
||||
* only stripped when it is "Part 1" (AoT season 3 carries "... ภาค 3 Part 1"); stripping
|
||||
* any number would read JoJo's "Part 6" as a continuation of its "Part 5".
|
||||
*
|
||||
* An entry naming a season never continues a different one: "Show Season 2" with the
|
||||
* synonym "Show Part 2" is season 2, not a back half of "Show". The season `seasonStart`
|
||||
* stands for is taken from its own titles, else from `startSeason` when the caller
|
||||
* knows it (the chain walk counts it, the episode remap was asked for it).
|
||||
*/
|
||||
function isSeasonContinuation(
|
||||
seasonStart: AnilistSeasonMedia,
|
||||
next: AnilistSeasonMedia,
|
||||
startSeason: number | null = null,
|
||||
): boolean {
|
||||
const markers = mediaTitles(next)
|
||||
.map((title) => splitPartMarker(title))
|
||||
.filter((marker): marker is NonNullable<typeof marker> => marker !== null && marker.part !== 1);
|
||||
if (markers.length === 0) return false;
|
||||
|
||||
const nextSeasons = namedSeasons(next);
|
||||
if (nextSeasons.size > 0) {
|
||||
const startNamed = namedSeasons(seasonStart);
|
||||
const startSeasons =
|
||||
startNamed.size > 0 ? startNamed : startSeason !== null ? new Set([startSeason]) : null;
|
||||
if (startSeasons && ![...nextSeasons].some((value) => startSeasons.has(value))) return false;
|
||||
}
|
||||
|
||||
const seasonKeys = new Set<string>();
|
||||
for (const title of mediaTitles(seasonStart)) {
|
||||
seasonKeys.add(title);
|
||||
const own = splitPartMarker(title);
|
||||
if (own?.part === 1) seasonKeys.add(own.base);
|
||||
}
|
||||
return markers.some((marker) => seasonKeys.has(marker.base));
|
||||
}
|
||||
|
||||
function exactMatchFor(candidate: AnilistSeasonMedia, titles: string[]): boolean {
|
||||
const candidateTitles = mediaTitles(candidate);
|
||||
return titles.some((title) => candidateTitles.includes(normalizeTitleIdentity(title)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -250,49 +438,31 @@ export function pickAnchorMedia(
|
||||
return scored[0]?.entry ?? null;
|
||||
}
|
||||
|
||||
async function walkSequelChain(
|
||||
anchor: AnilistSeasonMedia,
|
||||
season: number,
|
||||
deps: ResolveAnilistSeasonMediaDeps,
|
||||
): Promise<AnilistSeasonMedia | null> {
|
||||
// Walking fewer hops than requested would land on the wrong season and report it as
|
||||
// resolved, so refuse instead and let the caller fall through to its guarded fallback.
|
||||
const hops = season - 1;
|
||||
if (hops > MAX_SEQUEL_HOPS) {
|
||||
return null;
|
||||
}
|
||||
const visited = new Set<number>([anchor.id]);
|
||||
let current = anchor;
|
||||
/** SEQUEL entries of a media id, minus those already visited, best continuation first. */
|
||||
type SequelLookup = (id: number, visited: Set<number>) => Promise<AnilistSeasonMedia[]>;
|
||||
|
||||
for (let hop = 0; hop < hops; hop += 1) {
|
||||
// Transport errors propagate: a failed hop must not be mistaken for "no sequel exists".
|
||||
/**
|
||||
* Relation lookups for one resolution, memoized so the episode remap does not refetch
|
||||
* what the chain walk already loaded. Sorted with a season over a special, then the TV
|
||||
* line over other formats, then the earliest. Transport errors propagate: a failed lookup
|
||||
* must not be mistaken for "no sequel exists".
|
||||
*/
|
||||
function createSequelLookup(deps: ResolveAnilistSeasonMediaDeps): SequelLookup {
|
||||
const cache = new Map<number, Promise<AnilistSeasonMedia[]>>();
|
||||
const load = async (id: number): Promise<AnilistSeasonMedia[]> => {
|
||||
const response = await deps.execute<AnilistSeasonRelationsResponse>(
|
||||
ANILIST_SEASON_RELATIONS_QUERY,
|
||||
{ id: current.id },
|
||||
{ id },
|
||||
);
|
||||
|
||||
const sequels = (response.Media?.relations?.edges ?? [])
|
||||
.map((edge) => edge ?? null)
|
||||
.filter(
|
||||
(
|
||||
edge,
|
||||
): edge is {
|
||||
relationType?: string | null;
|
||||
node: AnilistSeasonMedia & { type?: string | null };
|
||||
} =>
|
||||
Boolean(edge?.node) &&
|
||||
(edge?.relationType || '').toUpperCase() === 'SEQUEL' &&
|
||||
(edge?.node?.type || 'ANIME').toUpperCase() === 'ANIME',
|
||||
)
|
||||
.map((edge) => edge.node)
|
||||
.filter((node) => !visited.has(node.id));
|
||||
|
||||
if (sequels.length === 0) {
|
||||
return null;
|
||||
const sequels: AnilistSeasonMedia[] = [];
|
||||
for (const edge of response.Media?.relations?.edges ?? []) {
|
||||
const node = edge?.node;
|
||||
if (!node || typeof node.id !== 'number') continue;
|
||||
if ((edge.relationType || '').toUpperCase() !== 'SEQUEL') continue;
|
||||
if ((node.type || 'ANIME').toUpperCase() !== 'ANIME') continue;
|
||||
sequels.push(node);
|
||||
}
|
||||
|
||||
// A franchise can branch (a TV sequel plus an ONA spinoff); prefer the TV line.
|
||||
sequels.sort((a, b) => {
|
||||
return sequels.sort((a, b) => {
|
||||
const rankDelta = formatRank(a) - formatRank(b);
|
||||
if (rankDelta !== 0) return rankDelta;
|
||||
const yearDelta =
|
||||
@@ -300,12 +470,121 @@ async function walkSequelChain(
|
||||
if (yearDelta !== 0) return yearDelta;
|
||||
return a.id - b.id;
|
||||
});
|
||||
};
|
||||
return async (id, visited) => {
|
||||
let pending = cache.get(id);
|
||||
if (!pending) {
|
||||
pending = load(id);
|
||||
cache.set(id, pending);
|
||||
// A failed lookup is retried by the next caller rather than cached.
|
||||
pending.catch(() => cache.delete(id));
|
||||
}
|
||||
return (await pending).filter((node) => !visited.has(node.id));
|
||||
};
|
||||
}
|
||||
|
||||
current = sequels[0]!;
|
||||
visited.add(current.id);
|
||||
type ChainResult = { media: AnilistSeasonMedia; via: 'named-season' | 'sequel-chain' };
|
||||
|
||||
async function walkSequelChain(
|
||||
anchor: AnilistSeasonMedia,
|
||||
season: number,
|
||||
sequelsOf: SequelLookup,
|
||||
): Promise<ChainResult | null> {
|
||||
// Advancing fewer seasons than requested would land on the wrong one and report it as
|
||||
// resolved, so refuse instead and let the caller fall through to its guarded fallback.
|
||||
const targetAdvances = season - 1;
|
||||
if (targetAdvances > MAX_SEQUEL_HOPS) {
|
||||
return null;
|
||||
}
|
||||
const visited = new Set<number>([anchor.id]);
|
||||
let current = anchor;
|
||||
// The last entry that counted as a season.
|
||||
let seasonStart = anchor;
|
||||
let advances = 0;
|
||||
// The unnamed entry the count landed on. The walk looks one season further before
|
||||
// accepting it, because an entry naming the requested season outranks the count: the
|
||||
// counted entry may be a continuation with no marker.
|
||||
let counted: AnilistSeasonMedia | null = null;
|
||||
// Set once counting reached the requested season on an entry whose title names a
|
||||
// different one. Only a named match can answer after that.
|
||||
let countContradicted = false;
|
||||
|
||||
for (let step = 0; step < MAX_SEQUEL_STEPS; step += 1) {
|
||||
const next = (await sequelsOf(current.id, visited))[0];
|
||||
if (!next) break;
|
||||
current = next;
|
||||
visited.add(next.id);
|
||||
|
||||
// Specials, movies and OVAs are walked through, because the rest of the franchise
|
||||
// hangs off them, but never counted.
|
||||
if (!isSeasonEntry(next)) continue;
|
||||
|
||||
const named = namedSeasons(next);
|
||||
if (isSeasonContinuation(seasonStart, next, advances + 1)) {
|
||||
// A back half naming the requested season ("Season 3 Part 2") vouches for the
|
||||
// entry its season started on.
|
||||
if (named.has(season)) return { media: seasonStart, via: 'named-season' };
|
||||
continue;
|
||||
}
|
||||
if (named.has(season)) return { media: next, via: 'named-season' };
|
||||
// The season after the counted one does not claim the requested number either.
|
||||
if (counted) break;
|
||||
if (countContradicted) {
|
||||
// Past the requested season by name: it is not on this chain.
|
||||
if ([...named].some((value) => value > season)) return null;
|
||||
continue;
|
||||
}
|
||||
|
||||
advances += 1;
|
||||
seasonStart = next;
|
||||
if (advances === targetAdvances) {
|
||||
if (named.size === 0) counted = next;
|
||||
else countContradicted = true;
|
||||
}
|
||||
}
|
||||
|
||||
return current.id === anchor.id ? null : current;
|
||||
return counted ? { media: counted, via: 'sequel-chain' } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the parsed episode runs past `seasonEntry` into a later part of the same season,
|
||||
* and if so, which entry airs it and at what episode number. Null when the episode fits
|
||||
* the season entry, its length is unknown, or no continuation covers the episode (e.g.
|
||||
* absolute numbering across seasons).
|
||||
*/
|
||||
async function findEpisodeEntry(
|
||||
seasonEntry: AnilistSeasonMedia,
|
||||
season: number,
|
||||
episode: number,
|
||||
sequelsOf: SequelLookup,
|
||||
): Promise<{ media: AnilistSeasonMedia; episode: number } | null> {
|
||||
const seasonLength = episodeCount(seasonEntry);
|
||||
if (seasonLength === null || episode <= seasonLength) return null;
|
||||
|
||||
const visited = new Set<number>([seasonEntry.id]);
|
||||
let current = seasonEntry;
|
||||
// The last part whose episodes are still counted in `remaining`; its length is known.
|
||||
let lastPart = seasonEntry;
|
||||
let remaining = episode;
|
||||
let parts = 1;
|
||||
|
||||
for (let step = 0; step < MAX_SEQUEL_STEPS; step += 1) {
|
||||
const next = (await sequelsOf(current.id, visited))[0];
|
||||
if (!next) return null;
|
||||
visited.add(next.id);
|
||||
current = next;
|
||||
// A recap special between the two halves airs none of the season's episodes.
|
||||
if (!isSeasonEntry(next)) continue;
|
||||
if (!isSeasonContinuation(seasonEntry, next, season)) return null;
|
||||
|
||||
remaining -= episodeCount(lastPart) ?? 0;
|
||||
lastPart = next;
|
||||
parts += 1;
|
||||
const length = episodeCount(next);
|
||||
if (length === null || remaining <= length) return { media: next, episode: remaining };
|
||||
if (parts >= MAX_SEASON_PARTS) return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -317,24 +596,45 @@ export function pickByAirOrder(
|
||||
season: number,
|
||||
media: AnilistSeasonMedia[],
|
||||
): AnilistSeasonMedia | null {
|
||||
const anchorTitles = mediaTitles(anchor).map((value) => stripSeasonSuffix(value));
|
||||
const anchorBase = anchorTitles.sort((a, b) => a.length - b.length)[0];
|
||||
if (!anchorBase) return null;
|
||||
// Any of the anchor's main titles, matched on word boundaries. Synonyms are too short
|
||||
// and loose ("SnK", "ReZero") to define a franchise, and a single title misses entries
|
||||
// that only spell another one out (Mushoku Tensei II's native title adds "Ⅱ" to the
|
||||
// word the season 1 native title ends on).
|
||||
const anchorBases = mainTitles(anchor)
|
||||
.map((value) => stripSeasonSuffix(value))
|
||||
.filter((value) => value.length > 0);
|
||||
if (anchorBases.length === 0) return null;
|
||||
|
||||
const franchise = media.filter((entry) => {
|
||||
if (!isSeasonalFormat(entry)) return false;
|
||||
if (!isSeasonEntry(entry)) return false;
|
||||
if (entry.id === anchor.id) return true;
|
||||
return mediaTitles(entry).some((candidate) =>
|
||||
stripSeasonSuffix(candidate).includes(anchorBase),
|
||||
return mediaTitles(entry).some((candidate) => {
|
||||
const padded = ` ${stripSeasonSuffix(candidate)} `;
|
||||
return anchorBases.some((base) => padded.includes(` ${base} `));
|
||||
});
|
||||
});
|
||||
|
||||
// Drop the back halves of split-cour seasons, which are separate entries here but not
|
||||
// separate seasons: counting them shifts every later season index. An entry is only
|
||||
// compared against the *other* entries' titles, so a season whose own localized synonym
|
||||
// spells it "<season> Part 1" is kept.
|
||||
const seasons = franchise.filter((entry) => {
|
||||
if (entry.id === anchor.id) return true;
|
||||
// The anchor is season 1 here, which lets the continuation check reject an entry
|
||||
// naming another season even when the anchor's own titles name none.
|
||||
return !franchise.some(
|
||||
(other) =>
|
||||
other.id !== entry.id &&
|
||||
isSeasonContinuation(other, entry, other.id === anchor.id ? 1 : null),
|
||||
);
|
||||
});
|
||||
if (franchise.length < season) return null;
|
||||
if (seasons.length < season) return null;
|
||||
|
||||
// Ordering by air date is only meaningful when every entry has one: an unknown year
|
||||
// would sort last and shift the season index while still reporting a resolved match.
|
||||
if (franchise.some((entry) => airYear(entry) === null)) return null;
|
||||
if (seasons.some((entry) => airYear(entry) === null)) return null;
|
||||
|
||||
const ordered = [...franchise].sort((a, b) => {
|
||||
const ordered = [...seasons].sort((a, b) => {
|
||||
const yearDelta = (airYear(a) ?? 0) - (airYear(b) ?? 0);
|
||||
if (yearDelta !== 0) return yearDelta;
|
||||
return a.id - b.id;
|
||||
@@ -343,7 +643,12 @@ export function pickByAirOrder(
|
||||
// The anchor has to be the first entry, otherwise this ordering is not a season list.
|
||||
if (ordered[0]?.id !== anchor.id) return null;
|
||||
|
||||
return ordered[season - 1] ?? null;
|
||||
const picked = ordered[season - 1] ?? null;
|
||||
if (!picked) return null;
|
||||
// An entry that names some other season shows this ordering is off.
|
||||
const named = namedSeasons(picked);
|
||||
if (named.size > 0 && !named.has(season)) return null;
|
||||
return picked;
|
||||
}
|
||||
|
||||
export async function resolveAnilistSeasonMedia(
|
||||
@@ -359,6 +664,10 @@ export async function resolveAnilistSeasonMedia(
|
||||
typeof input.season === 'number' && Number.isInteger(input.season) && input.season > 0
|
||||
? input.season
|
||||
: null;
|
||||
const episode =
|
||||
typeof input.episode === 'number' && Number.isInteger(input.episode) && input.episode > 0
|
||||
? input.episode
|
||||
: null;
|
||||
|
||||
const response = await deps.execute<AnilistSeasonSearchResponse>(ANILIST_SEASON_SEARCH_QUERY, {
|
||||
search: searchTitle,
|
||||
@@ -368,72 +677,83 @@ export async function resolveAnilistSeasonMedia(
|
||||
);
|
||||
if (media.length === 0) return null;
|
||||
|
||||
// Season 1 (or unknown) resolves against the episode count; later seasons must not,
|
||||
// because the anchor is season 1 and may be shorter than the requested episode.
|
||||
const anchor = pickAnchorMedia(searchTitle, media, {
|
||||
episode: season === null || season <= 1 ? input.episode : null,
|
||||
});
|
||||
if (!anchor) return null;
|
||||
// Certifies the media actually returned, never the anchor on its behalf: a
|
||||
// sequel-chain hop can land one season short (split-cour entries) while the
|
||||
// anchor title still matches perfectly, and that certainty must not carry
|
||||
// over to the hopped-to entry.
|
||||
const exactMatchFor = (candidate: AnilistSeasonMedia): boolean => {
|
||||
const titles = mediaTitles(candidate);
|
||||
return (
|
||||
titles.includes(normalizeTitleIdentity(searchTitle)) ||
|
||||
titles.includes(normalizeTitleIdentity(input.title))
|
||||
);
|
||||
// Certifies the media actually returned, never the anchor on its behalf: a hop can land
|
||||
// on the wrong entry while the anchor title still matches perfectly, and that certainty
|
||||
// must not carry over to the hopped-to entry.
|
||||
const parsedTitles = [searchTitle, input.title];
|
||||
const sequelsOf = createSequelLookup(deps);
|
||||
|
||||
const finish = (
|
||||
seasonEntry: AnilistSeasonMedia,
|
||||
via: AnilistSeasonResolutionVia,
|
||||
split: { media: AnilistSeasonMedia; episode: number } | null = null,
|
||||
seasonResolved = true,
|
||||
): AnilistSeasonResolution => {
|
||||
if (split) {
|
||||
deps.logInfo?.(
|
||||
`[anilist] episode ${episode} of "${searchTitle}" is episode ${split.episode} of ${displayTitle(split.media, searchTitle)} (${split.media.id})`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
id: seasonEntry.id,
|
||||
title: displayTitle(seasonEntry, searchTitle),
|
||||
episodes: episodeCount(seasonEntry),
|
||||
media: seasonEntry,
|
||||
seasonResolved,
|
||||
requestedSeason: season,
|
||||
via,
|
||||
exactTitleMatch: exactMatchFor(seasonEntry, parsedTitles),
|
||||
episodeEntry: split
|
||||
? {
|
||||
id: split.media.id,
|
||||
title: displayTitle(split.media, searchTitle),
|
||||
episodes: episodeCount(split.media),
|
||||
media: split.media,
|
||||
episode: split.episode,
|
||||
exactTitleMatch: exactMatchFor(split.media, parsedTitles),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
};
|
||||
|
||||
if (season === null || season <= 1) {
|
||||
return toResolution(anchor, searchTitle, season, 'anchor', true, exactMatchFor(anchor));
|
||||
// The best title match first. If the episode runs past it, a split-cour continuation
|
||||
// may air it ("S1E15" of 11 + 12). Only when none does, and the title match is not a
|
||||
// season itself (a same-titled movie or special), is the episode count used to pick
|
||||
// a longer entry; it must not swap season 1 for a later, longer season.
|
||||
const titleAnchor = pickAnchorMedia(searchTitle, media);
|
||||
if (!titleAnchor) return null;
|
||||
if (episode === null) return finish(titleAnchor, 'anchor');
|
||||
const split = await findEpisodeEntry(titleAnchor, 1, episode, sequelsOf);
|
||||
if (split) return finish(titleAnchor, 'anchor', split);
|
||||
if (isSeasonEntry(titleAnchor)) return finish(titleAnchor, 'anchor');
|
||||
const fitted = pickAnchorMedia(searchTitle, media, { episode });
|
||||
const laterSeason = fitted !== null && [...namedSeasons(fitted)].some((value) => value > 1);
|
||||
return finish(fitted && !laterSeason ? fitted : titleAnchor, 'anchor');
|
||||
}
|
||||
|
||||
let chainError: unknown = null;
|
||||
let viaChain: AnilistSeasonMedia | null = null;
|
||||
try {
|
||||
viaChain = await walkSequelChain(anchor, season, deps);
|
||||
} catch (error) {
|
||||
chainError = error;
|
||||
}
|
||||
if (viaChain) {
|
||||
// Later seasons must not filter by episode, because the anchor is season 1 and may be
|
||||
// shorter than the requested episode.
|
||||
const anchor = pickAnchorMedia(searchTitle, media);
|
||||
if (!anchor) return null;
|
||||
|
||||
// Transport failures propagate from here: the air-order fallback is for a chain that
|
||||
// answered and had no edge to follow, and running it after a failed hop would turn a
|
||||
// rate limit into a confident wrong season.
|
||||
const viaChain = await walkSequelChain(anchor, season, sequelsOf);
|
||||
const seasonEntry = viaChain?.media ?? pickByAirOrder(anchor, season, media);
|
||||
if (seasonEntry) {
|
||||
const via = viaChain?.via ?? 'air-order';
|
||||
deps.logInfo?.(
|
||||
`[anilist] season ${season} of "${searchTitle}" resolved via sequel chain: ${displayTitle(viaChain, searchTitle)} (${viaChain.id})`,
|
||||
`[anilist] season ${season} of "${searchTitle}" resolved via ${via}: ${displayTitle(seasonEntry, searchTitle)} (${seasonEntry.id})`,
|
||||
);
|
||||
return toResolution(
|
||||
viaChain,
|
||||
searchTitle,
|
||||
season,
|
||||
'sequel-chain',
|
||||
true,
|
||||
exactMatchFor(viaChain),
|
||||
);
|
||||
}
|
||||
|
||||
const viaAirOrder = pickByAirOrder(anchor, season, media);
|
||||
if (viaAirOrder) {
|
||||
deps.logInfo?.(
|
||||
`[anilist] season ${season} of "${searchTitle}" resolved via air order: ${displayTitle(viaAirOrder, searchTitle)} (${viaAirOrder.id})`,
|
||||
);
|
||||
return toResolution(
|
||||
viaAirOrder,
|
||||
searchTitle,
|
||||
season,
|
||||
'air-order',
|
||||
true,
|
||||
exactMatchFor(viaAirOrder),
|
||||
);
|
||||
}
|
||||
|
||||
// The chain failed for transport reasons rather than because the season is absent;
|
||||
// surface that so callers retry instead of reporting an unresolvable season.
|
||||
if (chainError) {
|
||||
throw chainError;
|
||||
const split =
|
||||
episode === null ? null : await findEpisodeEntry(seasonEntry, season, episode, sequelsOf);
|
||||
return finish(seasonEntry, via, split);
|
||||
}
|
||||
|
||||
deps.logInfo?.(
|
||||
`[anilist] could not resolve season ${season} of "${searchTitle}"; falling back to ${displayTitle(anchor, searchTitle)} (${anchor.id})`,
|
||||
);
|
||||
return toResolution(anchor, searchTitle, season, 'anchor', false, exactMatchFor(anchor));
|
||||
return finish(anchor, 'anchor', null, false);
|
||||
}
|
||||
@@ -2949,6 +2949,38 @@ test('Jellyfin metadata refresh preserves a manual episode assignment', async ()
|
||||
}
|
||||
});
|
||||
|
||||
test('mpv media-title updates do not overwrite a Jellyfin video title', async () => {
|
||||
const dbPath = makeDbPath();
|
||||
let tracker: ImmersionTrackerService | null = null;
|
||||
|
||||
try {
|
||||
const Ctor = await loadTrackerCtor();
|
||||
tracker = new Ctor({ dbPath });
|
||||
const streamUrl = 'http://jellyfin.local/Videos/item-3/stream?static=true&api_key=token';
|
||||
tracker.recordJellyfinPlaybackMetadata({
|
||||
mediaPath: streamUrl,
|
||||
displayTitle: 'Show S01E03 Third',
|
||||
itemTitle: 'Third',
|
||||
seriesTitle: 'Show',
|
||||
seasonNumber: 1,
|
||||
episodeNumber: 3,
|
||||
itemId: 'item-3',
|
||||
});
|
||||
tracker.handleMediaChange(streamUrl, 'Show S01E03 Third');
|
||||
// mpv restores the previous episode's title as it leaves this playlist entry.
|
||||
tracker.handleMediaTitleUpdate('Show S01E02 Second');
|
||||
tracker.handleMediaChange(streamUrl, 'Show S01E02 Second');
|
||||
|
||||
const row = (tracker as unknown as { db: DatabaseSync }).db
|
||||
.prepare('SELECT canonical_title AS title FROM imm_videos')
|
||||
.get() as { title: string };
|
||||
assert.equal(row.title, 'Show S01E03 Third');
|
||||
} finally {
|
||||
tracker?.destroy();
|
||||
cleanupDbPath(dbPath);
|
||||
}
|
||||
});
|
||||
|
||||
test('startup repairs existing Jellyfin stream video links to metadata rows', async () => {
|
||||
const dbPath = makeDbPath();
|
||||
let tracker: ImmersionTrackerService | null = null;
|
||||
|
||||
@@ -4,6 +4,18 @@ import { createLogger } from '../../logger';
|
||||
import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity';
|
||||
import { MediaGenerator } from '../../media-generator';
|
||||
import type { CoverArtFetcher } from './anilist/cover-art-fetcher';
|
||||
import type { AnilistRelationFetcher } from './anilist/franchise-relation-fetcher';
|
||||
import {
|
||||
createFranchiseRelationRefresher,
|
||||
type FranchiseRelationRefresher,
|
||||
} from './immersion-tracker/franchise-relation-refresher';
|
||||
import {
|
||||
getAnimeGroupPlacement,
|
||||
getAnimeLibraryGroups,
|
||||
setAnimeGroupOverride,
|
||||
type AnimeGroupOverrideResult,
|
||||
type AnimeGroupOverrideTarget,
|
||||
} from './immersion-tracker/query-library-groups';
|
||||
import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata';
|
||||
import {
|
||||
pruneRawRetention,
|
||||
@@ -61,6 +73,7 @@ import type {
|
||||
StatsTrendGroupBy,
|
||||
StatsTrendRange,
|
||||
} from '../../types/stats-http-contract';
|
||||
import type { AnimeGroupPlacement, AnimeLibraryGroup } from '../../types/stats-wire';
|
||||
import {
|
||||
getKanjiAnimeAppearances,
|
||||
getKanjiDetail,
|
||||
@@ -452,6 +465,7 @@ export class ImmersionTrackerService {
|
||||
private readonly mediaGenerator = new MediaGenerator();
|
||||
private readonly preparedStatements: TrackerPreparedStatements;
|
||||
private coverArtFetcher: CoverArtFetcher | null = null;
|
||||
private franchiseRelations: FranchiseRelationRefresher | null = null;
|
||||
private readonly pendingCoverFetches = new Map<number, Promise<boolean>>();
|
||||
private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>();
|
||||
private readonly recordedSubtitleKeys = new Set<string>();
|
||||
@@ -621,6 +635,7 @@ export class ImmersionTrackerService {
|
||||
}
|
||||
this.finalizeActiveSession();
|
||||
this.isDestroyed = true;
|
||||
this.franchiseRelations?.stop();
|
||||
this.deleteMaintenanceScheduler.destroy();
|
||||
this.destroyDeleteMaintenanceRunner();
|
||||
this.destroyVocabularySummaryRunner();
|
||||
@@ -833,6 +848,27 @@ export class ImmersionTrackerService {
|
||||
return getAnimeLibrary(this.db);
|
||||
}
|
||||
|
||||
/** The library as franchise cards; also schedules a background AniList relation refresh. */
|
||||
async getAnimeLibraryGroups(): Promise<AnimeLibraryGroup[]> {
|
||||
this.relinkYoutubeAnimeLibrary();
|
||||
const groups = getAnimeLibraryGroups(this.db);
|
||||
this.franchiseRelations?.requestRefresh();
|
||||
return groups;
|
||||
}
|
||||
|
||||
async getAnimeGroupPlacement(animeId: number): Promise<AnimeGroupPlacement | null> {
|
||||
return getAnimeGroupPlacement(this.db, animeId);
|
||||
}
|
||||
|
||||
async setAnimeGroupOverride(
|
||||
animeId: number,
|
||||
target: AnimeGroupOverrideTarget,
|
||||
): Promise<AnimeGroupOverrideResult> {
|
||||
const result = setAnimeGroupOverride(this.db, animeId, target);
|
||||
if (result.ok) this.franchiseRelations?.requestRefresh({ force: true });
|
||||
return result;
|
||||
}
|
||||
|
||||
async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> {
|
||||
return getAnimeMergeRecommendations(this.db);
|
||||
}
|
||||
@@ -1122,6 +1158,7 @@ export class ImmersionTrackerService {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
this.franchiseRelations?.requestRefresh({ force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1248,6 +1285,19 @@ export class ImmersionTrackerService {
|
||||
this.coverArtFetcher = fetcher;
|
||||
}
|
||||
|
||||
/** Enables franchise grouping refreshes; null disables them (tests, offline runs). */
|
||||
setAnilistRelationFetcher(fetcher: AnilistRelationFetcher | null): void {
|
||||
this.franchiseRelations?.stop();
|
||||
this.franchiseRelations = fetcher
|
||||
? createFranchiseRelationRefresher({
|
||||
db: this.db,
|
||||
fetcher,
|
||||
logger: createLogger('immersion-tracker:franchise-relations'),
|
||||
})
|
||||
: null;
|
||||
this.franchiseRelations?.requestRefresh();
|
||||
}
|
||||
|
||||
async ensureAnimeCoverArt(animeId: number): Promise<boolean> {
|
||||
const existing = await this.getAnimeCoverArt(animeId);
|
||||
if (existing?.coverBlob) {
|
||||
@@ -1300,6 +1350,8 @@ export class ImmersionTrackerService {
|
||||
if (!fetched) {
|
||||
return false;
|
||||
}
|
||||
// A fresh AniList link may join this entry to a franchise card.
|
||||
this.franchiseRelations?.requestRefresh({ force: true });
|
||||
const cover = await this.getCoverArt(videoId);
|
||||
return cover?.coverBlob != null;
|
||||
})();
|
||||
@@ -2412,6 +2464,9 @@ export class ImmersionTrackerService {
|
||||
|
||||
private updateVideoTitleForActiveSession(canonicalTitle: string): void {
|
||||
if (!this.sessionState) return;
|
||||
// Jellyfin's title is authoritative. mpv's media-title can still name the previous playlist
|
||||
// entry while it switches files, so it must not overwrite a Jellyfin video's title.
|
||||
if (this.hasJellyfinMetadata(this.sessionState.videoId)) return;
|
||||
updateVideoTitleRecord(this.db, this.sessionState.videoId, canonicalTitle);
|
||||
}
|
||||
}
|
||||
@@ -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 * as fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { parseMediaInfo } from '../../../jimaku/utils';
|
||||
import { parseMediaLookupInfo } from '../../../jimaku/utils';
|
||||
import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../../../shared/media-identity';
|
||||
import {
|
||||
guessAnilistMediaInfo,
|
||||
@@ -214,7 +214,7 @@ export async function guessAnimeVideoMetadata(
|
||||
};
|
||||
}
|
||||
|
||||
const fallbackInfo = parseMediaInfo(lookupTarget);
|
||||
const fallbackInfo = parseMediaLookupInfo(mediaPath, mediaTitle);
|
||||
return {
|
||||
parsedBasename: parsedBasename ?? fallbackInfo.filename ?? null,
|
||||
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 { createHash } from 'node:crypto';
|
||||
import path from 'node:path';
|
||||
import { parseMediaInfo } from '../../../jimaku/utils';
|
||||
import { parseMediaInfo, parseMediaTitleInfo } from '../../../jimaku/utils';
|
||||
import { normalizeTitleIdentity } from '../../utils/title-normalization';
|
||||
import type { DatabaseSync } from './sqlite';
|
||||
import { nowMs } from './time';
|
||||
@@ -10,6 +10,7 @@ import { isVocabularyStatsRowVisible, type VocabularyVisibilityRow } from './voc
|
||||
import { SCHEMA_VERSION } from './types';
|
||||
import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types';
|
||||
import { toDbTimestamp } from './query-shared';
|
||||
import { ensureAnimeGroupingSchema } from './anilist-relation-cache';
|
||||
|
||||
export interface TrackerPreparedStatements {
|
||||
telemetryInsertStmt: ReturnType<DatabaseSync['prepare']>;
|
||||
@@ -404,7 +405,7 @@ function parseLegacyAnimeBackfillCandidate(
|
||||
|
||||
const fallbackTitle = canonicalTitle.trim();
|
||||
if (!fallbackTitle) return null;
|
||||
const fromTitle = parseMediaInfo(fallbackTitle);
|
||||
const fromTitle = parseMediaTitleInfo(fallbackTitle);
|
||||
if (!fromTitle.title || looksLikeEpisodeOnlyTitle(fromTitle.title)) {
|
||||
return null;
|
||||
}
|
||||
@@ -998,6 +999,7 @@ export function ensureSchema(db: DatabaseSync): void {
|
||||
ensureLifetimeSummaryTables(db);
|
||||
ensureStatsExcludedWordsTable(db);
|
||||
ensureAnimeMergeTables(db);
|
||||
ensureAnimeGroupingSchema(db);
|
||||
ensureSubtitleLineEventIndex(db);
|
||||
return;
|
||||
}
|
||||
@@ -1064,6 +1066,8 @@ export function ensureSchema(db: DatabaseSync): void {
|
||||
'INTEGER NOT NULL DEFAULT 0 CHECK(anime_assignment_locked IN (0, 1))',
|
||||
);
|
||||
ensureAnimeMergeTables(db);
|
||||
// Schema 27: franchise grouping (AniList relation cache + per-entry override).
|
||||
ensureAnimeGroupingSchema(db);
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS imm_sessions(
|
||||
session_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { MediaKind, TmdbMediaType } from '../../../shared/media-kind';
|
||||
|
||||
// 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_BATCH_SIZE = 25;
|
||||
export const DEFAULT_FLUSH_INTERVAL_MS = 500;
|
||||
|
||||
@@ -128,6 +128,7 @@ export {
|
||||
authenticateWithPassword as authenticateWithPasswordRuntime,
|
||||
listItems as listJellyfinItemsRuntime,
|
||||
listLibraries as listJellyfinLibrariesRuntime,
|
||||
listSeriesEpisodeIds as listJellyfinSeriesEpisodeIdsRuntime,
|
||||
listSubtitleTracks as listJellyfinSubtitleTracksRuntime,
|
||||
resolvePlaybackPlan as resolveJellyfinPlaybackPlanRuntime,
|
||||
ticksToSeconds as jellyfinTicksToSecondsRuntime,
|
||||
|
||||
@@ -40,10 +40,14 @@ import {
|
||||
parseSessionActionDispatchRequest,
|
||||
parseSubtitlePosition,
|
||||
parseSubsyncManualRunRequest,
|
||||
parseUnforwardedMpvKeyReport,
|
||||
parseYoutubePickerResolveRequest,
|
||||
} from '../../shared/ipc/validators';
|
||||
import { createLogger } from '../../logger';
|
||||
import { applyOverlayClickThrough } from './overlay-click-through';
|
||||
|
||||
const overlayInputLogger = createLogger('overlay:input');
|
||||
|
||||
const { ipcMain } = electron;
|
||||
|
||||
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) => {
|
||||
try {
|
||||
deps.recordSubtitleMiningContext?.(parseSubtitleMiningContext(payload));
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
authenticateWithPassword,
|
||||
listItems,
|
||||
listLibraries,
|
||||
listSeriesEpisodeIds,
|
||||
listSubtitleTracks,
|
||||
resolvePlaybackPlan,
|
||||
ticksToSeconds,
|
||||
@@ -886,3 +887,37 @@ test('toJellyfinOriginalStreamUrl maps direct and transcoded playback to the ori
|
||||
assert.equal(toJellyfinOriginalStreamUrl('https://jf/Videos/item-1/stream', 'item-1'), null);
|
||||
assert.equal(toJellyfinOriginalStreamUrl('/media/item-1.mkv', 'item-1'), null);
|
||||
});
|
||||
|
||||
test('listSeriesEpisodeIds returns playable episodes in series order', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let requestedUrl = '';
|
||||
globalThis.fetch = (async (input) => {
|
||||
requestedUrl = String(input);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
Items: [
|
||||
{ Id: 'ep-1', LocationType: 'FileSystem' },
|
||||
{ Id: 'ep-2', LocationType: 'Virtual' },
|
||||
{ Id: 'ep-3', LocationType: 'FileSystem' },
|
||||
{ Name: 'no id' },
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
);
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const ids = await listSeriesEpisodeIds(
|
||||
{ serverUrl: 'http://jellyfin.local', accessToken: 'token', userId: 'u1', username: 'kyle' },
|
||||
clientInfo,
|
||||
'series-1',
|
||||
);
|
||||
assert.deepEqual(ids, ['ep-1', 'ep-3']);
|
||||
const url = new URL(requestedUrl);
|
||||
assert.equal(url.pathname, '/Shows/series-1/Episodes');
|
||||
assert.equal(url.searchParams.get('UserId'), 'u1');
|
||||
assert.equal(url.searchParams.get('IsMissing'), 'false');
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
@@ -29,6 +29,8 @@ export interface JellyfinPlaybackPlan {
|
||||
title: string;
|
||||
itemTitle: string;
|
||||
seriesTitle: string | null;
|
||||
/** Set for episodes; lets playback queue the series' neighboring episodes. */
|
||||
seriesId: string | null;
|
||||
seasonNumber: number | null;
|
||||
episodeNumber: number | null;
|
||||
startTimeTicks: number;
|
||||
@@ -89,6 +91,8 @@ interface JellyfinItem {
|
||||
Name?: string;
|
||||
Type?: string;
|
||||
SeriesName?: string;
|
||||
SeriesId?: string;
|
||||
LocationType?: string;
|
||||
ParentIndexNumber?: number;
|
||||
IndexNumber?: number;
|
||||
UserData?: JellyfinItemUserData;
|
||||
@@ -579,6 +583,7 @@ export async function resolvePlaybackPlan(
|
||||
title: getDisplayTitle(item),
|
||||
itemTitle,
|
||||
seriesTitle,
|
||||
seriesId: item.Type === 'Episode' ? ensureString(item.SeriesId).trim() || null : null,
|
||||
seasonNumber: item.Type === 'Episode' ? asIntegerOrNull(item.ParentIndexNumber) : null,
|
||||
episodeNumber: item.Type === 'Episode' ? asIntegerOrNull(item.IndexNumber) : null,
|
||||
startTimeTicks,
|
||||
@@ -611,6 +616,33 @@ export async function resolvePlaybackPlan(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists a series' episode ids in playback order. The order runs across season boundaries and
|
||||
* skips episodes the server only knows from metadata.
|
||||
*/
|
||||
export async function listSeriesEpisodeIds(
|
||||
session: JellyfinAuthSession,
|
||||
client: JellyfinClientInfo,
|
||||
seriesId: string,
|
||||
): Promise<string[]> {
|
||||
const query = new URLSearchParams({
|
||||
UserId: session.userId,
|
||||
IsMissing: 'false',
|
||||
EnableImages: 'false',
|
||||
EnableUserData: 'false',
|
||||
});
|
||||
const payload = await jellyfinRequestJson<JellyfinItemsResponse>(
|
||||
`/Shows/${encodeURIComponent(seriesId)}/Episodes?${query.toString()}`,
|
||||
{ method: 'GET' },
|
||||
session,
|
||||
client,
|
||||
);
|
||||
return (Array.isArray(payload.Items) ? payload.Items : [])
|
||||
.filter((item) => item.LocationType !== 'Virtual')
|
||||
.map((item) => ensureString(item.Id))
|
||||
.filter((id) => id.length > 0);
|
||||
}
|
||||
|
||||
export function ticksToSeconds(ticks: number): number {
|
||||
return Math.max(0, Math.floor(ticks / JELLYFIN_TICKS_PER_SECOND));
|
||||
}
|
||||
@@ -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), []);
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
enrichSessionsWithKnownWordMetrics,
|
||||
isPositiveSafeInteger,
|
||||
loadKnownWordsSet,
|
||||
parseAnimeGroupOverrideBody,
|
||||
parseBooleanQuery,
|
||||
parseDuplicateLineCleanupBody,
|
||||
parseExcludedWordsBody,
|
||||
@@ -190,6 +191,11 @@ export function registerStatsLibraryRoutes(
|
||||
return c.json(statsJson('animeLibrary', rows));
|
||||
});
|
||||
|
||||
// Registered before `/api/stats/anime/:animeId` so `groups` is not read as an id.
|
||||
app.get('/api/stats/anime/groups', async (c) => {
|
||||
return c.json(statsJson('animeLibraryGroups', await tracker.getAnimeLibraryGroups()));
|
||||
});
|
||||
|
||||
app.get('/api/stats/anime/merge-recommendations', async (c) => {
|
||||
const recommendations = await tracker.getAnimeMergeRecommendations();
|
||||
return c.json(statsJson('animeMergeRecommendations', { recommendations }));
|
||||
@@ -208,11 +214,12 @@ export function registerStatsLibraryRoutes(
|
||||
if (animeId === null) return c.body(null, 400);
|
||||
const detail = await tracker.getAnimeDetail(animeId);
|
||||
if (!detail) return c.body(null, 404);
|
||||
const [episodes, anilistEntries] = await Promise.all([
|
||||
const [episodes, anilistEntries, group] = await Promise.all([
|
||||
tracker.getAnimeEpisodes(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) => {
|
||||
@@ -267,6 +274,22 @@ export function registerStatsLibraryRoutes(
|
||||
return c.json(statsJson('deleteAnime', { ok: true }));
|
||||
});
|
||||
|
||||
app.put('/api/stats/anime/:animeId/group', async (c) => {
|
||||
const animeId = parsePositiveId(c.req.param('animeId'));
|
||||
if (animeId === null) return c.body(null, 400);
|
||||
const request = parseAnimeGroupOverrideBody(await c.req.json().catch(() => null));
|
||||
if (!request) return c.body(null, 400);
|
||||
if (request.mode === 'join' && request.targetAnimeId === animeId) return c.body(null, 400);
|
||||
const result = await tracker.setAnimeGroupOverride(animeId, request);
|
||||
if (result.ok) return c.json(statsJson('setAnimeGroupOverride', { ok: true }));
|
||||
if (result.reason === 'not-found') return c.body(null, 404);
|
||||
const error =
|
||||
result.reason === 'unsupported-kind'
|
||||
? 'Only anime entries can be grouped.'
|
||||
: 'That title has no AniList entry to group with. Link it to AniList or merge the entries instead.';
|
||||
return c.json(statsJson('error', { error }), 409);
|
||||
});
|
||||
|
||||
app.post('/api/stats/anime/:animeId/merge', async (c) => {
|
||||
const animeId = parsePositiveId(c.req.param('animeId'));
|
||||
if (animeId === null) return c.body(null, 400);
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import { createLogger } from '../../../logger.js';
|
||||
import type { AnkiConnectConfig } from '../../../types.js';
|
||||
import type {
|
||||
StatsAnimeGroupOverrideRequest,
|
||||
StatsDayRange,
|
||||
StatsDictionaryWordQuery,
|
||||
StatsDictionaryWordSort,
|
||||
@@ -59,6 +60,15 @@ export function isPositiveSafeInteger(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
/** Validates a `PUT /api/stats/anime/:animeId/group` body; null for anything malformed. */
|
||||
export function parseAnimeGroupOverrideBody(body: unknown): StatsAnimeGroupOverrideRequest | null {
|
||||
if (!body || typeof body !== 'object') return null;
|
||||
const { mode, targetAnimeId } = body as Record<string, unknown>;
|
||||
if (mode === 'standalone' || mode === 'anilist') return { mode };
|
||||
if (mode === 'join' && isPositiveSafeInteger(targetAnimeId)) return { mode, targetAnimeId };
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parsePositiveId(raw: string | undefined): number | null {
|
||||
if (raw === undefined) return null;
|
||||
const value = Number(raw);
|
||||
|
||||
@@ -58,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_type',
|
||||
'metadata_json',
|
||||
'group_override',
|
||||
'group_override_updated_at',
|
||||
'CREATED_DATE',
|
||||
'LAST_UPDATE_DATE',
|
||||
] as const;
|
||||
@@ -146,6 +148,13 @@ export function mergeAnime(
|
||||
END
|
||||
WHERE anime_id = ?`,
|
||||
);
|
||||
// The franchise override holds AniList ids (or 0 / NULL), so it needs no id
|
||||
// remapping. The side that set or cleared it last wins.
|
||||
const takeNewerGroupOverride = local.query(
|
||||
`UPDATE imm_anime SET group_override = ?, group_override_updated_at = ?
|
||||
WHERE anime_id = ? AND (group_override_updated_at IS NULL
|
||||
OR CAST(group_override_updated_at AS INTEGER) < CAST(? AS INTEGER))`,
|
||||
);
|
||||
|
||||
for (const row of selectAll(
|
||||
remote,
|
||||
@@ -195,6 +204,14 @@ export function mergeAnime(
|
||||
row.media_kind,
|
||||
localId,
|
||||
);
|
||||
if (row.group_override_updated_at !== null) {
|
||||
takeNewerGroupOverride.run(
|
||||
row.group_override,
|
||||
row.group_override_updated_at,
|
||||
localId,
|
||||
row.group_override_updated_at,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Conflicting providers can share a title, but the stored title key is
|
||||
|
||||
@@ -20,6 +20,11 @@ export type { SyncMergeSummary } from './shared';
|
||||
* are updated incrementally so history older than the session retention
|
||||
* window is preserved on both sides. Idempotent: re-merging the same
|
||||
* snapshot is a no-op.
|
||||
*
|
||||
* A library entry's franchise override (`group_override`) is last-writer-wins
|
||||
* by `group_override_updated_at`. The AniList relation cache
|
||||
* (`imm_anilist_media`, `imm_anilist_relations`) is not merged: each machine
|
||||
* rebuilds it from AniList.
|
||||
*/
|
||||
export function mergeSnapshotIntoDb(localDbPath: string, snapshotPath: string): SyncMergeSummary {
|
||||
if (!fs.existsSync(localDbPath)) {
|
||||
|
||||
@@ -18,12 +18,12 @@ export async function downloadSubtitleGenerationArtifact(input: {
|
||||
const temporaryDirectory = await mkdtemp(
|
||||
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}...` });
|
||||
try {
|
||||
const response = await fetch(input.url, { signal: input.signal });
|
||||
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 reader = response.body.getReader();
|
||||
@@ -36,7 +36,8 @@ export async function downloadSubtitleGenerationArtifact(input: {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
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);
|
||||
await file.writeFile(value);
|
||||
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) {
|
||||
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();
|
||||
} finally {
|
||||
|
||||
@@ -46,7 +46,11 @@ function executableNames(name: string, env: NodeJS.ProcessEnv): string[] {
|
||||
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 ?? '')
|
||||
.split(path.delimiter)
|
||||
.map((entry) => entry.trim())
|
||||
|
||||
@@ -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
@@ -4,6 +4,7 @@ import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as childProcess from 'child_process';
|
||||
import { createLogger } from '../logger';
|
||||
import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../shared/media-identity';
|
||||
import {
|
||||
JimakuApiResponse,
|
||||
JimakuConfig,
|
||||
@@ -202,22 +203,60 @@ function cleanupTitle(value: string): string {
|
||||
.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 {
|
||||
if (!mediaPath) {
|
||||
return {
|
||||
title: '',
|
||||
season: null,
|
||||
episode: null,
|
||||
confidence: 'low',
|
||||
filename: '',
|
||||
rawTitle: '',
|
||||
};
|
||||
}
|
||||
if (!mediaPath) return { ...EMPTY_MEDIA_INFO };
|
||||
|
||||
const normalizedMediaPath = normalizeMediaPathForJimaku(mediaPath);
|
||||
const filename = path.basename(normalizedMediaPath);
|
||||
let name = filename.replace(/\.[^/.]+$/, '');
|
||||
name = name.replace(/\[[^\]]*]/g, ' ');
|
||||
return parseMediaName(
|
||||
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(/[._]/g, ' ');
|
||||
name = name.replace(/[–—]/g, '-');
|
||||
@@ -229,12 +268,11 @@ export function parseMediaInfo(mediaPath: string | null): JimakuMediaInfo {
|
||||
titlePart = name.slice(0, parsed.index);
|
||||
}
|
||||
|
||||
const seasonFromDir = parsed.season ?? detectSeasonFromDir(normalizedMediaPath);
|
||||
const title = cleanupTitle(titlePart || name);
|
||||
|
||||
return {
|
||||
title,
|
||||
season: seasonFromDir,
|
||||
season: parsed.season ?? seasonFallback,
|
||||
episode: parsed.episode,
|
||||
confidence: parsed.confidence,
|
||||
filename,
|
||||
|
||||
+6
-2
@@ -71,7 +71,7 @@ import type {
|
||||
SubtitlePosition,
|
||||
} 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 {
|
||||
createLogger,
|
||||
setLogFileToggles,
|
||||
@@ -155,6 +155,7 @@ import { createSyncAssembly } from './main/assemblies/sync';
|
||||
import { createYoutubeAssembly } from './main/assemblies/youtube';
|
||||
import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals';
|
||||
import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup';
|
||||
import { appendManagedFfmpegToPath, getManagedFfmpegDir } from './core/services/managed-ffmpeg';
|
||||
import { createOverlayAssembly } from './main/assemblies/overlay';
|
||||
import { createYomitanAssembly } from './main/assemblies/yomitan';
|
||||
import { createStatsAssembly } from './main/assemblies/stats';
|
||||
@@ -428,6 +429,8 @@ const {
|
||||
appState,
|
||||
appLifecycleApp,
|
||||
} = 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.
|
||||
const activeDictionaryBackend = configService.getConfig().dictionaryBackend;
|
||||
const yomitan = createYomitanAssembly({
|
||||
@@ -688,6 +691,7 @@ const firstRunSetup = createFirstRunSetupAssembly({
|
||||
ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(),
|
||||
getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(),
|
||||
createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(),
|
||||
waitForLoginShellPath: () => loginShellPathReady,
|
||||
getAppPath: (name) => app.getPath(name),
|
||||
trashItem: (targetPath) => shell.trashItem(targetPath),
|
||||
writeShortcutLink: (shortcutPath, operation, details) =>
|
||||
@@ -1586,7 +1590,7 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
||||
setFieldGroupingResolver: (resolver: ((choice: KikuFieldGroupingChoice) => void) | null) =>
|
||||
mining.setFieldGroupingResolver(resolver),
|
||||
parseMediaInfo: (mediaPath: string | null) =>
|
||||
parseMediaInfo(mediaRuntime.resolveMediaPathForJimaku(mediaPath)),
|
||||
parseMediaLookupInfo(mediaPath, appState.currentMediaTitle),
|
||||
getCurrentMediaPath: () => appState.currentMediaPath,
|
||||
jimakuFetchJson: <T>(
|
||||
endpoint: string,
|
||||
|
||||
@@ -30,6 +30,7 @@ function makeDeps(configDir: string): FirstRunSetupAssemblyDeps {
|
||||
ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'),
|
||||
getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'),
|
||||
createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'),
|
||||
waitForLoginShellPath: lazy('waitForLoginShellPath'),
|
||||
getAppPath: lazy('getAppPath'),
|
||||
trashItem: lazy('trashItem'),
|
||||
writeShortcutLink: lazy('writeShortcutLink'),
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import os from 'node:os';
|
||||
import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron';
|
||||
import type { ConfigService } from '../../config/service';
|
||||
import {
|
||||
appendManagedFfmpegToPath,
|
||||
detectFfmpeg,
|
||||
getManagedFfmpegDir,
|
||||
installManagedFfmpeg,
|
||||
} from '../../core/services/managed-ffmpeg';
|
||||
import { getYomitanDictionaryInfo } from '../../core/services';
|
||||
import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime';
|
||||
import type { Logger } from '../../logger';
|
||||
@@ -62,6 +68,8 @@ export interface FirstRunSetupAssemblyDeps {
|
||||
getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps;
|
||||
/** Resolves the launcher options after the login-shell PATH is applied. */
|
||||
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;
|
||||
trashItem: (targetPath: string) => Promise<void>;
|
||||
writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink'];
|
||||
@@ -83,6 +91,23 @@ export type FirstRunSetupAssembly = ReturnType<typeof createFirstRunSetupAssembl
|
||||
export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
|
||||
const { appState, configService, logger } = deps;
|
||||
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 = () =>
|
||||
resolveWindowsMpvShortcutPaths({
|
||||
appDataDir: deps.getAppPath('appData'),
|
||||
@@ -232,6 +257,9 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
|
||||
mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath),
|
||||
windowsMpvShortcuts: snapshot.windowsMpvShortcuts,
|
||||
commandLineLauncher: snapshot.commandLineLauncher,
|
||||
ffmpeg: await deps
|
||||
.waitForLoginShellPath()
|
||||
.then(() => detectFfmpeg({ managedDir: managedFfmpegDir })),
|
||||
message: firstRunSetupMessage,
|
||||
};
|
||||
},
|
||||
@@ -304,6 +332,10 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
|
||||
firstRunSetupMessage = snapshot.message;
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'install-ffmpeg') {
|
||||
firstRunSetupMessage = await installFfmpeg();
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'open-yomitan-settings') {
|
||||
firstRunSetupMessage = deps.openDictionarySettings()
|
||||
? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.`
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
JellyfinPlaybackReporter,
|
||||
JellyfinRemoteSessionService,
|
||||
jellyfinTicksToSecondsRuntime,
|
||||
listJellyfinSeriesEpisodeIdsRuntime,
|
||||
listJellyfinItemsRuntime,
|
||||
listJellyfinLibrariesRuntime,
|
||||
listJellyfinSubtitleTracksRuntime,
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
mergeJellyfinRecentServers,
|
||||
parseJellyfinSetupSubmissionUrl,
|
||||
persistJellyfinAuthSession,
|
||||
markJellyfinRemotePlaybackLoaded,
|
||||
type ActiveJellyfinRemotePlaybackState,
|
||||
} from '../runtime/domains/jellyfin';
|
||||
import { detectInstalledMpvPlugin } from '../runtime/first-run-setup-plugin';
|
||||
@@ -140,6 +142,7 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
|
||||
runJellyfinCommand,
|
||||
openJellyfinSetupWindow,
|
||||
ensureMpvConnectedForPlayback,
|
||||
playJellyfinItemInMpv,
|
||||
} = composeJellyfinRuntimeHandlers({
|
||||
getResolvedJellyfinConfigMainDeps: {
|
||||
getResolvedConfig: () => configService.getConfig(),
|
||||
@@ -237,6 +240,7 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
|
||||
setTimeout(callback, delayMs);
|
||||
},
|
||||
convertTicksToSeconds: (ticks) => jellyfinTicksToSecondsRuntime(ticks),
|
||||
getActivePlayback: () => activeJellyfinRemotePlayback,
|
||||
setActivePlayback: (state) => {
|
||||
activeJellyfinRemotePlayback = {
|
||||
...(state as ActiveJellyfinRemotePlaybackState),
|
||||
@@ -270,6 +274,11 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
|
||||
deps.ensureImmersionTrackerStarted();
|
||||
appState.immersionTracker?.recordJellyfinPlaybackMetadata(metadata);
|
||||
},
|
||||
getEpisodePlaylistSettings: () => configService.getConfig().jellyfin.episodePlaylist,
|
||||
listSeriesEpisodeIds: ({ session, clientInfo, seriesId }) =>
|
||||
listJellyfinSeriesEpisodeIdsRuntime(session, clientInfo, seriesId),
|
||||
readMpvPlaylist: async () => appState.mpvClient?.requestProperty('playlist') ?? [],
|
||||
logDebug: (message, error) => logger.debug(message, error),
|
||||
},
|
||||
remoteComposerOptions: {
|
||||
getConfiguredSession: () => getConfiguredJellyfinSession(getResolvedJellyfinConfig()),
|
||||
@@ -452,6 +461,15 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
|
||||
ensureMpvConnectedForPlayback,
|
||||
getTrayDiscoveryDeps: getJellyfinTrayDiscoveryDeps,
|
||||
getActivePlayback: () => activeJellyfinRemotePlayback,
|
||||
/**
|
||||
* Called with each new mpv path: takes over a queued Jellyfin episode mpv started from its
|
||||
* playlist, otherwise marks the active playback loaded. Must run before the immersion sync.
|
||||
*/
|
||||
handleMediaPathLoaded: (path: string) => {
|
||||
if (playJellyfinItemInMpv.adoptQueuedEpisode(path)) return;
|
||||
markJellyfinRemotePlaybackLoaded(activeJellyfinRemotePlayback, path);
|
||||
},
|
||||
handlePlaybackTimePos: () => playJellyfinItemInMpv.handlePlaybackTimePos(),
|
||||
getQuitOnDisconnectArmed: () => jellyfinPlayQuitOnDisconnectArmed,
|
||||
};
|
||||
}
|
||||
@@ -111,6 +111,8 @@ function makeDeps(recorder: Recorder): PlaybackAssemblyDeps {
|
||||
reportJellyfinRemoteStopped: spy('jellyfin.reportStopped', resolved),
|
||||
reportJellyfinRemoteProgress: spy('jellyfin.reportProgress', resolved),
|
||||
getActivePlayback: spy('jellyfin.getActivePlayback', () => null),
|
||||
handleMediaPathLoaded: spy('jellyfin.handleMediaPathLoaded', noop),
|
||||
handlePlaybackTimePos: spy('jellyfin.handlePlaybackTimePos', noop),
|
||||
startJellyfinRemoteSession: spy('jellyfin.startRemoteSession', resolved),
|
||||
},
|
||||
anilist: {
|
||||
|
||||
@@ -21,10 +21,7 @@ import { createAutoplayTokenizationWarmRelease } from '../runtime/autoplay-token
|
||||
import { composeMpvRuntimeHandlers } from '../runtime/composers';
|
||||
import { createCurrentMediaTokenizationGate } from '../runtime/current-media-tokenization-gate';
|
||||
import { createCachedInternalSubtitleTrackExtractor } from '../runtime/internal-subtitle-extraction';
|
||||
import {
|
||||
markJellyfinRemotePlaybackLoaded as markJellyfinRemotePlaybackLoadedState,
|
||||
shouldAutoLoadSecondarySubTrackForJellyfinPlayback,
|
||||
} from '../runtime/jellyfin-remote-playback';
|
||||
import { shouldAutoLoadSecondarySubTrackForJellyfinPlayback } from '../runtime/jellyfin-remote-playback';
|
||||
import { createJimakuAutoOpenRuntime } from '../runtime/jimaku-auto-open';
|
||||
import { createManagedLocalSubtitleSelectionRuntime } from '../runtime/local-subtitle-selection';
|
||||
import { focusMacOSOverlayWindow } from '../runtime/macos-overlay-window-focus';
|
||||
@@ -164,6 +161,8 @@ export interface PlaybackAssemblyDeps {
|
||||
| 'reportJellyfinRemoteStopped'
|
||||
| 'reportJellyfinRemoteProgress'
|
||||
| 'getActivePlayback'
|
||||
| 'handleMediaPathLoaded'
|
||||
| 'handlePlaybackTimePos'
|
||||
| 'startJellyfinRemoteSession'
|
||||
>;
|
||||
anilist: Pick<
|
||||
@@ -838,8 +837,8 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
immersionMediaRuntime.syncFromCurrentMediaState();
|
||||
},
|
||||
signalAutoplayReadyIfWarm: (path) => signalAutoplayReadyFromWarmTokenization?.(path),
|
||||
markJellyfinRemotePlaybackLoaded: (path) => {
|
||||
markJellyfinRemotePlaybackLoadedState(jellyfin.getActivePlayback(), path);
|
||||
handleJellyfinMediaPathLoaded: (path) => {
|
||||
jellyfin.handleMediaPathLoaded(path);
|
||||
},
|
||||
scheduleCharacterDictionarySync: () => {
|
||||
if (
|
||||
@@ -862,6 +861,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
},
|
||||
consumeExplicitSeek: () => consumeExplicitSeekIntent(),
|
||||
onTimePosUpdate: (time) => {
|
||||
jellyfin.handlePlaybackTimePos();
|
||||
const delta = time - lastObservedTimePos;
|
||||
if (subtitlePrefetchService && (delta > SEEK_THRESHOLD_SECONDS || delta < 0)) {
|
||||
subtitlePrefetchService.onSeek(time);
|
||||
@@ -1118,7 +1118,8 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
aniskipEnabled: configService.getConfig().mpv.aniskipEnabled,
|
||||
aniskipButtonKey: configService.getConfig().mpv.aniskipButtonKey,
|
||||
}),
|
||||
resolveMetadataForFile: (mediaPath) => resolveAniSkipMetadataForFile(mediaPath),
|
||||
resolveMetadataForFile: (mediaPath, episodeLength) =>
|
||||
resolveAniSkipMetadataForFile(mediaPath, { episodeLength }),
|
||||
sendMpvCommand: (command) => {
|
||||
appState.mpvClient?.send({ command });
|
||||
},
|
||||
@@ -1163,6 +1164,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
});
|
||||
client.on('connection-change', aniSkipRuntime.handleConnectionChange);
|
||||
client.on('media-path-change', aniSkipRuntime.handleMediaPathChange);
|
||||
client.on('duration-change', aniSkipRuntime.handleDurationChange);
|
||||
client.on('time-pos-change', aniSkipRuntime.handleTimePosChange);
|
||||
client.on('client-message', aniSkipRuntime.handleClientMessage);
|
||||
deps.getPluginHost().attachMpvClient(client);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import path from 'node:path';
|
||||
import { ImmersionTrackerService } from '../../core/services';
|
||||
import { createCoverArtFetcher } from '../../core/services/anilist/cover-art-fetcher';
|
||||
import { createAnilistRelationFetcher } from '../../core/services/anilist/franchise-relation-fetcher';
|
||||
import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter';
|
||||
import { resolveLegacyVocabularyPosFromTokens } from '../../core/services/immersion-tracker/legacy-vocabulary-pos';
|
||||
import type { StatsWindowOptions } from '../../core/services/stats-window';
|
||||
@@ -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.
|
||||
const statsOverlayOptions: StatsWindowOptions = {
|
||||
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?.setCoverArtFetcher(coverArtFetcher);
|
||||
appState.immersionTracker?.setAnilistRelationFetcher(anilistRelationFetcher);
|
||||
if (tracker) {
|
||||
// Start HTTP stats server
|
||||
if (!appState.statsServer) {
|
||||
|
||||
@@ -4,7 +4,13 @@ import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import test from 'node:test';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { getSnapshotPath, readSnapshot, writeSnapshot } from './cache';
|
||||
import {
|
||||
getSnapshotPath,
|
||||
readCachedMediaResolution,
|
||||
readSnapshot,
|
||||
writeCachedMediaResolution,
|
||||
writeSnapshot,
|
||||
} from './cache';
|
||||
import { CHARACTER_DICTIONARY_FORMAT_VERSION } from './constants';
|
||||
import type { CharacterDictionarySnapshot } from './types';
|
||||
|
||||
@@ -121,3 +127,20 @@ test('readSnapshot ignores snapshots written with an older format version', asyn
|
||||
|
||||
assert.equal(await readSnapshot(snapshotPath), null);
|
||||
});
|
||||
|
||||
test('media resolutions cached before the season resolver fix are re-resolved', () => {
|
||||
const outputDir = makeTempDir();
|
||||
const cachePath = path.join(outputDir, 'anilist-resolution-cache.json');
|
||||
// Written by the old resolver, which counted "Season 2 Part 2" as season 3.
|
||||
fs.writeFileSync(
|
||||
cachePath,
|
||||
JSON.stringify({
|
||||
entries: [{ seriesKey: 'mushoku-tensei-s3', mediaId: 166873, mediaTitle: 'Part 2' }],
|
||||
}),
|
||||
);
|
||||
assert.equal(readCachedMediaResolution(outputDir, 'mushoku-tensei-s3'), null);
|
||||
|
||||
const entry = { seriesKey: 'mushoku-tensei-s3', mediaId: 178789, mediaTitle: 'Season 3' };
|
||||
writeCachedMediaResolution(outputDir, entry);
|
||||
assert.deepEqual(readCachedMediaResolution(outputDir, 'mushoku-tensei-s3'), entry);
|
||||
});
|
||||
@@ -28,9 +28,17 @@ type MediaResolutionCacheEntry = {
|
||||
};
|
||||
|
||||
type MediaResolutionCacheFile = {
|
||||
version?: number;
|
||||
entries?: MediaResolutionCacheEntry[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Bump when the AniList season resolver changes what it returns, so matches it used to get
|
||||
* wrong are re-resolved instead of being served from here forever. Version 2: split-cour
|
||||
* continuations and specials no longer count as seasons.
|
||||
*/
|
||||
const MEDIA_RESOLUTION_CACHE_VERSION = 2;
|
||||
|
||||
function getMediaResolutionCachePath(outputDir: string): string {
|
||||
return path.join(outputDir, 'anilist-resolution-cache.json');
|
||||
}
|
||||
@@ -55,6 +63,7 @@ function readMediaResolutionEntries(outputDir: string): MediaResolutionCacheEntr
|
||||
const parsed = JSON.parse(
|
||||
fs.readFileSync(getMediaResolutionCachePath(outputDir), 'utf8'),
|
||||
) as MediaResolutionCacheFile;
|
||||
if (parsed.version !== MEDIA_RESOLUTION_CACHE_VERSION) return [];
|
||||
if (!Array.isArray(parsed.entries)) return [];
|
||||
const byKey = new Map<string, MediaResolutionCacheEntry>();
|
||||
for (const value of parsed.entries) {
|
||||
@@ -74,7 +83,11 @@ function writeMediaResolutionEntries(
|
||||
ensureDir(outputDir);
|
||||
fs.writeFileSync(
|
||||
getMediaResolutionCachePath(outputDir),
|
||||
JSON.stringify({ entries }, null, 2),
|
||||
JSON.stringify(
|
||||
{ version: MEDIA_RESOLUTION_CACHE_VERSION, entries } satisfies MediaResolutionCacheFile,
|
||||
null,
|
||||
2,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
@@ -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)),
|
||||
};
|
||||
}
|
||||
@@ -3,17 +3,21 @@ import assert from 'node:assert/strict';
|
||||
import {
|
||||
inferAniSkipMetadataForFile,
|
||||
parseAniSkipGuessitJson,
|
||||
parseAniSkipPayload,
|
||||
resolveAniSkipMetadataForFile,
|
||||
} from './aniskip-metadata';
|
||||
|
||||
function makeMockResponse(payload: unknown): Response {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => payload,
|
||||
} as Response;
|
||||
const LOOKUP = { episodeLength: 1440 };
|
||||
|
||||
function makeMockResponse(payload: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
const MAL_MY_SHOW = { categories: [{ items: [{ id: '1234', name: 'My Show' }] }] };
|
||||
|
||||
function normalizeFetchInput(input: string | URL | Request): string {
|
||||
if (typeof input === 'string') return input;
|
||||
if (input instanceof URL) return input.toString();
|
||||
@@ -46,8 +50,8 @@ test('parseAniSkipGuessitJson extracts title season and episode', () => {
|
||||
episode: 7,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
});
|
||||
});
|
||||
@@ -68,8 +72,8 @@ test('parseAniSkipGuessitJson prefers series over episode title', () => {
|
||||
episode: 10,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
});
|
||||
});
|
||||
@@ -111,10 +115,58 @@ test('inferAniSkipMetadataForFile handles release-group filename with trailing q
|
||||
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(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
requested.push(url);
|
||||
if (url.includes('myanimelist.net/search/prefix.json')) {
|
||||
return makeMockResponse({
|
||||
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({
|
||||
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}`);
|
||||
},
|
||||
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.introStart, 12.5);
|
||||
assert.equal(resolved.introEnd, 54.2);
|
||||
assert.deepEqual(resolved.intro, { start: 12.5, end: 54.2 });
|
||||
assert.deepEqual(resolved.outro, { start: 1300, end: 1390 });
|
||||
assert.equal(resolved.lookupStatus, 'ready');
|
||||
assert.equal(resolved.title, 'Anime My Show');
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
requested[1],
|
||||
'https://api.aniskip.com/v2/skip-times/1234/7?types=op&types=ed&episodeLength=1423.457',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile accepts intro payload starting at zero', async () => {
|
||||
test('resolveAniSkipMetadataForFile treats an AniSkip 404 as a definite miss', async () => {
|
||||
await withMockFetch(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
if (url.includes('myanimelist.net/search/prefix.json')) {
|
||||
return makeMockResponse({
|
||||
categories: [{ items: [{ id: '1234', name: 'My Show' }] }],
|
||||
});
|
||||
}
|
||||
if (url.includes('api.aniskip.com/v1/skip-times/1234/1')) {
|
||||
return makeMockResponse({
|
||||
found: true,
|
||||
results: [{ skip_type: 'op', interval: { start_time: 0, end_time: 89.5 } }],
|
||||
});
|
||||
}
|
||||
throw new Error(`unexpected url: ${url}`);
|
||||
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
|
||||
return makeMockResponse(
|
||||
{ found: false, results: [], message: 'No skip times found', statusCode: 404 },
|
||||
404,
|
||||
);
|
||||
},
|
||||
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.introStart, 0);
|
||||
assert.equal(resolved.introEnd, 89.5);
|
||||
assert.equal(resolved.lookupStatus, 'ready');
|
||||
assert.equal(resolved.lookupStatus, 'missing_payload');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile reports transient failures as lookup_failed', async () => {
|
||||
const failures: Array<[string, () => Promise<Response>]> = [
|
||||
['AniSkip rate limit', async () => makeMockResponse({ statusCode: 429 }, 429)],
|
||||
['AniSkip server error', async () => makeMockResponse({ statusCode: 503 }, 503)],
|
||||
[
|
||||
'network error',
|
||||
async () => {
|
||||
throw new TypeError('fetch failed');
|
||||
},
|
||||
],
|
||||
];
|
||||
for (const [label, failAniSkip] of failures) {
|
||||
await withMockFetch(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
|
||||
return failAniSkip();
|
||||
},
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
|
||||
assert.equal(resolved.lookupStatus, 'lookup_failed', label);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
await withMockFetch(
|
||||
async () => makeMockResponse({}, 429),
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
|
||||
assert.equal(resolved.lookupStatus, 'lookup_failed', 'MAL rate limit');
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -177,7 +263,7 @@ test('resolveAniSkipMetadataForFile emits missing_mal_id when MAL search misses'
|
||||
await withMockFetch(
|
||||
async () => makeMockResponse({ categories: [] }),
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv');
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv', LOOKUP);
|
||||
assert.equal(resolved.malId, null);
|
||||
assert.equal(resolved.lookupStatus, 'missing_mal_id');
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import type { SkipInterval } from './aniskip-chapters';
|
||||
|
||||
export type AniSkipLookupStatus =
|
||||
| 'ready'
|
||||
@@ -15,11 +16,16 @@ export interface AniSkipMetadata {
|
||||
episode: number | null;
|
||||
source: 'guessit' | 'fallback';
|
||||
malId: number | null;
|
||||
introStart: number | null;
|
||||
introEnd: number | null;
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
lookupStatus?: AniSkipLookupStatus;
|
||||
}
|
||||
|
||||
export interface AniSkipLookupOptions {
|
||||
/** Length of the playing file in seconds; AniSkip v2 uses it to pick times marked on the same cut. */
|
||||
episodeLength: number;
|
||||
}
|
||||
|
||||
interface InferAniSkipDeps {
|
||||
commandExists: (name: string) => boolean;
|
||||
runGuessit: (mediaPath: string) => string | null;
|
||||
@@ -39,12 +45,12 @@ interface MalSearchResponse {
|
||||
}
|
||||
|
||||
interface AniSkipIntervalPayload {
|
||||
start_time?: unknown;
|
||||
end_time?: unknown;
|
||||
startTime?: unknown;
|
||||
endTime?: unknown;
|
||||
}
|
||||
|
||||
interface AniSkipSkipItemPayload {
|
||||
skip_type?: unknown;
|
||||
skipType?: 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 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_FETCH_TIMEOUT_MS = 8000;
|
||||
// AniSkip allows 120 requests a minute; one lookup per file load stays far below that,
|
||||
// but a gap keeps fast playlist skipping from bursting.
|
||||
const ANISKIP_MIN_REQUEST_GAP_MS = 1000;
|
||||
const MAL_MATCH_STOPWORDS = new Set([
|
||||
'the',
|
||||
'this',
|
||||
@@ -261,49 +270,71 @@ function toMalSearchItems(payload: unknown): MalSearchResult[] {
|
||||
return items;
|
||||
}
|
||||
|
||||
function parseAniSkipPayload(payload: unknown): { start: number; end: number } | null {
|
||||
const parsed = payload as AniSkipPayloadResponse;
|
||||
const results = Array.isArray(parsed?.results) ? parsed.results : null;
|
||||
if (!results) return null;
|
||||
|
||||
for (const rawResult of results) {
|
||||
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;
|
||||
function parseInterval(raw: unknown): SkipInterval | null {
|
||||
if (typeof raw !== 'object' || raw === null) return null;
|
||||
const interval = raw as AniSkipIntervalPayload;
|
||||
const start = toNonNegativeNumber(interval.startTime);
|
||||
const end = toPositiveNumber(interval.endTime);
|
||||
return start !== null && end !== null && end > start ? { start, end } : null;
|
||||
}
|
||||
|
||||
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, {
|
||||
headers: {
|
||||
'User-Agent': ANISKIP_USER_AGENT,
|
||||
},
|
||||
signal: AbortSignal.timeout(ANISKIP_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
try {
|
||||
return (await response.json()) as T;
|
||||
} catch {
|
||||
return null;
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status} from ${new URL(url).host}`);
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
let lastAniSkipRequestAt = 0;
|
||||
let aniSkipRequestQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
/**
|
||||
* Resolves when the caller may send its AniSkip request. Callers are released
|
||||
* one at a time, each at least ANISKIP_MIN_REQUEST_GAP_MS after the previous
|
||||
* release, so timers that fire late cannot release a burst.
|
||||
*/
|
||||
function waitForAniSkipRequestSlot(): Promise<void> {
|
||||
const slot = aniSkipRequestQueue.then(async () => {
|
||||
const waitMs = lastAniSkipRequestAt + ANISKIP_MIN_REQUEST_GAP_MS - Date.now();
|
||||
if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs));
|
||||
lastAniSkipRequestAt = Date.now();
|
||||
});
|
||||
aniSkipRequestQueue = slot;
|
||||
return slot;
|
||||
}
|
||||
|
||||
async function resolveMalIdFromTitle(title: string, season: number | null): Promise<number | null> {
|
||||
const lookup = season && season > 1 ? `${title} Season ${season}` : title;
|
||||
const payload = await fetchJson<unknown>(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
|
||||
const payload = await fetchJson(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
|
||||
const items = toMalSearchItems(payload);
|
||||
if (!items.length) return null;
|
||||
|
||||
@@ -326,16 +357,17 @@ async function resolveMalIdFromTitle(title: string, season: number | null): Prom
|
||||
return bestMalId;
|
||||
}
|
||||
|
||||
async function fetchAniSkipPayload(
|
||||
async function fetchAniSkipIntervals(
|
||||
malId: number,
|
||||
episode: number,
|
||||
): Promise<{ start: number; end: number } | null> {
|
||||
const payload = await fetchJson<unknown>(
|
||||
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed`,
|
||||
episodeLength: number,
|
||||
): Promise<{ intro: SkipInterval | null; outro: SkipInterval | null }> {
|
||||
await waitForAniSkipRequestSlot();
|
||||
const length = Math.round(episodeLength * 1000) / 1000;
|
||||
const payload = await fetchJson(
|
||||
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed&episodeLength=${length}`,
|
||||
);
|
||||
const parsed = payload as AniSkipPayloadResponse;
|
||||
if (!parsed || parsed.found !== true) return null;
|
||||
return parseAniSkipPayload(parsed);
|
||||
return parseAniSkipPayload(payload);
|
||||
}
|
||||
|
||||
function detectEpisodeFromName(baseName: string): number | null {
|
||||
@@ -456,8 +488,8 @@ export function parseAniSkipGuessitJson(stdout: string, mediaPath: string): AniS
|
||||
episode: episodeFromDirect ?? episodeFromList,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
};
|
||||
} catch {
|
||||
@@ -501,13 +533,20 @@ export function inferAniSkipMetadataForFile(
|
||||
episode: detectEpisodeFromName(baseName),
|
||||
source: 'fallback',
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
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);
|
||||
if (!inferred.title) {
|
||||
return { ...inferred, lookupStatus: 'lookup_failed' };
|
||||
@@ -516,50 +555,25 @@ export async function resolveAniSkipMetadataForFile(mediaPath: string): Promise<
|
||||
try {
|
||||
const malId = await resolveMalIdFromTitle(inferred.title, inferred.season);
|
||||
if (!malId) {
|
||||
return {
|
||||
...inferred,
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_mal_id',
|
||||
};
|
||||
return { ...inferred, lookupStatus: 'missing_mal_id' };
|
||||
}
|
||||
|
||||
if (!inferred.episode) {
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_episode',
|
||||
};
|
||||
}
|
||||
|
||||
const payload = await fetchAniSkipPayload(malId, inferred.episode);
|
||||
if (!payload) {
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_payload',
|
||||
};
|
||||
return { ...inferred, malId, lookupStatus: 'missing_episode' };
|
||||
}
|
||||
|
||||
const { intro, outro } = await fetchAniSkipIntervals(
|
||||
malId,
|
||||
inferred.episode,
|
||||
options.episodeLength,
|
||||
);
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
introStart: payload.start,
|
||||
introEnd: payload.end,
|
||||
lookupStatus: 'ready',
|
||||
intro,
|
||||
outro,
|
||||
lookupStatus: intro || outro ? 'ready' : 'missing_payload',
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
...inferred,
|
||||
malId: inferred.malId,
|
||||
introStart: inferred.introStart,
|
||||
introEnd: inferred.introEnd,
|
||||
lookupStatus: 'lookup_failed',
|
||||
};
|
||||
return { ...inferred, lookupStatus: 'lookup_failed' };
|
||||
}
|
||||
}
|
||||
@@ -10,19 +10,22 @@ function readyMetadata(overrides: Partial<AniSkipMetadata> = {}): AniSkipMetadat
|
||||
episode: 1,
|
||||
source: 'fallback',
|
||||
malId: 1234,
|
||||
introStart: 10,
|
||||
introEnd: 95.5,
|
||||
intro: { start: 10, end: 95.5 },
|
||||
outro: null,
|
||||
lookupStatus: 'ready',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const NO_SKIP_TIMES = { intro: null, outro: null } as const;
|
||||
|
||||
function createHarness(options?: {
|
||||
enabled?: boolean;
|
||||
buttonKey?: string;
|
||||
metadata?: AniSkipMetadata | (() => Promise<AniSkipMetadata>);
|
||||
chapterList?: unknown;
|
||||
playbackFeedback?: boolean;
|
||||
duration?: number | null;
|
||||
}) {
|
||||
const state = {
|
||||
enabled: options?.enabled ?? true,
|
||||
@@ -31,9 +34,14 @@ function createHarness(options?: {
|
||||
osd: [] as string[],
|
||||
feedback: [] as string[],
|
||||
resolveCalls: [] as string[],
|
||||
episodeLengths: [] as number[],
|
||||
connected: true,
|
||||
duration: options?.duration === undefined ? 1440 : options.duration,
|
||||
timePos: 0,
|
||||
chapterList: options?.chapterList ?? [],
|
||||
chapterListFails: false,
|
||||
// When set, chapter-list reads wait for it before answering.
|
||||
chapterGate: null as Promise<void> | null,
|
||||
};
|
||||
|
||||
const deps = {
|
||||
@@ -41,8 +49,9 @@ function createHarness(options?: {
|
||||
aniskipEnabled: state.enabled,
|
||||
aniskipButtonKey: state.buttonKey,
|
||||
}),
|
||||
resolveMetadataForFile: async (mediaPath) => {
|
||||
resolveMetadataForFile: async (mediaPath, episodeLength) => {
|
||||
state.resolveCalls.push(mediaPath);
|
||||
state.episodeLengths.push(episodeLength);
|
||||
const metadata = options?.metadata;
|
||||
if (typeof metadata === 'function') return metadata();
|
||||
return metadata ?? readyMetadata();
|
||||
@@ -51,7 +60,15 @@ function createHarness(options?: {
|
||||
state.commands.push(command);
|
||||
},
|
||||
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;
|
||||
},
|
||||
isMpvConnected: () => state.connected,
|
||||
@@ -84,6 +101,10 @@ async function flushAsync(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function seekCommands(commands: unknown[][]): unknown[][] {
|
||||
return commands.filter((command) => command[0] === 'set_property' && command[1] === 'time-pos');
|
||||
}
|
||||
|
||||
test('isRemoteMediaPath detects URLs but not local paths', () => {
|
||||
assert.equal(isRemoteMediaPath('https://example.com/stream.mkv'), true);
|
||||
assert.equal(isRemoteMediaPath('rtmp://example.com/live'), true);
|
||||
@@ -101,6 +122,7 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(state.resolveCalls, ['/media/anime/My Show/ep1.mkv']);
|
||||
assert.deepEqual(state.episodeLengths, [1440]);
|
||||
const chapterCommands = chapterListCommands(state.commands);
|
||||
assert.equal(chapterCommands.length, 1);
|
||||
const chapters = chapterCommands[0]![2] as Array<{ time: number; title: string }>;
|
||||
@@ -109,7 +131,10 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
|
||||
{ time: 10, title: 'AniSkip Intro Start' },
|
||||
{ time: 95.5, title: 'AniSkip Intro End' },
|
||||
]);
|
||||
assert.deepEqual(runtime.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 () => {
|
||||
@@ -131,21 +156,18 @@ test('skip intro seeks to intro end only inside the intro window', async () => {
|
||||
|
||||
state.timePos = 200;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Skip intro only during intro']);
|
||||
assert.deepEqual(state.osd, ['Skip only during intro or outro']);
|
||||
|
||||
state.timePos = 30;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Skip intro only during intro', 'Skipped intro']);
|
||||
const seek = state.commands.find(
|
||||
(command) => command[0] === 'set_property' && command[1] === 'time-pos',
|
||||
);
|
||||
assert.deepEqual(seek, ['set_property', 'time-pos', 95.5]);
|
||||
assert.deepEqual(state.osd, ['Skip only during intro or outro', 'Skipped intro']);
|
||||
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 95.5]]);
|
||||
});
|
||||
|
||||
test('skip intro reports unavailable when no window was found', () => {
|
||||
const { runtime, state } = createHarness();
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Intro skip unavailable']);
|
||||
assert.deepEqual(state.osd, ['Intro/outro skip unavailable']);
|
||||
});
|
||||
|
||||
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: 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 () => {
|
||||
@@ -170,7 +192,7 @@ test('prompt and skip messages use playback feedback when configured', async ()
|
||||
state.timePos = 30;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
|
||||
assert.deepEqual(state.feedback, ['You can skip by pressing TAB', 'Skipped intro']);
|
||||
assert.deepEqual(state.feedback, ['You can skip the intro by pressing TAB', 'Skipped intro']);
|
||||
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);
|
||||
});
|
||||
|
||||
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({
|
||||
metadata: readyMetadata({
|
||||
malId: 1234,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_payload',
|
||||
}),
|
||||
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(runtime.getIntroWindow(), null);
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
assert.equal(chapterListCommands(state.commands).length, 0);
|
||||
|
||||
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']);
|
||||
});
|
||||
|
||||
test('transient lookup failures are retried on the next media load', async () => {
|
||||
let failures = 0;
|
||||
test('transient lookup failures are not cached and retry on the next media load', async () => {
|
||||
let calls = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: async () => {
|
||||
failures += 1;
|
||||
return readyMetadata(
|
||||
failures === 1 ? { introStart: null, introEnd: null, lookupStatus: 'lookup_failed' } : {},
|
||||
);
|
||||
calls += 1;
|
||||
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(runtime.getIntroWindow(), null);
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
|
||||
runtime.handleMediaPathChange({ path: '' });
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
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', () => {
|
||||
@@ -292,3 +401,174 @@ test('disconnect clears bindings so reconnect rebinds the skip key', () => {
|
||||
['keybind', 'TAB', 'script-message subminer-skip-intro'],
|
||||
]);
|
||||
});
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
test('a failed chapter-list read leaves the file chapters untouched', async () => {
|
||||
const harness = createHarness({
|
||||
chapterList: [{ time: 0, title: 'Prologue' }],
|
||||
metadata: async () => {
|
||||
harness.state.chapterListFails = true;
|
||||
return readyMetadata();
|
||||
},
|
||||
});
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.equal(harness.runtime.getSkipWindows().intro?.source, 'aniskip');
|
||||
assert.equal(chapterListCommands(harness.state.commands).length, 0);
|
||||
});
|
||||
|
||||
test('markers are not written into a file that replaced the one being read', async () => {
|
||||
const gate = deferred<void>();
|
||||
let calls = 0;
|
||||
const harness = createHarness({
|
||||
metadata: async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
harness.state.chapterGate = gate.promise;
|
||||
return readyMetadata();
|
||||
}
|
||||
return readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' });
|
||||
},
|
||||
});
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/a.mkv' });
|
||||
await flushAsync();
|
||||
// The marker write for a.mkv is waiting on its chapter-list read.
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/b.mkv' });
|
||||
harness.state.chapterGate = null;
|
||||
gate.resolve();
|
||||
await flushAsync();
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(harness.state.resolveCalls, ['/media/a.mkv', '/media/b.mkv']);
|
||||
assert.equal(chapterListCommands(harness.state.commands).length, 0);
|
||||
});
|
||||
|
||||
test('a file-chapter intro is usable while the AniSkip lookup is still running', async () => {
|
||||
const lookup = deferred<AniSkipMetadata>();
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Opening' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
],
|
||||
metadata: () => lookup.promise,
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 0, end: 90, source: 'chapters' },
|
||||
outro: null,
|
||||
});
|
||||
runtime.handleTimePosChange({ time: 1 });
|
||||
assert.equal(state.osd.length, 1);
|
||||
|
||||
lookup.resolve(
|
||||
readyMetadata({ intro: { start: 3, end: 93 }, outro: { start: 1330, end: 1420 } }),
|
||||
);
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 0, end: 90, source: 'chapters' },
|
||||
outro: { start: 1330, end: 1420, source: 'aniskip' },
|
||||
});
|
||||
// The intro prompt already shown is not shown again.
|
||||
runtime.handleTimePosChange({ time: 1.5 });
|
||||
assert.equal(state.osd.length, 1);
|
||||
});
|
||||
|
||||
test('a lookup superseded by a refresh does not overwrite the cache', async () => {
|
||||
const first = deferred<AniSkipMetadata>();
|
||||
let calls = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: () => {
|
||||
calls += 1;
|
||||
return calls === 1 ? first.promise : Promise.resolve(readyMetadata());
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleClientMessage({ args: ['subminer-aniskip-refresh'] });
|
||||
await flushAsync();
|
||||
first.resolve(readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }));
|
||||
await flushAsync();
|
||||
|
||||
runtime.handleMediaPathChange({ path: '/media/other.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/show.mkv', '/media/other.mkv']);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
|
||||
});
|
||||
|
||||
test('a same-media reload retries a transient lookup failure', async () => {
|
||||
let calls = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: async () => {
|
||||
calls += 1;
|
||||
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(state.resolveCalls.length, 2);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
|
||||
});
|
||||
|
||||
test('a failed chapter-list read is retried on the next duration change or reload', async () => {
|
||||
const stream = 'https://jellyfin.example/Videos/1/stream.mkv';
|
||||
const chapters = [
|
||||
{ time: 0, title: 'OP' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
];
|
||||
for (const retry of ['duration', 'reload'] as const) {
|
||||
const { runtime, state } = createHarness({ chapterList: chapters });
|
||||
state.chapterListFails = true;
|
||||
runtime.handleMediaPathChange({ path: stream });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
|
||||
state.chapterListFails = false;
|
||||
if (retry === 'duration') runtime.handleDurationChange({ duration: 1440 });
|
||||
else runtime.handleMediaPathChange({ path: stream });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 0, end: 90, source: 'chapters' });
|
||||
}
|
||||
});
|
||||
|
||||
test('a successful empty chapter list is not read again on a duration change', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleDurationChange({ duration: 1441 });
|
||||
await flushAsync();
|
||||
assert.equal(state.resolveCalls.length, 1);
|
||||
});
|
||||
|
||||
test('a cached lookup is reused only for the episode length it was fetched for', async () => {
|
||||
const { runtime, state } = createHarness();
|
||||
// A failing chapter read keeps resolution retrying on each duration change.
|
||||
state.chapterListFails = true;
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleDurationChange({ duration: 1440 });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.episodeLengths, [1440]);
|
||||
|
||||
runtime.handleDurationChange({ duration: 1500 });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.episodeLengths, [1440, 1500]);
|
||||
});
|
||||
+276
-122
@@ -1,11 +1,16 @@
|
||||
import type { AniSkipMetadata } from './aniskip-metadata';
|
||||
import {
|
||||
ANISKIP_CHAPTER_PREFIX,
|
||||
classifyChapterSkipIntervals,
|
||||
type SkipInterval,
|
||||
} from './aniskip-chapters';
|
||||
|
||||
/** mpv script-message that skips whichever of the intro or outro is playing. */
|
||||
export const ANISKIP_SKIP_INTRO_MESSAGE = 'subminer-skip-intro';
|
||||
export const ANISKIP_REFRESH_MESSAGE = 'subminer-aniskip-refresh';
|
||||
|
||||
const DEFAULT_ANISKIP_BUTTON_KEY = 'TAB';
|
||||
const LEGACY_ANISKIP_BUTTON_KEY = 'y-k';
|
||||
const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
|
||||
const SKIP_WINDOW_EPSILON_SECONDS = 0.35;
|
||||
const PROMPT_WINDOW_SECONDS = 3;
|
||||
const PROMPT_OSD_DURATION_MS = 3000;
|
||||
@@ -16,7 +21,7 @@ export interface AniSkipRuntimeConfig {
|
||||
|
||||
export interface AniSkipRuntimeDeps {
|
||||
getAniSkipConfig: () => AniSkipRuntimeConfig;
|
||||
resolveMetadataForFile: (mediaPath: string) => Promise<AniSkipMetadata>;
|
||||
resolveMetadataForFile: (mediaPath: string, episodeLength: number) => Promise<AniSkipMetadata>;
|
||||
sendMpvCommand: (command: unknown[]) => void;
|
||||
requestMpvProperty: (name: string) => Promise<unknown>;
|
||||
isMpvConnected: () => boolean;
|
||||
@@ -28,26 +33,65 @@ export interface AniSkipRuntimeDeps {
|
||||
logDebug: (message: string) => void;
|
||||
}
|
||||
|
||||
export interface AniSkipIntroWindow {
|
||||
start: number;
|
||||
end: number;
|
||||
export type SkipWindowKind = 'intro' | 'outro';
|
||||
|
||||
export interface AniSkipWindow extends SkipInterval {
|
||||
/** `chapters` = the file's own chapters; `aniskip` = the AniSkip database. */
|
||||
source: 'chapters' | 'aniskip';
|
||||
}
|
||||
|
||||
export interface AniSkipWindows {
|
||||
intro: AniSkipWindow | null;
|
||||
outro: AniSkipWindow | null;
|
||||
}
|
||||
|
||||
interface AniSkipLookupResult {
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
malId: number | null;
|
||||
}
|
||||
|
||||
type MpvChapter = { time?: unknown; title?: unknown };
|
||||
|
||||
const KIND_LABEL: Record<SkipWindowKind, { chapter: string; word: string }> = {
|
||||
intro: { chapter: 'Intro', word: 'intro' },
|
||||
outro: { chapter: 'Outro', word: 'outro' },
|
||||
};
|
||||
|
||||
export function isRemoteMediaPath(mediaPath: string): boolean {
|
||||
return /^[a-zA-Z][\w+.-]*:\/\//.test(mediaPath.trim());
|
||||
}
|
||||
|
||||
function isAniSkipChapter(chapter: MpvChapter): boolean {
|
||||
return typeof chapter?.title === 'string' && chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX);
|
||||
}
|
||||
|
||||
function isUsableDuration(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the intro and outro for each loaded file (file chapters first, then
|
||||
* AniSkip for whatever the chapters lack), marks them as chapters, prompts when
|
||||
* one starts, and skips the active one when the skip key is pressed.
|
||||
*/
|
||||
export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
let requestGeneration = 0;
|
||||
let currentMediaPath = '';
|
||||
let introWindow: AniSkipIntroWindow | null = null;
|
||||
let promptShown = false;
|
||||
let currentDuration: number | null = null;
|
||||
// True once resolution for the current media has started (or finished).
|
||||
let resolutionStarted = false;
|
||||
// True when resolution for the current media hit a retryable failure (the
|
||||
// chapter-list read or the AniSkip lookup), so a reload or duration change
|
||||
// runs it again.
|
||||
let retryResolution = false;
|
||||
let windows: AniSkipWindows = { intro: null, outro: null };
|
||||
const promptShown: Record<SkipWindowKind, boolean> = { intro: false, outro: false };
|
||||
let boundButtonKey: string | null = null;
|
||||
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 {
|
||||
const key = deps.getAniSkipConfig().aniskipButtonKey.trim();
|
||||
@@ -93,22 +137,39 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
}
|
||||
}
|
||||
|
||||
async function setIntroChapters(introStart: number, introEnd: number): Promise<void> {
|
||||
let existing: MpvChapter[] = [];
|
||||
async function readChapterList(): Promise<MpvChapter[] | null> {
|
||||
try {
|
||||
const chapterList = await deps.requestMpvProperty('chapter-list');
|
||||
if (Array.isArray(chapterList)) {
|
||||
existing = chapterList as MpvChapter[];
|
||||
}
|
||||
return Array.isArray(chapterList) ? (chapterList as MpvChapter[]) : [];
|
||||
} 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),
|
||||
);
|
||||
chapters.push({ time: introStart, title: 'AniSkip Intro Start' });
|
||||
chapters.push({ time: introEnd, title: 'AniSkip Intro End' });
|
||||
}
|
||||
|
||||
/** True while the given request generation still owns the given media. */
|
||||
function ownsPlayback(generation: number, mediaPath: string): boolean {
|
||||
return generation === requestGeneration && mediaPath === currentMediaPath;
|
||||
}
|
||||
|
||||
/** Replaces SubMiner's marker chapters with ones for the AniSkip-sourced windows. */
|
||||
async function setSkipChapters(): Promise<void> {
|
||||
const generation = requestGeneration;
|
||||
const mediaPath = currentMediaPath;
|
||||
const markers: MpvChapter[] = [];
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = windows[kind];
|
||||
if (window?.source !== 'aniskip') continue;
|
||||
const label = KIND_LABEL[kind].chapter;
|
||||
markers.push({ time: window.start, title: `${ANISKIP_CHAPTER_PREFIX}${label} Start` });
|
||||
markers.push({ time: window.end, title: `${ANISKIP_CHAPTER_PREFIX}${label} End` });
|
||||
}
|
||||
if (markers.length === 0) return;
|
||||
const existing = await readChapterList();
|
||||
// A failed read must not wipe the file's chapters, and a read that finished
|
||||
// after the media changed must not write into the next file.
|
||||
if (!existing || !ownsPlayback(generation, mediaPath)) return;
|
||||
const chapters = existing.filter((chapter) => !isAniSkipChapter(chapter)).concat(markers);
|
||||
chapters.sort((a, b) => {
|
||||
const aTime = typeof a.time === 'number' ? a.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]);
|
||||
}
|
||||
|
||||
async function removeIntroChapters(): Promise<void> {
|
||||
async function removeSkipChapters(): Promise<void> {
|
||||
if (!deps.isMpvConnected()) return;
|
||||
let existing: MpvChapter[] = [];
|
||||
try {
|
||||
const chapterList = await deps.requestMpvProperty('chapter-list');
|
||||
if (Array.isArray(chapterList)) {
|
||||
existing = chapterList as MpvChapter[];
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const filtered = existing.filter(
|
||||
(chapter) =>
|
||||
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
|
||||
);
|
||||
const generation = requestGeneration;
|
||||
const mediaPath = currentMediaPath;
|
||||
const existing = await readChapterList();
|
||||
if (!existing || !ownsPlayback(generation, mediaPath)) return;
|
||||
const filtered = existing.filter((chapter) => !isAniSkipChapter(chapter));
|
||||
if (filtered.length !== existing.length) {
|
||||
deps.sendMpvCommand(['set_property', 'chapter-list', filtered]);
|
||||
}
|
||||
@@ -139,81 +192,162 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
|
||||
function clearState(): void {
|
||||
requestGeneration += 1;
|
||||
introWindow = null;
|
||||
promptShown = false;
|
||||
resolutionStarted = false;
|
||||
retryResolution = false;
|
||||
windows = { intro: null, outro: null };
|
||||
promptShown.intro = false;
|
||||
promptShown.outro = false;
|
||||
}
|
||||
|
||||
async function applyIntroWindow(window: AniSkipIntroWindow): Promise<void> {
|
||||
introWindow = window;
|
||||
promptShown = false;
|
||||
await setIntroChapters(window.start, window.end);
|
||||
function logWindow(kind: SkipWindowKind, window: AniSkipWindow, malId: number | null): void {
|
||||
deps.logInfo(
|
||||
`AniSkip intro window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (MAL ${
|
||||
window.malId ?? '-'
|
||||
})`,
|
||||
`AniSkip ${kind} window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (source=${
|
||||
window.source
|
||||
}, MAL ${malId ?? '-'})`,
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveForMedia(mediaPath: string, options?: { force?: boolean }): Promise<void> {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
if (!mediaPath || isRemoteMediaPath(mediaPath)) {
|
||||
deps.logDebug('AniSkip lookup skipped: no local media path');
|
||||
return;
|
||||
/** Installs the file-chapter windows, resetting the prompts. */
|
||||
function applyChapterWindows(next: AniSkipWindows): void {
|
||||
windows = next;
|
||||
promptShown.intro = false;
|
||||
promptShown.outro = false;
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = next[kind];
|
||||
if (window) logWindow(kind, window, null);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
const cached = introWindowCache.get(mediaPath);
|
||||
if (cached !== undefined) {
|
||||
if (cached) {
|
||||
await applyIntroWindow(cached);
|
||||
}
|
||||
return;
|
||||
if (added.length === 0) return;
|
||||
for (const kind of added) {
|
||||
const window = windows[kind];
|
||||
if (window) logWindow(kind, window, lookup.malId);
|
||||
}
|
||||
await setSkipChapters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up AniSkip, using the cache for definitive answers fetched at the same
|
||||
* episode length. Null means a retryable failure.
|
||||
*/
|
||||
async function lookUpAniSkip(
|
||||
mediaPath: string,
|
||||
duration: number,
|
||||
generation: number,
|
||||
): Promise<AniSkipLookupResult | null> {
|
||||
const cached = lookupCache.get(mediaPath);
|
||||
if (cached?.duration === duration) return cached.result;
|
||||
|
||||
let metadata: AniSkipMetadata;
|
||||
try {
|
||||
metadata = await deps.resolveMetadataForFile(mediaPath);
|
||||
metadata = await deps.resolveMetadataForFile(mediaPath, duration);
|
||||
} catch (error) {
|
||||
deps.logWarn('AniSkip metadata lookup failed', error);
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
if (generation !== requestGeneration || mediaPath !== currentMediaPath) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
metadata.lookupStatus !== 'ready' ||
|
||||
metadata.introStart === null ||
|
||||
metadata.introEnd === null ||
|
||||
metadata.introEnd <= metadata.introStart
|
||||
) {
|
||||
// Only definitive "no skip window exists" results are cached; transient
|
||||
// lookup failures stay retryable on the next load or refresh.
|
||||
if (metadata.lookupStatus !== 'lookup_failed') {
|
||||
introWindowCache.set(mediaPath, null);
|
||||
}
|
||||
deps.logInfo(
|
||||
`AniSkip: no intro window for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const window: AniSkipIntroWindow = {
|
||||
start: metadata.introStart,
|
||||
end: metadata.introEnd,
|
||||
const result: AniSkipLookupResult = {
|
||||
intro: metadata.intro,
|
||||
outro: metadata.outro,
|
||||
malId: metadata.malId,
|
||||
};
|
||||
introWindowCache.set(mediaPath, window);
|
||||
await applyIntroWindow(window);
|
||||
if (metadata.lookupStatus === 'lookup_failed') {
|
||||
deps.logInfo(`AniSkip lookup failed for "${metadata.title}"; will retry on next load`);
|
||||
return null;
|
||||
}
|
||||
// Every other status is definitive (a 404 or an unmatched title), so cache it,
|
||||
// unless a refresh or media change superseded this lookup while it ran.
|
||||
if (generation === requestGeneration) lookupCache.set(mediaPath, { duration, result });
|
||||
if (metadata.lookupStatus !== 'ready') {
|
||||
deps.logInfo(
|
||||
`AniSkip: no skip times for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function skipIntroNow(): void {
|
||||
async function resolveForMedia(mediaPath: string, duration: number): Promise<void> {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
if (!introWindow) {
|
||||
showPlaybackFeedback('Intro skip unavailable');
|
||||
const generation = requestGeneration;
|
||||
const isStale = () => generation !== requestGeneration || mediaPath !== currentMediaPath;
|
||||
|
||||
const chapterList = await readChapterList();
|
||||
if (isStale()) return;
|
||||
// A failed read is retried later; a successful empty list is a final answer.
|
||||
if (chapterList === null) retryResolution = true;
|
||||
const fromChapters = classifyChapterSkipIntervals(chapterList ?? [], duration);
|
||||
const next: AniSkipWindows = {
|
||||
intro: fromChapters.intro ? { ...fromChapters.intro, source: 'chapters' } : null,
|
||||
outro: fromChapters.outro ? { ...fromChapters.outro, source: 'chapters' } : null,
|
||||
};
|
||||
// Chapter windows work right away; AniSkip only fills what they lack.
|
||||
applyChapterWindows(next);
|
||||
if (next.intro && next.outro) return;
|
||||
if (isRemoteMediaPath(mediaPath)) {
|
||||
deps.logDebug('AniSkip lookup skipped for remote media; using file chapters only');
|
||||
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;
|
||||
}
|
||||
const now = deps.getCurrentTimePos();
|
||||
@@ -221,40 +355,56 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
showPlaybackFeedback('Skip unavailable');
|
||||
return;
|
||||
}
|
||||
if (
|
||||
now < introWindow.start - SKIP_WINDOW_EPSILON_SECONDS ||
|
||||
now > introWindow.end + SKIP_WINDOW_EPSILON_SECONDS
|
||||
) {
|
||||
showPlaybackFeedback('Skip intro only during intro');
|
||||
const kind = getActiveWindow(now);
|
||||
const window = kind ? windows[kind] : null;
|
||||
if (!kind || !window) {
|
||||
showPlaybackFeedback('Skip only during intro or outro');
|
||||
return;
|
||||
}
|
||||
deps.sendMpvCommand(['set_property', 'time-pos', introWindow.end]);
|
||||
showPlaybackFeedback('Skipped intro');
|
||||
deps.sendMpvCommand(['set_property', 'time-pos', window.end]);
|
||||
showPlaybackFeedback(`Skipped ${KIND_LABEL[kind].word}`);
|
||||
}
|
||||
|
||||
function handleTimePosChange({ time }: { time: number }): void {
|
||||
if (!introWindow || promptShown) return;
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
const promptWindowEnd = Math.min(introWindow.start + PROMPT_WINDOW_SECONDS, introWindow.end);
|
||||
if (time >= introWindow.start && time < promptWindowEnd) {
|
||||
promptShown = true;
|
||||
showPlaybackFeedback(`You can skip by pressing ${resolveButtonKey()}`);
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = windows[kind];
|
||||
if (!window || promptShown[kind]) continue;
|
||||
const promptWindowEnd = Math.min(window.start + PROMPT_WINDOW_SECONDS, window.end);
|
||||
if (time >= window.start && time < promptWindowEnd) {
|
||||
promptShown[kind] = true;
|
||||
showPlaybackFeedback(
|
||||
`You can skip the ${KIND_LABEL[kind].word} by pressing ${resolveButtonKey()}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleDurationChange({ duration }: { duration: number }): void {
|
||||
if (!isUsableDuration(duration) || !currentMediaPath) return;
|
||||
currentDuration = duration;
|
||||
if (retryResolution) clearState();
|
||||
maybeStartResolution();
|
||||
}
|
||||
|
||||
function handleMediaPathChange({ path }: { path: string }): void {
|
||||
const nextPath = typeof path === 'string' ? path : '';
|
||||
if (nextPath === currentMediaPath && 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.
|
||||
void setIntroChapters(introWindow.start, introWindow.end).catch(() => {});
|
||||
void setSkipChapters().catch(() => {});
|
||||
return;
|
||||
}
|
||||
currentMediaPath = nextPath;
|
||||
currentDuration = null;
|
||||
clearState();
|
||||
if (!nextPath) return;
|
||||
void resolveForMedia(nextPath).catch((error) => {
|
||||
deps.logWarn('AniSkip media resolution failed', error);
|
||||
});
|
||||
if (!nextPath || !deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
requestCurrentDuration();
|
||||
}
|
||||
|
||||
function handleConnectionChange({ connected }: { connected: boolean }): void {
|
||||
@@ -263,6 +413,7 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
legacyFallbackBound = false;
|
||||
clearState();
|
||||
currentMediaPath = '';
|
||||
currentDuration = null;
|
||||
return;
|
||||
}
|
||||
bindSkipKeys();
|
||||
@@ -271,43 +422,46 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
function handleClientMessage({ args }: { args: string[] }): void {
|
||||
const messageName = args[0];
|
||||
if (messageName === ANISKIP_SKIP_INTRO_MESSAGE) {
|
||||
skipIntroNow();
|
||||
skipNow();
|
||||
return;
|
||||
}
|
||||
if (messageName === ANISKIP_REFRESH_MESSAGE) {
|
||||
const mediaPath = currentMediaPath;
|
||||
if (!mediaPath) return;
|
||||
if (!currentMediaPath) return;
|
||||
lookupCache.delete(currentMediaPath);
|
||||
clearState();
|
||||
void removeIntroChapters().catch(() => {});
|
||||
void resolveForMedia(mediaPath, { force: true }).catch((error) => {
|
||||
deps.logWarn('AniSkip refresh failed', error);
|
||||
});
|
||||
void removeSkipChapters().catch(() => {});
|
||||
if (currentDuration === null) {
|
||||
requestCurrentDuration();
|
||||
return;
|
||||
}
|
||||
maybeStartResolution();
|
||||
}
|
||||
}
|
||||
|
||||
function applyConfigChange(): void {
|
||||
bindSkipKeys();
|
||||
const enabled = deps.getAniSkipConfig().aniskipEnabled;
|
||||
if (!enabled) {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) {
|
||||
clearState();
|
||||
void removeIntroChapters().catch(() => {});
|
||||
void removeSkipChapters().catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (!introWindow && currentMediaPath) {
|
||||
void resolveForMedia(currentMediaPath).catch((error) => {
|
||||
deps.logWarn('AniSkip media resolution failed', error);
|
||||
});
|
||||
if (!currentMediaPath || resolutionStarted) return;
|
||||
if (currentDuration === null) {
|
||||
requestCurrentDuration();
|
||||
return;
|
||||
}
|
||||
maybeStartResolution();
|
||||
}
|
||||
|
||||
return {
|
||||
handleConnectionChange,
|
||||
handleMediaPathChange,
|
||||
handleDurationChange,
|
||||
handleTimePosChange,
|
||||
handleClientMessage,
|
||||
applyConfigChange,
|
||||
skipIntroNow,
|
||||
getIntroWindow: () => introWindow,
|
||||
skipNow,
|
||||
getSkipWindows: (): AniSkipWindows => windows,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import type { ActiveJellyfinRemotePlaybackState } from '../jellyfin-remote-commands';
|
||||
import { composeJellyfinRemoteHandlers } from './jellyfin-remote-composer';
|
||||
|
||||
function makeHandlers() {
|
||||
return composeJellyfinRemoteHandlers({
|
||||
getConfiguredSession: () => null,
|
||||
getClientInfo: () => ({ clientName: 'SubMiner', clientVersion: '1', deviceId: 'did' }),
|
||||
getJellyfinConfig: () => ({}),
|
||||
playJellyfinItem: async () => {},
|
||||
logWarn: () => {},
|
||||
getMpvClient: () => null,
|
||||
sendMpvCommand: () => {},
|
||||
jellyfinTicksToSeconds: (ticks) => ticks / 10_000_000,
|
||||
getActivePlayback: () => null,
|
||||
clearActivePlayback: () => {},
|
||||
getNow: () => 0,
|
||||
getLastProgressAtMs: () => 0,
|
||||
setLastProgressAtMs: () => {},
|
||||
progressIntervalMs: 3000,
|
||||
ticksPerSecond: 10_000_000,
|
||||
logDebug: () => {},
|
||||
});
|
||||
}
|
||||
|
||||
test('a tracked episode start holds its own stop and the next transition', async () => {
|
||||
const handlers = makeHandlers();
|
||||
const events: string[] = [];
|
||||
const playback: ActiveJellyfinRemotePlaybackState = {
|
||||
itemId: 'ep1',
|
||||
playMethod: 'DirectPlay',
|
||||
reporter: {
|
||||
reportPlaying: async () => {},
|
||||
reportProgress: async () => {},
|
||||
reportStopped: async () => void events.push('stopped:ep1'),
|
||||
},
|
||||
};
|
||||
let finishStart = () => {};
|
||||
handlers.trackJellyfinPlaybackStart(
|
||||
new Promise<void>((resolve) => {
|
||||
finishStart = () => {
|
||||
events.push('started:ep1');
|
||||
resolve();
|
||||
};
|
||||
}),
|
||||
playback,
|
||||
);
|
||||
|
||||
const stopped = handlers.reportJellyfinPlaybackSuperseded(playback);
|
||||
const transitionsDone = handlers.waitForJellyfinTransitionReports().then(() => {
|
||||
events.push('transitions settled');
|
||||
});
|
||||
await Promise.resolve();
|
||||
assert.deepEqual(events, [], 'the stop and the next start wait for the start in flight');
|
||||
|
||||
finishStart();
|
||||
await Promise.all([stopped, transitionsDone]);
|
||||
assert.deepEqual(events, ['started:ep1', 'stopped:ep1', 'transitions settled']);
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
createJellyfinRemoteReportTracker,
|
||||
createReportJellyfinRemoteProgressHandler,
|
||||
createReportJellyfinRemoteStoppedHandler,
|
||||
createReportSupersededJellyfinPlaybackHandler,
|
||||
type JellyfinRemoteGeneralCommandHandlerDeps,
|
||||
type JellyfinRemotePlayHandlerDeps,
|
||||
type JellyfinRemotePlaystateHandlerDeps,
|
||||
@@ -40,6 +41,16 @@ export type JellyfinRemoteComposerOptions = ComposerInputs<{
|
||||
export type JellyfinRemoteComposerResult = ComposerOutputs<{
|
||||
reportJellyfinRemoteProgress: ReturnType<typeof createReportJellyfinRemoteProgressHandler>;
|
||||
reportJellyfinRemoteStopped: ReturnType<typeof createReportJellyfinRemoteStoppedHandler>;
|
||||
reportJellyfinPlaybackSuperseded: ReturnType<
|
||||
typeof createReportSupersededJellyfinPlaybackHandler
|
||||
>;
|
||||
/** Resolves once no episode start or stop report is in flight. */
|
||||
waitForJellyfinTransitionReports: () => Promise<void>;
|
||||
/** Tracks an episode start report, so its own stop and later starts wait for it. */
|
||||
trackJellyfinPlaybackStart: (
|
||||
report: Promise<void>,
|
||||
playback: Parameters<ReturnType<typeof createReportSupersededJellyfinPlaybackHandler>>[0],
|
||||
) => void;
|
||||
handleJellyfinRemotePlay: (payload: RemotePlayPayload) => Promise<void>;
|
||||
handleJellyfinRemotePlaystate: (payload: RemotePlaystatePayload) => Promise<void>;
|
||||
handleJellyfinRemoteGeneralCommand: (payload: RemoteGeneralPayload) => Promise<void>;
|
||||
@@ -61,7 +72,10 @@ export function composeJellyfinRemoteHandlers(
|
||||
logDebug: options.logDebug,
|
||||
reportTracker,
|
||||
});
|
||||
const reportJellyfinRemoteStopped = createReportJellyfinRemoteStoppedHandler({
|
||||
// Every episode start and stop report in flight. Jellyfin keeps whichever start arrives last
|
||||
// as the now-playing item and clears it on any stop, so a start waits for all of these.
|
||||
const transitionReportTracker = createJellyfinRemoteReportTracker();
|
||||
const reportStopped = createReportJellyfinRemoteStoppedHandler({
|
||||
getActivePlayback: options.getActivePlayback,
|
||||
clearActivePlayback: options.clearActivePlayback,
|
||||
getMpvClient: options.getMpvClient,
|
||||
@@ -71,10 +85,35 @@ export function composeJellyfinRemoteHandlers(
|
||||
logWarn: options.logWarn,
|
||||
reportTracker,
|
||||
});
|
||||
const reportSuperseded = createReportSupersededJellyfinPlaybackHandler({
|
||||
ticksPerSecond: options.ticksPerSecond,
|
||||
logDebug: options.logDebug,
|
||||
logWarn: options.logWarn,
|
||||
reportTracker,
|
||||
});
|
||||
const reportJellyfinRemoteStopped = (): Promise<void> => {
|
||||
const report = reportStopped();
|
||||
transitionReportTracker.track(report, null);
|
||||
return report;
|
||||
};
|
||||
const reportJellyfinPlaybackSuperseded = (
|
||||
playback: Parameters<typeof reportSuperseded>[0],
|
||||
): Promise<void> => {
|
||||
const report = reportSuperseded(playback);
|
||||
transitionReportTracker.track(report, playback);
|
||||
return report;
|
||||
};
|
||||
|
||||
return {
|
||||
reportJellyfinRemoteProgress,
|
||||
reportJellyfinRemoteStopped,
|
||||
reportJellyfinPlaybackSuperseded,
|
||||
waitForJellyfinTransitionReports: () => transitionReportTracker.settled(),
|
||||
trackJellyfinPlaybackStart: (report, playback) => {
|
||||
// Tagged with its playback in the shared tracker, so that playback's stop waits for it.
|
||||
reportTracker.track(report, playback);
|
||||
transitionReportTracker.track(report, playback);
|
||||
},
|
||||
handleJellyfinRemotePlay: createHandleJellyfinRemotePlay({
|
||||
getConfiguredSession: options.getConfiguredSession,
|
||||
getClientInfo: options.getClientInfo,
|
||||
|
||||
@@ -50,7 +50,11 @@ export type JellyfinRuntimeComposerOptions = ComposerInputs<{
|
||||
>[0];
|
||||
playJellyfinItemInMpvMainDeps: Omit<
|
||||
PlayJellyfinItemMainDeps,
|
||||
'ensureMpvConnectedForPlayback' | 'preloadExternalSubtitles'
|
||||
| 'ensureMpvConnectedForPlayback'
|
||||
| 'preloadExternalSubtitles'
|
||||
| 'reportPlaybackSuperseded'
|
||||
| 'waitForTransitionReports'
|
||||
| 'trackPlaybackStart'
|
||||
>;
|
||||
remoteComposerOptions: Omit<
|
||||
JellyfinRemoteComposerOptions,
|
||||
@@ -157,11 +161,18 @@ export function composeJellyfinRuntimeHandlers(
|
||||
preloadExternalSubtitles: (params) => {
|
||||
void preloadJellyfinExternalSubtitles(params);
|
||||
},
|
||||
// The remote handlers are built below and share the report tracker with the stop handler.
|
||||
reportPlaybackSuperseded: (playback) => reportJellyfinPlaybackSuperseded(playback),
|
||||
waitForTransitionReports: () => waitForJellyfinTransitionReports(),
|
||||
trackPlaybackStart: (report, playback) => trackJellyfinPlaybackStart(report, playback),
|
||||
});
|
||||
|
||||
const {
|
||||
reportJellyfinRemoteProgress,
|
||||
reportJellyfinRemoteStopped,
|
||||
reportJellyfinPlaybackSuperseded,
|
||||
waitForJellyfinTransitionReports,
|
||||
trackJellyfinPlaybackStart,
|
||||
handleJellyfinRemotePlay,
|
||||
handleJellyfinRemotePlaystate,
|
||||
handleJellyfinRemoteGeneralCommand,
|
||||
|
||||
@@ -7,6 +7,14 @@ import {
|
||||
parseFirstRunSetupSubmissionUrl,
|
||||
} from './first-run-setup-window';
|
||||
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(
|
||||
overrides: Partial<CommandLineLauncherSnapshot> = {},
|
||||
@@ -52,6 +60,7 @@ test('buildFirstRunSetupHtml shows legacy mpv plugin removal action with confirm
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
});
|
||||
@@ -90,6 +99,7 @@ test('buildFirstRunSetupHtml marks an invalid configured mpv path as invalid', (
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
});
|
||||
@@ -117,6 +127,7 @@ test('buildFirstRunSetupHtml explains the config blocker when setup is missing c
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
});
|
||||
@@ -146,6 +157,7 @@ test('buildFirstRunSetupHtml explains external yomitan mode and keeps finish ena
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
});
|
||||
@@ -221,6 +233,7 @@ test('buildFirstRunSetupHtml reports a broken included runtime in the optional l
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot({
|
||||
bun: {
|
||||
status: 'failed',
|
||||
@@ -275,6 +288,7 @@ test('buildFirstRunSetupHtml labels a missing launcher without error-message wor
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot({
|
||||
bun: {
|
||||
status: 'ready',
|
||||
@@ -310,6 +324,7 @@ test('buildFirstRunSetupHtml disables launcher install when no target is install
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot({
|
||||
launcher: {
|
||||
status: 'not_installable',
|
||||
@@ -403,6 +418,7 @@ test('opening first-run setup shows and focuses window after content loads', asy
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
}),
|
||||
@@ -469,6 +485,7 @@ test('opening first-run setup skips rendering if window is destroyed after snaps
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
};
|
||||
@@ -538,6 +555,7 @@ test('first-run setup action can skip rerender after launching another window',
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
}),
|
||||
@@ -620,6 +638,7 @@ test('closing incomplete first-run setup quits app outside background mode', asy
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
}),
|
||||
@@ -692,6 +711,7 @@ test('closing completed first-run setup quits app when completion policy allows
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
}),
|
||||
@@ -747,6 +767,7 @@ test('Hachidori setup names the active dictionary backend', () => {
|
||||
desktopInstalled: false,
|
||||
status: 'optional',
|
||||
},
|
||||
ffmpeg: READY_FFMPEG,
|
||||
commandLineLauncher: createCommandLineLauncherSnapshot(),
|
||||
message: null,
|
||||
});
|
||||
@@ -775,3 +796,55 @@ test('setup parses link and unlink actions without losing the host address', ()
|
||||
{ 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 { DictionaryBackend } from '../../types/config';
|
||||
import { getFirstRunSetupCompletionMessage } from './first-run-setup-service';
|
||||
@@ -34,6 +35,7 @@ export type FirstRunSetupSubmission =
|
||||
| 'remove-legacy-plugin'
|
||||
| 'install-bun'
|
||||
| 'install-command-line-launcher'
|
||||
| 'install-ffmpeg'
|
||||
| 'open-yomitan-settings'
|
||||
| 'open-config-settings'
|
||||
| 'refresh'
|
||||
@@ -63,6 +65,7 @@ export interface FirstRunSetupHtmlModel {
|
||||
status: 'installed' | 'optional' | 'skipped' | 'failed';
|
||||
};
|
||||
commandLineLauncher: CommandLineLauncherSnapshot;
|
||||
ffmpeg: FfmpegSetupStatus;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
@@ -154,6 +157,56 @@ function renderCommandLineLauncherSection(
|
||||
</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 {
|
||||
const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? [];
|
||||
const finishButtonLabel =
|
||||
@@ -535,6 +588,7 @@ export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
|
||||
${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)}
|
||||
</div>
|
||||
${hostCard}
|
||||
${renderFfmpegCard(model.ffmpeg)}
|
||||
${mpvExecutablePathCard}
|
||||
${windowsShortcutCard}
|
||||
${renderCommandLineLauncherSection(model.commandLineLauncher)}
|
||||
@@ -566,6 +620,7 @@ export function parseFirstRunSetupSubmissionUrl(rawUrl: string): FirstRunSetupSu
|
||||
action !== 'configure-windows-mpv-shortcuts' &&
|
||||
action !== 'install-bun' &&
|
||||
action !== 'install-command-line-launcher' &&
|
||||
action !== 'install-ffmpeg' &&
|
||||
action !== 'open-yomitan-settings' &&
|
||||
action !== 'open-config-settings' &&
|
||||
action !== 'refresh' &&
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
createJellyfinEpisodePlaylist,
|
||||
selectEpisodeWindow,
|
||||
type JellyfinEpisodePlaylistSettings,
|
||||
type JellyfinPlaylistEntry,
|
||||
} from './jellyfin-episode-playlist';
|
||||
|
||||
const EPISODES = ['e1', 'e2', 'e3', 'e4', 'e5', 'e6'];
|
||||
|
||||
test('selectEpisodeWindow centers on the current episode and stays full at series edges', () => {
|
||||
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e3', 3), {
|
||||
previousIds: ['e2'],
|
||||
nextIds: ['e4'],
|
||||
});
|
||||
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e3', 4), {
|
||||
previousIds: ['e2'],
|
||||
nextIds: ['e4', 'e5'],
|
||||
});
|
||||
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e1', 3), {
|
||||
previousIds: [],
|
||||
nextIds: ['e2', 'e3'],
|
||||
});
|
||||
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e6', 3), {
|
||||
previousIds: ['e4', 'e5'],
|
||||
nextIds: [],
|
||||
});
|
||||
assert.deepEqual(selectEpisodeWindow(['e1', 'e2'], 'e1', 5), {
|
||||
previousIds: [],
|
||||
nextIds: ['e2'],
|
||||
});
|
||||
assert.deepEqual(selectEpisodeWindow(EPISODES, 'missing', 3), { previousIds: [], nextIds: [] });
|
||||
});
|
||||
|
||||
type Entry = JellyfinPlaylistEntry;
|
||||
|
||||
const url = (itemId: string) => `https://jf.example/Videos/${itemId}/stream`;
|
||||
const entry = (itemId: string): Entry => ({
|
||||
itemId,
|
||||
seriesId: 'series',
|
||||
playbackUrl: url(itemId),
|
||||
loadfileOptions: `opts-${itemId}`,
|
||||
title: `Show ${itemId}`,
|
||||
});
|
||||
|
||||
/** mpv's playlist, kept in sync with the commands the queue sends. */
|
||||
function makeHarness(
|
||||
settings: JellyfinEpisodePlaylistSettings = { enabled: true, maxEpisodes: 3 },
|
||||
) {
|
||||
const playlist: Array<{ filename: string; current: boolean; title?: string }> = [];
|
||||
const commands: Array<Array<string | number>> = [];
|
||||
let episodeListCalls = 0;
|
||||
let afterRead: (() => void) | undefined;
|
||||
const queue = createJellyfinEpisodePlaylist<null, Entry>({
|
||||
getSettings: () => settings,
|
||||
listSeriesEpisodeIds: async () => {
|
||||
episodeListCalls += 1;
|
||||
return EPISODES;
|
||||
},
|
||||
prepareEntry: async (_context, itemId) => entry(itemId),
|
||||
readMpvPlaylist: async () => {
|
||||
const snapshot = playlist.map((item) => ({ ...item }));
|
||||
// Lets a test move mpv on after the read, like a keypress landing mid-run.
|
||||
afterRead?.();
|
||||
return snapshot;
|
||||
},
|
||||
sendMpvCommand: (command) => {
|
||||
commands.push(command);
|
||||
if (command[0] === 'playlist-remove') playlist.splice(Number(command[1]), 1);
|
||||
if (command[0] === 'loadfile') {
|
||||
playlist.splice(Number(command[3]), 0, { filename: String(command[1]), current: false });
|
||||
}
|
||||
const titleIndex = /^playlist\/(\d+)\/title$/.exec(String(command[1]))?.[1];
|
||||
if (command[0] === 'set_property' && titleIndex !== undefined) {
|
||||
playlist[Number(titleIndex)]!.title = String(command[2]);
|
||||
}
|
||||
},
|
||||
logDebug: () => {},
|
||||
});
|
||||
const playing = (itemId: string) => {
|
||||
for (const item of playlist) item.current = item.filename === url(itemId);
|
||||
if (!playlist.some((item) => item.current)) {
|
||||
playlist.splice(0, playlist.length, { filename: url(itemId), current: true });
|
||||
}
|
||||
};
|
||||
return {
|
||||
queue,
|
||||
commands,
|
||||
playlist,
|
||||
playing,
|
||||
episodeListCalls: () => episodeListCalls,
|
||||
setAfterRead: (callback: (() => void) | undefined) => {
|
||||
afterRead = callback;
|
||||
},
|
||||
filenames: () => playlist.map((item) => item.filename),
|
||||
titles: () => playlist.map((item) => item.title),
|
||||
};
|
||||
}
|
||||
|
||||
test('queueNeighbors inserts the episode window around the current entry', async () => {
|
||||
const harness = makeHarness();
|
||||
harness.playing('e3');
|
||||
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
|
||||
assert.deepEqual(harness.filenames(), [url('e2'), url('e3'), url('e4')]);
|
||||
assert.deepEqual(
|
||||
harness.commands.filter((command) => command[0] === 'loadfile'),
|
||||
[
|
||||
['loadfile', url('e4'), 'insert-at', 1, 'opts-e4'],
|
||||
['loadfile', url('e2'), 'insert-at', 0, 'opts-e2'],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(harness.commands.at(-1), [
|
||||
'script-message',
|
||||
'subminer-managed-playlist-entries',
|
||||
url('e3'),
|
||||
url('e4'),
|
||||
url('e2'),
|
||||
]);
|
||||
assert.deepEqual(harness.titles(), ['Show e2', 'Show e3', 'Show e4']);
|
||||
assert.equal(harness.queue.find(url('e4'))?.entry.itemId, 'e4');
|
||||
assert.equal(harness.queue.find(url('e5')), null);
|
||||
});
|
||||
|
||||
test('queueNeighbors slides the window when mpv moves to a queued episode', async () => {
|
||||
const harness = makeHarness();
|
||||
harness.playing('e3');
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
|
||||
harness.playing('e4');
|
||||
await harness.queue.queueNeighbors(null, entry('e4'));
|
||||
|
||||
assert.deepEqual(harness.filenames(), [url('e3'), url('e4'), url('e5')]);
|
||||
assert.deepEqual(harness.titles(), ['Show e3', 'Show e4', 'Show e5']);
|
||||
assert.equal(harness.queue.find(url('e2')), null);
|
||||
assert.equal(harness.episodeListCalls(), 1, 'series order is reused while navigating');
|
||||
});
|
||||
|
||||
test('queueNeighbors keeps entries still in the window and edits only its far ends', async () => {
|
||||
const harness = makeHarness();
|
||||
harness.playing('e3');
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
harness.playing('e4');
|
||||
const commandsBefore = harness.commands.length;
|
||||
|
||||
await harness.queue.queueNeighbors(null, entry('e4'));
|
||||
|
||||
assert.deepEqual(
|
||||
harness.commands
|
||||
.slice(commandsBefore)
|
||||
.filter((command) => command[0] === 'loadfile' || command[0] === 'playlist-remove'),
|
||||
[
|
||||
['playlist-remove', 0],
|
||||
['loadfile', url('e5'), 'insert-at', 2, 'opts-e5'],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('queueNeighbors never undoes a navigation that lands after its playlist read', async () => {
|
||||
const harness = makeHarness();
|
||||
harness.playing('e3');
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
harness.playing('e4');
|
||||
// The read sees e4 playing; the user steps back to e3 before the edits arrive.
|
||||
harness.setAfterRead(() => harness.playing('e3'));
|
||||
|
||||
await harness.queue.queueNeighbors(null, entry('e4'));
|
||||
|
||||
assert.equal(harness.playlist.find((item) => item.current)?.filename, url('e3'));
|
||||
assert.deepEqual(harness.filenames(), [url('e3'), url('e4'), url('e5')]);
|
||||
});
|
||||
|
||||
test('queueNeighbors keeps the episode just left even with the smallest configured window', async () => {
|
||||
const harness = makeHarness({ enabled: true, maxEpisodes: 2 });
|
||||
harness.playing('e3');
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
harness.playing('e4');
|
||||
// The read sees e4 playing; the user steps back to e3 before the edits arrive.
|
||||
harness.setAfterRead(() => harness.playing('e3'));
|
||||
|
||||
await harness.queue.queueNeighbors(null, entry('e4'));
|
||||
|
||||
assert.equal(harness.playlist.find((item) => item.current)?.filename, url('e3'));
|
||||
assert.ok(harness.filenames().includes(url('e3')));
|
||||
});
|
||||
|
||||
test('queueNeighbors leaves the playlist alone once mpv has moved past the item', async () => {
|
||||
const harness = makeHarness();
|
||||
harness.playing('e3');
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
harness.playing('e4');
|
||||
const before = harness.filenames();
|
||||
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
|
||||
assert.deepEqual(harness.filenames(), before);
|
||||
});
|
||||
|
||||
test('queueNeighbors drops queued entries and adds none when the playlist is disabled', async () => {
|
||||
const settings = { enabled: true, maxEpisodes: 3 };
|
||||
const harness = makeHarness(settings);
|
||||
harness.playing('e3');
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
|
||||
settings.enabled = false;
|
||||
await harness.queue.queueNeighbors(null, entry('e3'));
|
||||
|
||||
assert.deepEqual(harness.filenames(), [url('e3')]);
|
||||
});
|
||||
|
||||
test('reset cancels a queue run that is still resolving episodes', async () => {
|
||||
const harness = makeHarness();
|
||||
harness.playing('e3');
|
||||
const pending = harness.queue.queueNeighbors(null, entry('e3'));
|
||||
harness.queue.reset();
|
||||
await pending;
|
||||
|
||||
assert.deepEqual(harness.filenames(), [url('e3')]);
|
||||
assert.equal(harness.queue.find(url('e3')), null);
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
/** What the episode playlist needs from a prepared Jellyfin item. */
|
||||
export type JellyfinPlaylistEntry = {
|
||||
itemId: string;
|
||||
/** Set for episodes; the playlist only queues neighbors within a series. */
|
||||
seriesId: string | null;
|
||||
/** The URL handed to mpv, which mpv reports back as `path` when it starts the entry. */
|
||||
playbackUrl: string;
|
||||
/** Per-file mpv options, applied whenever mpv starts this entry. */
|
||||
loadfileOptions: string;
|
||||
/** Shown in mpv's playlist, which otherwise lists the stream URL and its API key. */
|
||||
title: string;
|
||||
};
|
||||
|
||||
export type JellyfinEpisodePlaylistSettings = {
|
||||
enabled: boolean;
|
||||
/** Most entries kept in mpv's playlist, the current one included. Raised to at least 3. */
|
||||
maxEpisodes: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A window of 3 or more always holds the current episode's immediate neighbors (it only shifts
|
||||
* at a series edge, where that neighbor does not exist). Removals then stay at least two steps
|
||||
* from the playing entry, so a queue run cannot remove the episode a user just stepped back to.
|
||||
*/
|
||||
const MIN_WINDOW_EPISODES = 3;
|
||||
|
||||
export type JellyfinQueuedEpisode<Context, Entry> = {
|
||||
context: Context;
|
||||
entry: Entry;
|
||||
};
|
||||
|
||||
/** Tells the mpv plugin which playlist entries the app starts itself, so it skips its own startup. */
|
||||
export const MANAGED_PLAYLIST_ENTRIES_SCRIPT_MESSAGE = 'subminer-managed-playlist-entries';
|
||||
|
||||
type MpvPlaylistItem = { filename: string; current: boolean };
|
||||
|
||||
function parseMpvPlaylist(raw: unknown): MpvPlaylistItem[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.map((item: unknown) => {
|
||||
const record = item && typeof item === 'object' ? (item as Record<string, unknown>) : {};
|
||||
return {
|
||||
filename: typeof record.filename === 'string' ? record.filename : '',
|
||||
current: record.current === true,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks up to `maxEpisodes` ids around `currentId`, centered on it (an extra slot goes forward)
|
||||
* and shifted inward at either end of the series so the window stays full.
|
||||
*/
|
||||
export function selectEpisodeWindow(
|
||||
episodeIds: readonly string[],
|
||||
currentId: string,
|
||||
maxEpisodes: number,
|
||||
): { previousIds: string[]; nextIds: string[] } {
|
||||
const index = episodeIds.indexOf(currentId);
|
||||
const size = Math.min(episodeIds.length, Math.max(1, Math.floor(maxEpisodes)));
|
||||
if (index < 0 || size <= 1) return { previousIds: [], nextIds: [] };
|
||||
const start = Math.min(Math.max(0, index - Math.floor((size - 1) / 2)), episodeIds.length - size);
|
||||
return {
|
||||
previousIds: episodeIds.slice(start, index),
|
||||
nextIds: episodeIds.slice(index + 1, start + size),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the episodes around the playing Jellyfin item in mpv's playlist, so mpv's own playlist
|
||||
* navigation (and end-of-file advance) moves through the series. mpv starts those entries by
|
||||
* itself; `find` lets the playback handler recognize them from mpv's `path`.
|
||||
*/
|
||||
export function createJellyfinEpisodePlaylist<Context, Entry extends JellyfinPlaylistEntry>(deps: {
|
||||
getSettings: () => JellyfinEpisodePlaylistSettings;
|
||||
listSeriesEpisodeIds: (context: Context, seriesId: string) => Promise<string[]>;
|
||||
prepareEntry: (context: Context, itemId: string) => Promise<Entry>;
|
||||
readMpvPlaylist: () => Promise<unknown>;
|
||||
sendMpvCommand: (command: Array<string | number>) => void;
|
||||
logDebug: (message: string, error?: unknown) => void;
|
||||
}) {
|
||||
let queued = new Map<string, JellyfinQueuedEpisode<Context, Entry>>();
|
||||
// Episode order per series, fetched once per explicit playback and reused while navigating.
|
||||
let seriesEpisodeIds = new Map<string, Promise<string[]>>();
|
||||
// Bumped by every reset and queue run, so a slow run never edits a playlist that moved on.
|
||||
let generation = 0;
|
||||
|
||||
function getSeriesEpisodeIds(context: Context, seriesId: string): Promise<string[]> {
|
||||
let ids = seriesEpisodeIds.get(seriesId);
|
||||
if (!ids) {
|
||||
ids = deps.listSeriesEpisodeIds(context, seriesId);
|
||||
seriesEpisodeIds.set(seriesId, ids);
|
||||
// A failed lookup is retried on the next queue run.
|
||||
ids.catch(() => seriesEpisodeIds.delete(seriesId));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
async function prepareEntries(context: Context, itemIds: string[]): Promise<Map<string, Entry>> {
|
||||
const prepared = new Map<string, Entry>();
|
||||
await Promise.all(
|
||||
itemIds.map((itemId) =>
|
||||
deps.prepareEntry(context, itemId).then(
|
||||
(entry) => {
|
||||
prepared.set(itemId, entry);
|
||||
},
|
||||
(error: unknown) => {
|
||||
deps.logDebug(`Failed to prepare Jellyfin episode ${itemId} for the playlist`, error);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
return prepared;
|
||||
}
|
||||
|
||||
async function queueNeighbors(context: Context, current: Entry): Promise<void> {
|
||||
const run = ++generation;
|
||||
const settings = deps.getSettings();
|
||||
let windowIds = [current.itemId];
|
||||
if (settings.enabled && current.seriesId) {
|
||||
const episodeIds = await getSeriesEpisodeIds(context, current.seriesId);
|
||||
const window = selectEpisodeWindow(
|
||||
episodeIds,
|
||||
current.itemId,
|
||||
Math.max(MIN_WINDOW_EPISODES, settings.maxEpisodes),
|
||||
);
|
||||
windowIds = [...window.previousIds, current.itemId, ...window.nextIds];
|
||||
}
|
||||
// Entries already queued stay where they are, so only the missing ones are resolved.
|
||||
const queuedItemIds = new Set([...queued.values()].map(({ entry }) => entry.itemId));
|
||||
const prepared = await prepareEntries(
|
||||
context,
|
||||
windowIds.filter((itemId) => itemId !== current.itemId && !queuedItemIds.has(itemId)),
|
||||
);
|
||||
if (run !== generation) return;
|
||||
|
||||
const playlist = parseMpvPlaylist(await deps.readMpvPlaylist());
|
||||
if (run !== generation) return;
|
||||
const currentIndex = playlist.findIndex((item) => item.current);
|
||||
// mpv already left this item, so the run that follows it owns the playlist.
|
||||
if (playlist[currentIndex]?.filename !== current.playbackUrl) return;
|
||||
|
||||
// mpv may have moved on since the read, so this only touches entries outside the window
|
||||
// and never removes one the user could have just navigated to. `model` mirrors mpv's
|
||||
// playlist by item id (null for entries the app did not queue) as the commands edit it.
|
||||
const model = playlist.map((item) =>
|
||||
item.filename === current.playbackUrl
|
||||
? current.itemId
|
||||
: (queued.get(item.filename)?.entry.itemId ?? null),
|
||||
);
|
||||
for (let index = model.length - 1; index >= 0; index -= 1) {
|
||||
const itemId = model[index];
|
||||
if (itemId === null || itemId === undefined || windowIds.includes(itemId)) continue;
|
||||
deps.sendMpvCommand(['playlist-remove', index]);
|
||||
model.splice(index, 1);
|
||||
}
|
||||
|
||||
const nextQueued = new Map<string, JellyfinQueuedEpisode<Context, Entry>>();
|
||||
for (const queuedEpisode of queued.values()) {
|
||||
if (model.includes(queuedEpisode.entry.itemId)) {
|
||||
nextQueued.set(queuedEpisode.entry.playbackUrl, queuedEpisode);
|
||||
}
|
||||
}
|
||||
nextQueued.set(current.playbackUrl, { context, entry: current });
|
||||
// Each insert is followed by its title, sent while the entry is still at that index.
|
||||
const insertEntry = (entry: Entry, index: number) => {
|
||||
deps.sendMpvCommand([
|
||||
'loadfile',
|
||||
entry.playbackUrl,
|
||||
'insert-at',
|
||||
index,
|
||||
entry.loadfileOptions,
|
||||
]);
|
||||
deps.sendMpvCommand(['set_property', `playlist/${index}/title`, entry.title]);
|
||||
model.splice(index, 0, entry.itemId);
|
||||
nextQueued.set(entry.playbackUrl, { context, entry });
|
||||
};
|
||||
const currentAt = windowIds.indexOf(current.itemId);
|
||||
deps.sendMpvCommand([
|
||||
'set_property',
|
||||
`playlist/${model.indexOf(current.itemId)}/title`,
|
||||
current.title,
|
||||
]);
|
||||
// Walk outward from the current entry, inserting each missing episode beside its
|
||||
// neighbor in the window.
|
||||
let anchor = model.indexOf(current.itemId);
|
||||
for (const itemId of windowIds.slice(currentAt + 1)) {
|
||||
const entry = prepared.get(itemId);
|
||||
if (model.includes(itemId)) anchor = model.indexOf(itemId);
|
||||
else if (entry) insertEntry(entry, ++anchor);
|
||||
}
|
||||
anchor = model.indexOf(current.itemId);
|
||||
for (const itemId of windowIds.slice(0, currentAt).reverse()) {
|
||||
const entry = prepared.get(itemId);
|
||||
if (model.includes(itemId)) anchor = model.indexOf(itemId);
|
||||
else if (entry) insertEntry(entry, anchor);
|
||||
}
|
||||
queued = nextQueued;
|
||||
deps.sendMpvCommand([
|
||||
'script-message',
|
||||
MANAGED_PLAYLIST_ENTRIES_SCRIPT_MESSAGE,
|
||||
...queued.keys(),
|
||||
]);
|
||||
}
|
||||
|
||||
return {
|
||||
/** Forgets queued entries and cancels queue runs in flight, for a new explicit playback. */
|
||||
reset(): void {
|
||||
generation += 1;
|
||||
queued = new Map();
|
||||
seriesEpisodeIds = new Map();
|
||||
},
|
||||
/** The queued episode whose playback URL mpv reports as `path`, if any. */
|
||||
find(path: string): JellyfinQueuedEpisode<Context, Entry> | null {
|
||||
return queued.get(path) ?? null;
|
||||
},
|
||||
/** Fills mpv's playlist with the episodes around `current`, mpv's current entry. */
|
||||
queueNeighbors: (context: Context, current: Entry): Promise<void> =>
|
||||
queueNeighbors(context, current).catch((error: unknown) => {
|
||||
deps.logDebug('Failed to queue adjacent Jellyfin episodes', error);
|
||||
}),
|
||||
};
|
||||
}
|
||||
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user