mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-07-28 16:49:50 -07:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
57ac9d73e7
|
|||
|
d25950c041
|
|||
|
59c305e023
|
|||
|
9f85c55d23
|
@@ -66,7 +66,7 @@ Local stats dashboard tracking watch time, vocabulary growth, mining throughput,
|
||||
Browse sibling episode files and the active mpv queue in one overlay modal. Open it with `Ctrl+Alt+P` to append episodes from the current directory, jump to queued items, remove entries, or reorder the playlist without leaving playback.
|
||||
|
||||
<div align="center">
|
||||
<img src="docs-site/public/screenshots/playlist-browser.png" width="800" alt="Playlist browser modal showing sibling episode files beside the active mpv queue">
|
||||
<img src="docs-site/public/screenshots/playlist-browser.png" width="800" alt="Stats dashboard showing watch time, cards mined, streaks, and tracking data">
|
||||
</div>
|
||||
|
||||
<br>
|
||||
@@ -90,14 +90,6 @@ Browse sibling episode files and the active mpv queue in one overlay modal. Open
|
||||
<td><b>Jimaku</b></td>
|
||||
<td>Search and download Japanese subtitles</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>TsukiHime</b></td>
|
||||
<td>Search and download subtitles extracted from anime releases, with Japanese and secondary-language tabs (<code>Ctrl+Shift+T</code>) — no API key, requires <code>xz</code> on your <code>PATH</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>AniSkip</b></td>
|
||||
<td>Automatic intro detection with chapter markers and a one-key skip (<code>TAB</code> by default)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>alass / ffsubsync</b></td>
|
||||
<td>Manual subtitle retiming — requires <code>alass</code> or <code>ffsubsync</code> on your <code>PATH</code> (optional; subtitle syncing is disabled without them)</td>
|
||||
@@ -118,19 +110,18 @@ Browse sibling episode files and the active mpv queue in one overlay modal. Open
|
||||
|
||||
## Requirements
|
||||
|
||||
Only **mpv** is required to run SubMiner. Anki + AnkiConnect are required to mine cards, which is the point of the app, but everything else is optional.
|
||||
Only **mpv** and Anki+AnkiConnect are required. Everything else is optional but enhances the experience.
|
||||
|
||||
| Dependency | Status | What it does |
|
||||
| -------------------- | ---------------- | -------------------------------------------------------- |
|
||||
| mpv | Required | The video player SubMiner overlays on |
|
||||
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
|
||||
| ffmpeg | Recommended | Audio clips & screenshots for Anki cards |
|
||||
| MeCab + mecab-ipadic | Recommended | More precise annotations and filtering |
|
||||
| yt-dlp | Optional | YouTube playback |
|
||||
| xz | Optional | TsukiHime subtitle downloads (not on Windows by default) |
|
||||
| alass / ffsubsync | Optional | Subtitle sync |
|
||||
| guessit | Optional | Better anime title and episode detection |
|
||||
| fzf / rofi | Optional | Video picker in the `subminer` launcher (Linux/macOS) |
|
||||
| Dependency | Status | What it does |
|
||||
| -------------------- | ----------- | ---------------------------------------- |
|
||||
| mpv | Required | The video player SubMiner overlays on |
|
||||
| Anki + AnkiConnect | Required | Card creation from the Yomitan popup |
|
||||
| ffmpeg | Recommended | Audio clips & screenshots for Anki cards |
|
||||
| MeCab + mecab-ipadic | Recommended | More precise annotations and filtering |
|
||||
| yt-dlp | Optional | YouTube playback |
|
||||
| fzf / rofi | Optional | Video picker in the launcher |
|
||||
| alass / ffsubsync | Optional | Subtitle sync |
|
||||
| guessit | Optional | Better anime title and episode detection |
|
||||
|
||||
<details>
|
||||
<summary><b>Platform-specific install commands</b></summary>
|
||||
@@ -147,23 +138,9 @@ sudo pacman -S --needed mpv ffmpeg mecab mecab-ipadic
|
||||
brew install mpv ffmpeg mecab mecab-ipadic
|
||||
```
|
||||
|
||||
**Windows:**
|
||||
**Windows:** Install [mpv](https://mpv.io/installation/) and [ffmpeg](https://ffmpeg.org/download.html) and ensure both are on `PATH`.
|
||||
|
||||
```powershell
|
||||
winget install shinchiro.mpv
|
||||
winget install Gyan.FFmpeg
|
||||
```
|
||||
|
||||
Then reopen your terminal and check `mpv --version` and `ffmpeg -version`. winget puts `ffmpeg` on `PATH` automatically; mpv uses a regular installer that may not, so if `mpv` is not found, either add its folder (usually `%LOCALAPPDATA%\Programs\mpv`) to `PATH` or set `mpv.executablePath` during first-run setup.
|
||||
|
||||
[Scoop](https://scoop.sh) is the alternative if you want one package manager for everything, since it is the only one that also carries `xz`:
|
||||
|
||||
```powershell
|
||||
scoop bucket add extras
|
||||
scoop install extras/mpv main/ffmpeg main/yt-dlp main/xz
|
||||
```
|
||||
|
||||
See the [full requirements list](https://docs.subminer.moe/installation#_1-install-requirements) for optional dependencies.
|
||||
See the [full requirements list](https://docs.subminer.moe/installation#1-install-requirements) for optional dependencies.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -189,11 +166,6 @@ paru -S subminer-bin
|
||||
mkdir -p ~/.local/bin
|
||||
wget https://github.com/ksyasuda/SubMiner/releases/latest/download/SubMiner.AppImage -O ~/.local/bin/SubMiner.AppImage \
|
||||
&& chmod +x ~/.local/bin/SubMiner.AppImage
|
||||
```
|
||||
|
||||
The AppImage is all you need. The optional `subminer` command-line launcher runs on [Bun](https://bun.sh), and first-run setup can install both for you. To grab it manually instead, install Bun first, then:
|
||||
|
||||
```bash
|
||||
wget https://github.com/ksyasuda/SubMiner/releases/latest/download/subminer -O ~/.local/bin/subminer \
|
||||
&& chmod +x ~/.local/bin/subminer
|
||||
```
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
type: fixed
|
||||
area: anilist
|
||||
|
||||
- Season 2 and later files now resolve to the right AniList entry. AniList has no numbered seasons (sequels are separate entries titled `Zoku`, `Kan`, `2nd Season`), so the old `<title> Season N` search returned nothing and silently fell back to the season 1 entry: an Oregairu S03 episode loaded the season 1 character dictionary and pushed watch progress onto season 1. SubMiner now searches the base title and walks AniList `SEQUEL` relations to reach the requested season, ordering the franchise's TV entries by air date when the relation chain is incomplete.
|
||||
- When the season still cannot be located, SubMiner no longer writes progress to the season 1 entry; it skips the update and points at the manual AniList override instead. The character dictionary logs the same warning and states which entry it fell back to.
|
||||
- Character dictionary overrides are now scoped by detected season as well as directory, so seasons kept in one flat folder no longer share (or overwrite) each other's override, and an override now also pins the entry used for AniList watch progress: correcting a wrong match once fixes both the dictionary and progress tracking.
|
||||
- Cover art lookup uses the same season-aware resolution, so per-season art no longer falls back to the season 1 cover.
|
||||
- An unresolvable season is no longer cached as if it were a normal match, so the fallback cannot silently stick for every later episode of that series.
|
||||
@@ -691,7 +691,7 @@
|
||||
"executablePath": "", // Optional absolute path to mpv.exe for Windows launch flows. Leave empty to auto-discover from SUBMINER_MPV_PATH or PATH.
|
||||
"launchMode": "normal", // Default window state for SubMiner-managed mpv launches. Values: normal | maximized | fullscreen
|
||||
"profile": "", // Optional mpv profile name passed to SubMiner-managed mpv launches. Leave empty to pass no profile.
|
||||
"socketPath": "/tmp/subminer-socket", // mpv IPC socket path used by SubMiner-managed playback and the bundled mpv plugin.
|
||||
"socketPath": "\\\\.\\pipe\\subminer-socket", // mpv IPC socket path used by SubMiner-managed playback and the bundled mpv plugin.
|
||||
"backend": "auto", // Window tracking backend passed to the bundled mpv plugin. Auto detects the current platform. Values: auto | hyprland | sway | x11 | macos | windows
|
||||
"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
|
||||
|
||||
@@ -28,7 +28,7 @@ const outDir = optionalEnv(process.env.SUBMINER_DOCS_OUT_DIR);
|
||||
const docsSourceDir = optionalEnv(process.env.SUBMINER_DOCS_SOURCE_DIR) ?? process.cwd();
|
||||
const channel = normalizeChannel(optionalEnv(process.env.SUBMINER_DOCS_CHANNEL));
|
||||
const docsVersion = optionalEnv(process.env.SUBMINER_DOCS_VERSION);
|
||||
const latestStable = optionalEnv(process.env.SUBMINER_DOCS_LATEST_STABLE) ?? 'v0.18.0';
|
||||
const latestStable = optionalEnv(process.env.SUBMINER_DOCS_LATEST_STABLE) ?? 'v0.14.0';
|
||||
const versionManifest = parseVersionManifest(process.env.SUBMINER_DOCS_VERSION_MANIFEST);
|
||||
const versionLinkOrigin =
|
||||
optionalEnv(process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN) ?? 'production';
|
||||
@@ -306,7 +306,6 @@ const sidebar: DefaultTheme.SidebarItem[] = [
|
||||
{ text: 'Usage', link: '/usage' },
|
||||
{ text: 'Mining Workflow', link: '/mining-workflow' },
|
||||
{ text: 'Launcher Script', link: '/launcher-script' },
|
||||
{ text: 'Feature Demos', link: '/demos' },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -39,7 +39,7 @@ SubMiner monitors playback and triggers an AniList progress update when an episo
|
||||
The update flow:
|
||||
|
||||
1. **Title detection** -- SubMiner extracts the anime title, season, and episode number from the media filename and path. Season folders such as `Season 2` are treated as a strong season signal. SubMiner tries [`guessit`](https://github.com/guessit-io/guessit) first for accurate parsing, then falls back to an internal filename parser if guessit is unavailable.
|
||||
2. **AniList search** -- The detected title is searched against the AniList GraphQL API. For season 2 and later files, SubMiner searches the season-specific title first, then falls back to the base title. SubMiner picks the best match by comparing titles (romaji, English, native) and filtering by episode count.
|
||||
2. **AniList search** -- The base title (with any `Season N` / `SN` marker stripped) is searched against the AniList GraphQL API, and SubMiner picks the best match by comparing titles (romaji, English, native, synonyms) and filtering by episode count. AniList has no notion of numbered seasons -- sequels are separate entries with their own titles (`Zoku`, `Kan`, `2nd Season`), so searching `<title> Season 3` finds nothing. For season 2 and later, SubMiner instead walks `SEQUEL` relations from the season 1 entry, preferring the TV line, and falls back to ordering the franchise's TV entries by air date when the relation chain is incomplete. If neither locates the season, SubMiner **skips the update** rather than writing progress to the season 1 entry, and tells you to pin the right entry with a [character dictionary override](/character-dictionary#correcting-anilist-matches).
|
||||
3. **Progress check** -- SubMiner fetches your current list entry for the matched media. The media must already be in Planning or Watching; otherwise SubMiner shows an MPV message explaining that the update is not possible. If your recorded progress already meets or exceeds the detected episode, the update is skipped.
|
||||
4. **Mutation** -- A `SaveMediaListEntry` mutation sets the new progress and marks the entry as `CURRENT`, or `COMPLETED` when the watched episode is the final episode of the season (the "already at this progress" skip is bypassed for the final episode so completion still lands).
|
||||
|
||||
@@ -93,15 +93,15 @@ All AniList API calls go through a shared rate limiter that enforces a sliding w
|
||||
}
|
||||
```
|
||||
|
||||
| Option | Values | Description |
|
||||
| ------------------------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| `enabled` | `true`, `false` | Enable AniList post-watch progress updates (default: `false`) |
|
||||
| `accessToken` | string | Explicit AniList access token override; when blank, SubMiner uses the stored encrypted token (default: `""`) |
|
||||
| `characterDictionary.maxLoaded` | number | Number of recent media snapshots kept in the merged dictionary (default: `3`) |
|
||||
| `characterDictionary.refreshTtlHours` | number | Hours before a cached media snapshot is refreshed (default: `168`, clamped to 1–8760) |
|
||||
| `characterDictionary.evictionPolicy` | `"delete"`, `"disable"` | What happens to snapshots evicted beyond `maxLoaded` (default: `"delete"`) |
|
||||
| `characterDictionary.profileScope` | `"all"`, `"active"` | Apply dictionary to all Yomitan profiles or only the active one |
|
||||
| `characterDictionary.collapsibleSections.*` | `true`, `false` | Control which dictionary entry sections start expanded |
|
||||
| Option | Values | Description |
|
||||
| ------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| `enabled` | `true`, `false` | Enable AniList post-watch progress updates (default: `false`) |
|
||||
| `accessToken` | string | Explicit AniList access token override; when blank, SubMiner uses the stored encrypted token (default: `""`) |
|
||||
| `characterDictionary.maxLoaded` | number | Number of recent media snapshots kept in the merged dictionary (default: `3`) |
|
||||
| `characterDictionary.refreshTtlHours` | number | Hours before a cached media snapshot is refreshed (default: `168`, clamped to 1–8760) |
|
||||
| `characterDictionary.evictionPolicy` | `"delete"`, `"disable"` | What happens to snapshots evicted beyond `maxLoaded` (default: `"delete"`) |
|
||||
| `characterDictionary.profileScope` | `"all"`, `"active"` | Apply dictionary to all Yomitan profiles or only the active one |
|
||||
| `characterDictionary.collapsibleSections.*` | `true`, `false` | Control which dictionary entry sections start expanded |
|
||||
|
||||
There is no `characterDictionary.enabled` key: character dictionary sync is enabled by `subtitleStyle.nameMatchEnabled`. See the [Character Dictionary](/character-dictionary) page for full details on the character dictionary feature, including name generation, matching, auto-sync lifecycle, and dictionary entry format.
|
||||
|
||||
|
||||
@@ -223,7 +223,9 @@ SubMiner.AppImage --dictionary-select --dictionary-anilist-id 21355 --dictionary
|
||||
subminer app --session-action '{"actionId":"openCharacterDictionaryManager"}'
|
||||
```
|
||||
|
||||
SubMiner stores manual selections in `character-dictionaries/anilist-overrides.json`. The episode's parent directory defines the override scope, so later episodes in the same season directory keep the selected AniList ID even if their filename guesses differ. Separate season directories can keep separate overrides and character dictionaries. When you replace a wrong match, SubMiner removes that stale media ID from the merged dictionary's active set and rebuilds/imports the merged character dictionary.
|
||||
SubMiner stores manual selections in `character-dictionaries/anilist-overrides.json`. The episode's parent directory **and detected season** define the override scope, so later episodes in the same season keep the selected AniList ID even if their filename guesses differ, while a different season never inherits the override -- including when every season sits in one flat folder. When you replace a wrong match, SubMiner removes that stale media ID from the merged dictionary's active set and rebuilds/imports the merged character dictionary.
|
||||
|
||||
An override also pins the entry used for [AniList watch progress](/anilist-integration), so correcting a wrong match once fixes both the character dictionary and progress tracking.
|
||||
|
||||
## Managing Loaded Entries
|
||||
|
||||
|
||||
@@ -71,10 +71,6 @@ When both files exist, SubMiner prefers `config.jsonc` over `config.json`.
|
||||
|
||||
See [config.example.jsonc](/config.example.jsonc) for a comprehensive example with all available options, default values, and detailed comments. Only include the options you want to customize in your config file.
|
||||
|
||||
::: warning One value in that file is platform-specific
|
||||
The example is generated with a fixed Linux/macOS socket path so it stays reproducible, so it shows `"socketPath": "/tmp/subminer-socket"`. On Windows the real default is `\\\\.\\pipe\\subminer-socket`. Leave `mpv.socketPath` out of your config entirely unless you need a custom path, and SubMiner picks the right one for your platform.
|
||||
:::
|
||||
|
||||
Generate a fresh default config from the centralized config registry:
|
||||
|
||||
```bash
|
||||
@@ -149,13 +145,12 @@ The configuration file includes several main sections:
|
||||
- [**Shared AI Provider**](#shared-ai-provider) - Canonical OpenAI-compatible provider config shared by Anki and YouTube subtitle fixing
|
||||
- [**AnkiConnect**](#ankiconnect) - Automatic Anki card creation with media
|
||||
- [**Kiku/Lapis Integration**](#kiku-lapis-integration) - Sentence cards and duplicate handling for Kiku/Lapis note types
|
||||
- [**N+1 Word Highlighting**](#n-1-word-highlighting) - Known-word cache and single-target highlighting
|
||||
- [**N+1 Word Highlighting**](#n1-word-highlighting) - Known-word cache and single-target highlighting
|
||||
- [**Field Grouping Modes**](#field-grouping-modes) - Kiku/Lapis duplicate card merging
|
||||
|
||||
**External Integrations**
|
||||
|
||||
- [**Jimaku**](#jimaku) - Jimaku API configuration and defaults
|
||||
- [**TsukiHime**](#tsukihime) - Multi-language subtitle search and download
|
||||
- [**Subtitle Sync**](#subtitle-sync) - Sync current subtitle with `alass`/`ffsubsync`
|
||||
- [**AniList**](#anilist) - Optional post-watch progress updates
|
||||
- [**Yomitan**](#yomitan) - Reuse an external read-only Yomitan profile
|
||||
@@ -543,8 +538,6 @@ Display a second subtitle track (e.g., English alongside Japanese) in the overla
|
||||
|
||||
See `config.example.jsonc` for detailed configuration options.
|
||||
|
||||
Secondary subtitles do **not** auto-load by default. To turn them on for local and Jellyfin playback, set `autoLoadSecondarySub` to `true` and list the language codes you want:
|
||||
|
||||
```json
|
||||
{
|
||||
"secondarySub": {
|
||||
@@ -555,15 +548,11 @@ Secondary subtitles do **not** auto-load by default. To turn them on for local a
|
||||
}
|
||||
```
|
||||
|
||||
| Option | Values | Description |
|
||||
| ----------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `secondarySubLanguages` | string[] | Language codes to auto-load (e.g., `["eng", "en"]`); non-Signs/Songs tracks are preferred when several tracks match. Default is empty (`[]`). |
|
||||
| `autoLoadSecondarySub` | `true`, `false` | Auto-detect and load a matching secondary subtitle track for local/Jellyfin sidecar files (default: `false`) |
|
||||
| `defaultMode` | `"hidden"`, `"visible"`, `"hover"` | Initial display mode (default: `"hover"`) |
|
||||
|
||||
These two settings apply to local and Jellyfin playback only. YouTube secondary selection is fixed to English and ignores them; see [YouTube Integration](/youtube-integration#secondary-subtitle-languages). `defaultMode` still controls how the loaded secondary bar is displayed in every case.
|
||||
|
||||
Because the mined-card translation field is filled from the secondary subtitle when one is present, leaving `autoLoadSecondarySub` off means local-file cards fall back to AI translation (when configured) or the original sentence text.
|
||||
| Option | Values | Description |
|
||||
| ----------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| `secondarySubLanguages` | string[] | Language codes to auto-load (e.g., `["eng", "en"]`); non-Signs/Songs tracks are preferred when several tracks match |
|
||||
| `autoLoadSecondarySub` | `true`, `false` | Auto-detect and load matching secondary subtitle track |
|
||||
| `defaultMode` | `"hidden"`, `"visible"`, `"hover"` | Initial display mode (default: `"hover"`) |
|
||||
|
||||
The secondary-subtitle language list also acts as the fallback secondary-language priority for managed startup subtitle selection on local playback and YouTube playback.
|
||||
|
||||
@@ -874,8 +863,8 @@ When config hot-reload updates shortcut/keybinding/style values, close and reope
|
||||
Use the runtime options palette to toggle settings live while SubMiner is running. These changes are session-only and reset on restart.
|
||||
|
||||
Current runtime options cover automatic card updates, known-word highlighting,
|
||||
known-word maturity coloring, N+1 annotation, JLPT underlines, frequency
|
||||
highlighting, known-word match mode, and Kiku field grouping mode.
|
||||
N+1 annotation, JLPT underlines, frequency highlighting, known-word match mode,
|
||||
and Kiku field grouping mode.
|
||||
|
||||
Annotation toggles only apply to new subtitle lines after the toggle. The currently displayed line is not re-tokenized in place.
|
||||
|
||||
@@ -1042,8 +1031,6 @@ This example is intentionally compact. The option table below documents availabl
|
||||
| `ankiConnect.knownWords.matchMode` | `"headword"`, `"surface"` | Matching strategy for known-word highlighting (default: `"headword"`). `headword` uses token headwords; `surface` uses visible subtitle text. |
|
||||
| `ankiConnect.knownWords.refreshMinutes` | number | Minutes between known-word cache refreshes (default: `1440`) |
|
||||
| `ankiConnect.knownWords.decks` | object | Deck→fields mapping used for known-word cache query scope (e.g. `{ "Kaishi 1.5k": ["Word"] }`). |
|
||||
| `ankiConnect.knownWords.maturityEnabled` | `true`, `false` | Color known words by Anki card maturity (new/learning/young/mature) instead of one color. Requires `knownWords.highlightEnabled` (default: `false`). Tier colors come from `subtitleStyle.knownWordMaturityColors`. |
|
||||
| `ankiConnect.knownWords.matureThresholdDays` | number | Card interval in days at which a known word counts as mature (default: `21`, matching Anki's own convention) |
|
||||
| `ankiConnect.nPlusOne.enabled` | `true`, `false` | Enable N+1 subtitle highlighting (highlights the one unknown word in a sentence). Independent from `knownWords.highlightEnabled`. Requires known-word cache data (default: `false`). |
|
||||
| `ankiConnect.nPlusOne.minSentenceWords` | number | Minimum number of words required in a sentence before single unknown-word N+1 highlighting can trigger (default: `3`). |
|
||||
| `behavior.notificationType` | `"overlay"`, `"system"`, `"both"`, `"none"` | Notification type on card update (default: `"overlay"`). `"both"` means overlay + system. `osd` and `osd-system` are legacy config-file-only values; use `"osd-system"` to keep the old OSD + system behavior. |
|
||||
@@ -1089,7 +1076,6 @@ Known-word cache policy:
|
||||
- `subtitleStyle.nPlusOneColor` sets the color for the single target token when exactly one eligible unknown word exists.
|
||||
- The N+1 minimum sentence-word setting controls the token count required before N+1 highlighting can trigger.
|
||||
- `subtitleStyle.knownWordColor` sets the known-word highlight color for tokens already in Anki.
|
||||
- Set `ankiConnect.knownWords.maturityEnabled` to `true` to color known words by Anki card maturity instead, using the four `subtitleStyle.knownWordMaturityColors` tiers. See [Known-Word Maturity Highlighting](/subtitle-annotations#known-word-maturity-highlighting) for how tiers are derived. Changing it or `matureThresholdDays` forces a full cache refresh.
|
||||
- The known-word deck map accepts an object keyed by deck name.
|
||||
- Prefer expression/word fields such as `Expression` or `Word`. Avoid reading-only fields unless you intentionally want homophone readings to count as known words.
|
||||
- Cache state is persisted to `known-words-cache.json` under the app `userData` directory.
|
||||
@@ -1128,7 +1114,6 @@ When the manual merge popup opens, SubMiner pauses playback and closes any open
|
||||
|
||||
<video controls playsinline preload="metadata" :poster="withBase('/assets/kiku-integration-poster.jpg')" style="width: 100%; max-width: 960px;">
|
||||
<source :src="withBase('/assets/kiku-integration.webm')" type="video/webm" />
|
||||
<source :src="withBase('/assets/kiku-integration.mp4')" type="video/mp4" />
|
||||
Your browser does not support the video tag.
|
||||
</video>
|
||||
|
||||
@@ -1154,28 +1139,6 @@ Configure Jimaku API access and defaults:
|
||||
|
||||
Jimaku is rate limited; if you hit a limit, SubMiner will surface the retry delay from the API response.
|
||||
|
||||
### TsukiHime
|
||||
|
||||
TsukiHime subtitle search works out of the box and needs no account or API key. It does require the `xz` binary on your `PATH`, because TsukiHime serves extracted subtitles xz-compressed.
|
||||
|
||||
```json
|
||||
{
|
||||
"tsukihime": {
|
||||
"apiBaseUrl": "https://api.tsukihime.org/v1",
|
||||
"maxSearchResults": 10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Option | Values | Description |
|
||||
| ---------------------------- | ------------ | ---------------------------------------------------------------------------------------------------- |
|
||||
| `tsukihime.apiBaseUrl` | string (URL) | Base URL of the TsukiHime API (default: `https://api.tsukihime.org/v1`). Only change it for a mirror. |
|
||||
| `tsukihime.maxSearchResults` | number | Maximum releases returned per search (default: `10`; the API caps this at 100) |
|
||||
|
||||
The keyboard shortcut lives under `shortcuts.openTsukihime` (default `Ctrl+Shift+T`; set to `null` to disable). The older `animetosho` section and `shortcuts.openAnimetosho` are still accepted as deprecated aliases, with the current names taking precedence when both are set.
|
||||
|
||||
See [TsukiHime Integration](/tsukihime-integration) for the modal workflow, language tabs, and troubleshooting.
|
||||
|
||||
### Subtitle Sync
|
||||
|
||||
Sync the active subtitle track from the overlay picker using `alass` or `ffsubsync`. Both are **optional external tools** that must be installed separately and available on your `PATH` (or configured via the path options below).
|
||||
@@ -1528,7 +1491,7 @@ Configure the mpv executable, profile, and window state for SubMiner-managed mpv
|
||||
"executablePath": "",
|
||||
"launchMode": "normal",
|
||||
"profile": "",
|
||||
"socketPath": "/tmp/subminer-socket",
|
||||
"socketPath": "\\\\.\\pipe\\subminer-socket",
|
||||
"backend": "auto",
|
||||
"autoStartSubMiner": true,
|
||||
"pauseUntilOverlayReady": true,
|
||||
|
||||
@@ -20,6 +20,9 @@ Mine vocabulary cards from Yomitan or directly from subtitle lines. SubMiner aut
|
||||
</a>
|
||||
</video>
|
||||
|
||||
::: info VIDEO COMING SOON
|
||||
:::
|
||||
|
||||
## Subtitle Download & Sync
|
||||
|
||||
Search and download subtitles from Jimaku, then retime them with alass or ffsubsync - all from within SubMiner.
|
||||
|
||||
@@ -14,10 +14,6 @@ const ankiIntegrationContents = readFileSync(
|
||||
'utf8',
|
||||
);
|
||||
const configurationContents = readFileSync(new URL('./configuration.md', import.meta.url), 'utf8');
|
||||
const troubleshootingContents = readFileSync(
|
||||
new URL('./troubleshooting.md', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
function extractReleaseHeadings(content: string, count: number): string[] {
|
||||
return Array.from(content.matchAll(/^## v[^\n]+$/gm))
|
||||
@@ -62,33 +58,6 @@ test('docs reflect current launcher and release surfaces', () => {
|
||||
expect(changelogContents).toContain('v0.5.1 (2026-03-09)');
|
||||
});
|
||||
|
||||
test('docs document config surfaces that are easy to miss when they ship', () => {
|
||||
// Anki maturity-based known-word highlighting (#172) landed in
|
||||
// subtitle-annotations.md but was missing from the config reference.
|
||||
expect(configurationContents).toContain('ankiConnect.knownWords.maturityEnabled');
|
||||
expect(configurationContents).toContain('ankiConnect.knownWords.matureThresholdDays');
|
||||
|
||||
// Every top-level config block should be reachable from the config reference.
|
||||
expect(configurationContents).toContain('### TsukiHime');
|
||||
expect(configurationContents).toContain('tsukihime.maxSearchResults');
|
||||
|
||||
// xz is a hard runtime dependency of the TsukiHime download path.
|
||||
expect(installationContents).toContain('xz');
|
||||
});
|
||||
|
||||
test('docs state the real secondary-subtitle and Anki field-matching behavior', () => {
|
||||
// secondarySub auto-load is off by default; the config example previously
|
||||
// implied otherwise while youtube-integration.md documented it correctly.
|
||||
expect(configurationContents).toContain('Secondary subtitles do **not** auto-load by default');
|
||||
expect(configurationContents).toContain('default: `false`');
|
||||
|
||||
// Anki field names are matched case-insensitively (src/anki-integration.ts
|
||||
// resolveFieldName: exact match first, then a lowercase comparison).
|
||||
expect(usageContents).not.toContain('exactly (case-sensitive)');
|
||||
expect(troubleshootingContents).not.toContain('exactly (case-sensitive)');
|
||||
expect(ankiIntegrationContents).toContain('case-insensitively');
|
||||
});
|
||||
|
||||
test('docs dev server links version navigation to local dev routes', () => {
|
||||
expect(docsPackageContents).toContain('scripts/build-versioned-docs.ts');
|
||||
expect(docsPackageContents).toContain(
|
||||
|
||||
+17
-109
@@ -12,23 +12,20 @@ Three steps to get started:
|
||||
|
||||
Only **mpv** is strictly required to run SubMiner. Everything else enhances the experience but is optional.
|
||||
|
||||
Several entries below exist only for the `subminer` command-line launcher, which is Linux and macOS only. On Windows you launch playback with the **SubMiner mpv** shortcut instead, so you can ignore those rows.
|
||||
|
||||
| Dependency | Status | Platforms | What it does |
|
||||
| -------------------- | ----------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| mpv | Required | All | The video player SubMiner overlays on. Must support `--input-ipc-server`. |
|
||||
| ffmpeg | Recommended | All | Audio extraction and screenshots for Anki cards. Without it SubMiner still runs, but media fields will be empty. |
|
||||
| MeCab + mecab-ipadic | Recommended | All | Part-of-speech filtering for more precise N+1, JLPT, and frequency annotations. Without it annotations still render, but POS-based filtering is less accurate. |
|
||||
| yt-dlp | Optional | All | YouTube playback and subtitle extraction. |
|
||||
| xz | Optional | All | Required for TsukiHime subtitle downloads (subtitles are served xz-compressed). Preinstalled on most Linux distros; not present on Windows by default. |
|
||||
| guessit | Optional | All | Better AniSkip title/season/episode parsing. |
|
||||
| alass | Optional | All | Subtitle sync engine (preferred). Disabled without alass or ffsubsync. |
|
||||
| ffsubsync | Optional | All | Audio-based subtitle sync engine. Disabled without alass or ffsubsync. |
|
||||
| fzf | Optional | Linux, macOS | Terminal-based video picker in the `subminer` launcher. |
|
||||
| rofi | Optional | Linux | GUI-based video picker in the `subminer` launcher. |
|
||||
| chafa | Optional | Linux, macOS | Thumbnail previews in the fzf picker. |
|
||||
| ffmpegthumbnailer | Optional | Linux, macOS | Video thumbnail generation for the pickers. |
|
||||
| fuse2 | Required | Linux | Needed to run the AppImage. |
|
||||
| Dependency | Status | What it does |
|
||||
| -------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| mpv | Required | The video player SubMiner overlays on. Must support `--input-ipc-server`. |
|
||||
| ffmpeg | Recommended | Audio extraction and screenshots for Anki cards. Without it SubMiner still runs, but media fields will be empty. |
|
||||
| MeCab + mecab-ipadic | Recommended | Part-of-speech filtering for more precise N+1, JLPT, and frequency annotations. Without it annotations still render, but POS-based filtering is less accurate. |
|
||||
| yt-dlp | Optional | YouTube playback and subtitle extraction. |
|
||||
| fzf | Optional | Terminal-based video picker in the launcher. |
|
||||
| rofi | Optional | GUI-based video picker (Linux). |
|
||||
| chafa | Optional | Thumbnail previews in fzf. |
|
||||
| ffmpegthumbnailer | Optional | Video thumbnail generation for the picker. |
|
||||
| guessit | Optional | Better AniSkip title/season/episode parsing. |
|
||||
| alass | Optional | Subtitle sync engine (preferred). Disabled without alass or ffsubsync. |
|
||||
| ffsubsync | Optional | Audio-based subtitle sync engine. Disabled without alass or ffsubsync. |
|
||||
| fuse2 | Linux only | Required to run the AppImage. |
|
||||
|
||||
### Linux
|
||||
|
||||
@@ -112,98 +109,9 @@ pip install ffsubsync
|
||||
|
||||
### Windows
|
||||
|
||||
Windows 10 or later. No compositor tools or window helpers are needed - native window tracking is built in.
|
||||
Windows 10 or later. Install [`mpv`](https://mpv.io/installation/) and [`ffmpeg`](https://ffmpeg.org/download.html) and ensure both are on `PATH`. Optionally install [MeCab for Windows](https://taku910.github.io/mecab/#download) with the UTF-8 dictionary.
|
||||
|
||||
You need **mpv** (required) and **ffmpeg** (strongly recommended, for card audio and screenshots), and both must be on your `PATH`.
|
||||
|
||||
::: tip What is PATH?
|
||||
`PATH` is the list of folders Windows searches when a program asks to run another program by name. SubMiner runs `mpv` and `ffmpeg` by name, so if their folders are not on `PATH`, SubMiner cannot find them even though they are installed. The routes below mostly handle `PATH` for you; the manual route explains how to add a folder yourself.
|
||||
:::
|
||||
|
||||
You can install these with a package manager or by hand. Coverage differs, so pick based on what you need:
|
||||
|
||||
| Dependency | winget | Scoop |
|
||||
| ---------------- | --------------- | ------------- |
|
||||
| mpv (required) | `shinchiro.mpv` | `extras/mpv` |
|
||||
| ffmpeg | `Gyan.FFmpeg` | `main/ffmpeg` |
|
||||
| yt-dlp (YouTube) | `yt-dlp.yt-dlp` | `main/yt-dlp` |
|
||||
| xz (TsukiHime) | not packaged | `main/xz` |
|
||||
|
||||
Use **winget** if you want Microsoft's first-party tool and don't need TsukiHime subtitle downloads. Use **Scoop** if you want one package manager to cover everything, since it is the only one that also packages `xz`.
|
||||
|
||||
#### Recommended: winget
|
||||
|
||||
[winget](https://learn.microsoft.com/windows/package-manager/winget/) is Microsoft's own package manager and ships with Windows 11 and current Windows 10 (it comes with **App Installer** from the Microsoft Store). In **PowerShell** or **Command Prompt**:
|
||||
|
||||
```powershell
|
||||
winget install shinchiro.mpv
|
||||
winget install Gyan.FFmpeg
|
||||
```
|
||||
|
||||
Close and reopen your terminal, then check that both are found:
|
||||
|
||||
```powershell
|
||||
mpv --version
|
||||
ffmpeg -version
|
||||
```
|
||||
|
||||
`ffmpeg` is installed as a portable package, so winget links it into a folder that is already on your `PATH` and it should work right away.
|
||||
|
||||
`mpv` uses a regular installer, and depending on the version it may **not** add itself to `PATH`. If `mpv --version` says `not recognized`, you have two easy options:
|
||||
|
||||
- Note where it installed (usually `%LOCALAPPDATA%\Programs\mpv`) and add that folder to `PATH` using the manual steps below, or
|
||||
- Skip `PATH` entirely and set `mpv.executablePath` to the full path of `mpv.exe` during first-run setup.
|
||||
|
||||
Once `mpv --version` works, or you have the full path to `mpv.exe` ready, continue to [step 2](#_2-install-subminer).
|
||||
|
||||
<details>
|
||||
<summary><b>Alternative: Scoop (covers every dependency, no admin rights)</b></summary>
|
||||
|
||||
[Scoop](https://scoop.sh) installs into your user profile, needs no administrator prompt, and always puts commands on `PATH`. It is the only Windows package manager that carries all of SubMiner's optional dependencies, including `xz`, so it is the best choice if you want a single tool to manage everything.
|
||||
|
||||
```powershell
|
||||
# One-time Scoop setup (skip if you already have it)
|
||||
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
|
||||
Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression
|
||||
|
||||
# mpv lives in the "extras" bucket; everything else is in "main"
|
||||
scoop bucket add extras
|
||||
scoop install extras/mpv main/ffmpeg
|
||||
|
||||
# Optional: yt-dlp for YouTube playback, xz for TsukiHime subtitle downloads
|
||||
scoop install main/yt-dlp main/xz
|
||||
```
|
||||
|
||||
Close and reopen your terminal, then verify with `mpv --version` and `ffmpeg -version`.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Manual install (download the zips yourself)</b></summary>
|
||||
|
||||
1. Download mpv from [mpv.io/installation](https://mpv.io/installation/) (the Windows builds link) and ffmpeg from [ffmpeg.org/download.html](https://ffmpeg.org/download.html).
|
||||
2. Unzip each one somewhere permanent, for example `C:\Tools\mpv` and `C:\Tools\ffmpeg`. Note the folder that actually contains `mpv.exe` and the one containing `ffmpeg.exe` (for ffmpeg this is usually a `bin` subfolder).
|
||||
3. Press `Win`, type **Edit the system environment variables**, and open it. Click **Environment Variables…**, select **Path** under **User variables**, click **Edit…**, then use **New** to add each of those two folders. Confirm with **OK** on every dialog. Microsoft documents this in more detail under [environment variables](https://learn.microsoft.com/windows/deployment/usmt/usmt-recognized-environment-variables).
|
||||
4. Close and reopen your terminal, since `PATH` changes only apply to newly opened windows. Then check:
|
||||
|
||||
```powershell
|
||||
mpv --version
|
||||
ffmpeg -version
|
||||
```
|
||||
|
||||
If you see `not recognized as the name of a cmdlet`, the folder you added is not the one holding the `.exe`. Reopen the Path editor and double-check.
|
||||
|
||||
::: tip mpv can skip PATH, ffmpeg cannot
|
||||
If you would rather not edit `PATH` for mpv, set `mpv.executablePath` to the full path of `mpv.exe` during first-run setup instead.
|
||||
|
||||
There is no equivalent setting for ffmpeg: SubMiner invokes it by bare name when generating card audio and screenshots, so ffmpeg has to be on `PATH`. Without it, cards are still created but their audio and image fields come out empty. (`subsync.ffmpeg_path` only affects subtitle sync, not card media.)
|
||||
:::
|
||||
|
||||
</details>
|
||||
|
||||
**Optional extras:** [MeCab for Windows](https://taku910.github.io/mecab/#download) with the UTF-8 dictionary improves annotation accuracy; it is not in any package manager, so install it from that page. `xz` is needed only for [TsukiHime](/tsukihime-integration) subtitle downloads and is not packaged by winget or Chocolatey, so use `scoop install main/xz` or download [XZ Utils](https://tukaani.org/xz/) and add its folder to `PATH`.
|
||||
|
||||
The `subminer` command-line launcher and its picker tools (`fzf`, `rofi`, `chafa`, `ffmpegthumbnailer`) are Linux/macOS only; on Windows you use the **SubMiner mpv** shortcut instead.
|
||||
No compositor tools or window helpers are needed - native window tracking is built in.
|
||||
|
||||
## 2. Install SubMiner
|
||||
|
||||
@@ -370,7 +278,7 @@ Run the built-in diagnostic to confirm everything is working:
|
||||
subminer doctor
|
||||
```
|
||||
|
||||
This checks for the app binary, mpv, ffmpeg, yt-dlp, fzf, rofi, your config file, and the mpv socket path. Only the app binary and mpv are hard failures; the rest are reported as optional. Fix any hard failures before continuing.
|
||||
This checks for the app binary, mpv, ffmpeg, config file, and socket path. Fix any failures before continuing.
|
||||
|
||||
## Anki Setup (Recommended)
|
||||
|
||||
|
||||
@@ -112,5 +112,5 @@ Verify mpv is running and connected via IPC. SubMiner loads the subtitle by issu
|
||||
## Related
|
||||
|
||||
- [Configuration Reference](/configuration#jimaku) - full config options
|
||||
- [Mining Workflow](/mining-workflow#related-features) - how Jimaku fits into the sentence mining loop
|
||||
- [Mining Workflow](/mining-workflow#jimaku-subtitle-search) - how Jimaku fits into the sentence mining loop
|
||||
- [Troubleshooting](/troubleshooting#jimaku) - additional error guidance
|
||||
|
||||
@@ -176,22 +176,22 @@ Use `subminer <subcommand> -h` for command-specific help.
|
||||
|
||||
## Options
|
||||
|
||||
| Flag | Description |
|
||||
| --------------------- | ---------------------------------------------------------------------------- |
|
||||
| `-d, --directory` | Video search directory (default: cwd) |
|
||||
| `-r, --recursive` | Search directories recursively |
|
||||
| `-R, --rofi` | Use rofi instead of fzf |
|
||||
| `-H, --history` | Browse local watch history (see [Watch History](#watch-history)) |
|
||||
| `-v, --version` | Print the launcher's own version (can differ from the installed app binary) |
|
||||
| `-u, --update` | Check for SubMiner updates and update the app/launcher when possible |
|
||||
| `--start` | Explicitly start overlay after mpv launches |
|
||||
| `-S, --start-overlay` | Force the visible overlay on start |
|
||||
| `-T, --no-texthooker` | Disable texthooker server |
|
||||
| `-p, --profile` | mpv profile name (no default; omitted unless set) |
|
||||
| `-a, --args` | Pass additional mpv arguments as a quoted string |
|
||||
| `-b, --backend` | Force window backend (`auto`, `hyprland`, `sway`, `x11`, `macos`, `windows`) |
|
||||
| `--settings` | Open the SubMiner settings window |
|
||||
| `--log-level` | Logger verbosity (`debug`, `info`, `warn`, `error`) |
|
||||
| Flag | Description |
|
||||
| --------------------- | --------------------------------------------------------------------------- |
|
||||
| `-d, --directory` | Video search directory (default: cwd) |
|
||||
| `-r, --recursive` | Search directories recursively |
|
||||
| `-R, --rofi` | Use rofi instead of fzf |
|
||||
| `-H, --history` | Browse local watch history (see [Watch History](#watch-history)) |
|
||||
| `-v, --version` | Print the launcher's own version (can differ from the installed app binary) |
|
||||
| `-u, --update` | Check for SubMiner updates and update the app/launcher when possible |
|
||||
| `--start` | Explicitly start overlay after mpv launches |
|
||||
| `-S, --start-overlay` | Force the visible overlay on start |
|
||||
| `-T, --no-texthooker` | Disable texthooker server |
|
||||
| `-p, --profile` | mpv profile name (no default; omitted unless set) |
|
||||
| `-a, --args` | Pass additional mpv arguments as a quoted string |
|
||||
| `-b, --backend` | Force window backend (`hyprland`, `sway`, `x11`, `macos`, `windows`) |
|
||||
| `--settings` | Open the SubMiner settings window |
|
||||
| `--log-level` | Logger verbosity (`debug`, `info`, `warn`, `error`) |
|
||||
|
||||
App-binary flags such as `--setup`, `--dev`, and `--debug` are not launcher flags - pass them through with `subminer app`, for example `subminer app --setup`.
|
||||
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const docsSiteDir = fileURLToPath(new URL('.', import.meta.url));
|
||||
|
||||
// Mirrors VitePress' heading slugifier (vitepress/dist/node, `rControl` + `rSpecial`).
|
||||
// Note that a *run* of special characters collapses to a single `-`, so
|
||||
// "KDE Plasma & other" becomes "kde-plasma-other", not "kde-plasma--other".
|
||||
const rControl = new RegExp('[\\u0000-\\u001f]', 'g');
|
||||
const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'“”‘’<>,.?/]+/g;
|
||||
|
||||
function slugify(heading: string): string {
|
||||
return heading
|
||||
.replace(rControl, '')
|
||||
.replace(rSpecial, '-')
|
||||
.replace(/-{2,}/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.replace(/^(\d)/, '_$1')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
const EXCLUDED_PAGES = new Set(['README.md']);
|
||||
const PUBLIC_PREFIXES = ['/assets/', '/screenshots/', '/config.example.jsonc', '/favicon'];
|
||||
|
||||
function loadPages(): Map<string, string> {
|
||||
const pages = new Map<string, string>();
|
||||
for (const file of readdirSync(docsSiteDir)) {
|
||||
if (!file.endsWith('.md') || EXCLUDED_PAGES.has(file)) continue;
|
||||
const route = `/${file.replace(/\.md$/, '')}`;
|
||||
pages.set(route, readFileSync(`${docsSiteDir}${file}`, 'utf8'));
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
|
||||
function anchorsFor(contents: string): Set<string> {
|
||||
const anchors = new Set<string>();
|
||||
for (const match of contents.matchAll(/^#{1,6}\s+(.+?)\s*$/gm)) {
|
||||
let heading = match[1]!;
|
||||
const explicitId = heading.match(/\{#([^}]+)\}\s*$/);
|
||||
if (explicitId) {
|
||||
anchors.add(explicitId[1]!);
|
||||
heading = heading.replace(/\{#[^}]+\}\s*$/, '');
|
||||
}
|
||||
anchors.add(slugify(heading.replace(/`/g, '')));
|
||||
}
|
||||
return anchors;
|
||||
}
|
||||
|
||||
function resolveRoute(target: string, fromRoute: string): string {
|
||||
if (target === '') return fromRoute;
|
||||
if (target.startsWith('./')) return `/${target.slice(2).replace(/\.md$/, '')}`;
|
||||
const normalized = target.replace(/\.md$/, '').replace(/\/$/, '');
|
||||
return normalized === '' ? '/index' : normalized;
|
||||
}
|
||||
|
||||
const pages = loadPages();
|
||||
const anchors = new Map([...pages].map(([route, body]) => [route, anchorsFor(body)]));
|
||||
|
||||
test('every internal docs link resolves to an existing page', () => {
|
||||
const broken: string[] = [];
|
||||
|
||||
for (const [route, body] of pages) {
|
||||
for (const match of body.matchAll(/\]\((\/[^)\s]*|\.\/[^)\s]*)\)/g)) {
|
||||
const link = match[1]!;
|
||||
const target = link.split('#')[0]!;
|
||||
if (PUBLIC_PREFIXES.some((prefix) => target.startsWith(prefix))) continue;
|
||||
|
||||
const resolved = resolveRoute(target, route);
|
||||
if (resolved !== '/index' && !pages.has(resolved)) {
|
||||
broken.push(`${route.slice(1)}.md -> ${link}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(broken).toEqual([]);
|
||||
});
|
||||
|
||||
test('every internal docs anchor matches a real heading slug', () => {
|
||||
const broken: string[] = [];
|
||||
|
||||
for (const [route, body] of pages) {
|
||||
for (const match of body.matchAll(/\]\((\/[^)\s]*|\.\/[^)\s]*|#[^)\s]*)\)/g)) {
|
||||
const link = match[1]!;
|
||||
const hashIndex = link.indexOf('#');
|
||||
if (hashIndex < 0) continue;
|
||||
|
||||
const target = link.slice(0, hashIndex);
|
||||
const anchor = link.slice(hashIndex + 1);
|
||||
if (PUBLIC_PREFIXES.some((prefix) => target.startsWith(prefix))) continue;
|
||||
|
||||
const resolved = resolveRoute(target, route);
|
||||
const pageAnchors = anchors.get(resolved);
|
||||
if (!pageAnchors || pageAnchors.has(anchor)) continue;
|
||||
|
||||
broken.push(`${route.slice(1)}.md -> ${link}`);
|
||||
}
|
||||
}
|
||||
|
||||
expect(broken).toEqual([]);
|
||||
});
|
||||
|
||||
test('slugify matches the VitePress cases these docs actually rely on', () => {
|
||||
// Regression guards for the anchors that were previously wrong.
|
||||
expect(slugify('N+1 Word Highlighting')).toBe('n-1-word-highlighting');
|
||||
expect(slugify('KDE Plasma & other Wayland compositors')).toBe(
|
||||
'kde-plasma-other-wayland-compositors',
|
||||
);
|
||||
expect(slugify('Proxy Mode Setup (Yomitan / Texthooker)')).toBe(
|
||||
'proxy-mode-setup-yomitan-texthooker',
|
||||
);
|
||||
expect(slugify('Kiku/Lapis Integration')).toBe('kiku-lapis-integration');
|
||||
expect(slugify('Secondary Subtitles')).toBe('secondary-subtitles');
|
||||
expect(slugify('2. Install SubMiner')).toBe('_2-install-subminer');
|
||||
});
|
||||
|
||||
test('every docs page is reachable from the sidebar', async () => {
|
||||
const { default: config } = await import('./.vitepress/config');
|
||||
const sidebar = config.themeConfig?.sidebar as Array<{
|
||||
items?: Array<{ text: string; link?: string }>;
|
||||
}>;
|
||||
|
||||
const linked = new Set<string>();
|
||||
for (const group of sidebar) {
|
||||
for (const item of group.items ?? []) {
|
||||
if (item.link) linked.add(item.link === '/' ? '/index' : item.link);
|
||||
}
|
||||
}
|
||||
|
||||
const orphans = [...pages.keys()].filter((route) => !linked.has(route));
|
||||
expect(orphans).toEqual([]);
|
||||
});
|
||||
@@ -183,7 +183,7 @@ If you want to build your own browser client, websocket consumer, or automation
|
||||
These features support the mining loop but have their own dedicated pages:
|
||||
|
||||
- **[Jimaku subtitle search](/jimaku-integration)** - search and download anime subtitle files directly from the overlay (`Ctrl+Shift+J` by default), then load them into mpv.
|
||||
- **[N+1 word highlighting](/subtitle-annotations#n-1-word-highlighting)** - cross-reference your Anki decks to highlight known words, making true N+1 sentences (exactly one unknown word) easy to spot during immersion.
|
||||
- **[N+1 word highlighting](/subtitle-annotations#n1-word-highlighting)** - cross-reference your Anki decks to highlight known words, making true N+1 sentences (exactly one unknown word) easy to spot during immersion.
|
||||
- **[Immersion tracking](/immersion-tracking)** - log watching and mining activity to a local database and view session times, words seen, and cards mined in the built-in stats dashboard.
|
||||
|
||||
Next: [Anki Integration](/anki-integration) - field mapping, media generation, and card enrichment configuration.
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"docs:dev": "SUBMINER_DOCS_VERSION_LINK_ORIGIN=local bun run ../scripts/build-versioned-docs.ts && SUBMINER_DOCS_VERSION_LINK_ORIGIN=local SUBMINER_DOCS_VERSION_MANIFEST=\"$(bun run ../scripts/print-docs-version-manifest.ts)\" VITE_EXTRA_EXTENSIONS=jsonc vitepress dev --host 0.0.0.0 --port 5173 --strictPort",
|
||||
"docs:build": "VITE_EXTRA_EXTENSIONS=jsonc vitepress build",
|
||||
"docs:preview": "VITE_EXTRA_EXTENSIONS=jsonc vitepress preview --host 0.0.0.0 --port 4173 --strictPort",
|
||||
"test": "bun test plausible.test.ts index.assets.test.ts docs-sync.test.ts links.test.ts seo.test.ts .vitepress/theme/status-line.test.ts ../scripts/docs-versioning.test.ts"
|
||||
"test": "bun test plausible.test.ts index.assets.test.ts docs-sync.test.ts seo.test.ts .vitepress/theme/status-line.test.ts ../scripts/docs-versioning.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@catppuccin/vitepress": "^0.1.2",
|
||||
|
||||
@@ -691,7 +691,7 @@
|
||||
"executablePath": "", // Optional absolute path to mpv.exe for Windows launch flows. Leave empty to auto-discover from SUBMINER_MPV_PATH or PATH.
|
||||
"launchMode": "normal", // Default window state for SubMiner-managed mpv launches. Values: normal | maximized | fullscreen
|
||||
"profile": "", // Optional mpv profile name passed to SubMiner-managed mpv launches. Leave empty to pass no profile.
|
||||
"socketPath": "/tmp/subminer-socket", // mpv IPC socket path used by SubMiner-managed playback and the bundled mpv plugin.
|
||||
"socketPath": "\\\\.\\pipe\\subminer-socket", // mpv IPC socket path used by SubMiner-managed playback and the bundled mpv plugin.
|
||||
"backend": "auto", // Window tracking backend passed to the bundled mpv plugin. Auto detects the current platform. Values: auto | hyprland | sway | x11 | macos | windows
|
||||
"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
|
||||
|
||||
@@ -251,9 +251,7 @@ test('dev docs version links use local targets for version route testing', async
|
||||
delete process.env.SUBMINER_DOCS_CHANNEL;
|
||||
delete process.env.SUBMINER_DOCS_BASE;
|
||||
delete process.env.SUBMINER_DOCS_VERSION;
|
||||
// Set explicitly (like the sibling version-nav tests) so this assertion stays
|
||||
// pinned to the manifest under test instead of the config's fallback constant.
|
||||
process.env.SUBMINER_DOCS_LATEST_STABLE = 'v0.14.0';
|
||||
delete process.env.SUBMINER_DOCS_LATEST_STABLE;
|
||||
process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = 'local';
|
||||
process.env.SUBMINER_DOCS_VERSION_MANIFEST = JSON.stringify({
|
||||
latestStable: 'v0.14.0',
|
||||
|
||||
+87
-104
@@ -16,6 +16,90 @@ SubMiner retries the connection automatically with increasing delays (200 ms, 50
|
||||
|
||||
If the overlay never appears at all, see [Playback Startup Flow](./architecture#playback-startup-flow) for how a managed launch starts mpv and brings up the overlay.
|
||||
|
||||
## Logging and App Mode
|
||||
|
||||
- Default log output is `warn`.
|
||||
- Use `--log-level` for more/less output.
|
||||
- Use `--dev`/`--debug` only to force app/dev mode (for example to get dev behavior from the overlay/app); they do not change log verbosity.
|
||||
- You can combine both, for example `SubMiner.AppImage --start --dev --log-level debug`, when you need maximum diagnostics.
|
||||
|
||||
## Performance and Resource Impact
|
||||
|
||||
### At a glance
|
||||
|
||||
- Baseline: `SubMiner --start` is usually lightweight for normal playback.
|
||||
- Common spikes come from:
|
||||
- first subtitle parse/tokenization bursts
|
||||
- media generation (`ffmpeg` audio/image and AVIF paths)
|
||||
- media sync and subtitle tooling (`alass`, `ffsubsync`)
|
||||
- `ankiConnect` enrichment (plus polling overhead when proxy mode is disabled)
|
||||
|
||||
### If playback feels sluggish
|
||||
|
||||
1. Reduce overlay workload:
|
||||
|
||||
- set secondary subtitles hidden:
|
||||
- `secondarySub.defaultMode: "hidden"`
|
||||
- disable optional enrichment:
|
||||
- `subtitleStyle.enableJlpt: false`
|
||||
- `subtitleStyle.frequencyDictionary.enabled: false`
|
||||
|
||||
2. Reduce rendering pressure:
|
||||
|
||||
- lower `subtitleStyle.css["font-size"]`
|
||||
- keep overlay complexity minimal during heavy CPU periods
|
||||
|
||||
3. Reduce media overhead:
|
||||
|
||||
- keep `ankiConnect.media.imageType` set to `static` (avoid animated AVIF unless needed)
|
||||
- lower `ankiConnect.media.imageQuality`
|
||||
- reduce `ankiConnect.media.maxMediaDuration`
|
||||
|
||||
4. Lower integration cost:
|
||||
|
||||
- disable AI translation when not needed (`ankiConnect.ai.enabled: false`)
|
||||
- if needed, run immersion telemetry with lower duration expectations (`immersionTracking.enabled: false` for constrained sessions)
|
||||
- favor the default lightweight YouTube subtitle startup settings on low-resource systems
|
||||
|
||||
### Practical low-impact profile
|
||||
|
||||
```json
|
||||
{
|
||||
"subtitleStyle": {
|
||||
"css": {
|
||||
"font-size": "30px"
|
||||
},
|
||||
"enableJlpt": false,
|
||||
"frequencyDictionary": {
|
||||
"enabled": false
|
||||
}
|
||||
},
|
||||
"secondarySub": {
|
||||
"defaultMode": "hidden"
|
||||
},
|
||||
"ankiConnect": {
|
||||
"media": {
|
||||
"imageType": "static",
|
||||
"imageQuality": 80,
|
||||
"maxMediaDuration": 12
|
||||
},
|
||||
"ai": {
|
||||
"enabled": false
|
||||
}
|
||||
},
|
||||
"immersionTracking": {
|
||||
"enabled": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### If usage is still high
|
||||
|
||||
- Confirm only one SubMiner instance is running.
|
||||
- Check whether bottlenecks are `ffmpeg`, `yt-dlp`, or sync tooling in system monitor.
|
||||
- Keep the default `warn` level for normal use; raise to `info` or `debug` only for targeted diagnosis.
|
||||
- Reproduce once with `SubMiner.AppImage --start --log-level debug` and open DevTools (`y` then `d`) if freezes recur.
|
||||
|
||||
**"Failed to parse MPV message"**
|
||||
|
||||
Logged when a malformed JSON line arrives from the mpv socket. Usually harmless - SubMiner skips the bad line and continues. If it happens constantly, check that nothing else is writing to the same socket path.
|
||||
@@ -64,7 +148,7 @@ SubMiner retries with exponential backoff (up to 5 s) and suppresses repeated er
|
||||
|
||||
**Cards are created but fields are empty**
|
||||
|
||||
Field names in your config must name a field that exists on your Anki note type. Matching is case-insensitive (`sentenceaudio` finds `SentenceAudio`), but the spelling must otherwise match, and unknown fields are skipped silently. Check `ankiConnect.fields` - for example, if your note type uses `SentenceAudio` but your config says `Audio`, the field will not be populated.
|
||||
Field names in your config must match your Anki note type exactly (case-sensitive). Check `ankiConnect.fields` - for example, if your note type uses `SentenceAudio` but your config says `Audio`, the field will not be populated.
|
||||
|
||||
See [Anki Integration](/anki-integration) for the full field mapping reference.
|
||||
|
||||
@@ -232,115 +316,17 @@ If subtitle sync fails (the error message is prefixed with the engine name):
|
||||
- Try running the sync tool manually to see detailed error output.
|
||||
- ffsubsync requires local files and cannot handle remote media streams (e.g., streaming URLs).
|
||||
|
||||
## TsukiHime
|
||||
|
||||
**"xz binary not found"**
|
||||
|
||||
TsukiHime serves extracted subtitles xz-compressed, so SubMiner shells out to `xz` to decompress them. Install it:
|
||||
|
||||
- **Arch Linux**: `sudo pacman -S xz`
|
||||
- **Ubuntu/Debian**: `sudo apt install xz-utils`
|
||||
- **Fedora**: `sudo dnf install xz`
|
||||
- **macOS**: `brew install xz`
|
||||
- **Windows**: neither winget nor Chocolatey packages `xz`. Use `scoop install main/xz`, or download XZ Utils from [tukaani.org/xz](https://tukaani.org/xz/) and add the folder containing `xz.exe` to your `PATH`. Restart SubMiner afterwards.
|
||||
|
||||
Most Linux distributions ship it already. See [TsukiHime Integration](/tsukihime-integration#troubleshooting) for the other TsukiHime error messages.
|
||||
|
||||
## Jimaku
|
||||
|
||||
**"Jimaku request failed" or HTTP 429**
|
||||
|
||||
The Jimaku API has rate limits. If you see 429 errors, wait for the retry duration shown in the OSD message and try again. If you have a Jimaku API key, set it in `jimaku.apiKey` or `jimaku.apiKeyCommand` to get higher rate limits.
|
||||
|
||||
## Logging and App Mode
|
||||
|
||||
- Default log output is `warn`.
|
||||
- Use `--log-level` for more/less output.
|
||||
- Use `--dev`/`--debug` only to force app/dev mode (for example to get dev behavior from the overlay/app); they do not change log verbosity.
|
||||
- You can combine both, for example `SubMiner.AppImage --start --dev --log-level debug`, when you need maximum diagnostics.
|
||||
|
||||
## Performance and Resource Impact
|
||||
|
||||
### At a glance
|
||||
|
||||
- Baseline: `SubMiner --start` is usually lightweight for normal playback.
|
||||
- Common spikes come from:
|
||||
- first subtitle parse/tokenization bursts
|
||||
- media generation (`ffmpeg` audio/image and AVIF paths)
|
||||
- media sync and subtitle tooling (`alass`, `ffsubsync`)
|
||||
- `ankiConnect` enrichment (plus polling overhead when proxy mode is disabled)
|
||||
|
||||
### If playback feels sluggish
|
||||
|
||||
1. Reduce overlay workload:
|
||||
|
||||
- set secondary subtitles hidden:
|
||||
- `secondarySub.defaultMode: "hidden"`
|
||||
- disable optional enrichment:
|
||||
- `subtitleStyle.enableJlpt: false`
|
||||
- `subtitleStyle.frequencyDictionary.enabled: false`
|
||||
|
||||
2. Reduce rendering pressure:
|
||||
|
||||
- lower `subtitleStyle.css["font-size"]`
|
||||
- keep overlay complexity minimal during heavy CPU periods
|
||||
|
||||
3. Reduce media overhead:
|
||||
|
||||
- keep `ankiConnect.media.imageType` set to `static` (avoid animated AVIF unless needed)
|
||||
- lower `ankiConnect.media.imageQuality`
|
||||
- reduce `ankiConnect.media.maxMediaDuration`
|
||||
|
||||
4. Lower integration cost:
|
||||
|
||||
- disable AI translation when not needed (`ankiConnect.ai.enabled: false`)
|
||||
- if needed, run immersion telemetry with lower duration expectations (`immersionTracking.enabled: false` for constrained sessions)
|
||||
- favor the default lightweight YouTube subtitle startup settings on low-resource systems
|
||||
|
||||
### Practical low-impact profile
|
||||
|
||||
```json
|
||||
{
|
||||
"subtitleStyle": {
|
||||
"css": {
|
||||
"font-size": "30px"
|
||||
},
|
||||
"enableJlpt": false,
|
||||
"frequencyDictionary": {
|
||||
"enabled": false
|
||||
}
|
||||
},
|
||||
"secondarySub": {
|
||||
"defaultMode": "hidden"
|
||||
},
|
||||
"ankiConnect": {
|
||||
"media": {
|
||||
"imageType": "static",
|
||||
"imageQuality": 80,
|
||||
"maxMediaDuration": 12
|
||||
},
|
||||
"ai": {
|
||||
"enabled": false
|
||||
}
|
||||
},
|
||||
"immersionTracking": {
|
||||
"enabled": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### If usage is still high
|
||||
|
||||
- Confirm only one SubMiner instance is running.
|
||||
- Check whether bottlenecks are `ffmpeg`, `yt-dlp`, or sync tooling in system monitor.
|
||||
- Keep the default `warn` level for normal use; raise to `info` or `debug` only for targeted diagnosis.
|
||||
- Reproduce once with `SubMiner.AppImage --start --log-level debug` and open DevTools (`y` then `d`) if freezes recur.
|
||||
|
||||
## Platform-Specific
|
||||
|
||||
### Linux
|
||||
|
||||
- **Wayland (Hyprland/Sway only)**: Native Wayland support is limited to Hyprland and Sway. Window tracking uses compositor-specific commands (`hyprctl` / `swaymsg`). If these are not on `PATH`, tracking will fail silently. Other Wayland compositors (KDE Plasma, GNOME, …) are not supported natively - both mpv and SubMiner must run under X11 or Xwayland instead. On those sessions SubMiner forces XWayland automatically for itself and for every mpv it launches (see [KDE Plasma & other Wayland compositors](#kde-plasma-other-wayland-compositors)).
|
||||
- **Wayland (Hyprland/Sway only)**: Native Wayland support is limited to Hyprland and Sway. Window tracking uses compositor-specific commands (`hyprctl` / `swaymsg`). If these are not on `PATH`, tracking will fail silently. Other Wayland compositors (KDE Plasma, GNOME, …) are not supported natively - both mpv and SubMiner must run under X11 or Xwayland instead. On those sessions SubMiner forces XWayland automatically for itself and for every mpv it launches (see [KDE Plasma & other Wayland compositors](#kde-plasma--other-wayland-compositors)).
|
||||
- **X11 / Xwayland**: Requires `xdotool`, `xprop`, and `xwininfo`. If missing, the overlay cannot track the mpv window position. This is the required backend for any Wayland compositor other than Hyprland or Sway - both mpv and SubMiner must be running under X11/Xwayland for window tracking _and_ for the overlay to stay above mpv (Wayland forbids clients from controlling window stacking). SubMiner uses a managed X11 overlay while mpv is windowed, switches to an override-redirect X11 overlay while tracked mpv is fullscreen, and hides/releases that overlay when another X11/Xwayland app takes focus. The visible overlay stays hidden until SubMiner has tracked mpv geometry, so startup should not create a display-sized fallback overlay while tokenization warms up.
|
||||
- **Tray icon missing**: SubMiner creates an Electron tray icon in `--background` mode, but Linux trays require a StatusNotifier/AppIndicator host. Hyprland does not provide one by itself; enable a tray in Waybar, Hyprpanel, or another panel. If Electron cannot register the tray, SubMiner logs a warning that mentions the missing tray host.
|
||||
- **Mouse passthrough**: On Linux X11/Xwayland, SubMiner uses `xdotool` to poll the cursor and only enables overlay input while the cursor is over subtitle or popup regions. Outside those regions, pointer input passes through to mpv. Native Wayland compositors other than Hyprland/Sway cannot provide the stacking control SubMiner needs.
|
||||
@@ -442,11 +428,8 @@ Feature-specific issues are covered in each feature's own page:
|
||||
- [Character Dictionary](/character-dictionary) - AniList character name matching and inline portraits
|
||||
- [Jellyfin Integration](/jellyfin-integration) - remote playback and library connection
|
||||
- [Jimaku Integration](/jimaku-integration) - subtitle fetching and API rate limits
|
||||
- [TsukiHime Integration](/tsukihime-integration) - multi-language subtitle download and `xz` decompression
|
||||
- [YouTube Integration](/youtube-integration) - subtitle generation and playback
|
||||
- [Immersion Tracking](/immersion-tracking) - telemetry, session logging, and the stats dashboard
|
||||
- [Launcher Script](/launcher-script) - `subminer` commands, pickers, watch history, and cross-machine sync
|
||||
- [MPV Plugin](/mpv-plugin) - in-player chords, script-opts, and binary auto-detection
|
||||
- [Immersion Tracking](/immersion-tracking) - telemetry and session logging
|
||||
- [WebSocket / Texthooker API](/websocket-texthooker-api) - external texthooker clients
|
||||
- [Subtitle Annotations](/subtitle-annotations) - N+1, frequency, JLPT, and name-match layers
|
||||
- [Subtitle Sidebar](/subtitle-sidebar) - sidebar navigation and behavior
|
||||
|
||||
+117
-96
@@ -33,7 +33,7 @@ If you want sentence, audio, and screenshot fields on your Anki cards, add this
|
||||
}
|
||||
```
|
||||
|
||||
Field names must match a field on your Anki note type. Matching is case-insensitive (an exact match wins, then a lowercase comparison), but the spelling must otherwise match. See [Anki Integration](/anki-integration) for the full reference.
|
||||
Field names must match your Anki note type exactly (case-sensitive). See [Anki Integration](/anki-integration) for the full reference.
|
||||
:::
|
||||
|
||||
## How It Works
|
||||
@@ -56,90 +56,126 @@ From there, subtitles render as interactive, hoverable word spans and you mine c
|
||||
|
||||
The mpv plugin is always available - it's bundled with SubMiner and injected at runtime. On Linux, normal `subminer` playback auto-installs the launcher-managed runtime plugin copy from the bundled app if that managed copy is missing, so no separate plugin install is needed for standard launcher usage. If you launch mpv yourself (without the launcher), pass `--input-ipc-server=/tmp/subminer-socket` in your mpv config for the overlay to connect.
|
||||
|
||||
## Live Config Reload
|
||||
|
||||
While SubMiner is running, it watches your active config file and applies safe updates automatically.
|
||||
|
||||
Live-updated settings include:
|
||||
|
||||
- `subtitleStyle`
|
||||
- `keybindings`
|
||||
- `shortcuts`
|
||||
- `secondarySub.defaultMode`
|
||||
- `subtitleSidebar`
|
||||
- `notifications`
|
||||
- `logging`
|
||||
- `jimaku`, `subsync`
|
||||
- `mpv.aniskipEnabled`, `mpv.aniskipButtonKey`
|
||||
- `stats.toggleKey`, `stats.markWatchedKey`
|
||||
- `youtube.primarySubLanguages`
|
||||
- most `ankiConnect.*` settings (including `ankiConnect.ai`)
|
||||
|
||||
Invalid config edits are rejected; SubMiner keeps the previous valid runtime config and shows an error notification.
|
||||
For restart-required sections, SubMiner shows a restart-needed notification.
|
||||
|
||||
## Commands
|
||||
|
||||
These are the commands you will actually use day to day. The full inventory of subcommands and flags lives in [Launcher Script](/launcher-script#subcommands).
|
||||
On Windows, replace `SubMiner.AppImage` with `SubMiner.exe` in the direct packaged-app examples below.
|
||||
|
||||
```bash
|
||||
subminer video.mkv # Play a specific file
|
||||
subminer # Browse the current directory (fzf picker)
|
||||
subminer -R # Browse with the rofi picker instead
|
||||
subminer -d ~/Anime -r # Browse a specific directory, recursively
|
||||
subminer -H # Browse watch history, then replay/next/previous
|
||||
# Browse and play videos
|
||||
subminer # Current directory (uses fzf)
|
||||
subminer -R # Use rofi instead of fzf
|
||||
subminer -d ~/Videos # Specific directory
|
||||
subminer -r -d ~/Anime # Recursive search
|
||||
subminer video.mkv # Play specific file (overlay auto-starts)
|
||||
subminer --start video.mkv # Explicit overlay start (use when mpv.autoStartSubMiner is false in config)
|
||||
subminer -S video.mkv # Also force the visible overlay on start (--start-overlay)
|
||||
subminer https://youtu.be/... # Play a YouTube URL
|
||||
subminer stats # Open the immersion stats dashboard
|
||||
subminer doctor # Check dependencies, config, and the mpv socket
|
||||
subminer settings # Open the SubMiner settings window
|
||||
subminer app --setup # Re-open first-run setup
|
||||
subminer -u # Check for updates
|
||||
```
|
||||
subminer ytsearch:"jp news" # Play first YouTube search result
|
||||
subminer -H # Browse history, then choose previous/replay/next after playback
|
||||
subminer app --setup # Open first-run setup popup
|
||||
subminer --version # Print the launcher's version
|
||||
subminer -v # Same as above
|
||||
subminer --log-level debug video.mkv # Enable verbose logs for launch/debugging
|
||||
subminer --log-level warn video.mkv # Set logging level explicitly
|
||||
subminer --args '--fs=opengl-hq --ytdl-format=bestvideo*+bestaudio/best' video.mkv # Pass extra mpv args
|
||||
|
||||
On **Windows** there is no `subminer` launcher. Use the **SubMiner mpv** shortcut for playback (see [Windows mpv Shortcut](#windows-mpv-shortcut)), and run `SubMiner.exe` directly for everything else.
|
||||
|
||||
Two flags are worth knowing early:
|
||||
|
||||
- `-a/--args` passes extra arguments straight to mpv, for example `subminer --args "--ao=alsa --volume=80" video.mkv`.
|
||||
- `--log-level debug` turns on verbose logging when something is not working.
|
||||
|
||||
<details>
|
||||
<summary><b>Less common launcher commands</b></summary>
|
||||
|
||||
```bash
|
||||
subminer --start video.mkv # Explicit overlay start (when mpv.autoStartSubMiner is false)
|
||||
subminer -S video.mkv # Also force the visible overlay on start
|
||||
subminer -T video.mkv # Disable the texthooker server
|
||||
subminer -b x11 video.mkv # Force a window backend
|
||||
# Options
|
||||
subminer -T video.mkv # Disable texthooker server
|
||||
subminer -b x11 video.mkv # Force X11 backend
|
||||
subminer video.mkv # No mpv profile passed by default
|
||||
subminer -p gpu-hq video.mkv # Use a specific mpv profile
|
||||
subminer ytsearch:"jp news" # Play the first YouTube search result
|
||||
subminer texthooker # Texthooker-only mode (-o also opens the browser)
|
||||
subminer jellyfin # Open Jellyfin setup window (subcommand form)
|
||||
subminer jellyfin -l --server http://127.0.0.1:8096 --username me --password 'secret'
|
||||
subminer jellyfin --logout # Clear stored Jellyfin token/session data
|
||||
subminer jellyfin -p # Interactive Jellyfin library/item picker + playback
|
||||
subminer jellyfin -d # Jellyfin cast-discovery mode (background tray app)
|
||||
subminer app --stop # Stop background app (including Jellyfin cast broadcast)
|
||||
subminer doctor # Dependency + config + socket diagnostics
|
||||
subminer logs -e # Export a sanitized log ZIP and print its path
|
||||
subminer config path # Print active config path
|
||||
subminer config show # Print active config contents
|
||||
subminer mpv socket # Print active mpv socket path
|
||||
subminer mpv status # Exit 0 if socket is ready, else exit 1
|
||||
subminer mpv idle # Launch detached idle mpv with SubMiner defaults
|
||||
subminer sync media-box # Sync stats/watch history with an SSH host
|
||||
subminer sync media-box --push # Merge this machine's stats into the host only
|
||||
subminer sync media-box --pull # Merge the host's stats into this machine only
|
||||
subminer sync media-box --check # Verify SSH and remote SubMiner without syncing
|
||||
subminer sync media-box --json # Emit machine-readable NDJSON progress
|
||||
subminer sync --ui # Open the Sync Stats & History window
|
||||
subminer sync --snapshot ~/subminer-snapshot.sqlite # Write a local DB snapshot
|
||||
subminer sync --merge ~/subminer-snapshot.sqlite # Merge a snapshot into the local DB
|
||||
subminer sync --make-temp # Create an internal sync temp directory
|
||||
subminer sync --remove-temp /tmp/subminer-sync-123 # Remove an internal sync temp directory
|
||||
subminer dictionary /path/to/file-or-directory # Generate character dictionary ZIP from target (manual Yomitan import)
|
||||
subminer dictionary --candidates /path/to/file.mkv
|
||||
subminer dictionary --select 21355 /path/to/file.mkv
|
||||
subminer texthooker # Launch texthooker-only mode
|
||||
subminer texthooker -o # Launch texthooker and open it in your browser
|
||||
subminer stats # Start the local stats server (see Immersion Tracking)
|
||||
subminer stats -b # Start/reuse the background stats daemon
|
||||
subminer stats -s # Stop the background stats daemon
|
||||
subminer stats cleanup # Backfill vocabulary metadata, prune stale rows
|
||||
subminer stats rebuild # Rebuild rollup data
|
||||
subminer doctor --refresh-known-words # Refresh the known-word cache
|
||||
subminer logs -e # Export a sanitized log ZIP and print its path
|
||||
subminer config path # Print the active config path
|
||||
subminer config show # Print the active config contents
|
||||
subminer mpv socket # Print the active mpv socket path
|
||||
subminer mpv status # Exit 0 if the socket is ready, else exit 1
|
||||
subminer mpv idle # Launch a detached idle mpv with SubMiner defaults
|
||||
subminer app --stop # Stop the background app
|
||||
subminer --version # Print the launcher's version
|
||||
```
|
||||
subminer app --anilist-setup # Pass args directly to SubMiner binary (example: AniList login flow)
|
||||
|
||||
Jellyfin, cross-machine sync, and character-dictionary commands have their own sections: [Jellyfin](/jellyfin-integration), [Sync Between Machines](/launcher-script#sync-between-machines), and [Character Dictionary](/character-dictionary).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Direct packaged-app flags (advanced)</b></summary>
|
||||
|
||||
These call the app binary directly rather than going through the launcher. On Windows, replace `SubMiner.AppImage` with `SubMiner.exe`.
|
||||
|
||||
```bash
|
||||
SubMiner.AppImage --background # Start in background (tray + IPC wait, minimal logs)
|
||||
SubMiner.AppImage --start --texthooker # Start overlay with texthooker
|
||||
SubMiner.AppImage --texthooker # Texthooker only (no overlay window)
|
||||
SubMiner.AppImage --setup # Open first-run setup
|
||||
# Direct packaged app control
|
||||
SubMiner.AppImage --background # Start in background (tray + IPC wait, minimal logs)
|
||||
SubMiner.AppImage --start --texthooker # Start overlay with texthooker
|
||||
SubMiner.AppImage --texthooker # Launch texthooker only (no overlay window)
|
||||
SubMiner.AppImage --texthooker --open-browser # Launch texthooker and open browser
|
||||
SubMiner.AppImage --setup # Open first-run setup popup
|
||||
SubMiner.AppImage --stop # Stop overlay
|
||||
SubMiner.AppImage --start --toggle # Start mpv IPC + toggle visibility
|
||||
SubMiner.AppImage --show-visible-overlay # Force show the visible overlay
|
||||
SubMiner.AppImage --hide-visible-overlay # Force hide the visible overlay
|
||||
SubMiner.AppImage --toggle-primary-subtitle-bar # Toggle the primary subtitle bar
|
||||
SubMiner.AppImage --toggle-subtitle-sidebar # Toggle the subtitle sidebar
|
||||
SubMiner.AppImage --open-tsukihime # Open TsukiHime subtitle search
|
||||
SubMiner.AppImage --start --toggle # Start MPV IPC + toggle visibility
|
||||
SubMiner.AppImage --show-visible-overlay # Force show visible overlay
|
||||
SubMiner.AppImage --hide-visible-overlay # Force hide visible overlay
|
||||
SubMiner.AppImage --toggle-primary-subtitle-bar # Toggle primary subtitle bar visibility
|
||||
SubMiner.AppImage --toggle-subtitle-sidebar # Toggle the subtitle sidebar
|
||||
SubMiner.AppImage --open-tsukihime # Open TsukiHime subtitle search
|
||||
SubMiner.AppImage --start --dev # Enable app/dev mode only
|
||||
SubMiner.AppImage --start --debug # Alias for --dev
|
||||
SubMiner.AppImage --start --log-level debug # Force verbose logging without app/dev mode
|
||||
SubMiner.AppImage --playback-feedback "your feedback" # Route playback feedback through the configured feedback surface
|
||||
SubMiner.AppImage --yomitan # Open Yomitan settings
|
||||
SubMiner.AppImage --settings # Open the SubMiner settings window
|
||||
SubMiner.AppImage --jellyfin # Open the Jellyfin setup window
|
||||
SubMiner.AppImage --dictionary # Generate a character dictionary ZIP
|
||||
SubMiner.AppImage --start --dev # Enable app/dev mode
|
||||
SubMiner.AppImage --start --log-level debug # Verbose logging without dev mode
|
||||
SubMiner.AppImage --settings # Open SubMiner settings window
|
||||
SubMiner.AppImage --jellyfin # Open Jellyfin setup window
|
||||
SubMiner.AppImage --jellyfin-login --jellyfin-server http://127.0.0.1:8096 --jellyfin-username me --jellyfin-password 'secret'
|
||||
SubMiner.AppImage --jellyfin-logout # Clear stored Jellyfin token/session data
|
||||
SubMiner.AppImage --jellyfin-libraries
|
||||
SubMiner.AppImage --jellyfin-items --jellyfin-library-id LIBRARY_ID --jellyfin-search anime --jellyfin-limit 20
|
||||
SubMiner.AppImage --jellyfin-play --jellyfin-item-id ITEM_ID --jellyfin-audio-stream-index 1 --jellyfin-subtitle-stream-index 2 # Requires connected mpv IPC (--start)
|
||||
SubMiner.AppImage --jellyfin-remote-announce # Force cast-target capability announce + visibility check
|
||||
SubMiner.AppImage --sync-cli --help # Show the packaged app's headless sync help
|
||||
SubMiner.AppImage --sync-cli sync media-box # Run the sync engine directly in headless mode
|
||||
SubMiner.AppImage --dictionary # Generate character dictionary ZIP for current anime
|
||||
SubMiner.AppImage --dictionary-candidates # List AniList candidates for current character dictionary series
|
||||
SubMiner.AppImage --dictionary-select --dictionary-anilist-id 21355 # Pin correct AniList media for series
|
||||
SubMiner.AppImage --help # Show all options
|
||||
```
|
||||
|
||||
The remaining flags are internal or scripting-only surfaces: the `--jellyfin-*` family (login, library listing, item playback, cast announce), `--sync-cli` (the app's headless sync entrypoint that `subminer sync` proxies to), `--dictionary-candidates` / `--dictionary-select`, and `--playback-feedback <text>`. Run `SubMiner.AppImage --help` for the complete list. The previous `--open-animetosho` flag is still accepted as a deprecated alias for `--open-tsukihime`.
|
||||
`--check` performs connection and version checks without changing data. `--json` emits the NDJSON event protocol used by the sync window. `--ui` opens that window in a detached app process and returns the shell immediately; closing a standalone-launched Sync window exits that app instance. `--make-temp` and `--remove-temp` are internal remote-transfer helpers and should normally be left to SubMiner. The packaged app's `--sync-cli` flag selects its headless sync-compatible entrypoint; the `subminer sync` launcher command proxies to it automatically.
|
||||
|
||||
</details>
|
||||
The previous `--open-animetosho` flag remains accepted as a deprecated alias for `--open-tsukihime`.
|
||||
|
||||
The tray menu includes `Export Logs`, which creates the same sanitized local-date log ZIP as `subminer logs -e` and shows the archive path when complete. Export sanitization masks common PII and secrets, including home-directory usernames, IP addresses, emails, auth/cookie headers, yt-dlp cookie arguments, URL credentials, token/key/password fields, and signed YouTube media URL query strings. The exported copy is sanitized; source log files remain unredacted on disk.
|
||||
|
||||
@@ -181,11 +217,18 @@ This flow requires `mpv.exe` to be discoverable. Leave `mpv.executablePath` blan
|
||||
|
||||
### Launcher Subcommands
|
||||
|
||||
The launcher groups related work under subcommands: `jellyfin` (aliased `jf`), `stats`, `sync`, `dictionary` (aliased `dict`), `texthooker`, `doctor`, `settings`, `config`, `mpv`, `logs`, and `app` (aliased `bin`) for passing arguments straight to the SubMiner binary.
|
||||
|
||||
Every subcommand has its own help page, for example `subminer jellyfin -h`. See [Launcher Script - Subcommands](/launcher-script#subcommands) for the full table, and [Sync Between Machines](/launcher-script#sync-between-machines) for the SSH stats/history sync.
|
||||
|
||||
A _texthooker_ is a web page that displays the current subtitle line as selectable text, so browser-based dictionary extensions and other tools can read along with playback.
|
||||
- `subminer jellyfin` / `subminer jf`: Jellyfin-focused workflow aliases.
|
||||
- `subminer doctor`: health checks for core dependencies and runtime paths.
|
||||
- `subminer settings`: open the SubMiner settings window (also `subminer --settings`).
|
||||
- `subminer logs -e`: export a sanitized ZIP of today's local-date logs, or the most recent logs when no current-day log exists. The exported copy masks common PII and secrets; on-disk logs are unchanged.
|
||||
- `subminer config`: config file helpers (`path`, `show`).
|
||||
- `subminer mpv`: mpv helpers (`status`, `socket`, `idle`).
|
||||
- `subminer sync <host>`: sync immersion stats and watch history with another machine over SSH. The host is the SSH destination (`user@host` or an SSH config alias). Use `--push` to merge only this machine's data into the host, or `--pull` to merge only the host's data into this machine; both remain insert-only and do not make either database an exact mirror. Remote launcher checks include standard SubMiner and Bun paths even when SSH omits them from `PATH`. Use `--snapshot <file>` to write a consistent local stats DB snapshot, `--merge <file>` to merge a snapshot into the local stats DB, and `--force` to skip the running stats/mpv safety check. Advanced options: `--db <file>` overrides the local stats DB path, and `--remote-cmd <cmd>` overrides the `subminer` command used on the remote host.
|
||||
- `subminer dictionary <path>`: generates a Yomitan-importable character dictionary ZIP from a file/directory target.
|
||||
- Use `subminer dictionary --candidates <path>` and `subminer dictionary --select <id> <path>` to correct AniList character-dictionary matches for a whole series.
|
||||
- `subminer texthooker`: texthooker-only shortcut (same behavior as `--texthooker`). A _texthooker_ is a web page that displays the current subtitle line as selectable text, so browser-based dictionary extensions and other tools can read along with playback.
|
||||
- `subminer app` / `subminer bin`: direct passthrough to the SubMiner binary/AppImage.
|
||||
- Subcommand help pages are available (for example `subminer jellyfin -h`).
|
||||
|
||||
### First-Run Setup
|
||||
|
||||
@@ -282,28 +325,6 @@ Notes:
|
||||
|
||||
For local video files, SubMiner uses the same config-driven language priorities to auto-select the primary and secondary subtitle tracks from internal and external subtitle sources.
|
||||
|
||||
## Live Config Reload
|
||||
|
||||
While SubMiner is running, it watches your active config file and applies safe updates automatically.
|
||||
|
||||
Live-updated settings include:
|
||||
|
||||
- `subtitleStyle`
|
||||
- `keybindings`
|
||||
- `shortcuts`
|
||||
- `secondarySub.defaultMode`
|
||||
- `subtitleSidebar`
|
||||
- `notifications`
|
||||
- `logging`
|
||||
- `jimaku`, `subsync`
|
||||
- `mpv.aniskipEnabled`, `mpv.aniskipButtonKey`
|
||||
- `stats.toggleKey`, `stats.markWatchedKey`
|
||||
- `youtube.primarySubLanguages`
|
||||
- most `ankiConnect.*` settings (including `ankiConnect.ai`)
|
||||
|
||||
Invalid config edits are rejected; SubMiner keeps the previous valid runtime config and shows an error notification.
|
||||
For restart-required sections, SubMiner shows a restart-needed notification.
|
||||
|
||||
## Controller Support
|
||||
|
||||
SubMiner supports gamepad/controller input for couch-friendly usage via the Chrome Gamepad API. Controller input drives the overlay while keyboard-only mode is enabled.
|
||||
|
||||
@@ -377,4 +377,4 @@ ws.on('message', async (raw) => {
|
||||
- [Mining Workflow - Texthooker](/mining-workflow#texthooker)
|
||||
- [MPV Plugin](/mpv-plugin)
|
||||
- [Launcher Script](/launcher-script)
|
||||
- [Anki Integration](/anki-integration#proxy-mode-setup-yomitan-texthooker)
|
||||
- [Anki Integration](/anki-integration#proxy-mode-setup-yomitan--texthooker)
|
||||
|
||||
@@ -153,6 +153,6 @@ These settings come from `config.jsonc` (or built-in defaults); there are no CLI
|
||||
|
||||
- [Usage --- YouTube Playback](/usage#youtube-playback)
|
||||
- [Configuration --- YouTube Playback Settings](/configuration#youtube-playback-settings)
|
||||
- [Configuration --- Secondary Subtitles](/configuration#secondary-subtitles)
|
||||
- [Configuration --- Secondary Subtitle](/configuration#secondary-subtitle)
|
||||
- [Keyboard Shortcuts](/shortcuts)
|
||||
- [Jellyfin Integration](/jellyfin-integration)
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "subminer",
|
||||
"productName": "SubMiner",
|
||||
"desktopName": "SubMiner.desktop",
|
||||
"version": "0.19.0-beta.4",
|
||||
"version": "0.19.0-beta.3",
|
||||
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
||||
"packageManager": "bun@1.3.5",
|
||||
"main": "dist/main-entry.js",
|
||||
|
||||
@@ -17,12 +17,6 @@
|
||||
- **Post-Playback History Menu**
|
||||
- After a watch-history episode ends or mpv closes, the fzf/rofi launcher returns to that series with options to play the previous or next episode, rewatch, pick another episode, or quit SubMiner.
|
||||
- Previous/Next continue across season directories, so you can binge a show without manually browsing folders.
|
||||
- The menu shown right after picking a series from `subminer -H` now offers the previous episode too, matching the post-playback menu.
|
||||
|
||||
- **Known-Word Highlighting by Anki Maturity**
|
||||
- Subtitle highlights for known words can now be colored by Anki card maturity (new, learning, young, mature), similar to asbplayer. Enable it with `ankiConnect.knownWords.maturityEnabled`, or toggle it live during a session.
|
||||
- The mature-interval threshold and the four tier colors are configurable, and the in-session help legend shows the active tier colors while maturity highlighting is on.
|
||||
- Tiers follow Anki's own card state: a lapsed card correctly shows as learning rather than young, and a note is treated as mature if any of its cards are mature. Stats and other known-word tools stay accurate with this new data.
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -34,9 +28,6 @@
|
||||
- **Word Highlighting Accuracy**
|
||||
- Fixed several incorrect word highlighting and annotation cases: inconsistent part-of-speech exclusions on merged quote-particle tokens, missing annotations for rare kanji, katakana punctuation wrongly treated as non-kana noise, and certain kanji vocabulary skipped for next-level ("N+1") highlighting.
|
||||
|
||||
- **Character Dictionary Season Overrides**
|
||||
- Manual AniList overrides for a series now stay in effect for every episode in the same season folder, even when individual episode filenames produce different automatic guesses.
|
||||
|
||||
- **Startup Playback Pausing Too Early**
|
||||
- Fixed playback resuming before subtitle processing finished warming up, which could briefly show untranslated subtitles right after opening a video.
|
||||
- Most noticeable when resuming mid-episode or when a subtitle cue starts within the first couple of seconds.
|
||||
@@ -49,13 +40,9 @@
|
||||
- Fixed video playback failing to start when another process already held the configured AnkiConnect proxy port; SubMiner now shows a notification explaining how to resolve the conflict instead of crashing.
|
||||
|
||||
- **Stats & Settings Reliability**
|
||||
- Fixed session stats reporting zero known words after the known-word cache gained maturity tiers.
|
||||
- Hardened the stats server against malformed requests, stalled AniList lookups, media mismatches during word mining, and missing Yomitan connections.
|
||||
- AnkiConnect settings validation now preserves valid custom configurations while safely falling back on invalid values instead of failing.
|
||||
|
||||
- **Rofi Menu Prompt Spacing**
|
||||
- Rofi menu prompts now keep a space between the prompt label and the input field instead of crowding the search placeholder text.
|
||||
|
||||
## What's Changed
|
||||
|
||||
- feat(shortcuts): make clipboard-video-append shortcut configurable by @ksyasuda in #158
|
||||
@@ -63,7 +50,6 @@
|
||||
- refactor(tsukihime): swap Animetosho backend for TsukiHime API by @ksyasuda in #165
|
||||
- refactor: split anki-connect and stats-server resolvers into modules by @ksyasuda in #169
|
||||
- feat(launcher): add post-playback history menu with previous episode by @ksyasuda in #170
|
||||
- Anki maturity-based known-word highlighting by @ksyasuda in #172
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -143,3 +143,50 @@ test('anilist update queue persists and reloads from disk', () => {
|
||||
});
|
||||
assert.equal(queueB.nextReady(Number.MAX_SAFE_INTEGER)?.title, 'Persist Demo');
|
||||
});
|
||||
|
||||
test('drops queued items whose persisted mediaId is not a positive integer', () => {
|
||||
const filePath = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'anilist-queue-mediaid-')),
|
||||
'queue.json',
|
||||
);
|
||||
const base = {
|
||||
episode: 1,
|
||||
createdAt: 1,
|
||||
attemptCount: 0,
|
||||
nextAttemptAt: 0,
|
||||
lastError: null,
|
||||
};
|
||||
fs.writeFileSync(
|
||||
filePath,
|
||||
JSON.stringify({
|
||||
pending: [
|
||||
{ ...base, key: 'ok-absent', title: 'A' },
|
||||
{ ...base, key: 'ok-null', title: 'B', mediaId: null },
|
||||
{ ...base, key: 'ok-valid', title: 'C', mediaId: 108489 },
|
||||
{ ...base, key: 'bad-string', title: 'D', mediaId: '108489' },
|
||||
{ ...base, key: 'bad-zero', title: 'E', mediaId: 0 },
|
||||
{ ...base, key: 'bad-negative', title: 'F', mediaId: -3 },
|
||||
{ ...base, key: 'bad-float', title: 'G', mediaId: 1.5 },
|
||||
{ ...base, key: 'bad-object', title: 'H', mediaId: { id: 1 } },
|
||||
],
|
||||
deadLetter: [],
|
||||
}),
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
const queue = createAnilistUpdateQueue(filePath, {
|
||||
info: () => {},
|
||||
warn: () => {},
|
||||
error: () => {},
|
||||
});
|
||||
|
||||
const keptKeys: string[] = [];
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
const next = queue.nextReady(1000);
|
||||
if (!next) break;
|
||||
keptKeys.push(next.key);
|
||||
queue.markSuccess(next.key);
|
||||
}
|
||||
|
||||
assert.deepEqual(keptKeys, ['ok-absent', 'ok-null', 'ok-valid']);
|
||||
});
|
||||
|
||||
@@ -10,6 +10,8 @@ export interface AnilistQueuedUpdate {
|
||||
key: string;
|
||||
title: string;
|
||||
season?: number | null;
|
||||
/** Pinned AniList media id from a manual override, when one applied at enqueue time. */
|
||||
mediaId?: number | null;
|
||||
episode: number;
|
||||
createdAt: number;
|
||||
attemptCount: number;
|
||||
@@ -29,13 +31,31 @@ export interface AnilistRetryQueueSnapshot {
|
||||
}
|
||||
|
||||
export interface AnilistUpdateQueue {
|
||||
enqueue: (key: string, title: string, episode: number, season?: number | null) => void;
|
||||
enqueue: (
|
||||
key: string,
|
||||
title: string,
|
||||
episode: number,
|
||||
season?: number | null,
|
||||
mediaId?: number | null,
|
||||
) => void;
|
||||
nextReady: (nowMs?: number) => AnilistQueuedUpdate | null;
|
||||
markSuccess: (key: string) => void;
|
||||
markFailure: (key: string, reason: string, nowMs?: number) => void;
|
||||
getSnapshot: (nowMs?: number) => AnilistRetryQueueSnapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* A persisted mediaId pins the update to a specific AniList entry, so a corrupted or
|
||||
* hand-edited queue file must not be able to feed a bogus id straight to the mutation.
|
||||
*/
|
||||
function isValidPersistedMediaId(value: unknown): boolean {
|
||||
return (
|
||||
value === undefined ||
|
||||
value === null ||
|
||||
(typeof value === 'number' && Number.isInteger(value) && value > 0)
|
||||
);
|
||||
}
|
||||
|
||||
function clampBackoffMs(attemptCount: number): number {
|
||||
const computed = INITIAL_BACKOFF_MS * Math.pow(2, Math.max(0, attemptCount - 1));
|
||||
return Math.min(MAX_BACKOFF_MS, computed);
|
||||
@@ -82,6 +102,7 @@ export function createAnilistUpdateQueue(
|
||||
typeof item.createdAt === 'number' &&
|
||||
typeof item.attemptCount === 'number' &&
|
||||
typeof item.nextAttemptAt === 'number' &&
|
||||
isValidPersistedMediaId(item.mediaId) &&
|
||||
(typeof item.lastError === 'string' || item.lastError === null),
|
||||
)
|
||||
.slice(0, MAX_ITEMS);
|
||||
@@ -96,6 +117,7 @@ export function createAnilistUpdateQueue(
|
||||
typeof item.createdAt === 'number' &&
|
||||
typeof item.attemptCount === 'number' &&
|
||||
typeof item.nextAttemptAt === 'number' &&
|
||||
isValidPersistedMediaId(item.mediaId) &&
|
||||
(typeof item.lastError === 'string' || item.lastError === null),
|
||||
)
|
||||
.slice(0, MAX_ITEMS);
|
||||
@@ -107,7 +129,13 @@ export function createAnilistUpdateQueue(
|
||||
load();
|
||||
|
||||
return {
|
||||
enqueue(key: string, title: string, episode: number, season: number | null = null): void {
|
||||
enqueue(
|
||||
key: string,
|
||||
title: string,
|
||||
episode: number,
|
||||
season: number | null = null,
|
||||
mediaId: number | null = null,
|
||||
): void {
|
||||
const existing =
|
||||
pending.find((item) => item.key === key) || deadLetter.find((item) => item.key === key);
|
||||
if (existing) {
|
||||
@@ -120,6 +148,7 @@ export function createAnilistUpdateQueue(
|
||||
key,
|
||||
title,
|
||||
season,
|
||||
mediaId,
|
||||
episode,
|
||||
createdAt: Date.now(),
|
||||
attemptCount: 0,
|
||||
|
||||
@@ -376,7 +376,7 @@ test('updateAnilistPostWatchProgress returns non-retryable error when media is n
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress prefers season-specific AniList matches', async () => {
|
||||
test('updateAnilistPostWatchProgress resolves later seasons through the sequel chain', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const searchTerms: string[] = [];
|
||||
let call = 0;
|
||||
@@ -389,21 +389,45 @@ test('updateAnilistPostWatchProgress prefers season-specific AniList matches', a
|
||||
data: {
|
||||
Page: {
|
||||
media: [
|
||||
{ id: 202, episodes: 12, title: { english: 'Demo Show Season 2' } },
|
||||
{ id: 101, episodes: 12, title: { english: 'Demo Show' } },
|
||||
{ id: 101, episodes: 12, format: 'TV', title: { english: 'Demo Show' } },
|
||||
{ id: 202, episodes: 12, format: 'TV', title: { english: 'Demo Show Sequel' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (call === 2) {
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
assert.equal(body.variables?.id, 101);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Media: { id: 202, mediaListEntry: null },
|
||||
Media: {
|
||||
relations: {
|
||||
edges: [
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: {
|
||||
id: 202,
|
||||
type: 'ANIME',
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
title: { english: 'Demo Show Sequel' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (call === 3) {
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Media: { id: 202, mediaListEntry: { progress: 1, status: 'CURRENT' } },
|
||||
},
|
||||
});
|
||||
}
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
SaveMediaListEntry: { progress: 2, status: 'CURRENT' },
|
||||
@@ -415,16 +439,118 @@ test('updateAnilistPostWatchProgress prefers season-specific AniList matches', a
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Demo Show', 2, {
|
||||
season: 2,
|
||||
});
|
||||
assert.deepEqual(searchTerms, ['Demo Show Season 2']);
|
||||
// Searches the bare title: AniList has no "Demo Show Season 2" entry to find.
|
||||
assert.deepEqual(searchTerms, ['Demo Show']);
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /Demo Show Sequel/);
|
||||
assert.equal(call, 4);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress refuses to update season 1 when the season is unresolvable', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let call = 0;
|
||||
globalThis.fetch = (async () => {
|
||||
call += 1;
|
||||
if (call === 1) {
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Page: {
|
||||
media: [{ id: 101, episodes: 12, format: 'TV', title: { english: 'Demo Show' } }],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
return createJsonResponse({ data: { Media: { relations: { edges: [] } } } });
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Demo Show', 2, { season: 3 });
|
||||
assert.equal(result.status, 'error');
|
||||
assert.equal(result.retryable, false);
|
||||
assert.match(result.message, /not in your AniList Planning or Watching list/i);
|
||||
assert.match(result.message, /could not find season 3/i);
|
||||
// Stops after search + relation lookup: no entry lookup, no save.
|
||||
assert.equal(call, 2);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress uses a pinned media id without searching', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let call = 0;
|
||||
globalThis.fetch = (async (_input, init) => {
|
||||
call += 1;
|
||||
const body = JSON.parse(String(init?.body)) as { variables?: Record<string, unknown> };
|
||||
if (call === 1) {
|
||||
assert.equal(body.variables?.mediaId, 108489);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Media: {
|
||||
id: 108489,
|
||||
episodes: 12,
|
||||
title: { english: 'Pinned Show' },
|
||||
mediaListEntry: { progress: 4, status: 'CURRENT' },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
assert.equal(body.variables?.mediaId, 108489);
|
||||
return createJsonResponse({
|
||||
data: { SaveMediaListEntry: { progress: 5, status: 'CURRENT' } },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Wrong Guess', 5, {
|
||||
season: 3,
|
||||
mediaId: 108489,
|
||||
});
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /Pinned Show/);
|
||||
assert.equal(call, 2);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress marks the final episode completed for a pinned media id', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let call = 0;
|
||||
globalThis.fetch = (async (_input, init) => {
|
||||
call += 1;
|
||||
const body = JSON.parse(String(init?.body)) as { variables?: Record<string, unknown> };
|
||||
if (call === 1) {
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Media: {
|
||||
id: 108489,
|
||||
episodes: 12,
|
||||
title: { english: 'Pinned Show' },
|
||||
mediaListEntry: { progress: 11, status: 'CURRENT' },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
assert.equal(body.variables?.status, 'COMPLETED');
|
||||
return createJsonResponse({
|
||||
data: { SaveMediaListEntry: { progress: 12, status: 'COMPLETED' } },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Pinned Show', 12, {
|
||||
mediaId: 108489,
|
||||
});
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /completed/i);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress does not update rewatching entries', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let call = 0;
|
||||
@@ -479,3 +605,33 @@ test('updateAnilistPostWatchProgress returns error when search fails', async ()
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress does not requeue a search that matched nothing', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () =>
|
||||
createJsonResponse({ data: { Page: { media: [] } } })) as typeof fetch;
|
||||
|
||||
try {
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Unknown Show', 3);
|
||||
assert.equal(result.status, 'error');
|
||||
assert.equal(result.retryable, false);
|
||||
assert.match(result.message, /no matches/i);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress still allows retry when the search itself fails', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () =>
|
||||
createJsonResponse({ errors: [{ message: 'upstream exploded' }] })) as typeof fetch;
|
||||
|
||||
try {
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Demo Show', 3);
|
||||
assert.equal(result.status, 'error');
|
||||
assert.notEqual(result.retryable, false);
|
||||
assert.match(result.message, /search failed/i);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as path from 'path';
|
||||
|
||||
import { parseMediaInfo } from '../../../jimaku/utils';
|
||||
import type { AnilistRateLimiter } from './rate-limiter';
|
||||
import { resolveAnilistSeasonMedia } from './season-resolver';
|
||||
|
||||
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
|
||||
|
||||
@@ -24,6 +25,12 @@ export interface AnilistPostWatchUpdateResult {
|
||||
export interface AnilistPostWatchUpdateOptions {
|
||||
rateLimiter?: AnilistRateLimiter;
|
||||
season?: number | null;
|
||||
/**
|
||||
* Pinned AniList media id (from a character dictionary manual override). When set,
|
||||
* the search/season resolution is skipped entirely.
|
||||
*/
|
||||
mediaId?: number | null;
|
||||
logInfo?: (message: string) => void;
|
||||
}
|
||||
|
||||
interface AnilistGraphQlError {
|
||||
@@ -35,23 +42,15 @@ interface AnilistGraphQlResponse<T> {
|
||||
errors?: AnilistGraphQlError[];
|
||||
}
|
||||
|
||||
interface AnilistSearchData {
|
||||
Page?: {
|
||||
media?: Array<{
|
||||
id: number;
|
||||
episodes: number | null;
|
||||
title?: {
|
||||
romaji?: string | null;
|
||||
english?: string | null;
|
||||
native?: string | null;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
interface AnilistMediaEntryData {
|
||||
Media?: {
|
||||
id: number;
|
||||
episodes?: number | null;
|
||||
title?: {
|
||||
romaji?: string | null;
|
||||
english?: string | null;
|
||||
native?: string | null;
|
||||
} | null;
|
||||
mediaListEntry?: {
|
||||
progress?: number | null;
|
||||
status?: string | null;
|
||||
@@ -154,32 +153,6 @@ function buildGuessitTitle(title: string, alternativeTitle: string | null): stri
|
||||
return title;
|
||||
}
|
||||
|
||||
function normalizeTitle(text: string): string {
|
||||
return text.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function titleMentionsSeason(title: string, season: number): boolean {
|
||||
const normalized = normalizeTitle(title);
|
||||
return (
|
||||
normalized.includes(`season ${season}`) ||
|
||||
normalized.includes(`s${String(season).padStart(2, '0')}`) ||
|
||||
normalized.includes(`s${season}`)
|
||||
);
|
||||
}
|
||||
|
||||
function buildSearchCandidates(title: string, season: number | null | undefined): string[] {
|
||||
const trimmed = title.trim();
|
||||
if (!trimmed) return [];
|
||||
const candidates =
|
||||
typeof season === 'number' &&
|
||||
Number.isInteger(season) &&
|
||||
season > 1 &&
|
||||
!titleMentionsSeason(trimmed, season)
|
||||
? [`${trimmed} Season ${season}`, trimmed]
|
||||
: [trimmed];
|
||||
return candidates.filter((candidate, index, all) => all.indexOf(candidate) === index);
|
||||
}
|
||||
|
||||
async function anilistGraphQl<T>(
|
||||
accessToken: string,
|
||||
query: string,
|
||||
@@ -216,38 +189,22 @@ function firstErrorMessage<T>(response: AnilistGraphQlResponse<T>): string | nul
|
||||
return firstError?.message ?? null;
|
||||
}
|
||||
|
||||
function pickBestSearchResult(
|
||||
title: string,
|
||||
episode: number,
|
||||
media: Array<{
|
||||
id: number;
|
||||
episodes: number | null;
|
||||
title?: {
|
||||
romaji?: string | null;
|
||||
english?: string | null;
|
||||
native?: string | null;
|
||||
};
|
||||
}>,
|
||||
): { id: number; title: string; episodes: number | null } | null {
|
||||
const filtered = media.filter((item) => {
|
||||
const totalEpisodes = item.episodes;
|
||||
return totalEpisodes === null || totalEpisodes >= episode;
|
||||
});
|
||||
const candidates = filtered.length > 0 ? filtered : media;
|
||||
if (candidates.length === 0) return null;
|
||||
|
||||
const normalizedTarget = normalizeTitle(title);
|
||||
const exact = candidates.find((item) => {
|
||||
const titles = [item.title?.romaji, item.title?.english, item.title?.native]
|
||||
.filter((value): value is string => typeof value === 'string')
|
||||
.map((value) => normalizeTitle(value));
|
||||
return titles.includes(normalizedTarget);
|
||||
});
|
||||
|
||||
const selected = exact ?? candidates[0]!;
|
||||
const selectedTitle =
|
||||
selected.title?.english || selected.title?.romaji || selected.title?.native || title;
|
||||
return { id: selected.id, title: selectedTitle, episodes: selected.episodes };
|
||||
/** The season resolver signals failure by throwing; anilistGraphQl reports it in-band. */
|
||||
function createAnilistSeasonQueryExecutor(
|
||||
accessToken: string,
|
||||
options: AnilistPostWatchUpdateOptions,
|
||||
) {
|
||||
return async <T>(query: string, variables: Record<string, unknown>): Promise<T> => {
|
||||
const response = await anilistGraphQl<T>(accessToken, query, variables, options);
|
||||
const error = firstErrorMessage(response);
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
if (!response.data) {
|
||||
throw new Error('AniList response missing data');
|
||||
}
|
||||
return response.data;
|
||||
};
|
||||
}
|
||||
|
||||
function isUpdateableListStatus(status: string | null | undefined): boolean {
|
||||
@@ -321,52 +278,53 @@ export async function updateAnilistPostWatchProgress(
|
||||
episode: number,
|
||||
options: AnilistPostWatchUpdateOptions = {},
|
||||
): Promise<AnilistPostWatchUpdateResult> {
|
||||
let media: NonNullable<NonNullable<AnilistSearchData['Page']>['media']> = [];
|
||||
let searchError: string | null = null;
|
||||
let pickTitle = title;
|
||||
const searchCandidates = buildSearchCandidates(title, options.season);
|
||||
for (const search of searchCandidates) {
|
||||
const searchResponse = await anilistGraphQl<AnilistSearchData>(
|
||||
accessToken,
|
||||
`
|
||||
query ($search: String!) {
|
||||
Page(perPage: 5) {
|
||||
media(search: $search, type: ANIME) {
|
||||
id
|
||||
episodes
|
||||
title {
|
||||
romaji
|
||||
english
|
||||
native
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
{ search },
|
||||
options,
|
||||
);
|
||||
searchError = firstErrorMessage(searchResponse);
|
||||
if (searchError) {
|
||||
break;
|
||||
}
|
||||
media = searchResponse.data?.Page?.media ?? [];
|
||||
if (media.length > 0) {
|
||||
pickTitle = search;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const pinnedMediaId =
|
||||
typeof options.mediaId === 'number' && Number.isInteger(options.mediaId) && options.mediaId > 0
|
||||
? options.mediaId
|
||||
: null;
|
||||
|
||||
if (searchError) {
|
||||
return {
|
||||
status: 'error',
|
||||
message: `AniList search failed: ${searchError}`,
|
||||
};
|
||||
}
|
||||
let mediaId = pinnedMediaId;
|
||||
let resolvedTitle: string | null = null;
|
||||
let resolvedEpisodes: number | null = null;
|
||||
|
||||
const picked = pickBestSearchResult(pickTitle, episode, media);
|
||||
if (!picked) {
|
||||
return { status: 'error', message: 'AniList search returned no matches.' };
|
||||
if (mediaId === null) {
|
||||
let resolution: Awaited<ReturnType<typeof resolveAnilistSeasonMedia>>;
|
||||
try {
|
||||
resolution = await resolveAnilistSeasonMedia(
|
||||
{ title, season: options.season, episode },
|
||||
{
|
||||
execute: createAnilistSeasonQueryExecutor(accessToken, options),
|
||||
logInfo: options.logInfo,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
return {
|
||||
status: 'error',
|
||||
message: `AniList search failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!resolution) {
|
||||
// A well-formed search that matched nothing is deterministic for this title, so
|
||||
// requeueing it just burns rate limit. Transient failures throw and are caught above.
|
||||
return {
|
||||
status: 'error',
|
||||
retryable: false,
|
||||
message: 'AniList search returned no matches.',
|
||||
};
|
||||
}
|
||||
if (!resolution.seasonResolved) {
|
||||
// Updating the season 1 entry here is worse than not updating at all.
|
||||
return {
|
||||
status: 'error',
|
||||
retryable: false,
|
||||
message: `AniList update skipped: could not find season ${resolution.requestedSeason} of "${title}" (only matched "${resolution.title}"). Pick the right entry with the character dictionary AniList override.`,
|
||||
};
|
||||
}
|
||||
|
||||
mediaId = resolution.id;
|
||||
resolvedTitle = resolution.title;
|
||||
resolvedEpisodes = resolution.episodes;
|
||||
}
|
||||
|
||||
const entryResponse = await anilistGraphQl<AnilistMediaEntryData>(
|
||||
@@ -375,6 +333,12 @@ export async function updateAnilistPostWatchProgress(
|
||||
query ($mediaId: Int!) {
|
||||
Media(id: $mediaId, type: ANIME) {
|
||||
id
|
||||
episodes
|
||||
title {
|
||||
romaji
|
||||
english
|
||||
native
|
||||
}
|
||||
mediaListEntry {
|
||||
progress
|
||||
status
|
||||
@@ -382,7 +346,7 @@ export async function updateAnilistPostWatchProgress(
|
||||
}
|
||||
}
|
||||
`,
|
||||
{ mediaId: picked.id },
|
||||
{ mediaId },
|
||||
options,
|
||||
);
|
||||
const entryError = firstErrorMessage(entryResponse);
|
||||
@@ -393,21 +357,34 @@ export async function updateAnilistPostWatchProgress(
|
||||
};
|
||||
}
|
||||
|
||||
const entry = entryResponse.data?.Media?.mediaListEntry ?? null;
|
||||
const entryMedia = entryResponse.data?.Media ?? null;
|
||||
const pickedTitle =
|
||||
resolvedTitle ||
|
||||
entryMedia?.title?.english?.trim() ||
|
||||
entryMedia?.title?.romaji?.trim() ||
|
||||
entryMedia?.title?.native?.trim() ||
|
||||
title;
|
||||
const pickedEpisodes =
|
||||
resolvedEpisodes ??
|
||||
(typeof entryMedia?.episodes === 'number' && entryMedia.episodes > 0
|
||||
? entryMedia.episodes
|
||||
: null);
|
||||
|
||||
const entry = entryMedia?.mediaListEntry ?? null;
|
||||
if (!entry || !isUpdateableListStatus(entry.status)) {
|
||||
return {
|
||||
status: 'error',
|
||||
retryable: false,
|
||||
message: `AniList update not possible: "${picked.title}" is ${formatListStatus(entry?.status)}. Add it to Planning or Watching, then mark watched again.`,
|
||||
message: `AniList update not possible: "${pickedTitle}" is ${formatListStatus(entry?.status)}. Add it to Planning or Watching, then mark watched again.`,
|
||||
};
|
||||
}
|
||||
|
||||
const currentProgress = entry.progress ?? 0;
|
||||
const shouldMarkCompleted = isKnownFinalEpisode(picked.episodes, episode);
|
||||
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, episode);
|
||||
if (typeof currentProgress === 'number' && currentProgress >= episode && !shouldMarkCompleted) {
|
||||
return {
|
||||
status: 'skipped',
|
||||
message: `AniList already at episode ${currentProgress} (${picked.title}).`,
|
||||
message: `AniList already at episode ${currentProgress} (${pickedTitle}).`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -422,7 +399,7 @@ export async function updateAnilistPostWatchProgress(
|
||||
}
|
||||
`,
|
||||
{
|
||||
mediaId: picked.id,
|
||||
mediaId,
|
||||
progress: episode,
|
||||
status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT',
|
||||
},
|
||||
@@ -436,7 +413,7 @@ export async function updateAnilistPostWatchProgress(
|
||||
return {
|
||||
status: 'updated',
|
||||
message: shouldMarkCompleted
|
||||
? `AniList updated "${picked.title}" to episode ${episode} and marked it completed.`
|
||||
: `AniList updated "${picked.title}" to episode ${episode}.`,
|
||||
? `AniList updated "${pickedTitle}" to episode ${episode} and marked it completed.`
|
||||
: `AniList updated "${pickedTitle}" to episode ${episode}.`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -201,17 +201,45 @@ test('fetchIfMissing uses guessit primary title and season when available', asyn
|
||||
});
|
||||
|
||||
const searchCalls: Array<{ search: string }> = [];
|
||||
const relationCalls: number[] = [];
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const raw = (init?.body as string | undefined) ?? '';
|
||||
const payload = JSON.parse(raw) as { variables: { search: string } };
|
||||
const search = payload.variables.search;
|
||||
searchCalls.push({ search });
|
||||
const payload = JSON.parse(raw) as { variables: { search?: string; id?: number } };
|
||||
|
||||
if (search.includes('Season 2')) {
|
||||
return Promise.resolve(createJsonResponse({ data: { Page: { media: [] } } }));
|
||||
if (typeof payload.variables.id === 'number') {
|
||||
relationCalls.push(payload.variables.id);
|
||||
return Promise.resolve(
|
||||
createJsonResponse({
|
||||
data: {
|
||||
Media: {
|
||||
relations: {
|
||||
edges: [
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: {
|
||||
id: 20,
|
||||
type: 'ANIME',
|
||||
episodes: 25,
|
||||
format: 'TV',
|
||||
seasonYear: 2017,
|
||||
coverImage: { large: 'https://images.test/cover-s2.jpg', medium: null },
|
||||
title: {
|
||||
romaji: 'Little Witch Academia 2',
|
||||
english: 'Little Witch Academia 2',
|
||||
native: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
searchCalls.push({ search: String(payload.variables.search) });
|
||||
return Promise.resolve(
|
||||
createJsonResponse({
|
||||
data: {
|
||||
@@ -220,6 +248,8 @@ test('fetchIfMissing uses guessit primary title and season when available', asyn
|
||||
{
|
||||
id: 19,
|
||||
episodes: 24,
|
||||
format: 'TV',
|
||||
seasonYear: 2013,
|
||||
coverImage: { large: 'https://images.test/cover.jpg', medium: null },
|
||||
title: {
|
||||
romaji: 'Little Witch Academia',
|
||||
@@ -251,9 +281,11 @@ test('fetchIfMissing uses guessit primary title and season when available', asyn
|
||||
const stored = getCoverArt(db, videoId);
|
||||
|
||||
assert.equal(fetched, true);
|
||||
assert.equal(searchCalls.length, 2);
|
||||
assert.equal(searchCalls[0]!.search, 'Little Witch Academia Season 2');
|
||||
assert.equal(stored?.anilistId, 19);
|
||||
// One search on the bare title, then a sequel hop to reach season 2.
|
||||
assert.equal(searchCalls.length, 1);
|
||||
assert.equal(searchCalls[0]!.search, 'Little Witch Academia');
|
||||
assert.deepEqual(relationCalls, [19]);
|
||||
assert.equal(stored?.anilistId, 20);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
db.close();
|
||||
@@ -324,3 +356,187 @@ test('fetchIfMissing falls back to internal parser when guessit throws', async (
|
||||
cleanupDbPath(dbPath);
|
||||
}
|
||||
});
|
||||
|
||||
test('fetchIfMissing caches a no-match when the season cannot be resolved', async () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = new Database(dbPath);
|
||||
ensureSchema(db);
|
||||
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-unresolved.mkv', {
|
||||
canonicalTitle: 'Unresolved Show (2013) - S03E01 - Something [1080p].mkv',
|
||||
sourcePath: '/tmp/cover-fetcher-unresolved.mkv',
|
||||
sourceType: SOURCE_TYPE_LOCAL,
|
||||
sourceUrl: null,
|
||||
});
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
if (!url.includes('graphql')) {
|
||||
return Promise.resolve(
|
||||
new Response(Buffer.from('01020304'), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'image/png' },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const payload = JSON.parse(String(init?.body ?? '{}')) as {
|
||||
variables?: { search?: string; id?: number };
|
||||
};
|
||||
if (typeof payload.variables?.id === 'number') {
|
||||
// No sequel edges, so season 3 cannot be reached from the season 1 anchor.
|
||||
return Promise.resolve(createJsonResponse({ data: { Media: { relations: { edges: [] } } } }));
|
||||
}
|
||||
return Promise.resolve(
|
||||
createJsonResponse({
|
||||
data: {
|
||||
Page: {
|
||||
media: [
|
||||
{
|
||||
id: 55,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2013,
|
||||
coverImage: { large: 'https://images.test/s1.jpg', medium: null },
|
||||
title: { romaji: 'Unresolved Show', english: 'Unresolved Show', native: null },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const fetcher = createCoverArtFetcher(
|
||||
{ acquire: async () => {}, recordResponse: () => {} },
|
||||
console,
|
||||
{
|
||||
runGuessit: async () =>
|
||||
JSON.stringify({ title: 'Unresolved Show', season: 3, episode: 1, year: 2013 }),
|
||||
},
|
||||
);
|
||||
|
||||
const fetched = await fetcher.fetchIfMissing(db, videoId, 'Unresolved Show');
|
||||
const stored = getCoverArt(db, videoId);
|
||||
|
||||
assert.equal(fetched, false);
|
||||
// Storing the season 1 artwork would leave a blob with no AniList id, which the
|
||||
// `existing.coverBlob` early return serves forever - the season could then never
|
||||
// re-resolve. A plain no-match keeps the existing retry window in play instead.
|
||||
assert.equal(stored?.coverBlob, null);
|
||||
assert.equal(stored?.coverUrl, null);
|
||||
assert.equal(stored?.anilistId, null);
|
||||
assert.equal(stored?.episodesTotal, null);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
db.close();
|
||||
cleanupDbPath(dbPath);
|
||||
}
|
||||
});
|
||||
|
||||
test('fetchIfMissing re-resolves an unresolved season once AniList publishes the relation', async () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = new Database(dbPath);
|
||||
ensureSchema(db);
|
||||
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-recovers.mkv', {
|
||||
canonicalTitle: 'Recovering Show (2013) - S02E01 - Something [1080p].mkv',
|
||||
sourcePath: '/tmp/cover-fetcher-recovers.mkv',
|
||||
sourceType: SOURCE_TYPE_LOCAL,
|
||||
sourceUrl: null,
|
||||
});
|
||||
|
||||
let sequelPublished = false;
|
||||
const originalFetch = globalThis.fetch;
|
||||
const originalNow = Date.now;
|
||||
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
if (!url.includes('graphql')) {
|
||||
return Promise.resolve(
|
||||
new Response(Buffer.from('01020304'), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'image/png' },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const payload = JSON.parse(String(init?.body ?? '{}')) as {
|
||||
variables?: { search?: string; id?: number };
|
||||
};
|
||||
if (typeof payload.variables?.id === 'number') {
|
||||
return Promise.resolve(
|
||||
createJsonResponse({
|
||||
data: {
|
||||
Media: {
|
||||
relations: {
|
||||
edges: sequelPublished
|
||||
? [
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: {
|
||||
id: 66,
|
||||
type: 'ANIME',
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2015,
|
||||
coverImage: { large: 'https://images.test/s2.jpg', medium: null },
|
||||
title: { romaji: 'Recovering Show 2', english: null, native: null },
|
||||
},
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(
|
||||
createJsonResponse({
|
||||
data: {
|
||||
Page: {
|
||||
media: [
|
||||
{
|
||||
id: 65,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2013,
|
||||
coverImage: { large: 'https://images.test/s1.jpg', medium: null },
|
||||
title: { romaji: 'Recovering Show', english: null, native: null },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const fetcher = createCoverArtFetcher(
|
||||
{ acquire: async () => {}, recordResponse: () => {} },
|
||||
console,
|
||||
{
|
||||
runGuessit: async () =>
|
||||
JSON.stringify({ title: 'Recovering Show', season: 2, episode: 1, year: 2013 }),
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(await fetcher.fetchIfMissing(db, videoId, 'Recovering Show'), false);
|
||||
assert.equal(getCoverArt(db, videoId)?.anilistId, null);
|
||||
|
||||
// AniList publishes the sequel relation, and the no-match retry window elapses.
|
||||
sequelPublished = true;
|
||||
const base = originalNow();
|
||||
Date.now = () => base + 10 * 60 * 1000;
|
||||
|
||||
assert.equal(await fetcher.fetchIfMissing(db, videoId, 'Recovering Show'), true);
|
||||
const recovered = getCoverArt(db, videoId);
|
||||
assert.equal(recovered?.anilistId, 66);
|
||||
assert.equal(recovered?.episodesTotal, 12);
|
||||
} finally {
|
||||
Date.now = originalNow;
|
||||
globalThis.fetch = originalFetch;
|
||||
db.close();
|
||||
cleanupDbPath(dbPath);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -11,43 +11,15 @@ import {
|
||||
runGuessit,
|
||||
type GuessAnilistMediaInfoDeps,
|
||||
} from './anilist-updater';
|
||||
import {
|
||||
resolveAnilistSeasonMedia,
|
||||
type AnilistQueryExecutor,
|
||||
type AnilistSeasonResolution,
|
||||
} from './season-resolver';
|
||||
|
||||
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
|
||||
const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
|
||||
|
||||
const SEARCH_QUERY = `
|
||||
query ($search: String!) {
|
||||
Page(perPage: 5) {
|
||||
media(search: $search, type: ANIME) {
|
||||
id
|
||||
episodes
|
||||
season
|
||||
seasonYear
|
||||
coverImage { large medium }
|
||||
title { romaji english native }
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
interface AnilistMedia {
|
||||
id: number;
|
||||
episodes: number | null;
|
||||
season: string | null;
|
||||
seasonYear: number | null;
|
||||
coverImage: { large: string | null; medium: string | null } | null;
|
||||
title: { romaji: string | null; english: string | null; native: string | null } | null;
|
||||
}
|
||||
|
||||
interface AnilistSearchResponse {
|
||||
data?: {
|
||||
Page?: {
|
||||
media?: AnilistMedia[];
|
||||
};
|
||||
};
|
||||
errors?: Array<{ message?: string }>;
|
||||
}
|
||||
|
||||
export interface CoverArtFetcher {
|
||||
fetchIfMissing(db: DatabaseSync, videoId: number, canonicalTitle: string): Promise<boolean>;
|
||||
}
|
||||
@@ -99,151 +71,45 @@ export function stripFilenameTags(raw: string): string {
|
||||
return title.trim().replace(/\s{2,}/g, ' ');
|
||||
}
|
||||
|
||||
function removeSeasonHint(title: string): string {
|
||||
return title
|
||||
.replace(/\bseason\s*\d+\b/gi, '')
|
||||
.replace(/\s{2,}/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function normalizeTitle(text: string): string {
|
||||
return text.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function extractCandidateSeasonHints(text: string): Set<number> {
|
||||
const normalized = normalizeTitle(text);
|
||||
const matches = [
|
||||
...normalized.matchAll(/\bseason\s*(\d{1,2})\b/gi),
|
||||
...normalized.matchAll(/\bs(\d{1,2})(?:\b|\D)/gi),
|
||||
];
|
||||
const values = new Set<number>();
|
||||
for (const match of matches) {
|
||||
const value = Number.parseInt(match[1]!, 10);
|
||||
if (Number.isInteger(value)) {
|
||||
values.add(value);
|
||||
}
|
||||
class AnilistRateLimitedError extends Error {
|
||||
constructor() {
|
||||
super('Anilist rate limit reached');
|
||||
this.name = 'AnilistRateLimitedError';
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function isSeasonMentioned(titles: string[], season: number | null): boolean {
|
||||
if (!season) {
|
||||
return false;
|
||||
}
|
||||
const hints = titles.flatMap((title) => [...extractCandidateSeasonHints(title)]);
|
||||
return hints.includes(season);
|
||||
}
|
||||
|
||||
function pickBestSearchResult(
|
||||
title: string,
|
||||
episode: number | null,
|
||||
season: number | null,
|
||||
media: AnilistMedia[],
|
||||
): { id: number; title: string } | null {
|
||||
const cleanedTitle = removeSeasonHint(title);
|
||||
const targets = [title, cleanedTitle]
|
||||
.map(normalizeTitle)
|
||||
.map((value) => value.trim())
|
||||
.filter((value, index, all) => value.length > 0 && all.indexOf(value) === index);
|
||||
|
||||
const filtered =
|
||||
episode === null
|
||||
? media
|
||||
: media.filter((item) => {
|
||||
const total = item.episodes;
|
||||
return total === null || total >= episode;
|
||||
});
|
||||
const candidates = filtered.length > 0 ? filtered : media;
|
||||
if (candidates.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const scored = candidates.map((item) => {
|
||||
const candidateTitles = [item.title?.romaji, item.title?.english, item.title?.native]
|
||||
.filter((value): value is string => typeof value === 'string')
|
||||
.map((value) => normalizeTitle(value));
|
||||
|
||||
let score = 0;
|
||||
|
||||
for (const target of targets) {
|
||||
if (candidateTitles.includes(target)) {
|
||||
score += 120;
|
||||
continue;
|
||||
}
|
||||
if (candidateTitles.some((itemTitle) => itemTitle.includes(target))) {
|
||||
score += 30;
|
||||
}
|
||||
if (candidateTitles.some((itemTitle) => target.includes(itemTitle))) {
|
||||
score += 10;
|
||||
}
|
||||
}
|
||||
|
||||
if (episode !== null && item.episodes === episode) {
|
||||
score += 20;
|
||||
}
|
||||
|
||||
if (season !== null && isSeasonMentioned(candidateTitles, season)) {
|
||||
score += 15;
|
||||
}
|
||||
|
||||
return { item, score };
|
||||
});
|
||||
|
||||
scored.sort((a, b) => {
|
||||
if (b.score !== a.score) return b.score - a.score;
|
||||
return b.item.id - a.item.id;
|
||||
});
|
||||
|
||||
const selected = scored[0]!;
|
||||
const selectedTitle =
|
||||
selected.item.title?.english ??
|
||||
selected.item.title?.romaji ??
|
||||
selected.item.title?.native ??
|
||||
title;
|
||||
return { id: selected.item.id, title: selectedTitle };
|
||||
}
|
||||
|
||||
function buildSearchCandidates(parsed: CoverArtCandidate): string[] {
|
||||
const candidateTitles = [
|
||||
...(parsed.source === 'guessit' && parsed.season !== null && parsed.season > 1
|
||||
? [`${parsed.title} Season ${parsed.season}`]
|
||||
: []),
|
||||
parsed.title,
|
||||
];
|
||||
return candidateTitles
|
||||
.map((title) => title.trim())
|
||||
.filter((title, index, all) => title.length > 0 && all.indexOf(title) === index);
|
||||
}
|
||||
|
||||
async function searchAnilist(
|
||||
async function executeAnilistQuery<T>(
|
||||
rateLimiter: AnilistRateLimiter,
|
||||
title: string,
|
||||
): Promise<{ media: AnilistMedia[]; rateLimited: boolean }> {
|
||||
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: SEARCH_QUERY, variables: { search: title } }),
|
||||
body: JSON.stringify({ query, variables }),
|
||||
});
|
||||
|
||||
rateLimiter.recordResponse(res.headers);
|
||||
|
||||
if (res.status === 429) {
|
||||
return { media: [], rateLimited: true };
|
||||
throw new AnilistRateLimitedError();
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as AnilistSearchResponse;
|
||||
const mediaList = json.data?.Page?.media;
|
||||
if (!mediaList || mediaList.length === 0) {
|
||||
return { media: [], rateLimited: false };
|
||||
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);
|
||||
}
|
||||
|
||||
return { media: mediaList, rateLimited: false };
|
||||
if (!json.data) {
|
||||
throw new Error('Anilist response missing data');
|
||||
}
|
||||
return json.data;
|
||||
}
|
||||
|
||||
async function downloadImage(url: string): Promise<Buffer | null> {
|
||||
@@ -376,49 +242,57 @@ export function createCoverArtFetcher(
|
||||
|
||||
const parsedInfo = await resolveMediaInfo(db, videoId, canonicalTitle);
|
||||
const searchBase = parsedInfo?.title ?? cleaned;
|
||||
const searchCandidates = parsedInfo ? buildSearchCandidates(parsedInfo) : [cleaned];
|
||||
const searchTitles = searchBase === cleaned ? [searchBase] : ([searchBase, cleaned] as const);
|
||||
|
||||
const effectiveCandidates = searchCandidates.includes(cleaned)
|
||||
? searchCandidates
|
||||
: [...searchCandidates, cleaned];
|
||||
const execute: AnilistQueryExecutor = (query, variables) =>
|
||||
executeAnilistQuery(rateLimiter, query, variables);
|
||||
|
||||
let selected: AnilistMedia | null = null;
|
||||
let rateLimited = false;
|
||||
|
||||
for (const candidate of effectiveCandidates) {
|
||||
logger.info('cover-art: searching Anilist for "%s" (videoId=%d)', candidate, videoId);
|
||||
|
||||
try {
|
||||
const result = await searchAnilist(rateLimiter, candidate);
|
||||
rateLimited = result.rateLimited;
|
||||
if (result.media.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const picked = pickBestSearchResult(
|
||||
searchBase,
|
||||
parsedInfo?.episode ?? null,
|
||||
parsedInfo?.season ?? null,
|
||||
result.media,
|
||||
let resolution: AnilistSeasonResolution | null = null;
|
||||
try {
|
||||
for (const searchTitle of searchTitles) {
|
||||
logger.info('cover-art: searching Anilist for "%s" (videoId=%d)', searchTitle, videoId);
|
||||
resolution = await resolveAnilistSeasonMedia(
|
||||
{
|
||||
title: searchTitle,
|
||||
season: parsedInfo?.season ?? null,
|
||||
episode: parsedInfo?.episode ?? null,
|
||||
},
|
||||
{ execute, logInfo: (message) => logger.info('%s', message) },
|
||||
);
|
||||
if (picked) {
|
||||
const match = result.media.find((media) => media.id === picked.id);
|
||||
if (match) {
|
||||
selected = match;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('cover-art: Anilist search error for "%s": %s', candidate, err);
|
||||
if (resolution) break;
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof AnilistRateLimitedError) {
|
||||
logger.warn('cover-art: rate-limited by Anilist, skipping videoId=%d', videoId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (rateLimited) {
|
||||
logger.warn('cover-art: rate-limited by Anilist, skipping videoId=%d', videoId);
|
||||
logger.error('cover-art: Anilist search error for "%s": %s', searchBase, err);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (resolution && !resolution.seasonResolved) {
|
||||
// Only the season 1 entry was found. Storing its artwork would leave a cover with
|
||||
// no AniList id, which the `existing.coverBlob` early return above serves forever,
|
||||
// so the season could never re-resolve once AniList publishes the relation.
|
||||
// Caching a plain no-match instead reuses the NO_MATCH_RETRY_MS retry window.
|
||||
logger.warn(
|
||||
'cover-art: could not find season %d of "%s" (only matched "%s"), caching no-match',
|
||||
resolution.requestedSeason,
|
||||
searchBase,
|
||||
resolution.title,
|
||||
);
|
||||
upsertCoverArt(db, videoId, {
|
||||
anilistId: null,
|
||||
coverUrl: null,
|
||||
coverBlob: null,
|
||||
titleRomaji: null,
|
||||
titleEnglish: null,
|
||||
episodesTotal: null,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const selected = resolution?.media ?? null;
|
||||
if (!selected) {
|
||||
logger.info('cover-art: no Anilist results for "%s", caching no-match', searchBase);
|
||||
upsertCoverArt(db, videoId, {
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
ANILIST_SEASON_RELATIONS_QUERY,
|
||||
ANILIST_SEASON_SEARCH_QUERY,
|
||||
pickByAirOrder,
|
||||
resolveAnilistSeasonMedia,
|
||||
stripSeasonSuffix,
|
||||
type AnilistSeasonMedia,
|
||||
} from './season-resolver';
|
||||
|
||||
/** Real AniList payloads for "My Teen Romantic Comedy SNAFU", trimmed to used fields. */
|
||||
const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 14813,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2013,
|
||||
title: {
|
||||
romaji: 'Yahari Ore no Seishun Love Come wa Machigatteiru.',
|
||||
english: 'My Teen Romantic Comedy SNAFU',
|
||||
native: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 18753,
|
||||
episodes: 1,
|
||||
format: 'OVA',
|
||||
seasonYear: 2013,
|
||||
title: { romaji: null, english: 'My Teen Romantic Comedy SNAFU OVA', native: null },
|
||||
},
|
||||
{
|
||||
id: 108489,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: {
|
||||
romaji: 'Yahari Ore no Seishun Love Come wa Machigatteiru. Kan',
|
||||
english: 'My Teen Romantic Comedy SNAFU Climax!',
|
||||
native: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 20698,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2015,
|
||||
title: {
|
||||
romaji: 'Yahari Ore no Seishun Love Come wa Machigatteiru. Zoku',
|
||||
english: 'My Teen Romantic Comedy SNAFU TOO!',
|
||||
native: null,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const OREGAIRU_RELATIONS: Record<
|
||||
number,
|
||||
Array<{ relationType: string; node: AnilistSeasonMedia }>
|
||||
> = {
|
||||
14813: [
|
||||
{
|
||||
relationType: 'SIDE_STORY',
|
||||
node: OREGAIRU_SEARCH[1]!,
|
||||
},
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: OREGAIRU_SEARCH[3]!,
|
||||
},
|
||||
],
|
||||
20698: [
|
||||
{
|
||||
relationType: 'PREQUEL',
|
||||
node: OREGAIRU_SEARCH[0]!,
|
||||
},
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: OREGAIRU_SEARCH[2]!,
|
||||
},
|
||||
],
|
||||
108489: [
|
||||
{
|
||||
relationType: 'PREQUEL',
|
||||
node: OREGAIRU_SEARCH[3]!,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function createExecutor(
|
||||
search: AnilistSeasonMedia[],
|
||||
relations: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {},
|
||||
) {
|
||||
const searches: string[] = [];
|
||||
const relationLookups: number[] = [];
|
||||
const execute = async <T>(query: string, variables: Record<string, unknown>): Promise<T> => {
|
||||
if (query === ANILIST_SEASON_SEARCH_QUERY) {
|
||||
searches.push(String(variables.search));
|
||||
return { Page: { media: search } } as T;
|
||||
}
|
||||
if (query === ANILIST_SEASON_RELATIONS_QUERY) {
|
||||
const id = Number(variables.id);
|
||||
relationLookups.push(id);
|
||||
return {
|
||||
Media: {
|
||||
relations: {
|
||||
edges: (relations[id] ?? []).map((edge) => ({
|
||||
relationType: edge.relationType,
|
||||
node: { ...edge.node, type: 'ANIME' },
|
||||
})),
|
||||
},
|
||||
},
|
||||
} as T;
|
||||
}
|
||||
throw new Error(`unexpected query: ${query}`);
|
||||
};
|
||||
return { execute, searches, relationLookups };
|
||||
}
|
||||
|
||||
test('stripSeasonSuffix drops release-name season markers', () => {
|
||||
assert.equal(stripSeasonSuffix('Some Show Season 3'), 'Some Show');
|
||||
assert.equal(stripSeasonSuffix('Some Show S3'), 'Some Show');
|
||||
assert.equal(stripSeasonSuffix('Some Show 2nd Season'), 'Some Show');
|
||||
assert.equal(stripSeasonSuffix('Some Show'), 'Some Show');
|
||||
});
|
||||
|
||||
test('resolves season 3 by walking sequel relations', async () => {
|
||||
const { execute, searches, relationLookups } = createExecutor(
|
||||
OREGAIRU_SEARCH,
|
||||
OREGAIRU_RELATIONS,
|
||||
);
|
||||
const result = await resolveAnilistSeasonMedia(
|
||||
{ title: 'My Teen Romantic Comedy SNAFU', season: 3, episode: 1 },
|
||||
{ execute },
|
||||
);
|
||||
|
||||
assert.equal(result?.id, 108489);
|
||||
assert.equal(result?.title, 'My Teen Romantic Comedy SNAFU Climax!');
|
||||
assert.equal(result?.episodes, 12);
|
||||
assert.equal(result?.seasonResolved, true);
|
||||
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]);
|
||||
});
|
||||
|
||||
test('season 1 resolves to the anchor without relation lookups', async () => {
|
||||
const { execute, relationLookups } = createExecutor(OREGAIRU_SEARCH, OREGAIRU_RELATIONS);
|
||||
const result = await resolveAnilistSeasonMedia(
|
||||
{ title: 'My Teen Romantic Comedy SNAFU', season: 1, episode: 5 },
|
||||
{ execute },
|
||||
);
|
||||
|
||||
assert.equal(result?.id, 14813);
|
||||
assert.equal(result?.seasonResolved, true);
|
||||
assert.equal(result?.via, 'anchor');
|
||||
assert.deepEqual(relationLookups, []);
|
||||
});
|
||||
|
||||
test('strips a season marker already present in the parsed title', async () => {
|
||||
const { execute, searches } = createExecutor(OREGAIRU_SEARCH, OREGAIRU_RELATIONS);
|
||||
const result = await resolveAnilistSeasonMedia(
|
||||
{ title: 'My Teen Romantic Comedy SNAFU Season 2', season: 2, episode: 3 },
|
||||
{ execute },
|
||||
);
|
||||
|
||||
assert.deepEqual(searches, ['My Teen Romantic Comedy SNAFU']);
|
||||
assert.equal(result?.id, 20698);
|
||||
assert.equal(result?.seasonResolved, true);
|
||||
});
|
||||
|
||||
test('falls back to air order when the sequel chain is broken', async () => {
|
||||
const { execute } = createExecutor(OREGAIRU_SEARCH, {});
|
||||
const result = await resolveAnilistSeasonMedia(
|
||||
{ title: 'My Teen Romantic Comedy SNAFU', season: 3, episode: 1 },
|
||||
{ execute },
|
||||
);
|
||||
|
||||
assert.equal(result?.id, 108489);
|
||||
assert.equal(result?.via, 'air-order');
|
||||
assert.equal(result?.seasonResolved, true);
|
||||
});
|
||||
|
||||
test('reports seasonResolved false rather than silently using season 1', async () => {
|
||||
const { execute } = createExecutor([OREGAIRU_SEARCH[0]!], {});
|
||||
const result = await resolveAnilistSeasonMedia(
|
||||
{ title: 'My Teen Romantic Comedy SNAFU', season: 3, episode: 1 },
|
||||
{ execute },
|
||||
);
|
||||
|
||||
assert.equal(result?.id, 14813);
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.via, 'anchor');
|
||||
assert.equal(result?.requestedSeason, 3);
|
||||
});
|
||||
|
||||
test('does not filter the anchor by an episode count the season 1 entry cannot have', async () => {
|
||||
const { execute } = createExecutor(OREGAIRU_SEARCH, OREGAIRU_RELATIONS);
|
||||
// Season 2 episode 13 exceeds nothing, but season 3 episode 13 exceeds Climax!'s 12.
|
||||
const result = await resolveAnilistSeasonMedia(
|
||||
{ title: 'My Teen Romantic Comedy SNAFU', season: 2, episode: 13 },
|
||||
{ execute },
|
||||
);
|
||||
|
||||
assert.equal(result?.id, 20698);
|
||||
assert.equal(result?.seasonResolved, true);
|
||||
});
|
||||
|
||||
test('prefers the TV sequel when a franchise branches into other formats', async () => {
|
||||
const branching: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {
|
||||
1: [
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: {
|
||||
id: 3,
|
||||
episodes: 6,
|
||||
format: 'ONA',
|
||||
seasonYear: 2019,
|
||||
title: { english: 'Spinoff' },
|
||||
},
|
||||
},
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: { id: 2, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show 2' } },
|
||||
},
|
||||
],
|
||||
};
|
||||
const { execute } = createExecutor(
|
||||
[{ id: 1, episodes: 12, format: 'TV', seasonYear: 2018, title: { english: 'Show' } }],
|
||||
branching,
|
||||
);
|
||||
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
|
||||
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
});
|
||||
|
||||
test('air-order fallback refuses when the anchor is not the earliest entry', () => {
|
||||
const anchor: AnilistSeasonMedia = {
|
||||
id: 2,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Show Later' },
|
||||
};
|
||||
const picked = pickByAirOrder(anchor, 2, [
|
||||
anchor,
|
||||
{ id: 1, format: 'TV', seasonYear: 2015, title: { english: 'Show Earlier' } },
|
||||
]);
|
||||
|
||||
assert.equal(picked, null);
|
||||
});
|
||||
|
||||
test('returns null when the search yields nothing', async () => {
|
||||
const { execute } = createExecutor([]);
|
||||
const result = await resolveAnilistSeasonMedia({ title: 'Nothing', season: 2 }, { execute });
|
||||
|
||||
assert.equal(result, null);
|
||||
});
|
||||
|
||||
test('refuses a season beyond the sequel-hop cap instead of returning a partial walk', async () => {
|
||||
// A 30-entry sequel chain: hopping the capped number of times would land on the wrong
|
||||
// season and report it resolved, so the walk must decline outright.
|
||||
const chain: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {};
|
||||
for (let id = 1; id < 30; id += 1) {
|
||||
chain[id] = [
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: {
|
||||
id: id + 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2000 + id,
|
||||
title: { english: `Show ${id + 1}` },
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
const { execute, relationLookups } = createExecutor(
|
||||
[{ id: 1, episodes: 12, format: 'TV', seasonYear: 2000, title: { english: 'Show' } }],
|
||||
chain,
|
||||
);
|
||||
|
||||
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 25 }, { execute });
|
||||
|
||||
assert.equal(result?.id, 1);
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.via, 'anchor');
|
||||
// Declines before spending any relation requests.
|
||||
assert.deepEqual(relationLookups, []);
|
||||
});
|
||||
|
||||
test('air-order fallback declines when a franchise entry has no air year', async () => {
|
||||
// The middle season has no year, so ordering it would shift every later season by one.
|
||||
const { execute } = createExecutor(
|
||||
[
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2013, title: { english: 'Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', title: { english: 'Show Zoku' } },
|
||||
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show Kan' } },
|
||||
],
|
||||
{},
|
||||
);
|
||||
|
||||
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
|
||||
|
||||
assert.equal(result?.id, 1);
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.via, 'anchor');
|
||||
});
|
||||
@@ -0,0 +1,407 @@
|
||||
/**
|
||||
* AniList has no concept of "season N": sequels are separate media with their own
|
||||
* titles (Zoku, Kan, 2nd Season, ...). Searching "<title> Season 3" therefore returns
|
||||
* nothing and callers silently fall back to the season 1 entry.
|
||||
*
|
||||
* This module resolves a parsed (title, season) pair to the right media by locating a
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export interface AnilistSeasonMediaTitle {
|
||||
romaji?: string | null;
|
||||
english?: string | null;
|
||||
native?: string | null;
|
||||
}
|
||||
|
||||
export interface AnilistSeasonMedia {
|
||||
id: number;
|
||||
episodes?: number | null;
|
||||
format?: string | null;
|
||||
seasonYear?: number | null;
|
||||
startDate?: { year?: number | null } | null;
|
||||
synonyms?: Array<string | null> | null;
|
||||
coverImage?: { large?: string | null; medium?: string | null } | null;
|
||||
title?: AnilistSeasonMediaTitle | null;
|
||||
}
|
||||
|
||||
export type AnilistQueryExecutor = <T>(
|
||||
query: string,
|
||||
variables: Record<string, unknown>,
|
||||
) => Promise<T>;
|
||||
|
||||
export type AnilistSeasonResolutionVia = 'anchor' | 'sequel-chain' | 'air-order';
|
||||
|
||||
export interface AnilistSeasonResolution {
|
||||
id: number;
|
||||
title: string;
|
||||
episodes: number | null;
|
||||
media: AnilistSeasonMedia;
|
||||
/** False when a season >= 2 was requested but no seasonal entry could be located. */
|
||||
seasonResolved: boolean;
|
||||
requestedSeason: number | null;
|
||||
via: AnilistSeasonResolutionVia;
|
||||
}
|
||||
|
||||
export interface ResolveAnilistSeasonMediaInput {
|
||||
title: string;
|
||||
season?: number | null;
|
||||
episode?: number | null;
|
||||
}
|
||||
|
||||
export interface ResolveAnilistSeasonMediaDeps {
|
||||
execute: AnilistQueryExecutor;
|
||||
logInfo?: (message: string) => void;
|
||||
}
|
||||
|
||||
const MEDIA_FIELDS = `
|
||||
id
|
||||
episodes
|
||||
format
|
||||
seasonYear
|
||||
startDate { year }
|
||||
synonyms
|
||||
coverImage { large medium }
|
||||
title { romaji english native }
|
||||
`;
|
||||
|
||||
export const ANILIST_SEASON_SEARCH_QUERY = `
|
||||
query ($search: String!) {
|
||||
Page(perPage: 10) {
|
||||
media(search: $search, type: ANIME, sort: [SEARCH_MATCH, POPULARITY_DESC]) {
|
||||
${MEDIA_FIELDS}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const ANILIST_SEASON_RELATIONS_QUERY = `
|
||||
query ($id: Int!) {
|
||||
Media(id: $id, type: ANIME) {
|
||||
id
|
||||
relations {
|
||||
edges {
|
||||
relationType
|
||||
node {
|
||||
type
|
||||
${MEDIA_FIELDS}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
interface AnilistSeasonSearchResponse {
|
||||
Page?: {
|
||||
media?: AnilistSeasonMedia[] | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface AnilistSeasonRelationsResponse {
|
||||
Media?: {
|
||||
relations?: {
|
||||
edges?: Array<{
|
||||
relationType?: string | null;
|
||||
node?: (AnilistSeasonMedia & { type?: string | null }) | null;
|
||||
} | null> | null;
|
||||
} | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** Formats that can carry a numbered TV season, best first. */
|
||||
const SEASONAL_FORMAT_PRIORITY = ['TV', 'TV_SHORT', 'ONA'];
|
||||
|
||||
const MAX_SEQUEL_HOPS = 12;
|
||||
|
||||
function normalizeTitle(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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".
|
||||
*/
|
||||
export function stripSeasonSuffix(title: string): string {
|
||||
return title
|
||||
.replace(/\bseason\s*\d{1,2}\b/gi, ' ')
|
||||
.replace(/\b\d{1,2}(?:st|nd|rd|th)\s+season\b/gi, ' ')
|
||||
.replace(/\bs\d{1,2}\b/gi, ' ')
|
||||
.replace(/\s{2,}/g, ' ')
|
||||
.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]
|
||||
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||
.map((value) => normalizeTitle(value));
|
||||
}
|
||||
|
||||
function displayTitle(media: AnilistSeasonMedia, fallback: string): string {
|
||||
return (
|
||||
media.title?.english?.trim() ||
|
||||
media.title?.romaji?.trim() ||
|
||||
media.title?.native?.trim() ||
|
||||
fallback.trim()
|
||||
);
|
||||
}
|
||||
|
||||
function episodeCount(media: AnilistSeasonMedia): number | null {
|
||||
return typeof media.episodes === 'number' && media.episodes > 0 ? media.episodes : null;
|
||||
}
|
||||
|
||||
function airYear(media: AnilistSeasonMedia): number | null {
|
||||
if (typeof media.seasonYear === 'number' && media.seasonYear > 0) {
|
||||
return media.seasonYear;
|
||||
}
|
||||
const startYear = media.startDate?.year;
|
||||
return typeof startYear === 'number' && startYear > 0 ? startYear : null;
|
||||
}
|
||||
|
||||
function isSeasonalFormat(media: AnilistSeasonMedia): boolean {
|
||||
const format = (media.format || '').toUpperCase();
|
||||
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;
|
||||
}
|
||||
|
||||
function toResolution(
|
||||
media: AnilistSeasonMedia,
|
||||
fallbackTitle: string,
|
||||
season: number | null,
|
||||
via: AnilistSeasonResolutionVia,
|
||||
seasonResolved: boolean,
|
||||
): AnilistSeasonResolution {
|
||||
return {
|
||||
id: media.id,
|
||||
title: displayTitle(media, fallbackTitle),
|
||||
episodes: episodeCount(media),
|
||||
media,
|
||||
seasonResolved,
|
||||
requestedSeason: season,
|
||||
via,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the franchise anchor (season 1 entry) for a search result set. The anchor is
|
||||
* matched on title alone - season is handled by walking relations from here.
|
||||
*/
|
||||
export function pickAnchorMedia(
|
||||
title: string,
|
||||
media: AnilistSeasonMedia[],
|
||||
options: { episode?: number | null } = {},
|
||||
): AnilistSeasonMedia | null {
|
||||
if (media.length === 0) return null;
|
||||
|
||||
const episode = options.episode;
|
||||
const episodeFiltered =
|
||||
typeof episode === 'number' && episode > 0
|
||||
? media.filter((entry) => {
|
||||
const total = episodeCount(entry);
|
||||
return total === null || total >= episode;
|
||||
})
|
||||
: media;
|
||||
const pool = episodeFiltered.length > 0 ? episodeFiltered : media;
|
||||
|
||||
const targets = [normalizeTitle(title), normalizeTitle(stripSeasonSuffix(title))].filter(
|
||||
(value, index, all) => value.length > 0 && all.indexOf(value) === index,
|
||||
);
|
||||
|
||||
const scored = pool.map((entry, index) => {
|
||||
const candidateTitles = mediaTitles(entry);
|
||||
let score = 0;
|
||||
for (const target of targets) {
|
||||
if (candidateTitles.includes(target)) {
|
||||
score += 120;
|
||||
continue;
|
||||
}
|
||||
if (candidateTitles.some((candidate) => candidate.startsWith(target))) {
|
||||
score += 40;
|
||||
} else if (candidateTitles.some((candidate) => candidate.includes(target))) {
|
||||
score += 25;
|
||||
}
|
||||
if (candidateTitles.some((candidate) => target.includes(candidate))) {
|
||||
score += 10;
|
||||
}
|
||||
}
|
||||
if (isSeasonalFormat(entry)) {
|
||||
score += 30;
|
||||
}
|
||||
return { entry, score, index };
|
||||
});
|
||||
|
||||
scored.sort((a, b) => {
|
||||
if (b.score !== a.score) return b.score - a.score;
|
||||
if (a.index !== b.index) return a.index - b.index;
|
||||
return a.entry.id - b.entry.id;
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
for (let hop = 0; hop < hops; hop += 1) {
|
||||
// Transport errors propagate: a failed hop must not be mistaken for "no sequel exists".
|
||||
const response = await deps.execute<AnilistSeasonRelationsResponse>(
|
||||
ANILIST_SEASON_RELATIONS_QUERY,
|
||||
{ id: current.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;
|
||||
}
|
||||
|
||||
// A franchise can branch (a TV sequel plus an ONA spinoff); prefer the TV line.
|
||||
sequels.sort((a, b) => {
|
||||
const rankDelta = formatRank(a) - formatRank(b);
|
||||
if (rankDelta !== 0) return rankDelta;
|
||||
const yearDelta =
|
||||
(airYear(a) ?? Number.MAX_SAFE_INTEGER) - (airYear(b) ?? Number.MAX_SAFE_INTEGER);
|
||||
if (yearDelta !== 0) return yearDelta;
|
||||
return a.id - b.id;
|
||||
});
|
||||
|
||||
current = sequels[0]!;
|
||||
visited.add(current.id);
|
||||
}
|
||||
|
||||
return current.id === anchor.id ? null : current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback for franchises whose SEQUEL edges are missing or route through a format we
|
||||
* skipped: order the franchise's seasonal entries by air date and index by season.
|
||||
*/
|
||||
export function pickByAirOrder(
|
||||
anchor: AnilistSeasonMedia,
|
||||
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;
|
||||
|
||||
const franchise = media.filter((entry) => {
|
||||
if (!isSeasonalFormat(entry)) return false;
|
||||
if (entry.id === anchor.id) return true;
|
||||
return mediaTitles(entry).some((candidate) =>
|
||||
stripSeasonSuffix(candidate).includes(anchorBase),
|
||||
);
|
||||
});
|
||||
if (franchise.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;
|
||||
|
||||
const ordered = [...franchise].sort((a, b) => {
|
||||
const yearDelta = (airYear(a) ?? 0) - (airYear(b) ?? 0);
|
||||
if (yearDelta !== 0) return yearDelta;
|
||||
return a.id - b.id;
|
||||
});
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
export async function resolveAnilistSeasonMedia(
|
||||
input: ResolveAnilistSeasonMediaInput,
|
||||
deps: ResolveAnilistSeasonMediaDeps,
|
||||
): Promise<AnilistSeasonResolution | null> {
|
||||
const searchTitle = stripSeasonSuffix(input.title).trim() || input.title.trim();
|
||||
if (!searchTitle) return null;
|
||||
|
||||
const season =
|
||||
typeof input.season === 'number' && Number.isInteger(input.season) && input.season > 0
|
||||
? input.season
|
||||
: null;
|
||||
|
||||
const response = await deps.execute<AnilistSeasonSearchResponse>(ANILIST_SEASON_SEARCH_QUERY, {
|
||||
search: searchTitle,
|
||||
});
|
||||
const media = (response.Page?.media ?? []).filter(
|
||||
(entry): entry is AnilistSeasonMedia => Boolean(entry) && typeof entry.id === 'number',
|
||||
);
|
||||
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;
|
||||
|
||||
if (season === null || season <= 1) {
|
||||
return toResolution(anchor, searchTitle, season, 'anchor', true);
|
||||
}
|
||||
|
||||
let chainError: unknown = null;
|
||||
let viaChain: AnilistSeasonMedia | null = null;
|
||||
try {
|
||||
viaChain = await walkSequelChain(anchor, season, deps);
|
||||
} catch (error) {
|
||||
chainError = error;
|
||||
}
|
||||
if (viaChain) {
|
||||
deps.logInfo?.(
|
||||
`[anilist] season ${season} of "${searchTitle}" resolved via sequel chain: ${displayTitle(viaChain, searchTitle)} (${viaChain.id})`,
|
||||
);
|
||||
return toResolution(viaChain, searchTitle, season, 'sequel-chain', true);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// The chain failed for transport reasons rather than because the season is absent;
|
||||
// surface that so callers retry instead of reporting an unresolvable season.
|
||||
if (chainError) {
|
||||
throw chainError;
|
||||
}
|
||||
|
||||
deps.logInfo?.(
|
||||
`[anilist] could not resolve season ${season} of "${searchTitle}"; falling back to ${displayTitle(anchor, searchTitle)} (${anchor.id})`,
|
||||
);
|
||||
return toResolution(anchor, searchTitle, season, 'anchor', false);
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { Database } from '../sqlite.js';
|
||||
import {
|
||||
applyPragmas,
|
||||
createTrackerPreparedStatements,
|
||||
ensureSchema,
|
||||
getOrCreateAnimeRecord,
|
||||
@@ -58,16 +57,6 @@ function makeDbPath(): string {
|
||||
return path.join(dir, 'immersion.sqlite');
|
||||
}
|
||||
|
||||
// Match the runtime's SQLite tuning (WAL + synchronous=NORMAL). Without it these
|
||||
// tests run at SQLite's defaults, where every statement is its own fsync-ing
|
||||
// transaction; on slow CI disks that is enough to push insert-heavy cases past
|
||||
// the 5s per-test timeout.
|
||||
function openTestDb(dbPath: string) {
|
||||
const db = new Database(dbPath);
|
||||
applyPragmas(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
function cleanupDbPath(dbPath: string): void {
|
||||
const dir = path.dirname(dbPath);
|
||||
if (!fs.existsSync(dir)) {
|
||||
@@ -183,7 +172,7 @@ function withMockNowMs<T>(fixedDateMs: string | number, run: () => T): T {
|
||||
|
||||
test('getSessionSummaries returns sessionId and canonicalTitle', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -242,7 +231,7 @@ test('getSessionSummaries returns sessionId and canonicalTitle', () => {
|
||||
|
||||
test('getAnimeEpisodes prefers the latest session media position when the latest session is still active', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -310,7 +299,7 @@ test('getAnimeEpisodes prefers the latest session media position when the latest
|
||||
|
||||
test('getAnimeEpisodes includes unwatched episodes for the anime', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -408,7 +397,7 @@ test('getAnimeEpisodes includes unwatched episodes for the anime', () => {
|
||||
|
||||
test('getAnimeEpisodes falls back to the latest subtitle segment end when session progress checkpoints are missing', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -480,7 +469,7 @@ test('getAnimeEpisodes falls back to the latest subtitle segment end when sessio
|
||||
|
||||
test('getAnimeEpisodes ignores zero-valued session checkpoints and falls back to subtitle progress', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -552,7 +541,7 @@ test('getAnimeEpisodes ignores zero-valued session checkpoints and falls back to
|
||||
|
||||
test('getSessionTimeline returns the full session when no limit is provided', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -603,7 +592,7 @@ test('getSessionTimeline returns the full session when no limit is provided', ()
|
||||
|
||||
test('getDailyRollups limits by distinct days (not rows)', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -636,7 +625,7 @@ test('getDailyRollups limits by distinct days (not rows)', () => {
|
||||
|
||||
test('getTrendsDashboard returns chart-ready aggregated series', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -790,7 +779,7 @@ test('getTrendsDashboard returns chart-ready aggregated series', () => {
|
||||
|
||||
test('getTrendsDashboard redacts legacy Jellyfin stream titles', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -880,7 +869,7 @@ test('getTrendsDashboard redacts legacy Jellyfin stream titles', () => {
|
||||
|
||||
test('getTrendsDashboard keeps local-midnight session buckets separate', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1016,7 +1005,7 @@ test('getTrendsDashboard keeps local-midnight session buckets separate', () => {
|
||||
|
||||
test('getTrendsDashboard 30d day range zero-fills empty calendar days', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
withMockNowMs('1772395200000', () => {
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1080,7 +1069,7 @@ test('getTrendsDashboard 30d day range zero-fills empty calendar days', () => {
|
||||
|
||||
test('getTrendsDashboard skips empty calendar days when zero-fill is disabled', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
withMockNowMs('1772395200000', () => {
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1134,7 +1123,7 @@ test(
|
||||
{ timeout: 20_000 },
|
||||
() => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
withMockNowMs('1772395200000', () => {
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1194,7 +1183,7 @@ test(
|
||||
|
||||
test('getTrendsDashboard month grouping spans every touched calendar month and keeps progress monthly', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
withMockNowMs('1772395200000', () => {
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1417,7 +1406,7 @@ test('getTrendsDashboard month grouping spans every touched calendar month and k
|
||||
|
||||
test('getQueryHints reads all-time totals from lifetime summary', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1487,7 +1476,7 @@ test('getQueryHints reads all-time totals from lifetime summary', () => {
|
||||
|
||||
test('getQueryHints computes weekly new-word cutoff from calendar midnights', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
withMockNowMs('1773601200000', () => {
|
||||
try {
|
||||
@@ -1539,7 +1528,7 @@ test('getQueryHints computes weekly new-word cutoff from calendar midnights', ()
|
||||
|
||||
test('word-count read models use filtered persisted occurrences with raw fallback', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1622,7 +1611,7 @@ test('word-count read models use filtered persisted occurrences with raw fallbac
|
||||
|
||||
test('rollups keep persisted totals when retained-session word counts are partial', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1683,7 +1672,7 @@ test('rollups keep persisted totals when retained-session word counts are partia
|
||||
|
||||
test('getQueryHints counts new words by distinct headword first-seen time', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1748,7 +1737,7 @@ test('getQueryHints counts new words by distinct headword first-seen time', () =
|
||||
|
||||
test('getSessionSummaries with no telemetry returns zero aggregates', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1782,7 +1771,7 @@ test('getSessionSummaries with no telemetry returns zero aggregates', () => {
|
||||
|
||||
test('getSessionSummaries uses denormalized session metrics for ended sessions without telemetry', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1834,7 +1823,7 @@ test('getSessionSummaries uses denormalized session metrics for ended sessions w
|
||||
|
||||
test('getVocabularyStats returns rows ordered by frequency descending', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1877,7 +1866,7 @@ test('getVocabularyStats returns rows ordered by frequency descending', () => {
|
||||
|
||||
test('getVocabularyStats filters rows that fail tokenizer vocabulary rules', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1932,7 +1921,7 @@ test('getVocabularyStats filters rows that fail tokenizer vocabulary rules', ()
|
||||
|
||||
test('getVocabularyStats pages past hidden rows until enough visible rows are collected', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1967,7 +1956,7 @@ test('getVocabularyStats pages past hidden rows until enough visible rows are co
|
||||
|
||||
test('getVocabularyStats returns empty array when no words exist', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -1981,7 +1970,7 @@ test('getVocabularyStats returns empty array when no words exist', () => {
|
||||
|
||||
test('cleanupVocabularyStats repairs stored POS metadata and removes excluded imm_words rows', async () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2111,7 +2100,7 @@ test('cleanupVocabularyStats repairs stored POS metadata and removes excluded im
|
||||
|
||||
test('getDailyRollups returns all rows for the most recent rollup days', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
try {
|
||||
ensureSchema(db);
|
||||
const insertRollup = db.prepare(
|
||||
@@ -2147,7 +2136,7 @@ test('getDailyRollups returns all rows for the most recent rollup days', () => {
|
||||
|
||||
test('getMonthlyRollups returns all rows for the most recent rollup months', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
try {
|
||||
ensureSchema(db);
|
||||
const insertRollup = db.prepare(
|
||||
@@ -2178,7 +2167,7 @@ test('getMonthlyRollups returns all rows for the most recent rollup months', ()
|
||||
|
||||
test('getMonthlyRollups derives rate metrics from stored monthly totals', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
try {
|
||||
ensureSchema(db);
|
||||
const insertRollup = db.prepare(
|
||||
@@ -2209,7 +2198,7 @@ test('getMonthlyRollups derives rate metrics from stored monthly totals', () =>
|
||||
|
||||
test('getAnimeDailyRollups returns all rows for the most recent rollup days', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
try {
|
||||
ensureSchema(db);
|
||||
const insertRollup = db.prepare(
|
||||
@@ -2265,7 +2254,7 @@ test('getAnimeDailyRollups returns all rows for the most recent rollup days', ()
|
||||
|
||||
test('cleanupVocabularyStats merges repaired duplicates instead of violating the imm_words unique key', async () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2378,7 +2367,7 @@ test('cleanupVocabularyStats merges repaired duplicates instead of violating the
|
||||
|
||||
test('getKanjiStats returns rows ordered by frequency descending', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2416,7 +2405,7 @@ test('getKanjiStats returns rows ordered by frequency descending', () => {
|
||||
|
||||
test('getKanjiStats returns empty array when no kanji exist', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2430,7 +2419,7 @@ test('getKanjiStats returns empty array when no kanji exist', () => {
|
||||
|
||||
test('getSessionEvents returns events ordered by ts_ms ascending', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2491,7 +2480,7 @@ test('getSessionEvents returns events ordered by ts_ms ascending', () => {
|
||||
|
||||
test('getSessionEvents round-trips wall-clock timestamps written through event inserts', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2535,7 +2524,7 @@ test('getSessionEvents round-trips wall-clock timestamps written through event i
|
||||
|
||||
test('getSessionEvents returns empty array for session with no events', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2558,7 +2547,7 @@ test('getSessionEvents returns empty array for session with no events', () => {
|
||||
|
||||
test('getSessionEvents filters events to the requested session id', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2624,7 +2613,7 @@ test('getSessionEvents filters events to the requested session id', () => {
|
||||
|
||||
test('getSessionEvents respects limit parameter', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2667,7 +2656,7 @@ test('getSessionEvents respects limit parameter', () => {
|
||||
|
||||
test('getSessionEvents filters by event type before applying limit', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2739,7 +2728,7 @@ test('getSessionEvents filters by event type before applying limit', () => {
|
||||
|
||||
test('getSessionWordsByLine joins word occurrences through imm_words.id', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -2814,7 +2803,7 @@ test('getSessionWordsByLine joins word occurrences through imm_words.id', () =>
|
||||
|
||||
test('anime-level queries group by anime_id and preserve episode-level rows', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3094,7 +3083,7 @@ test('anime-level queries group by anime_id and preserve episode-level rows', ()
|
||||
|
||||
test('anime library and detail still return lifetime rows without retained sessions', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3191,7 +3180,7 @@ test('anime library and detail still return lifetime rows without retained sessi
|
||||
|
||||
test('anime and media detail prefer lifetime totals over partial retained sessions', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3281,7 +3270,7 @@ test('anime and media detail prefer lifetime totals over partial retained sessio
|
||||
|
||||
test('media detail resolves retained sessions before lifetime summary exists', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3334,7 +3323,7 @@ test('media detail resolves retained sessions before lifetime summary exists', (
|
||||
|
||||
test('media library and detail queries read lifetime totals', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3426,7 +3415,7 @@ test('media library and detail queries read lifetime totals', () => {
|
||||
|
||||
test('media library and detail queries include joined youtube metadata when present', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3523,7 +3512,7 @@ test('media library and detail queries include joined youtube metadata when pres
|
||||
|
||||
test('cover art queries reuse a shared blob across duplicate anime art rows', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3650,7 +3639,7 @@ test('cover art queries reuse a shared blob across duplicate anime art rows', ()
|
||||
|
||||
test('upsertCoverArt prefers freshly fetched bytes over a reused shared hash', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3696,7 +3685,7 @@ test('upsertCoverArt prefers freshly fetched bytes over a reused shared hash', (
|
||||
|
||||
test('anime/media detail and episode queries use ended-session metrics when telemetry rows are absent', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3838,7 +3827,7 @@ test('anime/media detail and episode queries use ended-session metrics when tele
|
||||
|
||||
test('getWordOccurrences maps a normalized word back to anime, video, and subtitle line context', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -3913,7 +3902,7 @@ test('getWordOccurrences maps a normalized word back to anime, video, and subtit
|
||||
|
||||
test('searchSubtitleSentences searches known subtitle lines and returns media context', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4010,7 +3999,7 @@ test('searchSubtitleSentences searches known subtitle lines and returns media co
|
||||
|
||||
test('searchSubtitleSentences searches subtitle lines by resolved headword candidates', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4094,7 +4083,7 @@ test('searchSubtitleSentences searches subtitle lines by resolved headword candi
|
||||
|
||||
test('getKanjiOccurrences maps a kanji back to anime, video, and subtitle line context', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4169,7 +4158,7 @@ test('getKanjiOccurrences maps a kanji back to anime, video, and subtitle line c
|
||||
|
||||
test('deleteSession removes the session and all associated session-scoped rows', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4317,7 +4306,7 @@ test('deleteSession removes the session and all associated session-scoped rows',
|
||||
|
||||
test('deleteSession rebuilds word and kanji aggregates from retained subtitle lines', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4473,7 +4462,7 @@ test('deleteSession rebuilds word and kanji aggregates from retained subtitle li
|
||||
|
||||
test('deleteSession removes zero-session media from library and trends', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4678,7 +4667,7 @@ test('deleteSession removes zero-session media from library and trends', () => {
|
||||
|
||||
test('getTrendsDashboard builds librarySummary with per-title aggregates', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4785,7 +4774,7 @@ test('getTrendsDashboard builds librarySummary with per-title aggregates', () =>
|
||||
|
||||
test('getTrendsDashboard librarySummary returns null lookupsPerHundred when words is zero', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4867,7 +4856,7 @@ test('getTrendsDashboard librarySummary returns null lookupsPerHundred when word
|
||||
|
||||
test('getTrendsDashboard rollup word metrics keep persisted totals over partial session counts', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
@@ -4982,7 +4971,7 @@ test('getTrendsDashboard rollup word metrics keep persisted totals over partial
|
||||
|
||||
test('getTrendsDashboard librarySummary is empty when no rollups exist', () => {
|
||||
const dbPath = makeDbPath();
|
||||
const db = openTestDb(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
ensureSchema(db);
|
||||
|
||||
@@ -85,5 +85,5 @@ test('writeConfigExampleArtifacts creates parent directories for resolved output
|
||||
test('generateConfigExampleTemplate uses the canonical example socket path', () => {
|
||||
const template = generateConfigExampleTemplate();
|
||||
|
||||
assert.match(template, /"socketPath": "\/tmp\/subminer-socket"/);
|
||||
assert.match(template, /"socketPath": "\\\\\\\\.\\\\pipe\\\\subminer-socket"/);
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as path from 'path';
|
||||
import { DEFAULT_CONFIG, deepCloneConfig, generateConfigTemplate } from './config';
|
||||
import { getDefaultMpvSocketPath } from './shared/mpv-socket-path';
|
||||
|
||||
const CONFIG_EXAMPLE_PLATFORM: NodeJS.Platform = 'linux';
|
||||
const CONFIG_EXAMPLE_PLATFORM: NodeJS.Platform = 'win32';
|
||||
|
||||
export function generateConfigExampleTemplate(): string {
|
||||
const config = deepCloneConfig(DEFAULT_CONFIG);
|
||||
|
||||
+11
-4
@@ -3616,10 +3616,12 @@ const {
|
||||
);
|
||||
},
|
||||
refreshAnilistClientSecretState: () => refreshAnilistClientSecretState(),
|
||||
updateAnilistPostWatchProgress: (accessToken, title, episode, season) =>
|
||||
updateAnilistPostWatchProgress: (accessToken, title, episode, season, mediaId) =>
|
||||
updateAnilistPostWatchProgress(accessToken, title, episode, {
|
||||
rateLimiter: anilistRateLimiter,
|
||||
season,
|
||||
mediaId,
|
||||
logInfo: (message) => logger.info(message),
|
||||
}),
|
||||
markSuccess: (key) => {
|
||||
anilistUpdateQueue.markSuccess(key);
|
||||
@@ -3655,9 +3657,12 @@ const {
|
||||
hasAttemptedUpdateKey: (key) => anilistAttemptedUpdateKeys.has(key),
|
||||
processNextAnilistRetryUpdate: () => processNextAnilistRetryUpdate(),
|
||||
refreshAnilistClientSecretState: () => refreshAnilistClientSecretState(),
|
||||
enqueueRetry: (key, title, episode, season) => {
|
||||
anilistUpdateQueue.enqueue(key, title, episode, season);
|
||||
enqueueRetry: (key, title, episode, season, mediaId) => {
|
||||
anilistUpdateQueue.enqueue(key, title, episode, season, mediaId);
|
||||
},
|
||||
getCurrentMediaTitle: () => appState.currentMediaTitle,
|
||||
resolvePinnedAnilistMediaId: ({ mediaPath, mediaTitle, guess }) =>
|
||||
characterDictionaryRuntime.resolvePinnedMediaId({ mediaPath, mediaTitle, guess }),
|
||||
markRetryFailure: (key, message) => {
|
||||
anilistUpdateQueue.markFailure(key, message);
|
||||
},
|
||||
@@ -3665,10 +3670,12 @@ const {
|
||||
anilistUpdateQueue.markSuccess(key);
|
||||
},
|
||||
refreshRetryQueueState: () => anilistStateRuntime.refreshRetryQueueState(),
|
||||
updateAnilistPostWatchProgress: (accessToken, title, episode, season) =>
|
||||
updateAnilistPostWatchProgress: (accessToken, title, episode, season, mediaId) =>
|
||||
updateAnilistPostWatchProgress(accessToken, title, episode, {
|
||||
rateLimiter: anilistRateLimiter,
|
||||
season,
|
||||
mediaId,
|
||||
logInfo: (message) => logger.info(message),
|
||||
}),
|
||||
rememberAttemptedUpdateKey: (key) => {
|
||||
rememberAnilistAttemptedUpdate(key);
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
import {
|
||||
buildCharacterDictionarySeriesKey,
|
||||
createCharacterDictionaryManualSelectionStore,
|
||||
type CharacterDictionarySeriesKeyGuess,
|
||||
} from './character-dictionary-runtime/manual-selection';
|
||||
import { snapshotHasCharacterNameImages } from './character-dictionary-runtime/image-lookup';
|
||||
import { resolveJapaneseNameSplits } from './character-dictionary-runtime/name-split-resolver';
|
||||
@@ -168,6 +169,11 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
|
||||
targetPath?: string,
|
||||
options?: CharacterDictionaryGenerateOptions,
|
||||
) => Promise<CharacterDictionaryBuildResult>;
|
||||
resolvePinnedMediaId: (input: {
|
||||
mediaPath: string | null;
|
||||
mediaTitle: string | null;
|
||||
guess: CharacterDictionarySeriesKeyGuess | null;
|
||||
}) => Promise<number | null>;
|
||||
} {
|
||||
const outputDir = path.join(deps.userDataPath, 'character-dictionaries');
|
||||
const sleepMs = deps.sleep ?? sleep;
|
||||
@@ -272,7 +278,7 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
|
||||
: ''
|
||||
}`,
|
||||
);
|
||||
const override = await manualSelectionStore.getOverride(seriesKey);
|
||||
const override = await manualSelectionStore.getOverride(seriesKey, guessed.season);
|
||||
if (override) {
|
||||
deps.logInfo?.(
|
||||
`[dictionary] manual AniList override: ${override.mediaTitle} -> AniList ${override.mediaId}`,
|
||||
@@ -314,7 +320,17 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
|
||||
};
|
||||
}
|
||||
|
||||
const resolved = await resolveAniListMediaIdFromGuess(guessed, beforeRequest);
|
||||
const resolved = await resolveAniListMediaIdFromGuess(guessed, beforeRequest, (message) =>
|
||||
deps.logInfo?.(message),
|
||||
);
|
||||
if (resolved.seasonResolved === false) {
|
||||
deps.logWarn?.(
|
||||
`[dictionary] could not find season ${resolved.requestedSeason} of "${guessed.title}"; using ${resolved.title} (AniList ${resolved.id}). Set a manual AniList match to correct it.`,
|
||||
);
|
||||
// Caching the fallback would make the wrong season stick silently for every later
|
||||
// episode, so leave it uncached and re-resolve (and re-warn) until it is corrected.
|
||||
return resolved;
|
||||
}
|
||||
writeCachedMediaResolution(outputDir, {
|
||||
seriesKey,
|
||||
mediaId: resolved.id,
|
||||
@@ -509,7 +525,7 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
|
||||
? await searchAniListMediaCandidates(candidateSearchTitle, waitForAniListRequestSlot)
|
||||
: [];
|
||||
const [override, current] = await Promise.all([
|
||||
manualSelectionStore.getOverride(seriesKey),
|
||||
manualSelectionStore.getOverride(seriesKey, guessed.season),
|
||||
shouldUseExplicitSearch
|
||||
? Promise.resolve(null)
|
||||
: resolveAniListMediaIdFromGuess(guessed, waitForAniListRequestSlot)
|
||||
@@ -553,6 +569,7 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
|
||||
mediaId: selected.id,
|
||||
mediaTitle: selected.title,
|
||||
staleMediaIds,
|
||||
season: guessed.season,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
@@ -605,5 +622,14 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
|
||||
revision,
|
||||
};
|
||||
},
|
||||
resolvePinnedMediaId: async ({ mediaPath, mediaTitle, guess }) => {
|
||||
const seriesKey = buildCharacterDictionarySeriesKey({
|
||||
mediaPath: deps.resolveMediaPathForJimaku(mediaPath),
|
||||
mediaTitle,
|
||||
guess,
|
||||
});
|
||||
const override = await manualSelectionStore.getOverride(seriesKey, guess?.season ?? null);
|
||||
return override?.mediaId ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AnilistMediaGuess } from '../../core/services/anilist/anilist-updater';
|
||||
import { resolveAnilistSeasonMedia } from '../../core/services/anilist/season-resolver';
|
||||
import { ANILIST_GRAPHQL_URL } from './constants';
|
||||
import type {
|
||||
AniListMediaCandidate,
|
||||
@@ -73,57 +74,6 @@ type AniListCharacterPageResponse = {
|
||||
} | null;
|
||||
};
|
||||
|
||||
function normalizeTitle(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function pickAniListSearchResult(
|
||||
title: string,
|
||||
episode: number | null,
|
||||
media: Array<{
|
||||
id: number;
|
||||
episodes?: number | null;
|
||||
title?: {
|
||||
romaji?: string | null;
|
||||
english?: string | null;
|
||||
native?: string | null;
|
||||
};
|
||||
}>,
|
||||
): ResolvedAniListMedia | null {
|
||||
if (media.length === 0) return null;
|
||||
|
||||
const episodeFiltered =
|
||||
episode && episode > 0
|
||||
? media.filter((entry) => {
|
||||
const totalEpisodes = entry.episodes;
|
||||
return (
|
||||
typeof totalEpisodes !== 'number' || totalEpisodes <= 0 || episode <= totalEpisodes
|
||||
);
|
||||
})
|
||||
: media;
|
||||
const candidates = episodeFiltered.length > 0 ? episodeFiltered : media;
|
||||
const normalizedTitle = normalizeTitle(title);
|
||||
|
||||
const exact = candidates.find((entry) => {
|
||||
const titles = [entry.title?.english, entry.title?.romaji, entry.title?.native]
|
||||
.filter((value): value is string => typeof value === 'string')
|
||||
.map((value) => normalizeTitle(value));
|
||||
return titles.includes(normalizedTitle);
|
||||
});
|
||||
const selected = exact ?? candidates[0] ?? media[0];
|
||||
if (!selected) return null;
|
||||
|
||||
const selectedTitle =
|
||||
selected.title?.english?.trim() ||
|
||||
selected.title?.romaji?.trim() ||
|
||||
selected.title?.native?.trim() ||
|
||||
title.trim();
|
||||
return {
|
||||
id: selected.id,
|
||||
title: selectedTitle,
|
||||
};
|
||||
}
|
||||
|
||||
function toAniListMediaCandidate(
|
||||
entry: {
|
||||
id: number;
|
||||
@@ -242,35 +192,24 @@ function inferImageExt(contentType: string | null, bytes: Buffer): string {
|
||||
export async function resolveAniListMediaIdFromGuess(
|
||||
guess: AnilistMediaGuess,
|
||||
beforeRequest?: () => Promise<void>,
|
||||
logInfo?: (message: string) => void,
|
||||
): Promise<ResolvedAniListMedia> {
|
||||
const data = await fetchAniList<AniListSearchResponse>(
|
||||
`
|
||||
query($search: String!) {
|
||||
Page(perPage: 10) {
|
||||
media(search: $search, type: ANIME, sort: [SEARCH_MATCH, POPULARITY_DESC]) {
|
||||
id
|
||||
episodes
|
||||
title {
|
||||
romaji
|
||||
english
|
||||
native
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
const resolution = await resolveAnilistSeasonMedia(
|
||||
{ title: guess.title, season: guess.season, episode: guess.episode },
|
||||
{
|
||||
search: guess.title,
|
||||
execute: (query, variables) => fetchAniList(query, variables, beforeRequest),
|
||||
logInfo,
|
||||
},
|
||||
beforeRequest,
|
||||
);
|
||||
|
||||
const media = data.Page?.media ?? [];
|
||||
const resolved = pickAniListSearchResult(guess.title, guess.episode, media);
|
||||
if (!resolved) {
|
||||
if (!resolution) {
|
||||
throw new Error(`No AniList media match found for "${guess.title}".`);
|
||||
}
|
||||
return resolved;
|
||||
return {
|
||||
id: resolution.id,
|
||||
title: resolution.title,
|
||||
seasonResolved: resolution.seasonResolved,
|
||||
requestedSeason: resolution.requestedSeason,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchAniListMediaCandidates(
|
||||
|
||||
@@ -160,3 +160,73 @@ test('getManualSelectionSnapshot hydrates override episode count from searched c
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('resolvePinnedMediaId returns the manual override for the current season', async () => {
|
||||
const userDataPath = makeTempDir();
|
||||
const seasonThreePath = '/anime/Oregairu/My Teen Romantic Comedy SNAFU (2013) - S03E01.mkv';
|
||||
const guess = {
|
||||
title: 'My Teen Romantic Comedy SNAFU',
|
||||
year: 2013,
|
||||
season: 3,
|
||||
episode: 1,
|
||||
source: 'guessit' as const,
|
||||
};
|
||||
|
||||
const runtime = createCharacterDictionaryRuntimeService({
|
||||
userDataPath,
|
||||
getCurrentMediaPath: () => seasonThreePath,
|
||||
getCurrentMediaTitle: () => null,
|
||||
resolveMediaPathForJimaku: (mediaPath) => mediaPath,
|
||||
guessAnilistMediaInfo: async () => guess,
|
||||
now: () => 1_700_000_000_000,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
await runtime.resolvePinnedMediaId({
|
||||
mediaPath: seasonThreePath,
|
||||
mediaTitle: null,
|
||||
guess,
|
||||
}),
|
||||
null,
|
||||
);
|
||||
|
||||
const overridesPath = path.join(userDataPath, 'character-dictionaries', 'anilist-overrides.json');
|
||||
fs.mkdirSync(path.dirname(overridesPath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
overridesPath,
|
||||
JSON.stringify({
|
||||
overrides: [
|
||||
{
|
||||
seriesKey: buildCharacterDictionarySeriesKey({
|
||||
mediaPath: seasonThreePath,
|
||||
mediaTitle: null,
|
||||
guess,
|
||||
}),
|
||||
mediaId: 108489,
|
||||
mediaTitle: 'My Teen Romantic Comedy SNAFU Climax!',
|
||||
staleMediaIds: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
await runtime.resolvePinnedMediaId({
|
||||
mediaPath: seasonThreePath,
|
||||
mediaTitle: null,
|
||||
guess,
|
||||
}),
|
||||
108489,
|
||||
);
|
||||
|
||||
// The season 1 file in the same folder must not inherit the season 3 override.
|
||||
assert.equal(
|
||||
await runtime.resolvePinnedMediaId({
|
||||
mediaPath: '/anime/Oregairu/My Teen Romantic Comedy SNAFU (2013) - S01E01.mkv',
|
||||
mediaTitle: null,
|
||||
guess: { ...guess, season: 1 },
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -312,3 +312,131 @@ test('manual selection store keeps overrides separate for different season direc
|
||||
assert.notEqual(secondSeasonKey, firstSeasonKey);
|
||||
assert.equal(await store.getOverride(secondSeasonKey), null);
|
||||
});
|
||||
|
||||
test('buildCharacterDictionarySeriesKey tags seasons past the first', () => {
|
||||
const base = {
|
||||
title: 'My Teen Romantic Comedy SNAFU',
|
||||
year: 2013,
|
||||
episode: 1,
|
||||
source: 'guessit' as const,
|
||||
};
|
||||
const seasonOne = buildCharacterDictionarySeriesKey({
|
||||
mediaPath: '/anime/Oregairu/My Teen Romantic Comedy SNAFU (2013) - S01E01.mkv',
|
||||
mediaTitle: null,
|
||||
guess: { ...base, season: 1 },
|
||||
});
|
||||
const seasonThree = buildCharacterDictionarySeriesKey({
|
||||
mediaPath: '/anime/Oregairu/My Teen Romantic Comedy SNAFU (2013) - S03E01.mkv',
|
||||
mediaTitle: null,
|
||||
guess: { ...base, season: 3 },
|
||||
});
|
||||
|
||||
// Season 1 keeps the pre-existing key shape so cached snapshots stay valid.
|
||||
assert.equal(seasonOne, 'anime-oregairu--my-teen-romantic-comedy-snafu-2013');
|
||||
assert.equal(seasonThree, 'anime-oregairu--my-teen-romantic-comedy-snafu-s3-2013');
|
||||
});
|
||||
|
||||
test('manual selection store keeps seasons apart inside one flat directory', async () => {
|
||||
const userDataPath = makeTempDir();
|
||||
const store = createCharacterDictionaryManualSelectionStore({ userDataPath });
|
||||
const base = {
|
||||
title: 'My Teen Romantic Comedy SNAFU',
|
||||
year: 2013,
|
||||
episode: 1,
|
||||
source: 'guessit' as const,
|
||||
};
|
||||
const seasonOneKey = buildCharacterDictionarySeriesKey({
|
||||
mediaPath: '/anime/Oregairu/My Teen Romantic Comedy SNAFU (2013) - S01E01.mkv',
|
||||
mediaTitle: null,
|
||||
guess: { ...base, season: 1 },
|
||||
});
|
||||
const seasonThreeKey = buildCharacterDictionarySeriesKey({
|
||||
mediaPath: '/anime/Oregairu/My Teen Romantic Comedy SNAFU (2013) - S03E01.mkv',
|
||||
mediaTitle: null,
|
||||
guess: { ...base, season: 3 },
|
||||
});
|
||||
|
||||
await store.setOverride({
|
||||
seriesKey: seasonOneKey,
|
||||
mediaId: 14813,
|
||||
mediaTitle: 'My Teen Romantic Comedy SNAFU',
|
||||
staleMediaIds: [],
|
||||
});
|
||||
|
||||
// Same directory, different season: the season 1 override must not leak across.
|
||||
assert.equal(await store.getOverride(seasonThreeKey), null);
|
||||
|
||||
await store.setOverride({
|
||||
seriesKey: seasonThreeKey,
|
||||
mediaId: 108489,
|
||||
mediaTitle: 'My Teen Romantic Comedy SNAFU Climax!',
|
||||
staleMediaIds: [],
|
||||
});
|
||||
|
||||
assert.equal((await store.getOverride(seasonOneKey))?.mediaId, 14813);
|
||||
assert.equal((await store.getOverride(seasonThreeKey))?.mediaId, 108489);
|
||||
});
|
||||
|
||||
test('override scope uses the recorded season, not season-like text in the title', async () => {
|
||||
const userDataPath = makeTempDir();
|
||||
const store = createCharacterDictionaryManualSelectionStore({ userDataPath });
|
||||
// A title that itself normalizes to a trailing "-s2" would be misparsed as season 2.
|
||||
const trickyTitleKey = buildCharacterDictionarySeriesKey({
|
||||
mediaPath: '/anime/Mixed/Some Show S2 - S01E01.mkv',
|
||||
mediaTitle: null,
|
||||
guess: { title: 'Some Show S2', season: 1, episode: 1, source: 'guessit' },
|
||||
});
|
||||
const realSeasonTwoKey = buildCharacterDictionarySeriesKey({
|
||||
mediaPath: '/anime/Mixed/Other Show - S02E01.mkv',
|
||||
mediaTitle: null,
|
||||
guess: { title: 'Other Show', season: 2, episode: 1, source: 'guessit' },
|
||||
});
|
||||
|
||||
await store.setOverride({
|
||||
seriesKey: trickyTitleKey,
|
||||
mediaId: 111,
|
||||
mediaTitle: 'Some Show S2',
|
||||
staleMediaIds: [],
|
||||
season: 1,
|
||||
});
|
||||
await store.setOverride({
|
||||
seriesKey: realSeasonTwoKey,
|
||||
mediaId: 222,
|
||||
mediaTitle: 'Other Show 2',
|
||||
staleMediaIds: [],
|
||||
season: 2,
|
||||
});
|
||||
|
||||
// Same directory, genuinely different seasons: neither override may replace the other.
|
||||
assert.equal((await store.getOverride(trickyTitleKey, 1))?.mediaId, 111);
|
||||
assert.equal((await store.getOverride(realSeasonTwoKey, 2))?.mediaId, 222);
|
||||
});
|
||||
|
||||
test('override records without a stored season still resolve via the key', async () => {
|
||||
const userDataPath = makeTempDir();
|
||||
const store = createCharacterDictionaryManualSelectionStore({ userDataPath });
|
||||
const legacyKey = buildCharacterDictionarySeriesKey({
|
||||
mediaPath: REZERO_EP1,
|
||||
mediaTitle: null,
|
||||
guess: {
|
||||
title: 'Re ZERO, Starting Life in Another World',
|
||||
year: 2016,
|
||||
season: 1,
|
||||
episode: 1,
|
||||
source: 'guessit',
|
||||
},
|
||||
});
|
||||
const overridesPath = path.join(userDataPath, 'character-dictionaries', 'anilist-overrides.json');
|
||||
fs.mkdirSync(path.dirname(overridesPath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
overridesPath,
|
||||
JSON.stringify({
|
||||
overrides: [
|
||||
{ seriesKey: legacyKey, mediaId: 21355, mediaTitle: 'Re:ZERO', staleMediaIds: [] },
|
||||
],
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
assert.equal((await store.getOverride(legacyKey, 1))?.mediaId, 21355);
|
||||
});
|
||||
|
||||
@@ -8,6 +8,11 @@ export type CharacterDictionaryManualSelection = {
|
||||
mediaId: number;
|
||||
mediaTitle: string;
|
||||
staleMediaIds: number[];
|
||||
/**
|
||||
* Season this override was saved for. Recorded explicitly because inferring it from the
|
||||
* key text is ambiguous for titles that themselves end in a season-like token.
|
||||
*/
|
||||
season?: number | null;
|
||||
};
|
||||
|
||||
type ManualSelectionStoreFile = {
|
||||
@@ -20,6 +25,11 @@ function normalizeManualMediaId(value: unknown): number | null {
|
||||
return mediaId > 0 ? mediaId : null;
|
||||
}
|
||||
|
||||
function normalizeSeason(value: unknown): number | null {
|
||||
if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizeSeriesKeyPart(value: string): string {
|
||||
return value
|
||||
.normalize('NFKD')
|
||||
@@ -73,11 +83,13 @@ function normalizeOverride(value: unknown): CharacterDictionaryManualSelection |
|
||||
const mediaId = normalizeManualMediaId(raw.mediaId);
|
||||
const mediaTitle = typeof raw.mediaTitle === 'string' ? raw.mediaTitle.trim() : '';
|
||||
if (!seriesKey || mediaId === null || !mediaTitle) return null;
|
||||
const season = normalizeSeason(raw.season);
|
||||
return {
|
||||
seriesKey,
|
||||
mediaId,
|
||||
mediaTitle,
|
||||
staleMediaIds: dedupeNumbers(Array.isArray(raw.staleMediaIds) ? raw.staleMediaIds : []),
|
||||
...(season === null ? {} : { season }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -112,10 +124,29 @@ function getDirectoryScope(seriesKey: string): string | null {
|
||||
return scopedSeparatorIndex < 0 ? null : seriesKey.slice(0, scopedSeparatorIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback season for override records saved before the season was stored explicitly:
|
||||
* reads the "-s<N>" segment emitted by buildCharacterDictionarySeriesKey, which sits just
|
||||
* before the optional trailing year. Season 1 keys carry no segment and parse as 1.
|
||||
*/
|
||||
function getSeasonScopeFromKey(seriesKey: string): number {
|
||||
const match = /-s(\d{1,2})(?:-\d{4})?$/.exec(seriesKey);
|
||||
if (!match) return 1;
|
||||
const season = Number.parseInt(match[1]!, 10);
|
||||
return Number.isInteger(season) && season > 0 ? season : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subset of a parsed guess the series key is built from. Kept structural so callers
|
||||
* holding a narrower guess (the AniList post-watch runtime) can build the same key.
|
||||
*/
|
||||
export type CharacterDictionarySeriesKeyGuess = Pick<AnilistMediaGuess, 'title' | 'season'> &
|
||||
Partial<Omit<AnilistMediaGuess, 'title' | 'season'>>;
|
||||
|
||||
export function buildCharacterDictionarySeriesKey(input: {
|
||||
mediaPath: string | null;
|
||||
mediaTitle: string | null;
|
||||
guess: AnilistMediaGuess | null;
|
||||
guess: CharacterDictionarySeriesKeyGuess | null;
|
||||
}): string {
|
||||
const guessedTitle = input.guess?.title.trim() || input.guess?.alternativeTitle?.trim() || '';
|
||||
const sourceTitle =
|
||||
@@ -130,22 +161,40 @@ export function buildCharacterDictionarySeriesKey(input: {
|
||||
const base = normalizeSeriesKeyPart(withoutEpisode) || 'unknown';
|
||||
const directoryKey = getMediaDirectoryKey(input.mediaPath);
|
||||
const scopedBase = directoryKey ? `${directoryKey}--${base}` : base;
|
||||
return input.guess?.year ? `${scopedBase}-${input.guess.year}` : scopedBase;
|
||||
// Season 1 stays unsuffixed so existing keys, snapshots and overrides keep matching.
|
||||
const season = input.guess?.season;
|
||||
const seasonSegment =
|
||||
typeof season === 'number' && Number.isInteger(season) && season > 1 ? `-s${season}` : '';
|
||||
const withSeason = `${scopedBase}${seasonSegment}`;
|
||||
return input.guess?.year ? `${withSeason}-${input.guess.year}` : withSeason;
|
||||
}
|
||||
|
||||
/** Season an override applies to: the recorded value, else parsed from its key. */
|
||||
function getOverrideSeason(entry: CharacterDictionaryManualSelection): number {
|
||||
return normalizeSeason(entry.season) ?? getSeasonScopeFromKey(entry.seriesKey);
|
||||
}
|
||||
|
||||
export function createCharacterDictionaryManualSelectionStore(deps: { userDataPath: string }) {
|
||||
const filePath = path.join(deps.userDataPath, 'character-dictionaries', 'anilist-overrides.json');
|
||||
|
||||
return {
|
||||
getOverride: async (seriesKey: string): Promise<CharacterDictionaryManualSelection | null> => {
|
||||
getOverride: async (
|
||||
seriesKey: string,
|
||||
season?: number | null,
|
||||
): Promise<CharacterDictionaryManualSelection | null> => {
|
||||
const candidates = getLegacySeriesKeyCandidates(seriesKey);
|
||||
const overrides = readOverrides(filePath);
|
||||
const exactMatch = overrides.find((entry) => entry.seriesKey === candidates[0]);
|
||||
if (exactMatch) return exactMatch;
|
||||
const directoryScope = getDirectoryScope(seriesKey);
|
||||
if (directoryScope) {
|
||||
// Same folder is only evidence of the same show when it is also the same season;
|
||||
// a flat multi-season folder would otherwise spread one override across all of them.
|
||||
const seasonScope = normalizeSeason(season) ?? getSeasonScopeFromKey(seriesKey);
|
||||
const scopedMatches = overrides.filter(
|
||||
(entry) => getDirectoryScope(entry.seriesKey) === directoryScope,
|
||||
(entry) =>
|
||||
getDirectoryScope(entry.seriesKey) === directoryScope &&
|
||||
getOverrideSeason(entry) === seasonScope,
|
||||
);
|
||||
const selectedMediaIds = new Set(scopedMatches.map((entry) => entry.mediaId));
|
||||
if (scopedMatches.length > 0 && selectedMediaIds.size === 1) {
|
||||
@@ -168,9 +217,11 @@ export function createCharacterDictionaryManualSelectionStore(deps: { userDataPa
|
||||
throw new Error('Invalid character dictionary manual selection.');
|
||||
}
|
||||
const directoryScope = getDirectoryScope(normalized.seriesKey);
|
||||
const seasonScope = getOverrideSeason(normalized);
|
||||
const remaining = readOverrides(filePath).filter((entry) =>
|
||||
directoryScope
|
||||
? getDirectoryScope(entry.seriesKey) !== directoryScope
|
||||
? getDirectoryScope(entry.seriesKey) !== directoryScope ||
|
||||
getOverrideSeason(entry) !== seasonScope
|
||||
: entry.seriesKey !== normalized.seriesKey,
|
||||
);
|
||||
writeOverrides(filePath, [...remaining, normalized]);
|
||||
|
||||
@@ -324,3 +324,102 @@ test('generateForCurrentMedia keeps same-version snapshots without images when i
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('an unresolvable season is not cached as a normal AniList match', async () => {
|
||||
const userDataPath = makeTempDir();
|
||||
const originalFetch = globalThis.fetch;
|
||||
let searchCalls = 0;
|
||||
|
||||
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
if (url !== GRAPHQL_URL) {
|
||||
return new Response(PNG_1X1, { status: 200, headers: { 'content-type': 'image/png' } });
|
||||
}
|
||||
|
||||
const body = JSON.parse(String(init?.body ?? '{}')) as {
|
||||
query?: string;
|
||||
variables?: { search?: string; id?: number };
|
||||
};
|
||||
|
||||
if (body.query?.includes('characters(page: $page')) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
Media: {
|
||||
title: { english: 'My Teen Romantic Comedy SNAFU' },
|
||||
characters: {
|
||||
pageInfo: { hasNextPage: false },
|
||||
edges: [
|
||||
{
|
||||
role: 'MAIN',
|
||||
node: { id: 1, name: { full: 'Hachiman Hikigaya', native: '比企谷八幡' } },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { 'content-type': 'application/json' } },
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof body.variables?.id === 'number') {
|
||||
// No sequel edges: season 3 is unreachable from the season 1 anchor.
|
||||
return new Response(JSON.stringify({ data: { Media: { relations: { edges: [] } } } }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
searchCalls += 1;
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
Page: {
|
||||
media: [
|
||||
{
|
||||
id: 14813,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2013,
|
||||
title: { romaji: null, english: 'My Teen Romantic Comedy SNAFU', native: null },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { 'content-type': 'application/json' } },
|
||||
);
|
||||
}) as typeof globalThis.fetch;
|
||||
|
||||
const warnings: string[] = [];
|
||||
try {
|
||||
const runtime = createCharacterDictionaryRuntimeService({
|
||||
userDataPath,
|
||||
getCurrentMediaPath: () =>
|
||||
'/anime/Oregairu/My Teen Romantic Comedy SNAFU (2013) - S03E01.mkv',
|
||||
getCurrentMediaTitle: () => null,
|
||||
resolveMediaPathForJimaku: (mediaPath) => mediaPath,
|
||||
guessAnilistMediaInfo: async () => ({
|
||||
title: 'My Teen Romantic Comedy SNAFU',
|
||||
year: 2013,
|
||||
season: 3,
|
||||
episode: 1,
|
||||
source: 'guessit',
|
||||
}),
|
||||
now: () => 1_700_000_000_000,
|
||||
sleep: async () => {},
|
||||
logWarn: (message) => warnings.push(message),
|
||||
});
|
||||
|
||||
await runtime.getOrCreateCurrentSnapshot();
|
||||
const searchesAfterFirst = searchCalls;
|
||||
await runtime.getOrCreateCurrentSnapshot();
|
||||
|
||||
// Re-resolved rather than served from the resolution cache, and warned both times.
|
||||
assert.ok(searchCalls > searchesAfterFirst);
|
||||
assert.equal(warnings.filter((m) => /could not find season 3/i.test(m)).length, 2);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -181,4 +181,7 @@ export type ResolvedAniListMedia = {
|
||||
id: number;
|
||||
title: string;
|
||||
staleMediaIds?: number[];
|
||||
/** False when a season >= 2 was requested but only the season 1 entry could be found. */
|
||||
seasonResolved?: boolean;
|
||||
requestedSeason?: number | null;
|
||||
};
|
||||
|
||||
@@ -24,7 +24,8 @@ export function createBuildProcessNextAnilistRetryUpdateMainDepsHandler(
|
||||
title: string,
|
||||
episode: number,
|
||||
season?: number | null,
|
||||
) => deps.updateAnilistPostWatchProgress(accessToken, title, episode, season),
|
||||
mediaId?: number | null,
|
||||
) => deps.updateAnilistPostWatchProgress(accessToken, title, episode, season, mediaId),
|
||||
markSuccess: (key: string) => deps.markSuccess(key),
|
||||
rememberAttemptedUpdateKey: (key: string) => deps.rememberAttemptedUpdateKey(key),
|
||||
markFailure: (key: string, message: string) => deps.markFailure(key, message),
|
||||
@@ -52,8 +53,19 @@ export function createBuildMaybeRunAnilistPostWatchUpdateMainDepsHandler(
|
||||
hasAttemptedUpdateKey: (key: string) => deps.hasAttemptedUpdateKey(key),
|
||||
processNextAnilistRetryUpdate: () => deps.processNextAnilistRetryUpdate(),
|
||||
refreshAnilistClientSecretState: () => deps.refreshAnilistClientSecretState(),
|
||||
enqueueRetry: (key: string, title: string, episode: number, season?: number | null) =>
|
||||
deps.enqueueRetry(key, title, episode, season),
|
||||
enqueueRetry: (
|
||||
key: string,
|
||||
title: string,
|
||||
episode: number,
|
||||
season?: number | null,
|
||||
mediaId?: number | null,
|
||||
) => deps.enqueueRetry(key, title, episode, season, mediaId),
|
||||
getCurrentMediaTitle: deps.getCurrentMediaTitle
|
||||
? () => deps.getCurrentMediaTitle!()
|
||||
: undefined,
|
||||
resolvePinnedAnilistMediaId: deps.resolvePinnedAnilistMediaId
|
||||
? (input) => deps.resolvePinnedAnilistMediaId!(input)
|
||||
: undefined,
|
||||
markRetryFailure: (key: string, message: string) => deps.markRetryFailure(key, message),
|
||||
markRetrySuccess: (key: string) => deps.markRetrySuccess(key),
|
||||
refreshRetryQueueState: () => deps.refreshRetryQueueState(),
|
||||
@@ -62,7 +74,8 @@ export function createBuildMaybeRunAnilistPostWatchUpdateMainDepsHandler(
|
||||
title: string,
|
||||
episode: number,
|
||||
season?: number | null,
|
||||
) => deps.updateAnilistPostWatchProgress(accessToken, title, episode, season),
|
||||
mediaId?: number | null,
|
||||
) => deps.updateAnilistPostWatchProgress(accessToken, title, episode, season, mediaId),
|
||||
rememberAttemptedUpdateKey: (key: string) => deps.rememberAttemptedUpdateKey(key),
|
||||
showMpvOsd: (message: string) => deps.showMpvOsd(message),
|
||||
logInfo: (message: string) => deps.logInfo(message),
|
||||
|
||||
@@ -380,3 +380,155 @@ test('createMaybeRunAnilistPostWatchUpdateHandler notifies when retry already ha
|
||||
assert.equal(calls.includes('mark-failure'), false);
|
||||
assert.deepEqual(calls, ['inflight:true', 'process-retry', 'osd:retry ok', 'inflight:false']);
|
||||
});
|
||||
|
||||
test('createMaybeRunAnilistPostWatchUpdateHandler passes the pinned override media id', async () => {
|
||||
const updateArgs: Array<number | null | undefined> = [];
|
||||
const pinInputs: Array<{ mediaPath: string | null; mediaTitle: string | null; guess: unknown }> =
|
||||
[];
|
||||
const handler = createMaybeRunAnilistPostWatchUpdateHandler({
|
||||
getInFlight: () => false,
|
||||
setInFlight: () => {},
|
||||
getResolvedConfig: () => ({}),
|
||||
isAnilistTrackingEnabled: () => true,
|
||||
getCurrentMediaKey: () => '/tmp/video.mkv',
|
||||
hasMpvClient: () => true,
|
||||
getTrackedMediaKey: () => '/tmp/video.mkv',
|
||||
resetTrackedMedia: () => {},
|
||||
getWatchedSeconds: () => 1000,
|
||||
maybeProbeAnilistDuration: async () => 1000,
|
||||
ensureAnilistMediaGuess: async () => ({ title: 'Show', season: 3, episode: 1 }),
|
||||
hasAttemptedUpdateKey: () => false,
|
||||
processNextAnilistRetryUpdate: async () => ({ ok: true, message: 'noop' }),
|
||||
refreshAnilistClientSecretState: async () => 'token',
|
||||
enqueueRetry: () => {},
|
||||
getCurrentMediaTitle: () => 'Show S03E01.mkv',
|
||||
resolvePinnedAnilistMediaId: async (input) => {
|
||||
pinInputs.push(input);
|
||||
return 108489;
|
||||
},
|
||||
markRetryFailure: () => {},
|
||||
markRetrySuccess: () => {},
|
||||
refreshRetryQueueState: () => {},
|
||||
updateAnilistPostWatchProgress: async (_accessToken, _title, _episode, _season, mediaId) => {
|
||||
updateArgs.push(mediaId);
|
||||
return { status: 'updated', message: 'ok' };
|
||||
},
|
||||
rememberAttemptedUpdateKey: () => {},
|
||||
showMpvOsd: () => {},
|
||||
logInfo: () => {},
|
||||
logWarn: () => {},
|
||||
minWatchSeconds: 600,
|
||||
minWatchRatio: 0.85,
|
||||
});
|
||||
|
||||
await handler();
|
||||
assert.deepEqual(updateArgs, [108489]);
|
||||
// Resolved against the media this run captured, not whatever is playing now.
|
||||
assert.equal(pinInputs.length, 1);
|
||||
assert.equal(pinInputs[0]!.mediaPath, '/tmp/video.mkv');
|
||||
assert.equal(pinInputs[0]!.mediaTitle, 'Show S03E01.mkv');
|
||||
assert.deepEqual(pinInputs[0]!.guess, { title: 'Show', season: 3, episode: 1 });
|
||||
});
|
||||
|
||||
test('createMaybeRunAnilistPostWatchUpdateHandler queues the pinned media id for retry', async () => {
|
||||
const enqueued: Array<number | null | undefined> = [];
|
||||
const handler = createMaybeRunAnilistPostWatchUpdateHandler({
|
||||
getInFlight: () => false,
|
||||
setInFlight: () => {},
|
||||
getResolvedConfig: () => ({}),
|
||||
isAnilistTrackingEnabled: () => true,
|
||||
getCurrentMediaKey: () => '/tmp/video.mkv',
|
||||
hasMpvClient: () => true,
|
||||
getTrackedMediaKey: () => '/tmp/video.mkv',
|
||||
resetTrackedMedia: () => {},
|
||||
getWatchedSeconds: () => 1000,
|
||||
maybeProbeAnilistDuration: async () => 1000,
|
||||
ensureAnilistMediaGuess: async () => ({ title: 'Show', season: 3, episode: 1 }),
|
||||
hasAttemptedUpdateKey: () => false,
|
||||
processNextAnilistRetryUpdate: async () => ({ ok: true, message: 'noop' }),
|
||||
refreshAnilistClientSecretState: async () => null,
|
||||
enqueueRetry: (_key, _title, _episode, _season, mediaId) => {
|
||||
enqueued.push(mediaId);
|
||||
},
|
||||
resolvePinnedAnilistMediaId: async () => 108489,
|
||||
markRetryFailure: () => {},
|
||||
markRetrySuccess: () => {},
|
||||
refreshRetryQueueState: () => {},
|
||||
updateAnilistPostWatchProgress: async () => ({ status: 'updated', message: 'ok' }),
|
||||
rememberAttemptedUpdateKey: () => {},
|
||||
showMpvOsd: () => {},
|
||||
logInfo: () => {},
|
||||
logWarn: () => {},
|
||||
minWatchSeconds: 600,
|
||||
minWatchRatio: 0.85,
|
||||
});
|
||||
|
||||
await handler();
|
||||
assert.deepEqual(enqueued, [108489]);
|
||||
});
|
||||
|
||||
test('createMaybeRunAnilistPostWatchUpdateHandler still updates when the override lookup throws', async () => {
|
||||
const updateArgs: Array<number | null | undefined> = [];
|
||||
const warnings: string[] = [];
|
||||
const handler = createMaybeRunAnilistPostWatchUpdateHandler({
|
||||
getInFlight: () => false,
|
||||
setInFlight: () => {},
|
||||
getResolvedConfig: () => ({}),
|
||||
isAnilistTrackingEnabled: () => true,
|
||||
getCurrentMediaKey: () => '/tmp/video.mkv',
|
||||
hasMpvClient: () => true,
|
||||
getTrackedMediaKey: () => '/tmp/video.mkv',
|
||||
resetTrackedMedia: () => {},
|
||||
getWatchedSeconds: () => 1000,
|
||||
maybeProbeAnilistDuration: async () => 1000,
|
||||
ensureAnilistMediaGuess: async () => ({ title: 'Show', season: 3, episode: 1 }),
|
||||
hasAttemptedUpdateKey: () => false,
|
||||
processNextAnilistRetryUpdate: async () => ({ ok: true, message: 'noop' }),
|
||||
refreshAnilistClientSecretState: async () => 'token',
|
||||
enqueueRetry: () => {},
|
||||
resolvePinnedAnilistMediaId: async () => {
|
||||
throw new Error('store unreadable');
|
||||
},
|
||||
markRetryFailure: () => {},
|
||||
markRetrySuccess: () => {},
|
||||
refreshRetryQueueState: () => {},
|
||||
updateAnilistPostWatchProgress: async (_accessToken, _title, _episode, _season, mediaId) => {
|
||||
updateArgs.push(mediaId);
|
||||
return { status: 'updated', message: 'ok' };
|
||||
},
|
||||
rememberAttemptedUpdateKey: () => {},
|
||||
showMpvOsd: () => {},
|
||||
logInfo: () => {},
|
||||
logWarn: (message) => warnings.push(message),
|
||||
minWatchSeconds: 600,
|
||||
minWatchRatio: 0.85,
|
||||
});
|
||||
|
||||
await handler();
|
||||
assert.deepEqual(updateArgs, [null]);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0]!, /override lookup failed/i);
|
||||
});
|
||||
|
||||
test('createProcessNextAnilistRetryUpdateHandler forwards the queued media id', async () => {
|
||||
const received: Array<number | null | undefined> = [];
|
||||
const handler = createProcessNextAnilistRetryUpdateHandler({
|
||||
nextReady: () => ({ key: 'k1', title: 'Show', season: 3, mediaId: 108489, episode: 1 }),
|
||||
refreshRetryQueueState: () => {},
|
||||
setLastAttemptAt: () => {},
|
||||
setLastError: () => {},
|
||||
refreshAnilistClientSecretState: async () => 'token',
|
||||
updateAnilistPostWatchProgress: async (_accessToken, _title, _episode, _season, mediaId) => {
|
||||
received.push(mediaId);
|
||||
return { status: 'updated', message: 'ok' };
|
||||
},
|
||||
markSuccess: () => {},
|
||||
rememberAttemptedUpdateKey: () => {},
|
||||
markFailure: () => {},
|
||||
logInfo: () => {},
|
||||
now: () => 1,
|
||||
});
|
||||
|
||||
await handler();
|
||||
assert.deepEqual(received, [108489]);
|
||||
});
|
||||
|
||||
@@ -4,6 +4,8 @@ type AnilistGuess = {
|
||||
title: string;
|
||||
season: number | null;
|
||||
episode: number | null;
|
||||
alternativeTitle?: string;
|
||||
year?: number;
|
||||
};
|
||||
|
||||
type AnilistUpdateResult = {
|
||||
@@ -16,6 +18,7 @@ type RetryQueueItem = {
|
||||
key: string;
|
||||
title: string;
|
||||
season?: number | null;
|
||||
mediaId?: number | null;
|
||||
episode: number;
|
||||
};
|
||||
|
||||
@@ -58,6 +61,7 @@ export function createProcessNextAnilistRetryUpdateHandler(deps: {
|
||||
title: string,
|
||||
episode: number,
|
||||
season?: number | null,
|
||||
mediaId?: number | null,
|
||||
) => Promise<AnilistUpdateResult>;
|
||||
markSuccess: (key: string) => void;
|
||||
rememberAttemptedUpdateKey: (key: string) => void;
|
||||
@@ -84,6 +88,7 @@ export function createProcessNextAnilistRetryUpdateHandler(deps: {
|
||||
queued.title,
|
||||
queued.episode,
|
||||
queued.season ?? null,
|
||||
queued.mediaId ?? null,
|
||||
);
|
||||
if (result.status === 'updated' || result.status === 'skipped') {
|
||||
deps.markSuccess(queued.key);
|
||||
@@ -119,7 +124,23 @@ export function createMaybeRunAnilistPostWatchUpdateHandler(deps: {
|
||||
hasAttemptedUpdateKey: (key: string) => boolean;
|
||||
processNextAnilistRetryUpdate: () => Promise<{ ok: boolean; message: string }>;
|
||||
refreshAnilistClientSecretState: () => Promise<string | null>;
|
||||
enqueueRetry: (key: string, title: string, episode: number, season?: number | null) => void;
|
||||
enqueueRetry: (
|
||||
key: string,
|
||||
title: string,
|
||||
episode: number,
|
||||
season?: number | null,
|
||||
mediaId?: number | null,
|
||||
) => void;
|
||||
getCurrentMediaTitle?: () => string | null;
|
||||
/**
|
||||
* Pinned AniList media id from a manual dictionary override. Takes the media captured
|
||||
* by this run, so a mid-run file change cannot pin the update to a different show.
|
||||
*/
|
||||
resolvePinnedAnilistMediaId?: (input: {
|
||||
mediaPath: string | null;
|
||||
mediaTitle: string | null;
|
||||
guess: AnilistGuess;
|
||||
}) => Promise<number | null>;
|
||||
markRetryFailure: (key: string, message: string) => void;
|
||||
markRetrySuccess: (key: string) => void;
|
||||
refreshRetryQueueState: () => void;
|
||||
@@ -128,6 +149,7 @@ export function createMaybeRunAnilistPostWatchUpdateHandler(deps: {
|
||||
title: string,
|
||||
episode: number,
|
||||
season?: number | null,
|
||||
mediaId?: number | null,
|
||||
) => Promise<AnilistUpdateResult>;
|
||||
rememberAttemptedUpdateKey: (key: string) => void;
|
||||
showMpvOsd: (message: string) => void;
|
||||
@@ -157,6 +179,8 @@ export function createMaybeRunAnilistPostWatchUpdateHandler(deps: {
|
||||
if (deps.getTrackedMediaKey() !== mediaKey) {
|
||||
deps.resetTrackedMedia(mediaKey);
|
||||
}
|
||||
// Captured before any await: playback can advance while the update is in flight.
|
||||
const mediaTitle = deps.getCurrentMediaTitle?.() ?? null;
|
||||
|
||||
let watchedSeconds = 0;
|
||||
if (!force) {
|
||||
@@ -202,9 +226,23 @@ export function createMaybeRunAnilistPostWatchUpdateHandler(deps: {
|
||||
return;
|
||||
}
|
||||
|
||||
// A manual dictionary override is the user's explicit answer to "which AniList
|
||||
// entry is this?", so it wins over anything the title search would resolve.
|
||||
let pinnedMediaId: number | null = null;
|
||||
try {
|
||||
pinnedMediaId =
|
||||
(await deps.resolvePinnedAnilistMediaId?.({
|
||||
mediaPath: mediaKey,
|
||||
mediaTitle,
|
||||
guess,
|
||||
})) ?? null;
|
||||
} catch (error) {
|
||||
deps.logWarn(`AniList override lookup failed: ${String(error)}`);
|
||||
}
|
||||
|
||||
const accessToken = await deps.refreshAnilistClientSecretState();
|
||||
if (!accessToken) {
|
||||
deps.enqueueRetry(attemptKey, guess.title, guess.episode, guess.season);
|
||||
deps.enqueueRetry(attemptKey, guess.title, guess.episode, guess.season, pinnedMediaId);
|
||||
deps.markRetryFailure(attemptKey, 'cannot authenticate without anilist.accessToken');
|
||||
deps.refreshRetryQueueState();
|
||||
deps.showMpvOsd('AniList: access token not configured');
|
||||
@@ -216,6 +254,7 @@ export function createMaybeRunAnilistPostWatchUpdateHandler(deps: {
|
||||
guess.title,
|
||||
guess.episode,
|
||||
guess.season,
|
||||
pinnedMediaId,
|
||||
);
|
||||
if (result.status === 'updated') {
|
||||
deps.rememberAttemptedUpdateKey(attemptKey);
|
||||
@@ -241,7 +280,7 @@ export function createMaybeRunAnilistPostWatchUpdateHandler(deps: {
|
||||
return;
|
||||
}
|
||||
|
||||
deps.enqueueRetry(attemptKey, guess.title, guess.episode, guess.season);
|
||||
deps.enqueueRetry(attemptKey, guess.title, guess.episode, guess.season, pinnedMediaId);
|
||||
deps.markRetryFailure(attemptKey, result.message);
|
||||
deps.refreshRetryQueueState();
|
||||
deps.showMpvOsd(`AniList: ${result.message}`);
|
||||
|
||||
Reference in New Issue
Block a user