mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-23 04:46:08 -08:00
Compare commits
31
Commits
848a6c4021
...
v0.22.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e05fb34f7b
|
||
|
|
93045ebf9f
|
||
|
|
18490c9d4f
|
||
|
|
78809094d2 | ||
|
|
71251b8d7b | ||
|
|
9d2057cc30 | ||
|
|
ac3ceab856 | ||
|
|
ee52664655 | ||
|
|
0ae70b4ab2 | ||
|
|
0c1865f4a6
|
||
|
|
6fd55053d4 | ||
|
|
0360270e81
|
||
|
|
a8e929eb26
|
||
|
|
b31ddce627 | ||
|
|
79e5535823
|
||
|
|
5140b5e9be
|
||
|
|
c2dac537da
|
||
|
|
bc7e82fee6
|
||
|
|
c3e672efdb
|
||
|
|
269c0708cb | ||
|
|
f89f78b861 | ||
|
|
14ef7e823c | ||
|
|
a8bc585f75
|
||
|
|
5f635f3042
|
||
|
|
7c637149dd | ||
|
|
33f5f890d5 | ||
|
|
d8c2315405 | ||
|
|
8976d78390
|
||
|
|
1c50d249e0 | ||
|
|
8e29cb3c55 | ||
|
|
fa3051f9cb |
No files matched your search
@@ -32,6 +32,9 @@ jobs:
|
|||||||
- name: Verify native mpv process launch
|
- name: Verify native mpv process launch
|
||||||
run: bun test src/main/runtime/mpv-process.test.ts
|
run: bun test src/main/runtime/mpv-process.test.ts
|
||||||
|
|
||||||
|
- name: Verify mpv PID lookup and Windows tracker
|
||||||
|
run: bun test src/window-trackers/mpv-process-id.test.ts src/window-trackers/windows-tracker.test.ts
|
||||||
|
|
||||||
- name: Verify POSIX launcher bootstrap
|
- name: Verify POSIX launcher bootstrap
|
||||||
run: bun test src/main/runtime/posix-launcher-bootstrap.test.ts
|
run: bun test src/main/runtime/posix-launcher-bootstrap.test.ts
|
||||||
|
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ Start here, then leave this file.
|
|||||||
- Build/release scripts (`scripts/**`): `bun run test:scripts`
|
- Build/release scripts (`scripts/**`): `bun run test:scripts`
|
||||||
- Internal docs, `AGENTS.md`, or repo skills: `bun run test:docs:kb`
|
- Internal docs, `AGENTS.md`, or repo skills: `bun run test:docs:kb`
|
||||||
- User-facing `docs-site/`: `bun run docs:test`, then `bun run docs:build`
|
- User-facing `docs-site/`: `bun run docs:test`, then `bun run docs:build`
|
||||||
- macOS mpv window helper (`scripts/get-mpv-window-macos.swift`): compile it on macOS with `bun run build`
|
- macOS Swift helpers (`scripts/get-mpv-window-macos.swift`, `scripts/macos-controller-watch.swift`): compile them on macOS with `bun run build`
|
||||||
- Test lanes are directory-discovered via `scripts/test-lanes.ts`; never hand-list test files in `package.json`
|
- Test lanes are directory-discovered via `scripts/test-lanes.ts`; never hand-list test files in `package.json`
|
||||||
|
|
||||||
## Docs Upkeep
|
## Docs Upkeep
|
||||||
|
|||||||
@@ -1,5 +1,78 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v0.22.1 (2026-11-23)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **AniSkip Outro Skipping**:
|
||||||
|
- The AniSkip key now skips endings too, with its own prompt and chapter markers.
|
||||||
|
- Intros and outros are found from the file's own chapters first, so skipping also works for Jellyfin and other streams.
|
||||||
|
- Skip times now match your TV or Blu-ray cut.
|
||||||
|
- **Library Franchise Cards**: The stats library shows each anime once. Seasons, movies, and OVAs that AniList links together share one card, and opening the card lists each part with its own stats. To fix the grouping, use **Move to Another Anime…**, **Show On Its Own**, or **Put Back Where AniList Has It** on a title's page.
|
||||||
|
- **FFmpeg Download in Setup**: First-run setup shows whether FFmpeg and FFprobe can be used. If they're missing, **Download FFmpeg** installs a copy that SubMiner and the `subminer` command can use.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **AniList Season Matching**:
|
||||||
|
- Later seasons now find the right AniList entry, even when a series has split-season halves, specials, or movies.
|
||||||
|
- Episodes in the second half of a split season update the right entry at the right episode number.
|
||||||
|
- Character dictionary matches saved by older versions are checked again once.
|
||||||
|
- **AniSkip Lookups**: Rate limits, server errors, and network failures no longer count as "no intro" until restart. SubMiner tries again the next time the episode loads.
|
||||||
|
- **Jimaku Series Name**: The Jimaku modal fills in the series name, season, and episode again for Jellyfin episodes with a "/" in their name.
|
||||||
|
- **mpv Keys in the Overlay**: Keys bound in `input.conf` are no longer sent to a Yomitan popup that has already closed. They also no longer get lost when the overlay regains focus.
|
||||||
|
- **Windows Overlay**: The overlay now finds the mpv window more reliably, and you can set the IPC socket in `mpv.conf`. It no longer stays attached to an unrelated window, and stalled overlays are now explained in the normal log.
|
||||||
|
|
||||||
|
### Docs
|
||||||
|
- **Windows Overlay Troubleshooting**: New guide to collecting and reading Windows overlay warnings without turning on debug logging.
|
||||||
|
|
||||||
|
## v0.22.0 (2026-11-06)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Plugins**:
|
||||||
|
- JavaScript plugins load at startup from `<config dir>/plugins/<id>/` and are enabled under `plugins` in the config.
|
||||||
|
- Plugins can react to playback and mined cards, add bindable actions, run programs, and show results in overlay panels or their own windows.
|
||||||
|
- Example plugins cover AI line explanations (`ai-explain`), AnkiWeb sync (`anki-sync`), and show and episode tags on mined cards (`episode-tags`).
|
||||||
|
- Plugin authors get a versioned API with standalone types.
|
||||||
|
- **Subtitle Filters**: Remove text in parentheses, sound descriptions, speaker names, music notes, or custom regex matches from primary subtitles. Configure them in Settings under Behavior → Subtitle Filters.
|
||||||
|
- **Controller Combos**: Controller actions can now be combos, such as holding `L1` and pressing D-pad right. Click **Learn** in `Alt+C`, then hold one button and press another.
|
||||||
|
- **Controller Actions**: New bindings cover previous, next, replay, and play-next subtitle, hold-to-show secondary subtitle, and previous or next Yomitan entry. All are unbound by default and can be assigned in `Alt+C`.
|
||||||
|
- **Controller Dialog Layouts**: The media timing review and duplicate card dialogs can now be used with a controller and show button hints while one is connected. Remap both layouts per controller in `Alt+C`.
|
||||||
|
- **Controller Button Style**: Choose Xbox, Nintendo, or PlayStation button names per controller in `Alt+C`, or set a default with `controller.faceButtonLabels`.
|
||||||
|
- **Controller Clash Warnings**: `Alt+C` now warns when two actions share the same input.
|
||||||
|
- **Keyboard-Only Mode**:
|
||||||
|
- Press `C` or use the new controller binding to move by character, reaching words split by the subtitle parser.
|
||||||
|
- The new **Pause Video In Keyboard-Only Mode** setting pauses on entry and resumes on exit.
|
||||||
|
- **Jimaku Auto-Open**: Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to pause and open Jimaku when a local video has no Japanese subtitle track. Reopening Jimaku after the video changes now refreshes the title and episode.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Stats Trends and Vocabulary**:
|
||||||
|
- Trends adds a learning section, heatmap, title timeline, custom date ranges, and a page-wide title filter.
|
||||||
|
- Vocabulary now has one searchable word table, known words by frequency band, a growth chart, and a full kanji view.
|
||||||
|
- New word counts now count dictionary words, so a word's conjugations count once and totals are lower than before.
|
||||||
|
- Stats now explains when streamed words or lines can't be mined.
|
||||||
|
- **Bundled Hachidori**: Updated to upstream 0.4.0, adding every pitch accent in popup entries, per-kanji headword furigana, and Yomitan-style definition tags.
|
||||||
|
- **Controller Behavior**: **Toggle MPV Pause** now works outside keyboard-only mode. Connected and disabled messages now follow your `ankiConnect.behavior.notificationType` setting.
|
||||||
|
- **Dictionary Popup**: Turning keyboard-only mode off now also closes the popup.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Controller Settings (`Alt+C`)**:
|
||||||
|
- Remaps now apply right away, and Learn works on **(D-pad)** rows.
|
||||||
|
- Clicking a row shows **Learn**, **Clear**, and **Reset** again.
|
||||||
|
- The window previews your bindings until a press, then selects the pressed controller.
|
||||||
|
- Button names are now correct on standard-layout controllers.
|
||||||
|
- **Controller Input on macOS and Windows**: One press no longer runs its action twice. On macOS, buttons now work while mpv is in front.
|
||||||
|
- **Dictionary Popup**: Keyboard and controller lookups now pause and resume playback reliably. Moving between words right after closing a popup no longer reopens it.
|
||||||
|
- **Playback**: Reloading the current file no longer leaves playback paused. The "Overlay loading" message no longer sticks or turns into a false error when a playlist advances.
|
||||||
|
- **Stats**:
|
||||||
|
- The dashboard, Vocabulary tab, and sentence search load much faster on large databases, and Trends downloads far less data.
|
||||||
|
- Trends now counts each finished episode once, and its Library totals match the selected range.
|
||||||
|
- Word totals, readings, Hide Names, and rate charts are now accurate.
|
||||||
|
- Date handling is now correct in time zones ahead of UTC.
|
||||||
|
- **AniList**: Progress sync now adds a missing show to Watching, or Completed on the final episode, when the title matches exactly or is pinned. Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
|
||||||
|
- **Anki Sentence Audio**: Generated sentence audio no longer overwrites Yomitan's word audio on default configs. If you relied on the old default, set `ankiConnect.fields.audio` to `ExpressionAudio`.
|
||||||
|
- **AppImage**: Fixed "Service Crash" notifications on quit on Ubuntu 26.04 and newer.
|
||||||
|
|
||||||
|
### Docs
|
||||||
|
- **Keyboard and Controller Reference**: Keyboard shortcuts now list the keyboard-only `C` key, and the configuration reference points to Controller support for default button actions.
|
||||||
|
|
||||||
## v0.21.1 (2026-10-26)
|
## v0.21.1 (2026-10-26)
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ A stats dashboard tracks watch time, vocabulary growth, mining throughput, sessi
|
|||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td><b>Plugins</b></td>
|
<td><b>Plugins</b></td>
|
||||||
<td>Load your own JavaScript at startup to react to playback, run timers, add key-bound actions, and show results in an overlay panel. The bundled example explains the current line with Codex. <a href="https://docs.subminer.moe/plugins">Plugin guide</a></td>
|
<td>Load your own JavaScript at startup to react to playback, run timers, add key-bound actions, and show results in an overlay panel. Bundled examples explain the current line with Codex, sync Anki to AnkiWeb, and tag mined cards by episode. <a href="https://docs.subminer.moe/plugins">Plugin guide</a></td>
|
||||||
</tr>
|
</tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
@@ -121,7 +121,7 @@ SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to
|
|||||||
| mpv | Required | The video player SubMiner draws over |
|
| mpv | Required | The video player SubMiner draws over |
|
||||||
| fuse2 | Required (Linux) | Running the AppImage |
|
| fuse2 | Required (Linux) | Running the AppImage |
|
||||||
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
|
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
|
||||||
| ffmpeg | Recommended | Audio clips and screenshots on cards |
|
| ffmpeg | Recommended | Card audio and screenshots (first-run setup can download it) |
|
||||||
| MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting |
|
| MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting |
|
||||||
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
|
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
|
||||||
| yt-dlp | Optional | YouTube playback |
|
| yt-dlp | Optional | YouTube playback |
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
// Opens the Jimaku subtitle search when a file starts without a Japanese subtitle track.
|
|
||||||
// It waits a few seconds after the file loads so external subtitles mpv or SubMiner add count.
|
|
||||||
|
|
||||||
const DEFAULT_SETTINGS = {
|
|
||||||
// Built-in action to run, e.g. `openTsukihime` or `openSubtitleSelection`.
|
|
||||||
action: 'openJimaku',
|
|
||||||
// Track `lang` codes that count as Japanese. Track titles with "Japanese" or 日本語 count too.
|
|
||||||
languages: ['ja', 'jp', 'jpn'],
|
|
||||||
delayMs: 3_000,
|
|
||||||
// Also check http(s) streams; Jimaku can only search by name, which streams rarely have.
|
|
||||||
streams: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
const JAPANESE_TITLE = /japanese|日本語/i;
|
|
||||||
|
|
||||||
function activate(ctx) {
|
|
||||||
const settings = { ...DEFAULT_SETTINGS, ...ctx.settings };
|
|
||||||
const languages = new Set(settings.languages.map((lang) => lang.toLowerCase()));
|
|
||||||
let cancelCheck = null;
|
|
||||||
let playbackId = null;
|
|
||||||
|
|
||||||
function hasJapaneseSubtitle(trackList) {
|
|
||||||
return trackList.some(
|
|
||||||
(track) =>
|
|
||||||
track?.type === 'sub' &&
|
|
||||||
(languages.has(String(track.lang ?? '').toLowerCase()) ||
|
|
||||||
JAPANESE_TITLE.test(String(track.title ?? ''))),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function check(media) {
|
|
||||||
cancelCheck = null;
|
|
||||||
const trackList = await ctx.mpv.getProperty('track-list');
|
|
||||||
if (ctx.media.current()?.playbackId !== media.playbackId || !Array.isArray(trackList)) return;
|
|
||||||
if (hasJapaneseSubtitle(trackList)) return;
|
|
||||||
ctx.log.info(`No Japanese subtitles for ${media.path}; running ${settings.action}.`);
|
|
||||||
await ctx.actions.run(settings.action);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.media.on('change', (media) => {
|
|
||||||
if (media?.playbackId === playbackId) return;
|
|
||||||
playbackId = media?.playbackId ?? null;
|
|
||||||
cancelCheck?.();
|
|
||||||
cancelCheck = null;
|
|
||||||
if (!media) return;
|
|
||||||
if (!settings.streams && /^[a-z]+:\/\//i.test(media.path)) return;
|
|
||||||
cancelCheck = ctx.after(settings.delayMs, () => check(media));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { activate };
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "Auto Jimaku",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"apiVersion": 1,
|
|
||||||
"main": "main.js"
|
|
||||||
}
|
|
||||||
@@ -28,9 +28,6 @@
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"patchedDependencies": {
|
|
||||||
"@discordjs/rest@2.6.1": "patches/@discordjs%2Frest@2.6.1.patch",
|
|
||||||
},
|
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"@xmldom/xmldom": "0.8.15",
|
"@xmldom/xmldom": "0.8.15",
|
||||||
"app-builder-lib": "26.16.1",
|
"app-builder-lib": "26.16.1",
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- The controller settings window (`Alt+C`) no longer edits a controller it cannot see. A newly opened window cannot see any controller until you press one of its buttons (browsers hide a pad from a new window until then); it used to show and edit the global defaults meanwhile, and its status could stay stuck on "No controllers detected". Now it shows the bindings of the controller the overlay is using (or the saved one), labelled as a preview, and Learn, Clear, Reset and the button style are locked until the press.
|
|
||||||
- With several controllers connected, `Alt+C` now selects the one you just pressed, and Learn listens to that controller.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: anilist
|
|
||||||
|
|
||||||
- AniList progress sync now adds a show to your Watching list (or Completed on the final episode) when it is not on your list yet, instead of failing with "AniList update not possible". This only happens when the file title exactly matches an AniList title or the entry is pinned with the character dictionary override; loose matches still require adding the show yourself.
|
|
||||||
- Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: anki
|
|
||||||
|
|
||||||
- `ankiConnect.fields.audio` now defaults to `SentenceAudio` instead of `ExpressionAudio`, so generated sentence audio no longer overwrites Yomitan's word audio on default configs. `fields.wordAudio` still defaults to `ExpressionAudio`. If you relied on the old default, set `fields.audio` to `ExpressionAudio` explicitly.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: linux
|
|
||||||
|
|
||||||
- Fixed AppImage builds on Ubuntu 26.04+ (uutils coreutils) releasing their mount before Chromium child processes finished shutting down, which brought back "Service Crash" notifications on quit.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- Controller remaps made in `Alt+C` now apply right away; before, the overlay kept the old bindings until SubMiner restarted.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- `Alt+C` now warns when two controller actions share an input, as the dialog layouts already did. Both rows show "⚠ Same as …", including a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- `Alt+C` has a **Button Style** choice (Xbox, Nintendo or PlayStation), saved per controller. PlayStation is new: buttons and the review and duplicate card shortcuts show ╳ ○ □ △. `controller.faceButtonLabels` accepts `playstation` and stays the default for controllers without their own style.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- Clicking a row in `Alt+C` shows its **Learn**, **Clear** and **Reset** buttons again. The panel opened but was squeezed to nothing once the list was taller than the window, so **Clear** (set a binding to None) could not be reached.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- The duplicate card (field grouping) dialog has a controller layout: the D-pad picks the original or new card, `A` continues and confirms the merge, `B` cancels or goes back from the preview, `X` turns "Delete duplicate" on or off, `Y` switches Compact / Full, and the D-pad scrolls the preview. Each control shows its shortcut, and the layout can be changed per controller in the new **Duplicate card (field grouping)** group of `Alt+C`.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- Added a controller layout for the media timing review dialog covering every button, with L1 / R1 + D-pad combos for the clip start and end, and D-pad actions that repeat while held. Each button shows its controller shortcut while controller support is on, and the first press in a newly opened dialog already counts. The controller's usual actions pause while the dialog is open, including in the hidden subtitle overlay behind it.
|
|
||||||
- Added `controller.faceButtonLabels` (`xbox` or `nintendo`) so fixed controller layouts and the `Alt+C` button names follow the letters printed on the pad. Use `nintendo` for controllers with A on the right and B at the bottom.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: changed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- The controller's **Toggle MPV Pause** button now works without keyboard-only mode, so you can pause while just watching.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- The media timing review controller layout can now be changed in the new **Review media timing** group of `Alt+C`. Learn records a single button or a combo (hold one button, press another), any button can be a hold button, changes are saved per controller, rows warn about clashing inputs, and **Reset all** restores the default layout. The review's button hints follow your bindings.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- Added a controller binding that shows the secondary subtitle only while a button is held (`controller.bindings.holdSecondarySub`). It is unbound by default; assign it with Learn in the `Alt+C` controller modal. It works with or without keyboard-only mode and does not change the saved secondary subtitle mode.
|
|
||||||
- Added controller bindings to select the previous or next word entry in the open Yomitan popup (`controller.bindings.previousEntry` / `nextEntry`). Mine Card mines the selected entry. Both are unbound by default; assign them with Learn in the `Alt+C` controller modal.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- The `Alt+C` controller screen now shows the right button names for controllers that report the W3C standard layout (most Xbox, PlayStation, Switch and 8BitDo pads). Previously Select and Start showed as `L3` and `R3`, and the triggers as `Back` and `Start`. Bindings themselves were unaffected.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- New controller actions for subtitle lines, in the **Subtitles** group of `Alt+C`: **Previous Subtitle**, **Next Subtitle**, **Replay Subtitle** and **Play Next Subtitle**, matching `Shift+H`, `Shift+L`, `Ctrl+Shift+H` and `Ctrl+Shift+L`. They are unbound by default and work with or without keyboard-only mode.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- New **Pause Video In Keyboard-Only Mode** setting (`subtitleStyle.autoPauseVideoOnKeyboardMode`, off by default): turning keyboard-only mode on, from the keyboard or a controller, pauses the video, and turning it off resumes it. A video that was already paused, or that you played or paused yourself in the meantime, is left as it is.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: changed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- Turning keyboard-only mode off, from the keyboard or a controller, now also closes the dictionary popup.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: mpv-plugin
|
|
||||||
|
|
||||||
- Fixed the "Overlay loading" message staying on screen when mpv moves to the next file in a playlist, then turning into "Overlay did not become ready; check SubMiner logs" after 30 seconds even though the overlay was working. The overlay window is reused between files, so the plugin no longer restarts the loading message once the overlay has reported ready.
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
type: added
|
|
||||||
area: plugins
|
|
||||||
|
|
||||||
- Added JavaScript plugins loaded at startup from `<config dir>/plugins/<id>/` and enabled under `plugins` in the config. Plugins can listen to mpv events, run timers, register actions bound with `__plugin-action:<id>/<action>` keybindings or run with `--plugin-action`, run built-in actions, react to mined Anki cards and call AnkiConnect, start mpv, run programs, keep state in a per-plugin data folder, and show results in an overlay panel or their own window.
|
|
||||||
- Added an example `ai-explain` plugin that sends the current line and its neighbors to `codex exec` and shows a translation or grammar explanation.
|
|
||||||
- Added an example `anki-sync` plugin that syncs Anki to AnkiWeb after you mine cards, once mining goes quiet or playback ends.
|
|
||||||
- Added an example `episode-tags` plugin that tags mined cards with the show and episode, such as `show::Frieren::S01E07`.
|
|
||||||
- Added an example `auto-jimaku` plugin that opens the Jimaku search when a file starts without a Japanese subtitle track.
|
|
||||||
- Added a versioned plugin API with standalone authoring types, cached playback snapshots, lifecycle cancellation and cleanup, and awaitable mpv commands. Async activation is bounded and actions wait only for their own plugin. Shutdown skips pending loads, runs each deactivation once, and blocks calls from disposed plugins.
|
|
||||||
- Mining events preserve original and kept note ids with the media and subtitle captured when mining starts, so delayed enrichment and merges into older notes keep the source episode. Stats-dashboard cards do not trigger plugin events. Plugin subtitle lookups and mining provenance account for subtitle delay and return timing on the subtitle file's timeline.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- Moving between words with the keyboard or a controller right after closing the dictionary popup no longer reopens it. A popup that closed under the mouse pointer was still treated as open.
|
|
||||||
+39
-24
@@ -128,59 +128,62 @@
|
|||||||
"toggleLookup": {
|
"toggleLookup": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 0 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 0 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"closeLookup": {
|
"closeLookup": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 1 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 1 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"toggleKeyboardOnlyMode": {
|
"toggleKeyboardOnlyMode": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 3 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 3 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"mineCard": {
|
"mineCard": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 2 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 2 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"quitMpv": {
|
"quitMpv": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 6 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 6 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"previousAudio": {
|
"previousAudio": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"nextAudio": {
|
"nextAudio": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 5 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 5 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"playCurrentAudio": {
|
"playCurrentAudio": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 4 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 4 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"toggleMpvPause": {
|
"toggleMpvPause": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 9 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 9 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"holdSecondarySub": {
|
"holdSecondarySub": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"previousEntry": {
|
"previousEntry": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"nextEntry": {
|
"nextEntry": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
|
"toggleCharacterNavigation": {
|
||||||
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
|
}, // Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"previousSubtitle": {
|
"previousSubtitle": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"nextSubtitle": {
|
"nextSubtitle": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"replaySubtitle": {
|
"replaySubtitle": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"playNextSubtitle": {
|
"playNextSubtitle": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"leftStickHorizontal": {
|
"leftStickHorizontal": {
|
||||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||||
"axisIndex": 0, // Raw axis index captured for this analog controller action.
|
"axisIndex": 0, // Raw axis index captured for this analog controller action.
|
||||||
@@ -191,11 +194,6 @@
|
|||||||
"axisIndex": 1, // Raw axis index captured for this analog controller action.
|
"axisIndex": 1, // Raw axis index captured for this analog controller action.
|
||||||
"dpadFallback": "vertical" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
"dpadFallback": "vertical" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
||||||
}, // Axis binding descriptor used for primary popup scrolling. Use Alt+C learn mode or set a raw axis descriptor manually.
|
}, // Axis binding descriptor used for primary popup scrolling. Use Alt+C learn mode or set a raw axis descriptor manually.
|
||||||
"rightStickHorizontal": {
|
|
||||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
|
||||||
"axisIndex": 3, // Raw axis index captured for this analog controller action.
|
|
||||||
"dpadFallback": "none" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
|
||||||
}, // Axis binding descriptor reserved for alternate right-stick mappings. Use Alt+C learn mode or set a raw axis descriptor manually.
|
|
||||||
"rightStickVertical": {
|
"rightStickVertical": {
|
||||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||||
"axisIndex": 4, // Raw axis index captured for this analog controller action.
|
"axisIndex": 4, // Raw axis index captured for this analog controller action.
|
||||||
@@ -854,6 +852,22 @@
|
|||||||
} // CSS declaration object applied to the subtitle sidebar. Includes color, background-color, and all font properties.
|
} // CSS declaration object applied to the subtitle sidebar. Includes color, background-color, and all font properties.
|
||||||
}, // Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
|
}, // Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Subtitle Filters
|
||||||
|
// Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.
|
||||||
|
// Applies to the overlay, sidebar, mined sentences and stats.
|
||||||
|
// Hot-reload: filter changes apply to the current subtitle file immediately.
|
||||||
|
// ==========================================
|
||||||
|
"subtitleFilter": {
|
||||||
|
"presets": {
|
||||||
|
"parentheses": false, // Remove text in () and (), such as speaker names, readings and notes. A line wrapped entirely in parentheses, usually inner thoughts, is kept. Values: true | false
|
||||||
|
"brackets": false, // Remove text in [], [], 【】 and 〔〕, such as sound effects and music cues. Values: true | false
|
||||||
|
"speakerPrefix": false, // Remove a short name followed by a colon at the start of a line, as in 山田:元気? Values: true | false
|
||||||
|
"musicSymbols": false // Remove ♪, ♫ and ♬. A line left with only symbols such as ~ is removed. Values: true | false
|
||||||
|
}, // Built-in filters. Each removes its matches and is off by default.
|
||||||
|
"customRules": [] // Your own regex rules, applied in order after the presets. Each rule is { name, pattern, replacement, enabled }; patterns use the gmu flags, so ^ and $ match per line. Leave replacement empty to remove the match.
|
||||||
|
}, // Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// Shared AI Provider
|
// Shared AI Provider
|
||||||
// Canonical OpenAI-compatible provider transport settings shared by Anki and YouTube subtitle fixing.
|
// Canonical OpenAI-compatible provider transport settings shared by Anki and YouTube subtitle fixing.
|
||||||
@@ -976,7 +990,8 @@
|
|||||||
"apiKey": "", // Jimaku API key. Optional but recommended for higher rate limits. Get one for free at https://jimaku.cc.
|
"apiKey": "", // Jimaku API key. Optional but recommended for higher rate limits. Get one for free at https://jimaku.cc.
|
||||||
"apiKeyCommand": "", // Shell command that prints the Jimaku API key to stdout. Used instead of apiKey to avoid storing the key in plain text.
|
"apiKeyCommand": "", // Shell command that prints the Jimaku API key to stdout. Used instead of apiKey to avoid storing the key in plain text.
|
||||||
"languagePreference": "ja", // Preferred language used in Jimaku search. Values: ja | en | none
|
"languagePreference": "ja", // Preferred language used in Jimaku search. Values: ja | en | none
|
||||||
"maxEntryResults": 10 // Maximum Jimaku search results returned.
|
"maxEntryResults": 10, // Maximum Jimaku search results returned.
|
||||||
|
"autoOpenWhenPrimarySubtitleMissing": false // Pause playback and open the Jimaku modal when a local video has no subtitle track in youtube.primarySubLanguages (Japanese by default). Values: true | false
|
||||||
}, // Jimaku API configuration and defaults.
|
}, // Jimaku API configuration and defaults.
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -1065,8 +1080,8 @@
|
|||||||
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
|
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
|
||||||
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
|
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
|
||||||
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
|
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
|
||||||
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
|
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
|
||||||
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
|
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
|
||||||
}, // SubMiner-managed mpv launch and bundled plugin options.
|
}, // SubMiner-managed mpv launch and bundled plugin options.
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|||||||
@@ -26,8 +26,8 @@ On Linux, the token is stored with `gnome-libsecret` by default. If your keyring
|
|||||||
An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then:
|
An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then:
|
||||||
|
|
||||||
1. Reads the title, season, and episode from the file name and folder. Install [guessit](https://github.com/guessit-io/guessit) for better parsing. A folder named `Season 2` is a strong season hint.
|
1. Reads the title, season, and episode from the file name and folder. Install [guessit](https://github.com/guessit-io/guessit) for better parsing. A folder named `Season 2` is a strong season hint.
|
||||||
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels.
|
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels. Specials, movies, and the second half of a split season ("Part 2", "Cour 2") do not count as seasons, and an entry whose title names the season ("Season 3", "III") wins.
|
||||||
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode.
|
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode. AniList lists the second half of a split season as its own entry, so an episode past the first half goes there: episode 15 of a season split 11 + 12 is episode 4 of the second entry.
|
||||||
|
|
||||||
If the show is not on your list yet, SubMiner adds it as Watching, but only when the file title exactly matches an AniList title or you pinned the entry with the character dictionary's AniList override. For a looser match, add the show to Planning or Watching yourself. SubMiner never changes entries marked Completed, Paused, Dropped, or Rewatching, and it never lowers your progress.
|
If the show is not on your list yet, SubMiner adds it as Watching, but only when the file title exactly matches an AniList title or you pinned the entry with the character dictionary's AniList override. For a looser match, add the show to Planning or Watching yourself. SubMiner never changes entries marked Completed, Paused, Dropped, or Rewatching, and it never lowers your progress.
|
||||||
|
|
||||||
@@ -37,7 +37,9 @@ Failed updates are saved and retried in the background, up to 8 times with growi
|
|||||||
|
|
||||||
If a cover or title in the stats Library is wrong, open the title and use **Change AniList Entry**.
|
If a cover or title in the stats Library is wrong, open the title and use **Change AniList Entry**.
|
||||||
|
|
||||||
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary).
|
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary). The override is also the fix when AniList splits a season without marking the second half in any title.
|
||||||
|
|
||||||
|
Library entries matched by older versions keep their match after an update. If one points at the wrong season, use **Change AniList Entry**.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# AniSkip integration
|
# AniSkip integration
|
||||||
|
|
||||||
SubMiner looks up opening timestamps on [AniSkip](https://aniskip.com) so you can skip an anime's intro with one key.
|
SubMiner finds an anime's opening and ending so you can skip either with one key. It reads the file's own chapters first and asks [AniSkip](https://aniskip.com) for anything they lack.
|
||||||
|
|
||||||
## Setup
|
## Setup
|
||||||
|
|
||||||
@@ -23,17 +23,24 @@ python3 -m pip install --user guessit
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
When a local file loads, SubMiner reads the title and episode from the file name, finds the show on MyAnimeList, and asks AniSkip for the intro's timestamps. Streams and URLs are skipped.
|
Once a file's duration is known, SubMiner looks for the opening and ending in the file's chapters:
|
||||||
|
|
||||||
If AniSkip has an intro, SubMiner adds `AniSkip Intro Start` and `AniSkip Intro End` chapters. When the intro starts, mpv shows "You can skip by pressing TAB" (with your key) for 3 seconds. Press the key any time during the intro to jump to its end.
|
- By name: chapters called `Opening`, `OP`, `OP ...` or `オープニング`; and `Ending`, `ED`, `ED ...`, `Outro`, `End Credits`, `Closing Credits`, `エンディング`, or `Credits` in the second half of the episode.
|
||||||
|
- By length, in files with at least three chapters: a 55 to 150 second chapter in the first 30% of the episode (the one closest to 90 seconds) is the opening, and the first one after 70% is the ending.
|
||||||
|
|
||||||
|
If the chapters don't give both, SubMiner reads the title and episode from the file name, finds the show on MyAnimeList, and asks AniSkip for the rest, sending the file's length so the times match your cut (TV or Blu-ray). AniSkip lookups run for local files only; streams such as Jellyfin use their chapters alone.
|
||||||
|
|
||||||
|
For times that came from AniSkip, SubMiner adds `AniSkip Intro Start`/`End` and `AniSkip Outro Start`/`End` chapters. When the intro or outro starts, SubMiner shows "You can skip the intro by pressing TAB" (or "the outro", with your key) for 3 seconds. Press the key any time during either one to jump to its end. Nothing is skipped automatically.
|
||||||
|
|
||||||
With a custom key other than `TAB` or `y-k`, `y-k` also skips.
|
With a custom key other than `TAB` or `y-k`, `y-k` also skips.
|
||||||
|
|
||||||
|
A failed lookup (AniSkip or MyAnimeList down, rate limited, or offline) is retried the next time the file loads. A show or episode AniSkip has no times for is remembered until SubMiner restarts.
|
||||||
|
|
||||||
## Triggering from mpv
|
## Triggering from mpv
|
||||||
|
|
||||||
| Command | What it does |
|
| Command | What it does |
|
||||||
| ----------------------------------------- | ------------------------------------------------------- |
|
| ----------------------------------------- | ------------------------------------------------------- |
|
||||||
| `script-message subminer-skip-intro` | Skip to the end of the intro |
|
| `script-message subminer-skip-intro` | Skip to the end of the intro or outro that is playing |
|
||||||
| `script-message subminer-aniskip-refresh` | Look up the current file again, ignoring cached results |
|
| `script-message subminer-aniskip-refresh` | Look up the current file again, ignoring cached results |
|
||||||
|
|
||||||
Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show.
|
Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show.
|
||||||
@@ -8,7 +8,7 @@ For the day-to-day flow, see [Mining workflow](/mining-workflow). Every key on t
|
|||||||
|
|
||||||
1. Install [Anki](https://apps.ankiweb.net/).
|
1. Install [Anki](https://apps.ankiweb.net/).
|
||||||
2. Install AnkiConnect (add-on code `2055492159`).
|
2. Install AnkiConnect (add-on code `2055492159`).
|
||||||
3. Install FFmpeg and make sure it is on your `PATH`. SubMiner uses it for audio and images.
|
3. Install FFmpeg and make sure it is on your `PATH`, or download it from first-run setup. SubMiner uses it for audio and images.
|
||||||
4. Keep Anki running while you mine.
|
4. Keep Anki running while you mine.
|
||||||
|
|
||||||
If you changed AnkiConnect's port, set `ankiConnect.url` to match.
|
If you changed AnkiConnect's port, set `ankiConnect.url` to match.
|
||||||
@@ -162,7 +162,7 @@ When you cancel, you can go back to editing, keep the original timing, create th
|
|||||||
|
|
||||||
#### With a controller
|
#### With a controller
|
||||||
|
|
||||||
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each button shows its controller shortcut. It works with or without keyboard-only mode, and the controller's usual actions pause until the dialog closes. Buttons that were already held when the dialog opened, such as the mine button, wait for a fresh press.
|
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each button shows its controller shortcut once SubMiner has seen a controller, which takes one button press after connecting it. It works with or without keyboard-only mode, and the controller's usual actions pause until the dialog closes. Buttons that were already held when the dialog opened, such as the mine button, wait for a fresh press.
|
||||||
|
|
||||||
`A`, `B`, `X` and `Y` mean the letters printed on your controller. Pick your controller's **Button Style** in `Alt+C`: choose Nintendo if A is on the right and B at the bottom (Switch-style and many 8BitDo pads). On PlayStation, `A` is ╳, `B` ○, `X` □ and `Y` △, and the shortcuts on screen show those symbols.
|
`A`, `B`, `X` and `Y` mean the letters printed on your controller. Pick your controller's **Button Style** in `Alt+C`: choose Nintendo if A is on the right and B at the bottom (Switch-style and many 8BitDo pads). On PlayStation, `A` is ╳, `B` ○, `X` □ and `Y` △, and the shortcuts on screen show those symbols.
|
||||||
|
|
||||||
@@ -267,7 +267,7 @@ The manual dialog cancels itself after 90 seconds. Identical entries are not ded
|
|||||||
|
|
||||||
### With a controller {#field-grouping-with-a-controller}
|
### With a controller {#field-grouping-with-a-controller}
|
||||||
|
|
||||||
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each control shows its controller shortcut. Like the [media timing review](#with-a-controller), it works with or without keyboard-only mode, `A`/`B`/`X`/`Y` are the printed letters (set by **Button Style** in `Alt+C`), and a button already held when the dialog opens waits for a fresh press.
|
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each control shows its controller shortcut once SubMiner has seen a controller. Like the [media timing review](#with-a-controller), it works with or without keyboard-only mode, `A`/`B`/`X`/`Y` are the printed letters (set by **Button Style** in `Alt+C`), and a button already held when the dialog opens waits for a fresh press.
|
||||||
|
|
||||||
| Controller | Choosing the card | Merge preview |
|
| Controller | Choosing the card | Merge preview |
|
||||||
| ------------------ | --------------------------------- | ----------------------- |
|
| ------------------ | --------------------------------- | ----------------------- |
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ src/
|
|||||||
preload*.ts # preload bridges (overlay, settings, stats, sync, Jellyfin setup)
|
preload*.ts # preload bridges (overlay, settings, stats, sync, Jellyfin setup)
|
||||||
main/ # main-process runtime modules and IPC/CLI wiring
|
main/ # main-process runtime modules and IPC/CLI wiring
|
||||||
boot/ # pre-ready boot helpers
|
boot/ # pre-ready boot helpers
|
||||||
assemblies/ # per-domain assemblies main.ts builds once (startup, overlay, playback, mining, stats, Yomitan, shortcuts, tray, first-run setup, YouTube, Jellyfin, AniList, settings, sync, dictionaries, overlay modals)
|
assemblies/ # per-domain assemblies main.ts builds once (startup, overlay, playback, mining, stats, Yomitan, shortcuts, session actions, plugins, subtitle generation, tray, first-run setup, YouTube, Jellyfin, AniList, settings, sync, dictionaries, overlay modals)
|
||||||
runtime/composers/ # larger runtime clusters assembled for main.ts
|
runtime/composers/ # larger runtime clusters assembled for main.ts
|
||||||
runtime/domains/ # domain barrels (startup, overlay, mpv, ipc, shortcuts, anilist, jellyfin, mining)
|
runtime/domains/ # domain barrels (startup, overlay, mpv, ipc, shortcuts, anilist, jellyfin, mining)
|
||||||
core/services/ # focused services: mpv client, overlay, tokenizer, mining, integrations, stats
|
core/services/ # focused services: mpv client, overlay, tokenizer, mining, integrations, stats
|
||||||
@@ -46,7 +46,7 @@ A few ownership notes that are hard to guess from file names:
|
|||||||
|
|
||||||
- mpv access is split into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and property modules under `src/core/services/`.
|
- mpv access is split into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and property modules under `src/core/services/`.
|
||||||
- The renderer keeps `renderer.ts` to orchestration. Keyboard, mouse, and gamepad input live in `renderer/handlers/`, and each modal flow has its own file in `renderer/modals/`.
|
- The renderer keeps `renderer.ts` to orchestration. Keyboard, mouse, and gamepad input live in `renderer/handlers/`, and each modal flow has its own file in `renderer/modals/`.
|
||||||
- AniSkip intro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it.
|
- Intro/outro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which reads the file's chapters, asks AniSkip for what they lack, and drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it.
|
||||||
|
|
||||||
## Component diagram
|
## Component diagram
|
||||||
|
|
||||||
@@ -139,7 +139,7 @@ Runtime code uses dependency injection:
|
|||||||
2. Build its runtime dependencies in a `src/main/` module. Pass simple dependencies inline; extract an adapter only when it adds behavior or gets reused.
|
2. Build its runtime dependencies in a `src/main/` module. Pass simple dependencies inline; extract an adapter only when it adds behavior or gets reused.
|
||||||
3. Call the service from lifecycle or command wiring.
|
3. Call the service from lifecycle or command wiring.
|
||||||
|
|
||||||
Domain handlers live in the barrels under `src/main/runtime/domains/`. Larger clusters, such as app-ready startup, mpv, Jellyfin, AniList tracking, shortcuts, and IPC, are assembled by composers in `src/main/runtime/composers/`. A domain whose runtimes share state, such as app startup, the overlay windows, mpv playback and subtitle state, card mining, stats, YouTube, Jellyfin, AniList, config settings, sync, or the character dictionary, is grouped into one assembly in `src/main/assemblies/` that owns that state and returns its runtimes. An assembly that answers renderer IPC or CLI commands also returns typed `ipc`/`cli` slices, and `main.ts` registers the handlers by combining those slices. Handlers take their dependencies as a plain object passed straight to the handler factory, which keeps side effects out of the unit under test.
|
Domain handlers live in the barrels under `src/main/runtime/domains/`. Larger clusters, such as app-ready startup, mpv, Jellyfin, AniList tracking, shortcuts, and IPC, are assembled by composers in `src/main/runtime/composers/`. A domain whose runtimes share state, such as app startup, the overlay windows, mpv playback and subtitle state, card mining, stats, plugins, YouTube, Jellyfin, AniList, config settings, sync, or the character dictionary, is grouped into one assembly in `src/main/assemblies/` that owns that state and returns its runtimes. An assembly that answers renderer IPC or CLI commands also returns typed `ipc`/`cli` slices, and `main.ts` registers the handlers by combining those slices. Handlers take their dependencies as a plain object passed straight to the handler factory, which keeps side effects out of the unit under test.
|
||||||
|
|
||||||
Composers declare their inputs with `ComposerInputs<T>` and results with `ComposerOutputs<T>` from `src/main/runtime/composers/contracts.ts`. A missing dependency then fails at compile time.
|
Composers declare their inputs with `ComposerInputs<T>` and results with `ComposerOutputs<T>` from `src/main/runtime/composers/contracts.ts`. A missing dependency then fails at compile time.
|
||||||
|
|
||||||
|
|||||||
+81
-3
@@ -1,6 +1,84 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
## v0.21.1 (2026-10-26)
|
## v0.22.1 (2026-11-23)
|
||||||
|
|
||||||
|
**Added**
|
||||||
|
- **AniSkip Outro Skipping**:
|
||||||
|
- The AniSkip key now skips endings too, with its own prompt and chapter markers.
|
||||||
|
- Intros and outros are found from the file's own chapters first, so skipping also works for Jellyfin and other streams.
|
||||||
|
- Skip times now match your TV or Blu-ray cut.
|
||||||
|
- **Library Franchise Cards**: The stats library shows each anime once. Seasons, movies, and OVAs that AniList links together share one card, and opening the card lists each part with its own stats. To fix the grouping, use **Move to Another Anime…**, **Show On Its Own**, or **Put Back Where AniList Has It** on a title's page.
|
||||||
|
- **FFmpeg Download in Setup**: First-run setup shows whether FFmpeg and FFprobe can be used. If they're missing, **Download FFmpeg** installs a copy that SubMiner and the `subminer` command can use.
|
||||||
|
|
||||||
|
**Fixed**
|
||||||
|
- **AniList Season Matching**:
|
||||||
|
- Later seasons now find the right AniList entry, even when a series has split-season halves, specials, or movies.
|
||||||
|
- Episodes in the second half of a split season update the right entry at the right episode number.
|
||||||
|
- Character dictionary matches saved by older versions are checked again once.
|
||||||
|
- **AniSkip Lookups**: Rate limits, server errors, and network failures no longer count as "no intro" until restart. SubMiner tries again the next time the episode loads.
|
||||||
|
- **Jimaku Series Name**: The Jimaku modal fills in the series name, season, and episode again for Jellyfin episodes with a "/" in their name.
|
||||||
|
- **mpv Keys in the Overlay**: Keys bound in `input.conf` are no longer sent to a Yomitan popup that has already closed. They also no longer get lost when the overlay regains focus.
|
||||||
|
- **Windows Overlay**: The overlay now finds the mpv window more reliably, and you can set the IPC socket in `mpv.conf`. It no longer stays attached to an unrelated window, and stalled overlays are now explained in the normal log.
|
||||||
|
|
||||||
|
**Docs**
|
||||||
|
- **Windows Overlay Troubleshooting**: New guide to collecting and reading Windows overlay warnings without turning on debug logging.
|
||||||
|
|
||||||
|
## v0.22.0 (2026-11-06)
|
||||||
|
|
||||||
|
**Added**
|
||||||
|
- **Plugins**:
|
||||||
|
- JavaScript plugins load at startup from `<config dir>/plugins/<id>/` and are enabled under `plugins` in the config.
|
||||||
|
- Plugins can react to playback and mined cards, add bindable actions, run programs, and show results in overlay panels or their own windows.
|
||||||
|
- Example plugins cover AI line explanations (`ai-explain`), AnkiWeb sync (`anki-sync`), and show and episode tags on mined cards (`episode-tags`).
|
||||||
|
- Plugin authors get a versioned API with standalone types.
|
||||||
|
- **Subtitle Filters**: Remove text in parentheses, sound descriptions, speaker names, music notes, or custom regex matches from primary subtitles. Configure them in Settings under Behavior → Subtitle Filters.
|
||||||
|
- **Controller Combos**: Controller actions can now be combos, such as holding `L1` and pressing D-pad right. Click **Learn** in `Alt+C`, then hold one button and press another.
|
||||||
|
- **Controller Actions**: New bindings cover previous, next, replay, and play-next subtitle, hold-to-show secondary subtitle, and previous or next Yomitan entry. All are unbound by default and can be assigned in `Alt+C`.
|
||||||
|
- **Controller Dialog Layouts**: The media timing review and duplicate card dialogs can now be used with a controller and show button hints while one is connected. Remap both layouts per controller in `Alt+C`.
|
||||||
|
- **Controller Button Style**: Choose Xbox, Nintendo, or PlayStation button names per controller in `Alt+C`, or set a default with `controller.faceButtonLabels`.
|
||||||
|
- **Controller Clash Warnings**: `Alt+C` now warns when two actions share the same input.
|
||||||
|
- **Keyboard-Only Mode**:
|
||||||
|
- Press `C` or use the new controller binding to move by character, reaching words split by the subtitle parser.
|
||||||
|
- The new **Pause Video In Keyboard-Only Mode** setting pauses on entry and resumes on exit.
|
||||||
|
- **Jimaku Auto-Open**: Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to pause and open Jimaku when a local video has no Japanese subtitle track. Reopening Jimaku after the video changes now refreshes the title and episode.
|
||||||
|
|
||||||
|
**Changed**
|
||||||
|
- **Stats Trends and Vocabulary**:
|
||||||
|
- Trends adds a learning section, heatmap, title timeline, custom date ranges, and a page-wide title filter.
|
||||||
|
- Vocabulary now has one searchable word table, known words by frequency band, a growth chart, and a full kanji view.
|
||||||
|
- New word counts now count dictionary words, so a word's conjugations count once and totals are lower than before.
|
||||||
|
- Stats now explains when streamed words or lines can't be mined.
|
||||||
|
- **Bundled Hachidori**: Updated to upstream 0.4.0, adding every pitch accent in popup entries, per-kanji headword furigana, and Yomitan-style definition tags.
|
||||||
|
- **Controller Behavior**: **Toggle MPV Pause** now works outside keyboard-only mode. Connected and disabled messages now follow your `ankiConnect.behavior.notificationType` setting.
|
||||||
|
- **Dictionary Popup**: Turning keyboard-only mode off now also closes the popup.
|
||||||
|
|
||||||
|
**Fixed**
|
||||||
|
- **Controller Settings (`Alt+C`)**:
|
||||||
|
- Remaps now apply right away, and Learn works on **(D-pad)** rows.
|
||||||
|
- Clicking a row shows **Learn**, **Clear**, and **Reset** again.
|
||||||
|
- The window previews your bindings until a press, then selects the pressed controller.
|
||||||
|
- Button names are now correct on standard-layout controllers.
|
||||||
|
- **Controller Input on macOS and Windows**: One press no longer runs its action twice. On macOS, buttons now work while mpv is in front.
|
||||||
|
- **Dictionary Popup**: Keyboard and controller lookups now pause and resume playback reliably. Moving between words right after closing a popup no longer reopens it.
|
||||||
|
- **Playback**: Reloading the current file no longer leaves playback paused. The "Overlay loading" message no longer sticks or turns into a false error when a playlist advances.
|
||||||
|
- **Stats**:
|
||||||
|
- The dashboard, Vocabulary tab, and sentence search load much faster on large databases, and Trends downloads far less data.
|
||||||
|
- Trends now counts each finished episode once, and its Library totals match the selected range.
|
||||||
|
- Word totals, readings, Hide Names, and rate charts are now accurate.
|
||||||
|
- Date handling is now correct in time zones ahead of UTC.
|
||||||
|
- **AniList**: Progress sync now adds a missing show to Watching, or Completed on the final episode, when the title matches exactly or is pinned. Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
|
||||||
|
- **Anki Sentence Audio**: Generated sentence audio no longer overwrites Yomitan's word audio on default configs. If you relied on the old default, set `ankiConnect.fields.audio` to `ExpressionAudio`.
|
||||||
|
- **AppImage**: Fixed "Service Crash" notifications on quit on Ubuntu 26.04 and newer.
|
||||||
|
|
||||||
|
**Docs**
|
||||||
|
- **Keyboard and Controller Reference**: Keyboard shortcuts now list the keyboard-only `C` key, and the configuration reference points to Controller support for default button actions.
|
||||||
|
|
||||||
|
## Previous Versions
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>v0.21.x</summary>
|
||||||
|
|
||||||
|
<h2>v0.21.1 (2026-10-26)</h2>
|
||||||
|
|
||||||
**Changed**
|
**Changed**
|
||||||
- **Stats Session View**: Redesigned the expanded session view in the stats dashboard.
|
- **Stats Session View**: Redesigned the expanded session view in the stats dashboard.
|
||||||
@@ -23,7 +101,7 @@
|
|||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
## v0.21.0 (2026-10-24)
|
<h2>v0.21.0 (2026-10-24)</h2>
|
||||||
|
|
||||||
**Added**
|
**Added**
|
||||||
- **Hachidori Dictionary Backend**:
|
- **Hachidori Dictionary Backend**:
|
||||||
@@ -68,7 +146,7 @@
|
|||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
## Previous Versions
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>v0.20.x</summary>
|
<summary>v0.20.x</summary>
|
||||||
|
|||||||
+40
-12
@@ -52,7 +52,7 @@ SubMiner watches the config file while running. When it changes, live settings a
|
|||||||
|
|
||||||
These apply live:
|
These apply live:
|
||||||
|
|
||||||
- `subtitleStyle`, `subtitleSidebar`, `subtitleSelection`, `keybindings`, `shortcuts`
|
- `subtitleStyle`, `subtitleSidebar`, `subtitleSelection`, `subtitleFilter`, `keybindings`, `shortcuts`
|
||||||
- `logging.level`, `logging.rotation`, `logging.files`
|
- `logging.level`, `logging.rotation`, `logging.files`
|
||||||
- `secondarySub.defaultMode`, `youtube.primarySubLanguages`, `youtube.subtitleSource`
|
- `secondarySub.defaultMode`, `youtube.primarySubLanguages`, `youtube.subtitleSource`
|
||||||
- `mpv.aniskipEnabled`, `mpv.aniskipButtonKey`, `stats.toggleKey`, `stats.markWatchedKey`
|
- `mpv.aniskipEnabled`, `mpv.aniskipButtonKey`, `stats.toggleKey`, `stats.markWatchedKey`
|
||||||
@@ -221,6 +221,29 @@ Sidebar custom properties: `--subtitle-sidebar-max-width` (`420px`), `--subtitle
|
|||||||
|
|
||||||
If `embedded` layout places the video oddly on your system, switch back to `overlay`.
|
If `embedded` layout places the video oddly on your system, switch back to `overlay`.
|
||||||
|
|
||||||
|
### Subtitle filters {#subtitle-filters}
|
||||||
|
|
||||||
|
Removes unwanted text from primary subtitles, such as speaker names, readings and sound descriptions. Filtering happens as the line arrives, so the overlay, sidebar, mined sentences and stats all see the filtered text. A line left with no words is hidden. In the settings window, find it under **Behavior → Subtitle Filters**.
|
||||||
|
|
||||||
|
| Key | Default | What it does |
|
||||||
|
| -------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `subtitleFilter.presets.parentheses` | `false` | Remove `(…)` and `(…)` anywhere in a line. A line wrapped entirely in parentheses (inner thoughts) is kept |
|
||||||
|
| `subtitleFilter.presets.brackets` | `false` | Remove `[…]`, `[…]`, `【…】` and `〔…〕`, such as sound effects |
|
||||||
|
| `subtitleFilter.presets.speakerPrefix` | `false` | Remove a short name before a colon at the start of a line, as in `山田:` |
|
||||||
|
| `subtitleFilter.presets.musicSymbols` | `false` | Remove `♪`, `♫` and `♬` |
|
||||||
|
| `subtitleFilter.customRules` | `[]` | Your own regex rules, applied in order after the presets |
|
||||||
|
|
||||||
|
Each custom rule is `{ "name", "pattern", "replacement", "enabled" }`. Patterns are JavaScript regular expressions compiled with the `gmu` flags, so `^` and `$` match each line. An empty `replacement` removes the match.
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
"subtitleFilter": {
|
||||||
|
"presets": { "parentheses": true },
|
||||||
|
"customRules": [{ "name": "Join lines", "pattern": "\\n", "replacement": "", "enabled": true }],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Subtitle position
|
### Subtitle position
|
||||||
|
|
||||||
You can also drag subtitles with `Right-click + drag` while watching.
|
You can also drag subtitles with `Right-click + drag` while watching.
|
||||||
@@ -291,7 +314,7 @@ Adds a modal for choosing mpv's primary and secondary subtitle tracks. Open it w
|
|||||||
|
|
||||||
### Controller support
|
### Controller support
|
||||||
|
|
||||||
Gamepad input for the overlay, through the browser Gamepad API. Most actions only work while keyboard-only mode is on; the toggle for that mode, the secondary subtitle hold (`controller.bindings.holdSecondarySub`), pause (`toggleMpvPause`) and the subtitle line actions (`previousSubtitle`, `nextSubtitle`, `replaySubtitle`, `playNextSubtitle`) work either way. Use the `Alt+C` modal to pick a controller and learn bindings, and `Alt+Shift+C` to see raw button and axis values. Default button actions are on [Keyboard shortcuts](/shortcuts).
|
Gamepad input for the overlay, through the browser Gamepad API. Most actions only work while keyboard-only mode is on; the toggle for that mode, the secondary subtitle hold (`controller.bindings.holdSecondarySub`), pause (`toggleMpvPause`) and the subtitle line actions (`previousSubtitle`, `nextSubtitle`, `replaySubtitle`, `playNextSubtitle`) work either way. Use the `Alt+C` modal to pick a controller and learn bindings, and `Alt+Shift+C` to see raw button and axis values. Default button actions are in [Controller support](/usage#controller-support).
|
||||||
|
|
||||||
| Key | Default | What it does |
|
| Key | Default | What it does |
|
||||||
| ---------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| ---------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
@@ -306,7 +329,11 @@ Gamepad input for the overlay, through the browser Gamepad API. Most actions onl
|
|||||||
| `controller.repeatDelayMs` | `320` | Delay before a held button repeats |
|
| `controller.repeatDelayMs` | `320` | Delay before a held button repeats |
|
||||||
| `controller.repeatIntervalMs` | `120` | Repeat interval for held buttons |
|
| `controller.repeatIntervalMs` | `120` | Repeat interval for held buttons |
|
||||||
|
|
||||||
Bindings, including the media timing review and duplicate card dialog layouts, are set with `Alt+C` learn mode, which saves them per controller.
|
Bindings, including the media timing review and duplicate card dialog layouts, are set with `Alt+C` learn mode, which saves them per controller. Learn can also record a [combo](/usage#controller-support), saved on the binding as an optional `hold` input in the same form:
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
"nextAudio": { "kind": "button", "buttonIndex": 15, "hold": { "kind": "button", "buttonIndex": 4 } }
|
||||||
|
```
|
||||||
|
|
||||||
## Anki integration
|
## Anki integration
|
||||||
|
|
||||||
@@ -448,13 +475,14 @@ When SubMiner fills the sentence on a word card, it sets one card-type flag and
|
|||||||
|
|
||||||
Search and download Japanese subtitles from [Jimaku](https://jimaku.cc). See [Jimaku integration](/jimaku-integration).
|
Search and download Japanese subtitles from [Jimaku](https://jimaku.cc). See [Jimaku integration](/jimaku-integration).
|
||||||
|
|
||||||
| Key | Default | What it does |
|
| Key | Default | What it does |
|
||||||
| --------------------------- | --------------------- | ---------------------------------------------------------- |
|
| ------------------------------------------- | --------------------- | --------------------------------------------------------------------------------- |
|
||||||
| `jimaku.apiKey` | `""` | API key. Optional, but raises your rate limit |
|
| `jimaku.apiKey` | `""` | API key. Optional, but raises your rate limit |
|
||||||
| `jimaku.apiKeyCommand` | `""` | Shell command that prints the key. Use instead of `apiKey` |
|
| `jimaku.apiKeyCommand` | `""` | Shell command that prints the key. Use instead of `apiKey` |
|
||||||
| `jimaku.apiBaseUrl` | `"https://jimaku.cc"` | API base URL |
|
| `jimaku.apiBaseUrl` | `"https://jimaku.cc"` | API base URL |
|
||||||
| `jimaku.languagePreference` | `"ja"` | Preferred language: `ja`, `en`, or `none` |
|
| `jimaku.languagePreference` | `"ja"` | Preferred language: `ja`, `en`, or `none` |
|
||||||
| `jimaku.maxEntryResults` | `10` | Maximum search results |
|
| `jimaku.maxEntryResults` | `10` | Maximum search results |
|
||||||
|
| `jimaku.autoOpenWhenPrimarySubtitleMissing` | `false` | Pause and open the Jimaku modal when a local video has no Japanese subtitle track |
|
||||||
|
|
||||||
### TsukiHime
|
### TsukiHime
|
||||||
|
|
||||||
@@ -606,8 +634,8 @@ Settings for mpv instances that SubMiner starts, and for the bundled mpv plugin.
|
|||||||
| `mpv.autoStartSubMiner` | `true` | Start SubMiner in the background when mpv loads a file |
|
| `mpv.autoStartSubMiner` | `true` | Start SubMiner in the background when mpv loads a file |
|
||||||
| `mpv.pauseUntilOverlayReady` | `true` | Keep mpv paused until subtitles are ready, up to 30 seconds |
|
| `mpv.pauseUntilOverlayReady` | `true` | Keep mpv paused until subtitles are ready, up to 30 seconds |
|
||||||
| `mpv.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path |
|
| `mpv.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path |
|
||||||
| `mpv.aniskipEnabled` | `true` | Detect intros with AniSkip and show a skip prompt |
|
| `mpv.aniskipEnabled` | `true` | Detect intros and outros (file chapters, then AniSkip) and show a skip prompt |
|
||||||
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro while the prompt is shown |
|
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro or outro while it plays |
|
||||||
|
|
||||||
### YouTube playback settings
|
### YouTube playback settings
|
||||||
|
|
||||||
|
|||||||
@@ -50,11 +50,15 @@ Deleting a session or session group refreshes the Overview totals, charts, calen
|
|||||||
|
|
||||||
Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel.
|
Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel.
|
||||||
|
|
||||||
Seasons get separate cards when a season number is detected. Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
|
Seasons, movies, and OVAs of one anime share a card. SubMiner follows AniList's sequel, prequel, parent, side-story, summary, and compilation links, including through entries you have not watched, so two films can meet at a TV series you never played. Spin-offs and alternative versions keep their own cards. A shared card is named after the anime's first TV series, shows the cover of the earliest part you have, and opens to a list of its parts in release order. Relations come from AniList in the background and refresh weekly, so a newly linked show can take a minute to join its card.
|
||||||
|
|
||||||
|
If a part lands on the wrong card, open it and choose **Move to Another Anime…** (the target must be linked to AniList) or **Show On Its Own**. **Put Back Where AniList Has It** undoes either. This only changes how the library is listed; duplicate entries for the same season still need a merge.
|
||||||
|
|
||||||
|
Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
|
||||||
|
|
||||||
The same show can end up on several cards when release names disagree. To fix that:
|
The same show can end up on several cards when release names disagree. To fix that:
|
||||||
|
|
||||||
- Merge: click **Select**, tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
|
- Merge: click **Select** (the grid then lists every entry on its own), tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
|
||||||
- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction.
|
- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction.
|
||||||
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
|
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
|
||||||
|
|
||||||
@@ -64,7 +68,17 @@ The same show can end up on several cards when release names disagree. To fix th
|
|||||||
|
|
||||||
### Trends
|
### Trends
|
||||||
|
|
||||||
Charts for watch time, cards, words, and sessions per day or month, running totals, efficiency (words per minute, cards per hour), and viewing patterns by weekday and hour. Each chart has its own date range and grouping.
|
Pick a date range (or set **Custom** dates), group by day, week, or month, and the whole page follows. Your choices are remembered.
|
||||||
|
|
||||||
|
- **Summary**: totals for the range, compared with the period just before it.
|
||||||
|
- **Activity**: watch time, cards, words, and finished episodes. Click a bar to open that period's sessions.
|
||||||
|
- **Learning**: new words per 1,000 words seen, and how common those new words are. Conjugations of a word count once, and names are left out.
|
||||||
|
- **Efficiency**: words per minute, cards per hour, and lookups per 100 words. Daily views use a rolling 7 days, and gaps mean too little data to rate.
|
||||||
|
- **Running total**: one chart with a switcher for each metric, climbing from zero at the start of the range.
|
||||||
|
- **Patterns**: a day and hour heatmap of when you watch.
|
||||||
|
- **Titles**: a timeline of what you watched when, and a sortable summary table. Click a title, or use the filter box, to narrow the page to it. **↗** opens the title.
|
||||||
|
|
||||||
|
An episode counts as finished once, on the last day you watched it.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@@ -76,10 +90,15 @@ Session history. Expand a session for its pace, lines, known-word rate, lookups,
|
|||||||
|
|
||||||
### Vocabulary
|
### Vocabulary
|
||||||
|
|
||||||
Unique words and kanji you have seen, new words per day, frequency rank tables with Hide Known and Hide Kana filters, and a kanji breakdown. Click a word to see every line it appeared in.
|
Words are counted as dictionary words, so a word's conjugations count once. Names are left out unless you turn off **Hide names**.
|
||||||
|
|
||||||
- **Exclusions** hides words from every vocabulary view. You can restore them from the same dialog.
|
- **Summary**: words seen, how many are in Anki, new words this week, and kanji seen.
|
||||||
- **Duplicates** cleans up lines repeated by karaoke openings and animated signs (see [Repeated lines](#repeated-lines)).
|
- **Known Words by Frequency**: how much of each frequency band you already know.
|
||||||
|
- **Vocabulary Growth**: your running total of words seen.
|
||||||
|
- **Words**: one table for every word you have seen. **Worth mining** lists common words you haven't mined, most seen first. **All words**, **Across titles**, and **Newest** are the other views. Sort by any column, or filter by known words, names, kana, and part of speech. Searching looks through everything, including conjugated forms and readings. Click a word for its forms, where it appeared, and example lines you can mine from. **Hide** excludes a word.
|
||||||
|
- **Kanji**: every kanji you have seen, shaded by how often. Dashed kanji are not in any word you know.
|
||||||
|
|
||||||
|
**Exclusions** at the bottom of the page lists hidden words so you can restore them. **Clean up duplicates** removes lines repeated by karaoke openings and animated signs (see [Repeated lines](#repeated-lines)).
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@@ -89,7 +108,7 @@ Searches the primary subtitle lines and titles in your history. **Search by head
|
|||||||
|
|
||||||
## Mining from the dashboard
|
## Mining from the dashboard
|
||||||
|
|
||||||
Search results and the Vocabulary word panel can create cards from past lines, as long as the source video file is still available:
|
Search results and the Vocabulary word panel can create cards from past lines, as long as the source video file is still available. Lines from a stream, such as Jellyfin or YouTube, have no file to cut clips from, so they say so instead of offering mining. Lines you can mine are listed first. The word panel counts how many of a word's lines this affects, and the word table marks words with only streamed lines as **Stream only**.
|
||||||
|
|
||||||
- **Mine Word**: looks up the word with the selected dictionary backend (Yomitan or Hachidori), plus sentence, audio, and image. The history line you picked is the card's sentence, even while mpv plays another line. Hachidori uses its own Anki template, dictionary aliases, and frequency data.
|
- **Mine Word**: looks up the word with the selected dictionary backend (Yomitan or Hachidori), plus sentence, audio, and image. The history line you picked is the card's sentence, even while mpv plays another line. Hachidori uses its own Anki template, dictionary aliases, and frequency data.
|
||||||
- **Mine Sentence**: a sentence card with `IsSentenceCard` set, for Lapis and Kiku note types.
|
- **Mine Sentence**: a sentence card with `IsSentenceCard` set, for Lapis and Kiku note types.
|
||||||
@@ -103,7 +122,7 @@ Dashboard cards also get the `SubMiner::Stats` tag. With the Anki proxy off, Sub
|
|||||||
|
|
||||||
Karaoke openings and animated signs repeat the same text once per frame. SubMiner collapses these as it records, so one lyric is stored once. Stats recorded before that can hold hundreds of copies and skew Top Repeated Words.
|
Karaoke openings and animated signs repeat the same text once per frame. SubMiner collapses these as it records, so one lyric is stored once. Stats recorded before that can hold hundreds of copies and skew Top Repeated Words.
|
||||||
|
|
||||||
To clean them, use **Duplicates** in the Vocabulary tab: pick a time window, **Scan** to preview, then **Clean Up**. Or from the terminal:
|
To clean them, use **Clean up duplicates** in the Vocabulary tab: pick a time window, **Scan** to preview, then **Clean Up**. Or from the terminal:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
subminer stats cleanup --duplicate-lines --dry-run --lookback-days 30
|
subminer stats cleanup --duplicate-lines --dry-run --lookback-days 30
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ Getting started takes three steps:
|
|||||||
|
|
||||||
## 1. Install requirements
|
## 1. Install requirements
|
||||||
|
|
||||||
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot.
|
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. If you skip it, first-run setup can download a copy for SubMiner.
|
||||||
|
|
||||||
| Dependency | Needed for | Platforms |
|
| Dependency | Needed for | Platforms |
|
||||||
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
|
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
|
||||||
@@ -124,7 +124,7 @@ mpv --version
|
|||||||
ffmpeg -version
|
ffmpeg -version
|
||||||
```
|
```
|
||||||
|
|
||||||
ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`).
|
ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. Otherwise, use the FFmpeg download in first-run setup. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`).
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary>
|
<summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary>
|
||||||
@@ -262,8 +262,9 @@ Setup walks you through:
|
|||||||
|
|
||||||
1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows).
|
1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows).
|
||||||
2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser.
|
2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser.
|
||||||
3. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`.
|
3. **FFmpeg** (optional). If `ffmpeg` and `ffprobe` are on your `PATH` and run, there is nothing to do. Otherwise **Download FFmpeg** saves a static build to `tools/ffmpeg/` next to your config file. SubMiner and the `subminer` command use it only when FFmpeg is missing from `PATH`, so a system install always takes priority.
|
||||||
4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
|
4. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`.
|
||||||
|
5. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
|
||||||
|
|
||||||
**Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`.
|
**Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`.
|
||||||
|
|
||||||
|
|||||||
@@ -37,17 +37,32 @@ The file is saved next to the video (or to a temp directory for streams) and loa
|
|||||||
|
|
||||||
You can also open the modal with `subminer app --open-jimaku`, or change the shortcut with `shortcuts.openJimaku`.
|
You can also open the modal with `subminer app --open-jimaku`, or change the shortcut with `shortcuts.openJimaku`.
|
||||||
|
|
||||||
|
### Open automatically when a video has no Japanese subtitles
|
||||||
|
|
||||||
|
Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to `true` to skip the shortcut. When a local video loads without a subtitle track in `youtube.primarySubLanguages` (Japanese by default), SubMiner pauses playback about a second after the video loads and opens the Jimaku modal, so you can pick a subtitle before watching. Playback stays paused while the modal is open and resumes when it closes, whether or not you picked a subtitle. On a cold start it resumes once subtitle processing is ready, as usual, and a pause you made yourself before the modal opened is kept.
|
||||||
|
|
||||||
|
A single unlabeled sidecar file (such as `episode.srt` next to the video) counts as a Japanese track, matching how SubMiner auto-selects local subtitles. An embedded track with no language tag does not, so the modal still opens for it. Audio files, streams, YouTube, and Jellyfin playback are not checked.
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
"jimaku": {
|
||||||
|
"autoOpenWhenPrimarySubtitleMissing": true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
The file name parser understands `S01E03`, `1x03`, `E03`, `EP03`, and `Title - 03 -` patterns, and reads the season from a parent folder such as `Season 2`. It ignores bracket tags like `[SubGroup]` and year tags like `(2024)`.
|
The file name parser understands `S01E03`, `1x03`, `E03`, `EP03`, and `Title - 03 -` patterns, and reads the season from a parent folder such as `Season 2`. It ignores bracket tags like `[SubGroup]` and year tags like `(2024)`.
|
||||||
|
|
||||||
## Options
|
## Options
|
||||||
|
|
||||||
| Key | What it does |
|
| Key | What it does |
|
||||||
| --------------------------- | ------------------------------------------------------------------- |
|
| ------------------------------------------- | -------------------------------------------------------------------- |
|
||||||
| `jimaku.apiKey` | API key in plain text. |
|
| `jimaku.apiKey` | API key in plain text. |
|
||||||
| `jimaku.apiKeyCommand` | Shell command that prints the API key. |
|
| `jimaku.apiKeyCommand` | Shell command that prints the API key. |
|
||||||
| `jimaku.languagePreference` | Sorts files tagged with this language first: `ja`, `en`, or `none`. |
|
| `jimaku.languagePreference` | Sorts files tagged with this language first: `ja`, `en`, or `none`. |
|
||||||
| `jimaku.maxEntryResults` | Maximum entries per search. |
|
| `jimaku.maxEntryResults` | Maximum entries per search. |
|
||||||
| `jimaku.apiBaseUrl` | API address. Change only for a mirror. |
|
| `jimaku.apiBaseUrl` | API address. Change only for a mirror. |
|
||||||
|
| `jimaku.autoOpenWhenPrimarySubtitleMissing` | Pauses and opens the modal when a local video has no Japanese track. |
|
||||||
|
|
||||||
See [Configuration](/configuration#jimaku) for defaults.
|
See [Configuration](/configuration#jimaku) for defaults.
|
||||||
|
|
||||||
|
|||||||
@@ -145,7 +145,7 @@ subminer sync macbook --remote-cmd ~/Apps/SubMiner.AppImage # SubMiner in a cu
|
|||||||
subminer sync --ui # open the sync window
|
subminer sync --ui # open the sync window
|
||||||
```
|
```
|
||||||
|
|
||||||
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. `--push` and `--pull` do not delete anything on the receiving side.
|
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. The one setting it carries is a library title's anime card choice (**Move to Another Anime…**), where the most recent change wins. `--push` and `--pull` do not delete anything on the receiving side.
|
||||||
|
|
||||||
Before a command-line sync, close SubMiner on both machines and stop the stats server with `subminer stats -s`, or pass `--force`. The sync window does not need this. It syncs while SubMiner and playback are running, and skips the session in progress until it finishes.
|
Before a command-line sync, close SubMiner on both machines and stop the stats server with `subminer stats -s`, or pass `--force`. The sync window does not need this. It syncs while SubMiner and playback are running, and skips the session in progress until it finishes.
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ Most plugin keys are chords: press `y`, then the second key.
|
|||||||
|
|
||||||
`v` replaces mpv's own subtitle visibility toggle.
|
`v` replaces mpv's own subtitle visibility toggle.
|
||||||
|
|
||||||
The skip-intro key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration).
|
The intro/outro skip key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration).
|
||||||
|
|
||||||
The `y-y` menu lists Start overlay, Stop overlay, Toggle overlay, Open options, Restart overlay, Check status, and Stats. Press an item's number to run it. Stats only reminds you to press `` ` `` in the overlay.
|
The `y-y` menu lists Start overlay, Stop overlay, Toggle overlay, Open options, Restart overlay, Check status, and Stats. Press an item's number to run it. Stats only reminds you to press `` ` `` in the overlay.
|
||||||
|
|
||||||
|
|||||||
@@ -83,17 +83,6 @@ Anki must be running and logged in to AnkiWeb. Cards mined from the stats dashbo
|
|||||||
|
|
||||||
Templates can use `{show}`, `{season}`, `{episode}`, and `{ep}` (`S01E07`, or `E07` when there is no season). When a placeholder has no value, the tag stops before that `::` level, so a movie gets `show::<title>`. The parsing is a guess from the name: a title ending in a number, like `Mob Psycho 100`, reads that number as the episode.
|
Templates can use `{show}`, `{season}`, `{episode}`, and `{ep}` (`S01E07`, or `E07` when there is no season). When a placeholder has no value, the tag stops before that `::` level, so a movie gets `show::<title>`. The parsing is a guess from the name: a title ending in a number, like `Mob Psycho 100`, reads that number as the episode.
|
||||||
|
|
||||||
## Example: open Jimaku when a file has no Japanese subtitles
|
|
||||||
|
|
||||||
[`assets/plugins/auto-jimaku`](https://github.com/ksyasuda/SubMiner/tree/main/assets/plugins/auto-jimaku) opens the Jimaku search a few seconds after a file starts if none of its subtitle tracks is Japanese. A track counts as Japanese when its language code is in `languages`, or its title contains "Japanese" or 日本語.
|
|
||||||
|
|
||||||
| Setting | Default | What it does |
|
|
||||||
| ----------- | --------------------- | --------------------------------------------------------------- |
|
|
||||||
| `action` | `"openJimaku"` | Built-in action to run, e.g. `openTsukihime` |
|
|
||||||
| `languages` | `["ja", "jp", "jpn"]` | Track language codes that count as Japanese |
|
|
||||||
| `delayMs` | `3000` | Wait this long after the file starts, so external subs load |
|
|
||||||
| `streams` | `false` | Also check `http(s)` streams, which Jimaku usually can't search |
|
|
||||||
|
|
||||||
## Write a plugin
|
## Write a plugin
|
||||||
|
|
||||||
A plugin folder needs a `plugin.json`:
|
A plugin folder needs a `plugin.json`:
|
||||||
|
|||||||
@@ -128,59 +128,62 @@
|
|||||||
"toggleLookup": {
|
"toggleLookup": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 0 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 0 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"closeLookup": {
|
"closeLookup": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 1 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 1 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"toggleKeyboardOnlyMode": {
|
"toggleKeyboardOnlyMode": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 3 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 3 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"mineCard": {
|
"mineCard": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 2 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 2 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"quitMpv": {
|
"quitMpv": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 6 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 6 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"previousAudio": {
|
"previousAudio": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"nextAudio": {
|
"nextAudio": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 5 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 5 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"playCurrentAudio": {
|
"playCurrentAudio": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 4 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 4 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"toggleMpvPause": {
|
"toggleMpvPause": {
|
||||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
"buttonIndex": 9 // Raw button index captured for this discrete controller action.
|
"buttonIndex": 9 // Raw button index captured for this discrete controller action.
|
||||||
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"holdSecondarySub": {
|
"holdSecondarySub": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"previousEntry": {
|
"previousEntry": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"nextEntry": {
|
"nextEntry": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
|
"toggleCharacterNavigation": {
|
||||||
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
|
}, // Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"previousSubtitle": {
|
"previousSubtitle": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"nextSubtitle": {
|
"nextSubtitle": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"replaySubtitle": {
|
"replaySubtitle": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"playNextSubtitle": {
|
"playNextSubtitle": {
|
||||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||||
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||||
"leftStickHorizontal": {
|
"leftStickHorizontal": {
|
||||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||||
"axisIndex": 0, // Raw axis index captured for this analog controller action.
|
"axisIndex": 0, // Raw axis index captured for this analog controller action.
|
||||||
@@ -191,11 +194,6 @@
|
|||||||
"axisIndex": 1, // Raw axis index captured for this analog controller action.
|
"axisIndex": 1, // Raw axis index captured for this analog controller action.
|
||||||
"dpadFallback": "vertical" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
"dpadFallback": "vertical" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
||||||
}, // Axis binding descriptor used for primary popup scrolling. Use Alt+C learn mode or set a raw axis descriptor manually.
|
}, // Axis binding descriptor used for primary popup scrolling. Use Alt+C learn mode or set a raw axis descriptor manually.
|
||||||
"rightStickHorizontal": {
|
|
||||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
|
||||||
"axisIndex": 3, // Raw axis index captured for this analog controller action.
|
|
||||||
"dpadFallback": "none" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
|
||||||
}, // Axis binding descriptor reserved for alternate right-stick mappings. Use Alt+C learn mode or set a raw axis descriptor manually.
|
|
||||||
"rightStickVertical": {
|
"rightStickVertical": {
|
||||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||||
"axisIndex": 4, // Raw axis index captured for this analog controller action.
|
"axisIndex": 4, // Raw axis index captured for this analog controller action.
|
||||||
@@ -854,6 +852,22 @@
|
|||||||
} // CSS declaration object applied to the subtitle sidebar. Includes color, background-color, and all font properties.
|
} // CSS declaration object applied to the subtitle sidebar. Includes color, background-color, and all font properties.
|
||||||
}, // Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
|
}, // Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Subtitle Filters
|
||||||
|
// Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.
|
||||||
|
// Applies to the overlay, sidebar, mined sentences and stats.
|
||||||
|
// Hot-reload: filter changes apply to the current subtitle file immediately.
|
||||||
|
// ==========================================
|
||||||
|
"subtitleFilter": {
|
||||||
|
"presets": {
|
||||||
|
"parentheses": false, // Remove text in () and (), such as speaker names, readings and notes. A line wrapped entirely in parentheses, usually inner thoughts, is kept. Values: true | false
|
||||||
|
"brackets": false, // Remove text in [], [], 【】 and 〔〕, such as sound effects and music cues. Values: true | false
|
||||||
|
"speakerPrefix": false, // Remove a short name followed by a colon at the start of a line, as in 山田:元気? Values: true | false
|
||||||
|
"musicSymbols": false // Remove ♪, ♫ and ♬. A line left with only symbols such as ~ is removed. Values: true | false
|
||||||
|
}, // Built-in filters. Each removes its matches and is off by default.
|
||||||
|
"customRules": [] // Your own regex rules, applied in order after the presets. Each rule is { name, pattern, replacement, enabled }; patterns use the gmu flags, so ^ and $ match per line. Leave replacement empty to remove the match.
|
||||||
|
}, // Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// Shared AI Provider
|
// Shared AI Provider
|
||||||
// Canonical OpenAI-compatible provider transport settings shared by Anki and YouTube subtitle fixing.
|
// Canonical OpenAI-compatible provider transport settings shared by Anki and YouTube subtitle fixing.
|
||||||
@@ -976,7 +990,8 @@
|
|||||||
"apiKey": "", // Jimaku API key. Optional but recommended for higher rate limits. Get one for free at https://jimaku.cc.
|
"apiKey": "", // Jimaku API key. Optional but recommended for higher rate limits. Get one for free at https://jimaku.cc.
|
||||||
"apiKeyCommand": "", // Shell command that prints the Jimaku API key to stdout. Used instead of apiKey to avoid storing the key in plain text.
|
"apiKeyCommand": "", // Shell command that prints the Jimaku API key to stdout. Used instead of apiKey to avoid storing the key in plain text.
|
||||||
"languagePreference": "ja", // Preferred language used in Jimaku search. Values: ja | en | none
|
"languagePreference": "ja", // Preferred language used in Jimaku search. Values: ja | en | none
|
||||||
"maxEntryResults": 10 // Maximum Jimaku search results returned.
|
"maxEntryResults": 10, // Maximum Jimaku search results returned.
|
||||||
|
"autoOpenWhenPrimarySubtitleMissing": false // Pause playback and open the Jimaku modal when a local video has no subtitle track in youtube.primarySubLanguages (Japanese by default). Values: true | false
|
||||||
}, // Jimaku API configuration and defaults.
|
}, // Jimaku API configuration and defaults.
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -1065,8 +1080,8 @@
|
|||||||
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
|
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
|
||||||
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
|
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
|
||||||
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
|
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
|
||||||
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
|
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
|
||||||
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
|
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
|
||||||
}, // SubMiner-managed mpv launch and bundled plugin options.
|
}, // SubMiner-managed mpv launch and bundled plugin options.
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ Built into the overlay, not configurable:
|
|||||||
| Input | Action |
|
| Input | Action |
|
||||||
| ------------------------- | -------------------------------------------------- |
|
| ------------------------- | -------------------------------------------------- |
|
||||||
| `V` | Cycle primary subtitle bar: hidden, visible, hover |
|
| `V` | Cycle primary subtitle bar: hidden, visible, hover |
|
||||||
|
| `C` (keyboard-only mode) | Move by word or by character |
|
||||||
| Right-click | Pause or resume (outside the subtitle area) |
|
| Right-click | Pause or resume (outside the subtitle area) |
|
||||||
| Right-click + drag | Move the subtitles |
|
| Right-click + drag | Move the subtitles |
|
||||||
| Drop files on the overlay | Replace the mpv playlist |
|
| Drop files on the overlay | Replace the mpv playlist |
|
||||||
|
|||||||
@@ -51,6 +51,17 @@ When `connect ENOENT /tmp/subminer-socket` follows a cast in the app log, SubMin
|
|||||||
- Confirm SubMiner is running (`SubMiner.AppImage --start`, or check for the process).
|
- Confirm SubMiner is running (`SubMiner.AppImage --start`, or check for the process).
|
||||||
- Linux: Hyprland and Sway work natively. Any other compositor needs mpv and SubMiner under X11 or Xwayland, with `xdotool`, `xprop`, and `xwininfo` installed. See [KDE Plasma and other Wayland compositors](#kde-plasma-and-other-wayland-compositors).
|
- Linux: Hyprland and Sway work natively. Any other compositor needs mpv and SubMiner under X11 or Xwayland, with `xdotool`, `xprop`, and `xwininfo` installed. See [KDE Plasma and other Wayland compositors](#kde-plasma-and-other-wayland-compositors).
|
||||||
- macOS: grant Accessibility permission. See [macOS](#macos).
|
- macOS: grant Accessibility permission. See [macOS](#macos).
|
||||||
|
- Windows: leave the affected mpv window open for at least five seconds, then collect the daily
|
||||||
|
app log from the directory above. No debug setting is required: a stalled overlay logs
|
||||||
|
`Windows overlay is not visible after startup or tracking loss` with its PID, native window
|
||||||
|
handle, tracking state, geometry, opacity, and renderer readiness. The `reason` distinguishes
|
||||||
|
a missing mpv window, an unready renderer, a hidden window, and a transparent window.
|
||||||
|
This warning waits until mpv has answered on its IPC socket, so a requested overlay with no
|
||||||
|
mpv running stays quiet. PID lookup failures and native ownership or transparency errors also
|
||||||
|
appear at `warn`, and a PID lookup failure is the only trace if mpv never answers.
|
||||||
|
Repeated visibility/native-operation warnings are limited to one every 30 seconds; recovery
|
||||||
|
is recorded too. These logs diagnose attachment and readiness, but cannot prove that pixels
|
||||||
|
were drawn correctly by the graphics driver.
|
||||||
|
|
||||||
## Overlay is on the wrong monitor or position
|
## Overlay is on the wrong monitor or position
|
||||||
|
|
||||||
@@ -179,6 +190,10 @@ Another app or your desktop already uses `Alt+Shift+Y` (Yomitan settings). Free
|
|||||||
|
|
||||||
Overlay shortcuts only work while the overlay has focus. Click the overlay, or press `Alt+Shift+O` with mpv or the overlay focused.
|
Overlay shortcuts only work while the overlay has focus. Click the overlay, or press `Alt+Shift+O` with mpv or the overlay focused.
|
||||||
|
|
||||||
|
## An mpv key does nothing over the overlay
|
||||||
|
|
||||||
|
Keys from `input.conf` reach mpv through the overlay only in some cases (see [automatic mpv bindings](/shortcuts#automatic-mpv-bindings)). Run with `--log-level debug` and press the key: an `Overlay kept an mpv-bound key` line names the reason. To make a key work everywhere, add it to [`keybindings`](/configuration#keybindings) instead.
|
||||||
|
|
||||||
## Update checks
|
## Update checks
|
||||||
|
|
||||||
**"Update check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`.
|
**"Update check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`.
|
||||||
|
|||||||
+9
-2
@@ -160,11 +160,13 @@ On Wayland, the tray icon only appears if your panel provides a StatusNotifier (
|
|||||||
You can drive the overlay with a gamepad.
|
You can drive the overlay with a gamepad.
|
||||||
|
|
||||||
1. Set `controller.enabled` to `true` in your config.
|
1. Set `controller.enabled` to `true` in your config.
|
||||||
2. Connect a controller. SubMiner uses the first one it sees.
|
2. Connect a controller and press a button. SubMiner uses the first one it sees and announces it through [`ankiConnect.behavior.notificationType`](/configuration#ankiconnect).
|
||||||
3. Press `Y` on the controller to turn on keyboard-only mode. Most controller actions only work in this mode.
|
3. Press `Y` on the controller to turn on keyboard-only mode. Most controller actions only work in this mode.
|
||||||
4. Move between words with the left stick, press `A` to look one up, and `X` to mine it.
|
4. Move between words with the left stick, press `A` to look one up, and `X` to mine it.
|
||||||
|
|
||||||
Press `Alt+C` to choose a controller and remap buttons. Click an action's **Learn** button, then press the button you want. Set **Button Style** to Xbox, Nintendo or PlayStation so buttons are named as printed on your controller; it is saved per controller. Changes apply right away. When two actions share an input, both fire, so their rows show a ⚠ warning naming the other action; this includes a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action. The window only sees a controller after you press one of its buttons; until then it shows the bindings of the controller in use as a preview, and editing stays locked. With several controllers connected, it selects the one you pressed last. `Alt+Shift+C` shows raw input values for unusual pads.
|
Press `Alt+C` to choose a controller and remap buttons. Click an action's **Learn** button, then press the button you want, or hold one button and press another to make a combo such as `L1` + D-pad right. Set **Button Style** to Xbox, Nintendo or PlayStation so buttons are named as printed on your controller; it is saved per controller. Changes apply right away. When two actions share an input, both fire, so their rows show a ⚠ warning naming the other action; this includes a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action. The window only sees a controller after you press one of its buttons; until then it shows the bindings of the controller in use as a preview, and editing stays locked. With several controllers connected, it selects the one you pressed last. `Alt+Shift+C` shows raw input values for unusual pads.
|
||||||
|
|
||||||
|
A combo fires each time you press its second button while the first is down, so holding `L1` and pressing right twice runs it twice. While a combo's hold button is down, other buttons only run combos that use it, and its press no longer drives a **(D-pad)** or stick row. A hold button can keep its own action: that action then runs when you let go, unless you pressed another bound button during the hold. The exception is **Show Secondary Subtitle (Hold)**, which can't wait for release, so its row warns if it shares a hold button.
|
||||||
|
|
||||||
| Button | Action |
|
| Button | Action |
|
||||||
| --------------------- | -------------------------------------- |
|
| --------------------- | -------------------------------------- |
|
||||||
@@ -184,6 +186,7 @@ Press `Alt+C` to choose a controller and remap buttons. Click an action's **Lear
|
|||||||
| Unbound by default | Previous / next subtitle line |
|
| Unbound by default | Previous / next subtitle line |
|
||||||
| Unbound by default | Replay the current line, then pause |
|
| Unbound by default | Replay the current line, then pause |
|
||||||
| Unbound by default | Play the next line, then pause |
|
| Unbound by default | Play the next line, then pause |
|
||||||
|
| Unbound by default | Move by word or by character |
|
||||||
|
|
||||||
The secondary subtitle hold works with or without keyboard-only mode. Assign it with **Learn** on the **Show Secondary Subtitle (Hold)** row in `Alt+C`. While held, the secondary subtitle shows as if its mode were `visible`; releasing the button returns it to your chosen mode.
|
The secondary subtitle hold works with or without keyboard-only mode. Assign it with **Learn** on the **Show Secondary Subtitle (Hold)** row in `Alt+C`. While held, the secondary subtitle shows as if its mode were `visible`; releasing the button returns it to your chosen mode.
|
||||||
|
|
||||||
@@ -191,10 +194,14 @@ The **Subtitles** rows in `Alt+C` do the same as the keyboard shortcuts: **Previ
|
|||||||
|
|
||||||
**Previous Entry** and **Next Entry** move one word entry at a time in the open popup, and Mine Card then mines the selected entry. They send Yomitan's default `Alt+Up` / `Alt+Down` entry shortcuts, so they stop working if you rebind those in Yomitan's keyboard settings. If you assign them to the D-pad, click **Clear** on the **Popup Scroll (D-pad)** row too, or the D-pad will also scroll the popup.
|
**Previous Entry** and **Next Entry** move one word entry at a time in the open popup, and Mine Card then mines the selected entry. They send Yomitan's default `Alt+Up` / `Alt+Down` entry shortcuts, so they stop working if you rebind those in Yomitan's keyboard settings. If you assign them to the D-pad, click **Clear** on the **Popup Scroll (D-pad)** row too, or the D-pad will also scroll the popup.
|
||||||
|
|
||||||
|
When the subtitle is split in the wrong place, a word can start in the middle of a box (in もっとハ|キ|ハキしなくちゃ, ハキハキ starts at the last character of the first box) and moving by word never reaches it. In keyboard-only mode, press `C` on the keyboard, or the **Toggle Character Navigation** button (unbound by default, under **Navigation** in `Alt+C`), to move one character at a time: the box turns orange and covers one character, and a lookup searches from that character, so Yomitan finds the longest word starting there. Press it again to go back to moving by word. It stays on until you switch it back, even after leaving keyboard-only mode.
|
||||||
|
|
||||||
The media timing review and duplicate card (field grouping) dialogs have their own controller layouts, which you can change in the **Review media timing** and **Duplicate card (field grouping)** groups of `Alt+C`; see [Review media timing](/anki-integration#with-a-controller) and [Field grouping](/anki-integration#field-grouping-with-a-controller).
|
The media timing review and duplicate card (field grouping) dialogs have their own controller layouts, which you can change in the **Review media timing** and **Duplicate card (field grouping)** groups of `Alt+C`; see [Review media timing](/anki-integration#with-a-controller) and [Field grouping](/anki-integration#field-grouping-with-a-controller).
|
||||||
|
|
||||||
On controllers that report the W3C standard layout, the default quit button lands on `L2` instead of `Select`, and the default pause button on `Start` instead of `L3`. The default right-stick popup jump does nothing on these controllers; click **Learn** on **Popup Jump (Stick)** and move the right stick up or down to set it. Remap anything else with `Alt+C`, which names buttons according to the layout your controller reports. All options are in [Configuration](/configuration#controller-support).
|
On controllers that report the W3C standard layout, the default quit button lands on `L2` instead of `Select`, and the default pause button on `Start` instead of `L3`. The default right-stick popup jump does nothing on these controllers; click **Learn** on **Popup Jump (Stick)** and move the right stick up or down to set it. Remap anything else with `Alt+C`, which names buttons according to the layout your controller reports. All options are in [Configuration](/configuration#controller-support).
|
||||||
|
|
||||||
|
On macOS, a controller only reaches the app in front. When mpv is in front, a controller button brings the overlay to the front and then runs that button's action. With more than one controller connected, that first press only brings the overlay to the front; press the button again to run its action. Stick movements only work once the overlay is in front. Buttons pressed while another app is in front are left alone.
|
||||||
|
|
||||||
## Development profiles
|
## Development profiles
|
||||||
|
|
||||||
`--dev` and `--debug` use a separate `SubMiner-dev` profile. They do not read or modify dictionaries and configuration from the installed app unless `SUBMINER_USE_PRODUCTION_PROFILE=1` is explicitly set. See [Development](/development#run-locally).
|
`--dev` and `--debug` use a separate `SubMiner-dev` profile. They do not read or modify dictionaries and configuration from the installed app unless `SUBMINER_USE_PRODUCTION_PROFILE=1` is explicitly set. See [Development](/development#run-locally).
|
||||||
|
|||||||
@@ -229,7 +229,7 @@ script-message subminer-start backend=hyprland socket=/custom/path texthooker=no
|
|||||||
|
|
||||||
The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts.
|
The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts.
|
||||||
|
|
||||||
While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro, and `subminer-aniskip-refresh` reloads intro data, for example after your script changes title or episode metadata.
|
While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro or outro that is playing, and `subminer-aniskip-refresh` reloads intro and outro data, for example after your script changes title or episode metadata.
|
||||||
|
|
||||||
## Related pages
|
## Related pages
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
# Architecture Map
|
# Architecture Map
|
||||||
|
|
||||||
Status: active
|
Status: active
|
||||||
Last verified: 2026-05-23
|
Last verified: 2026-11-01
|
||||||
Owner: Kyle Yasuda
|
Owner: Kyle Yasuda
|
||||||
Read when: runtime ownership, composition boundaries, or layering questions
|
Read when: runtime ownership, composition boundaries, or layering questions
|
||||||
|
|
||||||
@@ -30,14 +30,14 @@ Update checks and startup launcher migration share a serialized update-state sto
|
|||||||
|
|
||||||
- `src/main/` owns composition, runtime setup, IPC wiring, and app lifecycle adapters.
|
- `src/main/` owns composition, runtime setup, IPC wiring, and app lifecycle adapters.
|
||||||
- `src/main/boot/` owns boot-phase assembly seams so `src/main.ts` can stay focused on lifecycle coordination and startup-path selection.
|
- `src/main/boot/` owns boot-phase assembly seams so `src/main.ts` can stay focused on lifecycle coordination and startup-path selection.
|
||||||
- `src/main/runtime/linux-overlay-mode-runtime.ts` owns Linux fullscreen mode state and window replacement. App cleanup cancels pending replacements; `main.ts` supplies window creation and subtitle refresh hooks.
|
- `src/main/runtime/linux-overlay-mode-runtime.ts` owns Linux fullscreen mode state and window replacement. App cleanup cancels pending replacements; the overlay assembly supplies window creation and subtitle refresh hooks.
|
||||||
- `src/core/services/` owns focused runtime services plus pure or side-effect-bounded logic.
|
- `src/core/services/` owns focused runtime services plus pure or side-effect-bounded logic.
|
||||||
- `src/core/services/subtitle-generation*.ts` shares local whisper.cpp transcription, safe model downloads, and progress between the launcher and Electron. Optional dialogue mode retains both Silero-detected speech and other audible sections, omits confidently silent gaps, decodes passages independently, and restores original media timing. `src/main/runtime/subtitle-generation-runtime.ts` owns the overlay job lifecycle and only loads completed subtitles into the same media. For Jellyfin playback it reads the item's original-file stream (`toJellyfinOriginalStreamUrl`) into one reused output folder, where each run best-effort deletes earlier files and writes a uniquely named SRT; transcoded playback uses Jellyfin's audio index and only external references, since mpv's track indexes describe the transcode. Subprocess errors redact URL tokens; `src/shared/subtitle-generation*.ts` owns configuration, the multilingual model catalog, and IPC contracts. The overlay runtime retains a session model selection, validates picker requests through IPC, and keeps external model paths authoritative.
|
- `src/core/services/subtitle-generation*.ts` shares local whisper.cpp transcription, safe model downloads, and progress between the launcher and Electron. Optional dialogue mode retains both Silero-detected speech and other audible sections, omits confidently silent gaps, decodes passages independently, and restores original media timing. `src/main/runtime/subtitle-generation-runtime.ts` owns the overlay job lifecycle and only loads completed subtitles into the same media. For Jellyfin playback it reads the item's original-file stream (`toJellyfinOriginalStreamUrl`) into one reused output folder, where each run best-effort deletes earlier files and writes a uniquely named SRT; transcoded playback uses Jellyfin's audio index and only external references, since mpv's track indexes describe the transcode. Subprocess errors redact URL tokens; `src/shared/subtitle-generation*.ts` owns configuration, the multilingual model catalog, and IPC contracts. The overlay runtime retains a session model selection, validates picker requests through IPC, and keeps external model paths authoritative.
|
||||||
- Subtitle model recommendations use bounded `nvidia-smi` and Whisper CUDA discovery probes in `subtitle-generation-acceleration.ts`. The overlay runtime caches results by executable path for 30 seconds and exposes acceleration status through the existing status IPC. Recommendations do not alter model selection or transcription arguments.
|
- Subtitle model recommendations use bounded `nvidia-smi` and Whisper CUDA discovery probes in `subtitle-generation-acceleration.ts`. The overlay runtime caches results by executable path for 30 seconds and exposes acceleration status through the existing status IPC. Recommendations do not alter model selection or transcription arguments.
|
||||||
- `subtitle-generation-reference.ts` ranks mpv's loaded text subtitle tracks, excludes signs/songs and forced references, and extracts timing hints with FFmpeg. The overlay and launcher snapshot references only for matching media, including active subtitle delays. Hints guide long-passage cuts with or without VAD; they never limit audio coverage or replace Whisper timestamps.
|
- `subtitle-generation-reference.ts` ranks mpv's loaded text subtitle tracks, excludes signs/songs and forced references, and extracts timing hints with FFmpeg. The overlay and launcher snapshot references only for matching media, including active subtitle delays. Hints guide long-passage cuts with or without VAD; they never limit audio coverage or replace Whisper timestamps.
|
||||||
- `src/main/runtime/subtitle-selection.ts` reads and validates mpv subtitle tracks and applies primary/secondary selections. Its opt-in session shortcut opens the shared overlay modal window, with renderer focus and subtitle suppression handled by the modal registry.
|
- `src/main/runtime/subtitle-selection.ts` reads and validates mpv subtitle tracks and applies primary/secondary selections. Its opt-in session shortcut opens the shared overlay modal window, with renderer focus and subtitle suppression handled by the modal registry.
|
||||||
- `src/shared/session-key-sequences.ts` rejects sequence prefixes reserved by single-key actions. The session-binding compiler reserves configured and built-in overlay keys; `src/main/runtime/session-bindings-runtime.ts` adds active mpv bindings and publishes the effective list to both the plugin artifact and the renderer through `session-bindings:changed`. mpv no-op `ignore` bindings do not reserve prefixes.
|
- `src/shared/session-key-sequences.ts` rejects sequence prefixes reserved by single-key actions. The session-binding compiler reserves configured and built-in overlay keys; `src/main/runtime/session-bindings-runtime.ts` adds active mpv bindings and publishes the effective list to both the plugin artifact and the renderer through `session-bindings:changed`. mpv no-op `ignore` bindings do not reserve prefixes.
|
||||||
- `src/core/services/plugins/` owns user plugins: discovery from `<config dir>/plugins/<id>/plugin.json` for ids enabled in `plugins`, the per-plugin `ctx`, guarded callbacks, and `exec` (no shell, AppImage `LD_LIBRARY_PATH` dropped). `main.ts` supplies the host's deps, attaches each new mpv client so plugin listeners survive client replacement, starts plugins from the app-ready path after logging is configured, and unloads them first in the `will-quit` cleanup, before any teardown. Plugins run in the main process with no sandbox. `src/plugin-api.ts` is the standalone public v1 type contract; internal mpv event and session-action types derive from it. Manifests may declare `apiVersion`, which is checked before loading code. Async activation is bounded and actions wait only for their own plugin. The host owns cached media snapshots and playback ids, including repeated loads of the same path. `ctx.signal` aborts as unloading starts; `ctx.onDispose` manages outside resources and late registrations are disposed immediately. Awaitable `ctx.mpv.request` uses the existing request/response transport. Plugin actions are the `runPluginAction` session action (keybinding command `__plugin-action:<id>/<name>`, CLI `--plugin-action <id>/<name>`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `<config dir>/plugin-data/<id>/` as `ctx.dataDir`. `ctx.anki` carries the `card-mined` event with unique kept `noteIds` and per-original-note records. Sentence-card creation snapshots media and subtitle context before asynchronous work; the proxy snapshots before forwarding an upstream request. `AnkiIntegration` keeps provenance under original ids through merges and queued YouTube jobs; polling uses null provenance. The event is fed by `AnkiIntegration.setCardsReadyCallback`: polling, the AnkiConnect proxy, and sentence-card creation report a note once its enrichment finishes (or when they see it, if auto-update is off); `AnkiIntegration` holds a sentence card's report until field grouping finishes, and the pending YouTube media queue reports notes whose media it is still waiting on (directly or through the note field grouping merged them into), which is later than `recordCardsMined` (stats counts at add time). Stats-dashboard mining does not emit it. `ctx.anki.invoke` sends one action to the effective `ankiConnect.url` with no retries. `src/main/runtime/plugin-window-runtime.ts` owns plugin windows (`ctx.ui.openWindow`): one window per plugin + HTML path, raised above the overlay like the settings windows, destroyed on unload. `src/main/runtime/plugin-panel-runtime.ts` owns the single `plugin-panel` modal: a new panel aborts the previous handle's signal, updates broadcast to both overlay windows keyed by `panelId`, and the latest content is re-sent once the renderer acknowledges the open.
|
- `src/core/services/plugins/` owns user plugins: discovery from `<config dir>/plugins/<id>/plugin.json` for ids enabled in `plugins`, the per-plugin `ctx`, guarded callbacks, and `exec` (no shell, AppImage `LD_LIBRARY_PATH` dropped). `src/main/assemblies/plugins.ts` builds the host. The playback assembly attaches each new mpv client so plugin listeners survive client replacement, the startup assembly starts plugins from the app-ready path after logging is configured, and the `will-quit` cleanup unloads them first, before any teardown. Plugins run in the main process with no sandbox. `src/plugin-api.ts` is the standalone public v1 type contract; internal mpv event and session-action types derive from it. Manifests may declare `apiVersion`, which is checked before loading code. Async activation is bounded and actions wait only for their own plugin. The host owns cached media snapshots and playback ids, including repeated loads of the same path. `ctx.signal` aborts as unloading starts; `ctx.onDispose` manages outside resources and late registrations are disposed immediately. Awaitable `ctx.mpv.request` uses the existing request/response transport. Plugin actions are the `runPluginAction` session action (keybinding command `__plugin-action:<id>/<name>`, CLI `--plugin-action <id>/<name>`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `<config dir>/plugin-data/<id>/` as `ctx.dataDir`. `ctx.anki` carries the `card-mined` event with unique kept `noteIds` and per-original-note records. Sentence-card creation snapshots media and subtitle context before asynchronous work; the proxy snapshots before forwarding an upstream request. `AnkiIntegration` keeps provenance under original ids through merges and queued YouTube jobs; polling uses null provenance. The event is fed by `AnkiIntegration.setCardsReadyCallback`: polling, the AnkiConnect proxy, and sentence-card creation report a note once its enrichment finishes (or when they see it, if auto-update is off); `AnkiIntegration` holds a sentence card's report until field grouping finishes, and the pending YouTube media queue reports notes whose media it is still waiting on (directly or through the note field grouping merged them into), which is later than `recordCardsMined` (stats counts at add time). Stats-dashboard mining does not emit it. `ctx.anki.invoke` sends one action to the effective `ankiConnect.url` with no retries. `src/main/runtime/plugin-window-runtime.ts` owns plugin windows (`ctx.ui.openWindow`): one window per plugin + HTML path, raised above the overlay like the settings windows, destroyed on unload. `src/main/runtime/plugin-panel-runtime.ts` owns the single `plugin-panel` modal: a new panel aborts the previous handle's signal, updates broadcast to both overlay windows keyed by `panelId`, and the latest content is re-sent once the renderer acknowledges the open.
|
||||||
- `src/renderer/` owns overlay rendering and input behavior.
|
- `src/renderer/` owns overlay rendering and input behavior.
|
||||||
- `src/config/` owns config definitions, defaults, loading, and resolution.
|
- `src/config/` owns config definitions, defaults, loading, and resolution.
|
||||||
- `src/types/` owns shared cross-runtime contracts via domain entrypoints; `src/types.ts` stays a compatibility barrel.
|
- `src/types/` owns shared cross-runtime contracts via domain entrypoints; `src/types.ts` stays a compatibility barrel.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
# Domain Ownership
|
# Domain Ownership
|
||||||
|
|
||||||
Status: active
|
Status: active
|
||||||
Last verified: 2026-10-31
|
Last verified: 2026-11-01
|
||||||
Owner: Kyle Yasuda
|
Owner: Kyle Yasuda
|
||||||
Read when: you need to find the owner module for a behavior or test surface
|
Read when: you need to find the owner module for a behavior or test surface
|
||||||
|
|
||||||
@@ -23,19 +23,38 @@ Read when: you need to find the owner module for a behavior or test surface
|
|||||||
- App startup: app-ready sequence, headless known-word refresh, overlay startup prerequisites and
|
- App startup: app-ready sequence, headless known-word refresh, overlay startup prerequisites and
|
||||||
overlay runtime bootstrap: `src/main/assemblies/startup.ts`
|
overlay runtime bootstrap: `src/main/assemblies/startup.ts`
|
||||||
- Overlay/window state: `src/core/services/overlay-*`, `src/main/overlay-*.ts`
|
- Overlay/window state: `src/core/services/overlay-*`, `src/main/overlay-*.ts`
|
||||||
Overlay windows, visibility, Linux fullscreen handling, and the overlay-window IPC handlers
|
Overlay windows, visibility, geometry and pointer interaction, Linux fullscreen handling, mpv
|
||||||
(modal open/close, pointer interaction, content measurement): `src/main/assemblies/overlay.ts`
|
subtitle suppression while the overlay shows, and the overlay-window IPC handlers (modal
|
||||||
|
open/close, pointer interaction, content measurement): `src/main/assemblies/overlay.ts`
|
||||||
Overlay-hosted modal openers: `src/main/assemblies/overlay-modals.ts`
|
Overlay-hosted modal openers: `src/main/assemblies/overlay-modals.ts`
|
||||||
|
Windows window tracking: `src/window-trackers/windows-tracker.ts` queries the target mpv IPC
|
||||||
|
socket for its PID through `mpv-process-id.ts`, then `win32.ts` matches native windows by PID.
|
||||||
|
Visible matches are revalidated every 10 seconds; a PID expires after 30 seconds without a
|
||||||
|
successful IPC response. Missing windows retry at one-second intervals. Custom executable
|
||||||
|
names remain supported because matching uses the IPC PID.
|
||||||
|
`src/core/services/overlay-visibility-diagnostics.ts` watches requested Windows overlays:
|
||||||
|
after five seconds hidden or transparent it logs a warn-level snapshot, repeating at most
|
||||||
|
every 30 seconds. Intentional hiding, minimization and having no mpv answer on the socket
|
||||||
|
yet suppress these warnings; an identified mpv whose window never matches does not. PID lookup
|
||||||
|
failures and native ownership/transparency failures also log at warn, including recovery.
|
||||||
- MPV runtime and protocol: `src/core/services/mpv*.ts`
|
- MPV runtime and protocol: `src/core/services/mpv*.ts`
|
||||||
mpv client creation, mpv event wiring, AniSkip, subtitle prefetch, and subtitle sidebar state: `src/main/assemblies/playback.ts`
|
mpv client creation, mpv event wiring, AniSkip, the autoplay-ready gate that releases mpv's
|
||||||
|
startup pause, managed local subtitle selection, subtitle prefetch, and subtitle sidebar state:
|
||||||
|
`src/main/assemblies/playback.ts`
|
||||||
- Keyboard input outside the renderer (overlay, global and numeric shortcuts, session bindings):
|
- Keyboard input outside the renderer (overlay, global and numeric shortcuts, session bindings):
|
||||||
`src/main/assemblies/shortcuts.ts`
|
`src/main/assemblies/shortcuts.ts`
|
||||||
|
- Session actions (the dispatcher behind shortcuts, controller buttons, CLI commands and plugin
|
||||||
|
actions), the secondary-subtitle mode cycle, and the overlay renderer's mpv commands:
|
||||||
|
`src/main/assemblies/session-actions.ts`
|
||||||
- System tray: `src/main/assemblies/tray.ts`
|
- System tray: `src/main/assemblies/tray.ts`
|
||||||
- Yomitan/Hachidori extension loading, parser runtime deps, and dictionary settings windows:
|
- Yomitan/Hachidori extension loading, parser runtime deps, and dictionary settings windows:
|
||||||
`src/main/assemblies/yomitan.ts`
|
`src/main/assemblies/yomitan.ts`
|
||||||
Windows executable lookup and detached process creation are shared in `src/main/runtime/mpv-process.ts`. The Windows launcher and Jellyfin handlers retain their own playback and connection workflows.
|
Windows executable lookup and detached process creation are shared in `src/main/runtime/mpv-process.ts`. The Windows launcher and Jellyfin handlers retain their own playback and connection workflows.
|
||||||
- Subtitle/token pipeline: `src/core/services/subtitle-*.ts`, `src/core/services/tokenizer*`, `src/core/services/tokenizer/`, `src/subsync/`
|
- Subtitle/token pipeline: `src/core/services/subtitle-*.ts`, `src/core/services/tokenizer*`, `src/core/services/tokenizer/`, `src/subsync/`
|
||||||
JLPT and frequency annotation lookups: `src/main/jlpt-runtime.ts`, `src/main/frequency-dictionary-runtime.ts`, assembled by `src/main/assemblies/dictionaries.ts`
|
JLPT and frequency annotation lookups: `src/main/jlpt-runtime.ts`, `src/main/frequency-dictionary-runtime.ts`, assembled by `src/main/assemblies/dictionaries.ts`
|
||||||
|
Annotation toggles (a cycled runtime option over its config value): `src/main/runtime/annotation-options.ts`
|
||||||
|
Whisper subtitle generation runtime, modal and IPC: `src/main/assemblies/subtitle-generation.ts`
|
||||||
|
Subtitle text filters (`subtitleFilter`): `src/shared/subtitle-text-filter.ts`. Primary text is filtered at its two entry points, live `sub-text` in `mpv-protocol.ts` and parsed cues in `playback.ts`, so every consumer sees the same text and live/cue matching still works. A config change re-reads `sub-text` and re-parses the active track (the prefetch controller's parse key).
|
||||||
- First-run setup: `src/main/runtime/first-run-setup-*.ts`, assembled by `src/main/assemblies/first-run-setup.ts`
|
- First-run setup: `src/main/runtime/first-run-setup-*.ts`, assembled by `src/main/assemblies/first-run-setup.ts`
|
||||||
- Anki workflow: `src/anki-integration/`, `src/core/services/anki-jimaku*.ts`
|
- Anki workflow: `src/anki-integration/`, `src/core/services/anki-jimaku*.ts`
|
||||||
Card mining handlers, the pending lookup context, field grouping, and media timing review wiring:
|
Card mining handlers, the pending lookup context, field grouping, and media timing review wiring:
|
||||||
@@ -45,16 +64,18 @@ Read when: you need to find the owner module for a behavior or test surface
|
|||||||
the stats overlay window options, and the `--stats` command are assembled by `src/main/assemblies/stats.ts`
|
the stats overlay window options, and the `--stats` command are assembled by `src/main/assemblies/stats.ts`
|
||||||
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
|
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
|
||||||
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
|
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
|
||||||
|
Franchise grouping is a view over `imm_anime`, never a merge: `query-library-groups.ts` groups library rows by union-find over the AniList relation cache (`imm_anilist_media` + `imm_anilist_relations`, written by `anilist-relation-cache.ts`; pure graph and walk in `anilist/franchise-graph.ts`, where `FRANCHISE_RELATION_TYPES` is the joining set). `franchise-relation-refresher.ts` walks from owned AniList ids (bounded depth and fetches per run, 7-day staleness, shared AniList rate limiter) when the grouped library is read, after cover art links an id, and after manual AniList or group changes; a failed fetch leaves cached rows untouched. `imm_anime.group_override` (NULL = AniList, 0 = on its own, positive = join the franchise containing that AniList id) is the only user state; `/api/stats/anime/groups` and `PUT /api/stats/anime/:id/group` expose it.
|
||||||
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
|
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
|
||||||
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
|
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
|
||||||
|
`imm_anime.group_override` merges last-writer-wins on `group_override_updated_at` (clears carry a timestamp too); its values are AniList ids, so no id remapping. The AniList relation cache is not merged: each machine rebuilds it, and stale or partial remote cache rows would otherwise outlive the 7-day refresh.
|
||||||
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
|
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
|
||||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`
|
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`. Every consumer maps a parsed title + season to an AniList entry through `anilist/season-resolver.ts` (sequel-chain walk; see its header for what counts as a season). Changing what it returns needs a `MEDIA_RESOLUTION_CACHE_VERSION` bump in `character-dictionary-runtime/cache.ts`, or old matches keep being served from `anilist-resolution-cache.json`.
|
||||||
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
|
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
|
||||||
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
|
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
|
||||||
assembled by `src/main/assemblies/jellyfin.ts`
|
assembled by `src/main/assemblies/jellyfin.ts`
|
||||||
- YouTube playback, subtitles, media cache, and in-app browser: `src/core/services/youtube/`,
|
- YouTube playback, subtitles, media cache, and in-app browser: `src/core/services/youtube/`,
|
||||||
`src/main/runtime/youtube-*`, assembled by `src/main/assemblies/youtube.ts`
|
`src/main/runtime/youtube-*`, assembled by `src/main/assemblies/youtube.ts`
|
||||||
- User plugins: `src/core/services/plugins/` (host, `ctx`, `exec`), `src/main/runtime/plugin-panel-runtime.ts` (panel modal), `src/main/runtime/plugin-window-runtime.ts` (plugin windows), `src/renderer/modals/plugin-panel*.ts`; examples in `assets/plugins/`
|
- User plugins: `src/core/services/plugins/` (host, `ctx`, `exec`), `src/main/runtime/plugin-panel-runtime.ts` (panel modal), `src/main/runtime/plugin-window-runtime.ts` (plugin windows), assembled by `src/main/assemblies/plugins.ts`; `src/renderer/modals/plugin-panel*.ts`; examples in `assets/plugins/`
|
||||||
- Window trackers: `src/window-trackers/`
|
- Window trackers: `src/window-trackers/`
|
||||||
- Stats HTTP app: `src/core/services/stats-server.ts`, with route groups and shared route support
|
- Stats HTTP app: `src/core/services/stats-server.ts`, with route groups and shared route support
|
||||||
in `src/core/services/stats-server/`
|
in `src/core/services/stats-server/`
|
||||||
|
|||||||
@@ -12,20 +12,42 @@ Trend charts now consume one chart-oriented backend payload from `/api/stats/tre
|
|||||||
- collapse multiple network round-trips into one request
|
- collapse multiple network round-trips into one request
|
||||||
- keep heavy chart shaping close to tracker/query logic
|
- keep heavy chart shaping close to tracker/query logic
|
||||||
|
|
||||||
|
## Date Ranges And Buckets
|
||||||
|
|
||||||
|
- A range resolves to calendar days (`resolveTrendWindow`). Rollups are selected by day span, never by "last N rows", so sparse activity cannot pull older days into a range. Custom ranges are `{ startDay, endDay }` from `range=custom&fromDay&toDay`.
|
||||||
|
- `all` spans the recorded data, not today.
|
||||||
|
- Day and week buckets read daily rollups. Month buckets read monthly rollups for months wholly in range, because the `minimal` and `deep-history` retention presets prune daily rollups first, and daily rollups for a partly covered month. Weeks start on Monday.
|
||||||
|
- `buckets` is the one axis for `activity`, `progress`, and `ratios`, index for index. Charts use it to map a clicked bar back to its days.
|
||||||
|
- Each `progress` point is the total at the end of its period, and the chart adds the zero starting point.
|
||||||
|
|
||||||
## Data Sources
|
## Data Sources
|
||||||
|
|
||||||
- rollup-backed:
|
- rollup-backed:
|
||||||
- activity charts
|
- activity charts and running totals
|
||||||
- cumulative watch/cards/tokens/sessions trends
|
- `titleTimeline`: sparse per-title minutes for active days only, because a dense title x day payload grew to several MB
|
||||||
- per-anime watch/cards/tokens/episodes series
|
|
||||||
- session-metric-backed:
|
- session-metric-backed:
|
||||||
- lookup trends
|
- lookups and lookup rate
|
||||||
- lookup rate trends
|
- `watchTimeByDayHour`, attributed to the hour each session started
|
||||||
- watch-time by day-of-week/hour
|
- rollup word counts and session metrics share one session query per request (`getTrendSessionRows`), so the per-session display-word count runs once instead of once per rollup query
|
||||||
|
- `imm_videos.watched`-backed:
|
||||||
|
- finished episodes count each watched video once, on the last day it has a rollup, since the flag has no timestamp
|
||||||
- vocabulary-backed:
|
- vocabulary-backed:
|
||||||
- new-words trend reads permanent daily lexical rollups
|
- `getNewWordFirstSeenRows` folds `imm_words` rows into dictionary words first, because the table is unique on (headword, word, reading) and stores each conjugation separately
|
||||||
- rollup rows count only vocabulary-visible tokens and normalize mixed legacy timestamp units
|
- the aggregate scans every word, so it is cached per connection until `total_changes()` or `PRAGMA data_version` moves
|
||||||
- a persisted rollup version invalidates stale materializations and triggers an atomic background rebuild
|
- Trends new-word metrics exclude names; the Vocabulary tab offers both
|
||||||
|
- `imm_lexical_daily_rollups` is no longer read for new-word counts (it counts surface forms). Its version state still gates the `vocabulary_visible` backfill.
|
||||||
|
|
||||||
|
## Vocabulary Word List
|
||||||
|
|
||||||
|
`/api/stats/vocabulary/words` (`query-vocabulary-words.ts`) folds `imm_words` into dictionary words on the server and filters, sorts, and pages there, because a client-side list can only hold a slice of the table. The fold is cached per connection until a write, the same way as the new-word aggregate. `titles` is computed for the returned rows; sorting or filtering by it needs every word's count (about 900ms), so that map tolerates five minutes of staleness. Names are detected with `isProperNounPos2`, since merged tokens store tags like `固有名詞|一般`.
|
||||||
|
|
||||||
|
## Rates
|
||||||
|
|
||||||
|
Rates are `null` when the underlying data is under 30 active minutes or 2,000 words, and charts draw that as a gap. Daily views rate a trailing 7 calendar days, volume-weighted, which is why the query loads days before the range. Week and month views rate each bucket.
|
||||||
|
|
||||||
|
## Title Filter
|
||||||
|
|
||||||
|
`title` narrows totals, charts, and patterns. `librarySummary` and `titleTimeline` stay complete so the page can switch titles. New words have no per-title record, so `learning` and `summary.current.newWords` are `null` while filtered.
|
||||||
|
|
||||||
## Metric Semantics
|
## Metric Semantics
|
||||||
|
|
||||||
@@ -39,6 +61,6 @@ Stats data crosses the process boundary over HTTP only. Shared JSON models live
|
|||||||
|
|
||||||
The stats preload bridge remains limited to native window behavior such as confirmation-dialog layering. Do not add stats data request channels back to Electron IPC.
|
The stats preload bridge remains limited to native window behavior such as confirmation-dialog layering. Do not add stats data request channels back to Electron IPC.
|
||||||
|
|
||||||
The stats UI should treat the trends payload as chart-ready data. Presentation-only work in the client is fine, but rebuilding the main trend datasets from raw sessions should stay out of the render path.
|
The stats UI should treat the trends payload as chart-ready data. Presentation-only work in the client is fine (including the title timeline layout), but rebuilding the main trend datasets from raw sessions should stay out of the render path.
|
||||||
|
|
||||||
For session detail timelines, omitting `limit` now means "return the full retained session telemetry/history". Explicit `limit` remains available for bounded callers, but the default stats UI path should not trim long sessions to the newest 200 samples.
|
For session detail timelines, omitting `limit` now means "return the full retained session telemetry/history". Explicit `limit` remains available for bounded callers, but the default stats UI path should not trim long sessions to the newest 200 samples.
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
# Subtitle Overlay Priming
|
# Subtitle Overlay Priming
|
||||||
|
|
||||||
Status: active
|
Status: active
|
||||||
Last verified: 2026-08-19
|
Last verified: 2026-11-01
|
||||||
Owner: Kyle Yasuda
|
Owner: Kyle Yasuda
|
||||||
Read when: debugging subtitle state or blank Linux/X11 overlay windows when the visible overlay is shown or recreated
|
Read when: debugging subtitle state or blank Linux/X11 overlay windows when the visible overlay is shown or recreated
|
||||||
|
|
||||||
@@ -19,13 +19,14 @@ subtitles do not draw.
|
|||||||
|
|
||||||
## Entry Points
|
## Entry Points
|
||||||
|
|
||||||
- `src/main.ts` calls `primeCurrentSubtitleForVisibleOverlay()` when manual visible-overlay show
|
- The overlay assembly (`src/main/assemblies/overlay.ts`) calls
|
||||||
paths run.
|
`primeCurrentSubtitleForVisibleOverlay()` when manual visible-overlay show paths run.
|
||||||
- `src/main.ts` calls `restoreVisibleOverlayWindowShapeForShow()` before visible-overlay show
|
- It calls `restoreVisibleOverlayWindowShapeForShow()` before visible-overlay show actions on
|
||||||
actions on Linux, and `resetVisibleOverlayInputState()` restores a full shape instead of applying
|
Linux, and `resetVisibleOverlayInputState()` restores a full shape instead of applying an empty
|
||||||
an empty shape.
|
shape (both in `src/main/runtime/visible-overlay-interaction-runtime.ts`).
|
||||||
- `src/main.ts` also restores the Linux/X11 shape after applying mpv overlay bounds, so a newly
|
- `src/main/runtime/overlay-geometry-runtime.ts` also restores the Linux/X11 shape after applying
|
||||||
created 800x600 hidden Electron window cannot keep clipping after it is resized to mpv geometry.
|
mpv overlay bounds, so a newly created 800x600 hidden Electron window cannot keep clipping after
|
||||||
|
it is resized to mpv geometry.
|
||||||
- `primeCurrentSubtitleForVisibleOverlay()` delegates to
|
- `primeCurrentSubtitleForVisibleOverlay()` delegates to
|
||||||
`primeVisibleOverlaySubtitleFromMpv()` in `src/main/runtime/current-subtitle-snapshot.ts`.
|
`primeVisibleOverlaySubtitleFromMpv()` in `src/main/runtime/current-subtitle-snapshot.ts`.
|
||||||
- `restoreVisibleOverlayWindowShapeForShow()` delegates to `restoreLinuxOverlayWindowShape()` in
|
- `restoreVisibleOverlayWindowShapeForShow()` delegates to `restoreLinuxOverlayWindowShape()` in
|
||||||
@@ -54,7 +55,7 @@ Both `onSubtitleChange` and `refreshCurrentSubtitle` pause `subtitlePrefetchServ
|
|||||||
the matching `subtitleProcessingController` method, giving the visible overlay priority over
|
the matching `subtitleProcessingController` method, giving the visible overlay priority over
|
||||||
background prefetch work. Prefetch is not re-centered here: restarting the run per line
|
background prefetch work. Prefetch is not re-centered here: restarting the run per line
|
||||||
(`onSeek`) discarded the in-flight tokenization every time the subtitle changed, so only real
|
(`onSeek`) discarded the in-flight tokenization every time the subtitle changed, so only real
|
||||||
seeks restart it (see `onTimePosUpdate` in `src/main.ts`).
|
seeks restart it (see the time-pos handling in `src/main/assemblies/playback.ts`).
|
||||||
|
|
||||||
On an uncached autoplay prime the raw payload is emitted here and reported to the controller with
|
On an uncached autoplay prime the raw payload is emitted here and reported to the controller with
|
||||||
`notePlainSubtitleEmitted`, so the controller skips its own plain emit for that line and the
|
`notePlainSubtitleEmitted`, so the controller skips its own plain emit for that line and the
|
||||||
|
|||||||
@@ -44,10 +44,5 @@ good test looks like here.
|
|||||||
|
|
||||||
## Known Debt
|
## Known Debt
|
||||||
|
|
||||||
- `src/main/main-wiring.test.ts` and `src/renderer/renderer-init-order.test.ts` still
|
- `src/renderer/renderer-init-order.test.ts` still regexes `renderer.ts` to guard startup
|
||||||
regex `main.ts` / `renderer.ts` to guard startup ordering. Replace each test with a
|
ordering. Replace it with a behavioral test as that logic moves out of `renderer.ts`.
|
||||||
behavioral one as the logic moves out of `main.ts` closures.
|
|
||||||
- `src/main/runtime/overlay-geometry-runtime.ts` and
|
|
||||||
`src/main/runtime/visible-overlay-interaction-runtime.ts` value-import Electron, so they
|
|
||||||
cannot load under `bun test` and stay outside `src/main/assemblies/overlay.ts`. Inject
|
|
||||||
`screen`/`dialog` to make them testable and movable.
|
|
||||||
+4
-1
@@ -21,7 +21,10 @@ function videoOutputArgs(display: E2eDisplay): string[] {
|
|||||||
// gpu-next's Vulkan path (libplacebo over MoltenVK) segfaults on the first frame
|
// gpu-next's Vulkan path (libplacebo over MoltenVK) segfaults on the first frame
|
||||||
// on GitHub's paravirtual macOS GPU with libplacebo 7.387. `--vo=libmpv` is mpv's
|
// on GitHub's paravirtual macOS GPU with libplacebo 7.387. `--vo=libmpv` is mpv's
|
||||||
// cocoa-cb OpenGL output, which avoids it and still opens the window the overlay tracks.
|
// cocoa-cb OpenGL output, which avoids it and still opens the window the overlay tracks.
|
||||||
if (process.platform === 'darwin') return ['--vo=libmpv'];
|
// Each new decoder asks that render thread for a direct-rendering image and waits with no
|
||||||
|
// timeout. cocoa-cb only answers from its main queue, which can stall on this runner, so a
|
||||||
|
// `loadfile` could freeze mpv's core and its IPC for good. `--vd-lavc-dr=no` skips the request.
|
||||||
|
if (process.platform === 'darwin') return ['--vo=libmpv', '--vd-lavc-dr=no'];
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+127
-1
@@ -15,7 +15,7 @@ let started: Promise<Started> | undefined;
|
|||||||
|
|
||||||
function useSession(): Promise<Started> {
|
function useSession(): Promise<Started> {
|
||||||
started ??= (async () => {
|
started ??= (async () => {
|
||||||
const session = await startE2eSession();
|
const session = await startE2eSession({ config: { controller: { enabled: true } } });
|
||||||
try {
|
try {
|
||||||
return { session, overlay: await session.openPage(OVERLAY_PAGE) };
|
return { session, overlay: await session.openPage(OVERLAY_PAGE) };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -114,6 +114,45 @@ test(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// The other tests read the renderer over CDP, which works even if the window never appears.
|
||||||
|
// Windows keeps the overlay hidden until the tracker identifies mpv's window.
|
||||||
|
// Bun's node:test ignores the `skip` option, so this picks `test.skip` instead.
|
||||||
|
const testOnWindows = process.platform === 'win32' ? test : test.skip;
|
||||||
|
testOnWindows('visible overlay window appears over mpv', { timeout: TEST_TIMEOUT_MS }, async () => {
|
||||||
|
const { session } = await useSession();
|
||||||
|
await session.runAppCommand('--show-visible-overlay');
|
||||||
|
const mpvPid = await session.mpv.command('get_property', 'pid');
|
||||||
|
assert.equal(typeof mpvPid, 'number');
|
||||||
|
const main = await session.mainProcess();
|
||||||
|
await waitUntil(
|
||||||
|
() =>
|
||||||
|
main.evaluate<boolean>(
|
||||||
|
`(() => {
|
||||||
|
const electron = process.mainModule.require('electron');
|
||||||
|
const overlay = electron.BrowserWindow.getAllWindows().find(
|
||||||
|
(w) => w.webContents.getURL().includes(${JSON.stringify(OVERLAY_PAGE)}));
|
||||||
|
if (!overlay?.isVisible() || overlay.getOpacity() !== 1 ||
|
||||||
|
overlay.__subminerOverlayContentReady !== true) return false;
|
||||||
|
// The inspector's mainModule can be Electron's bootstrap module. Resolve app
|
||||||
|
// dependencies from the repository instead of that module's search paths.
|
||||||
|
const appRequire = process.mainModule.require('node:module').createRequire(
|
||||||
|
process.mainModule.require('node:path').resolve('package.json'));
|
||||||
|
const koffi = appRequire('koffi');
|
||||||
|
const getWindow = koffi.load('user32.dll').func(
|
||||||
|
'intptr __stdcall GetWindow(intptr hwnd, uint uCmd)');
|
||||||
|
const handle = overlay.getNativeWindowHandle();
|
||||||
|
const hwnd = handle.length >= 8 ? Number(handle.readBigUInt64LE(0)) : handle.readUInt32LE(0);
|
||||||
|
const owner = getWindow(hwnd, 4); // GW_OWNER
|
||||||
|
const win32 = appRequire(
|
||||||
|
process.mainModule.require('node:path').resolve('dist/window-trackers/win32.js'));
|
||||||
|
return win32.findMpvWindows(${JSON.stringify(mpvPid)}).matches.some(
|
||||||
|
(match) => match.hwnd === owner);
|
||||||
|
})()`,
|
||||||
|
),
|
||||||
|
{ description: 'the visible overlay to be fully revealed and owned by the target mpv window' },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test(
|
test(
|
||||||
'seeking to another cue replaces the line and deinflects verbs to their headword',
|
'seeking to another cue replaces the line and deinflects verbs to their headword',
|
||||||
{ timeout: TEST_TIMEOUT_MS },
|
{ timeout: TEST_TIMEOUT_MS },
|
||||||
@@ -273,6 +312,93 @@ test(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// macOS and Windows keep a hidden modal renderer alive, and hidden windows keep polling because
|
||||||
|
// background throttling is off. A fake pad goes to every renderer, as a real pad would.
|
||||||
|
// Linux has no such window, and under Xvfb without a window manager the overlay reports hidden,
|
||||||
|
// so requestAnimationFrame and with it the controller poll never run. Bun's node:test ignores the
|
||||||
|
// `skip` option, so this picks `test.skip` instead.
|
||||||
|
const testOutsideLinux = process.platform === 'linux' ? test.skip : test;
|
||||||
|
testOutsideLinux(
|
||||||
|
'one controller press toggles mpv pause once across every window',
|
||||||
|
{ timeout: TEST_TIMEOUT_MS },
|
||||||
|
async () => {
|
||||||
|
const { session } = await useSession();
|
||||||
|
const START_BUTTON = 9;
|
||||||
|
const targets = (await listCdpTargets(session.cdpPort)).filter((target) =>
|
||||||
|
target.url.includes('renderer/index.html'),
|
||||||
|
);
|
||||||
|
const renderers = await Promise.all(targets.map(connectCdpPage));
|
||||||
|
const everyRenderer = (expression: string) =>
|
||||||
|
Promise.all(renderers.map((renderer) => renderer.evaluate(expression)));
|
||||||
|
const nextPolls = `new Promise((done) =>
|
||||||
|
requestAnimationFrame(() => requestAnimationFrame(() => done(true))))`;
|
||||||
|
try {
|
||||||
|
await everyRenderer(`(() => {
|
||||||
|
window.__fakePadPressed = false;
|
||||||
|
Object.defineProperty(navigator, 'getGamepads', {
|
||||||
|
configurable: true,
|
||||||
|
value: () => [{
|
||||||
|
id: 'E2E Pad (STANDARD GAMEPAD)',
|
||||||
|
index: 0,
|
||||||
|
connected: true,
|
||||||
|
mapping: 'standard',
|
||||||
|
axes: [0, 0, 0, 0],
|
||||||
|
buttons: Array.from({ length: 17 }, (_, index) => {
|
||||||
|
const pressed = window.__fakePadPressed && index === ${START_BUTTON};
|
||||||
|
return { value: pressed ? 1 : 0, pressed, touched: pressed };
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
})()`);
|
||||||
|
await everyRenderer(nextPolls);
|
||||||
|
await session.mpv.command('set_property', 'pause', true);
|
||||||
|
|
||||||
|
await everyRenderer('window.__fakePadPressed = true');
|
||||||
|
await everyRenderer(nextPolls);
|
||||||
|
await everyRenderer('window.__fakePadPressed = false');
|
||||||
|
await everyRenderer(nextPolls);
|
||||||
|
// Long enough for a second `cycle pause` to reach mpv and cancel the first.
|
||||||
|
await new Promise((done) => setTimeout(done, 300));
|
||||||
|
|
||||||
|
assert.equal(await session.mpv.command('get_property', 'pause'), false);
|
||||||
|
} finally {
|
||||||
|
await everyRenderer('delete navigator.getGamepads');
|
||||||
|
renderers.forEach((renderer) => renderer.close());
|
||||||
|
await session.mpv.command('set_property', 'pause', true);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'controller combos survive the real save path and can be rebound to one button',
|
||||||
|
{ timeout: TEST_TIMEOUT_MS },
|
||||||
|
async () => {
|
||||||
|
const { overlay } = await useSession();
|
||||||
|
const L1 = { kind: 'button', buttonIndex: 4 };
|
||||||
|
const DPAD_LEFT = { kind: 'button', buttonIndex: 14 };
|
||||||
|
const DPAD_RIGHT = { kind: 'button', buttonIndex: 15 };
|
||||||
|
const save = (bindings: Record<string, unknown>) =>
|
||||||
|
overlay.evaluate<Record<string, unknown>>(
|
||||||
|
`(async () => {
|
||||||
|
await window.electronAPI.saveControllerConfig(${JSON.stringify({ bindings })});
|
||||||
|
return (await window.electronAPI.getControllerConfig()).bindings;
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
|
||||||
|
await save({ previousEntry: { ...DPAD_LEFT, hold: L1 } });
|
||||||
|
const bothCombos = await save({ nextEntry: { ...DPAD_RIGHT, hold: L1 } });
|
||||||
|
assert.deepEqual(bothCombos.previousEntry, { ...DPAD_LEFT, hold: L1 });
|
||||||
|
assert.deepEqual(bothCombos.nextEntry, { ...DPAD_RIGHT, hold: L1 });
|
||||||
|
|
||||||
|
const rebound = await save({ previousEntry: DPAD_LEFT, nextEntry: { kind: 'none' } });
|
||||||
|
assert.deepEqual(rebound.previousEntry, DPAD_LEFT);
|
||||||
|
assert.deepEqual(rebound.nextEntry, { kind: 'none' });
|
||||||
|
|
||||||
|
await save({ previousEntry: { kind: 'none' } });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Runs last: it leaves the lookup popup open over the overlay.
|
// Runs last: it leaves the lookup popup open over the overlay.
|
||||||
test(
|
test(
|
||||||
'holding Shift over a word opens the Yomitan popup with its dictionary entry',
|
'holding Shift over a word opens the Yomitan popup with its dictionary entry',
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import packageJson from '../package.json';
|
import packageJson from '../package.json';
|
||||||
import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js';
|
import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js';
|
||||||
|
import { getDefaultConfigDir } from '../src/shared/setup-state.js';
|
||||||
|
import {
|
||||||
|
appendManagedFfmpegToPath,
|
||||||
|
getManagedFfmpegDir,
|
||||||
|
} from '../src/core/services/managed-ffmpeg.js';
|
||||||
import {
|
import {
|
||||||
loadLauncherJellyfinConfig,
|
loadLauncherJellyfinConfig,
|
||||||
loadLauncherLoggingConfig,
|
loadLauncherLoggingConfig,
|
||||||
@@ -65,6 +70,8 @@ function ensureAppPath(context: LauncherCommandContext): string {
|
|||||||
async function main(): Promise<void> {
|
async function main(): Promise<void> {
|
||||||
const scriptPath = process.argv[1] || 'subminer';
|
const scriptPath = process.argv[1] || 'subminer';
|
||||||
const scriptName = path.basename(scriptPath);
|
const scriptName = path.basename(scriptPath);
|
||||||
|
// Same PATH rule as the app: dependency checks and spawned tools see a setup-page FFmpeg.
|
||||||
|
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(getDefaultConfigDir()));
|
||||||
const launcherConfig = loadLauncherYoutubeSubgenConfig();
|
const launcherConfig = loadLauncherYoutubeSubgenConfig();
|
||||||
const launcherMpvConfig = loadLauncherMpvConfig();
|
const launcherMpvConfig = loadLauncherMpvConfig();
|
||||||
const launcherLoggingConfig = loadLauncherLoggingConfig();
|
const launcherLoggingConfig = loadLauncherLoggingConfig();
|
||||||
|
|||||||
@@ -543,8 +543,10 @@ test('launchAppBackgroundDetached starts background child directly', async () =>
|
|||||||
|
|
||||||
launchAppBackgroundDetached(appPath, 'info');
|
launchAppBackgroundDetached(appPath, 'info');
|
||||||
|
|
||||||
|
// The shell creates each file before writing to it, so wait for content, not existence.
|
||||||
|
const hasContent = (file: string) => fs.existsSync(file) && fs.statSync(file).size > 0;
|
||||||
const deadline = Date.now() + 1000;
|
const deadline = Date.now() + 1000;
|
||||||
while ((!fs.existsSync(argsPath) || !fs.existsSync(envPath)) && Date.now() < deadline) {
|
while ((!hasContent(argsPath) || !hasContent(envPath)) && Date.now() < deadline) {
|
||||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,9 @@ export const IMMERSION_DB_FIXTURE_DDL = `
|
|||||||
tmdb_type TEXT,
|
tmdb_type TEXT,
|
||||||
metadata_json TEXT,
|
metadata_json TEXT,
|
||||||
CREATED_DATE TEXT,
|
CREATED_DATE TEXT,
|
||||||
LAST_UPDATE_DATE TEXT
|
LAST_UPDATE_DATE TEXT,
|
||||||
|
group_override INTEGER,
|
||||||
|
group_override_updated_at TEXT
|
||||||
);
|
);
|
||||||
CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key);
|
CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key);
|
||||||
CREATE TABLE imm_videos(
|
CREATE TABLE imm_videos(
|
||||||
|
|||||||
+5
-4
@@ -2,7 +2,7 @@
|
|||||||
"name": "subminer",
|
"name": "subminer",
|
||||||
"productName": "SubMiner",
|
"productName": "SubMiner",
|
||||||
"desktopName": "SubMiner.desktop",
|
"desktopName": "SubMiner.desktop",
|
||||||
"version": "0.21.1",
|
"version": "0.22.1",
|
||||||
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
||||||
"packageManager": "bun@1.3.5",
|
"packageManager": "bun@1.3.5",
|
||||||
"main": "dist/main-entry.js",
|
"main": "dist/main-entry.js",
|
||||||
@@ -185,6 +185,10 @@
|
|||||||
{
|
{
|
||||||
"from": "dist/scripts/get-mpv-window-macos",
|
"from": "dist/scripts/get-mpv-window-macos",
|
||||||
"to": "scripts/get-mpv-window-macos"
|
"to": "scripts/get-mpv-window-macos"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "dist/scripts/macos-controller-watch",
|
||||||
|
"to": "scripts/macos-controller-watch"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"files": [
|
"files": [
|
||||||
@@ -283,8 +287,5 @@
|
|||||||
"printWidth": 100,
|
"printWidth": 100,
|
||||||
"singleQuote": true,
|
"singleQuote": true,
|
||||||
"trailingComma": "all"
|
"trailingComma": "all"
|
||||||
},
|
|
||||||
"patchedDependencies": {
|
|
||||||
"@discordjs/rest@2.6.1": "patches/@discordjs%2Frest@2.6.1.patch"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,88 +1,57 @@
|
|||||||
> This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release.
|
> This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release.
|
||||||
|
|
||||||
<!-- prerelease-version: 0.20.1-beta.2; since: v0.20.1-beta.1 -->
|
<!-- prerelease-version: 0.22.1-beta.2; since: v0.22.1-beta.1 -->
|
||||||
|
|
||||||
## Changes since v0.20.1-beta.1
|
## Changes since v0.22.1-beta.1
|
||||||
|
|
||||||
- Upgraded the desktop runtime to Electron 43.7.7.
|
- Later seasons now land on the right AniList entry even when the sequel chain includes split-season halves, specials, or movies (for example Mushoku Tensei S3, Re:ZERO S4, and Attack on Titan S4).
|
||||||
- SubMiner now refuses to start on an unsupported Electron runtime, or after an Electron major or minor downgrade, so your Yomitan profile data stays safe; patch downgrades are still allowed.
|
- Entries whose title names the season ("Season 3", "III", "第3期") are now preferred over counting sequels.
|
||||||
- Automatic character-dictionary updates now stop if a Yomitan profile that had dictionaries suddenly reports none.
|
- Episodes in the second half of a split season now update that half's AniList entry at the correct episode number.
|
||||||
- Development launches now use a separate `SubMiner-dev` profile unless you explicitly ask for the production profile.
|
- Character dictionary AniList matches cached by older versions are re-resolved once.
|
||||||
- Sentence mining (single and multi-line) no longer counts each card twice in session and lifetime stats.
|
- Added outro skipping: the AniSkip key now also skips endings, with its own prompt and chapter markers.
|
||||||
- Deleting sessions now updates word and kanji "first seen" and "last seen" dates correctly, and retention pruning keeps historical discovery dates and counts.
|
- Intro and outro detection now reads the file's own chapters first and only asks AniSkip for what is missing, so it also works for Jellyfin and other streams.
|
||||||
- Words hidden by the vocabulary filter are no longer counted in the new-words charts, so the charts now match the vocabulary summary.
|
- AniSkip lookups now send the episode length, so skip times match your TV or Blu-ray cut.
|
||||||
- A one-time background repair on next launch fixes stale "last seen" dates and existing chart mismatches.
|
- AniSkip rate limits, server errors, and network failures are no longer remembered as "no intro" until restart; the lookup is retried on the next load.
|
||||||
- Overview totals, charts, the activity calendar, and the vocabulary summary now refresh after you delete sessions, and a failed refresh keeps the dashboard visible with a retry option.
|
- The Jimaku modal fills in the series name again for Jellyfin episodes whose name contains a "/", and the AniList fallback guess is fixed for the same case.
|
||||||
- Subtitle generation now works during Windows YouTube playback and loads the generated subtitles into the playing video.
|
- The stats Library now shows each anime once, with its linked seasons, movies, and OVAs grouped into one card that lists the parts in release order.
|
||||||
- On Windows, moving on to a video queued from the YouTube browser window no longer drops the rest of mpv's queue.
|
- A title's page now has options to move it to another anime, show it on its own, or restore AniList's grouping, and `subminer sync` keeps the most recent choice.
|
||||||
- The stats docs now cover the automatic Overview refresh after deletions and how discovery dates are kept through retention pruning.
|
- mpv keys from `input.conf` are no longer sent to a Yomitan popup that has already closed.
|
||||||
|
- mpv keys are no longer dropped while the overlay reloads mpv's bindings after it regains focus.
|
||||||
|
- With `--log-level debug`, the log now says why the overlay kept an mpv-bound key instead of forwarding it.
|
||||||
|
- First-run setup now shows whether FFmpeg and FFprobe are usable, and a **Download FFmpeg** button saves a verified build that SubMiner and the `subminer` command use when no system FFmpeg is found.
|
||||||
|
|
||||||
## Highlights
|
## Highlights
|
||||||
### Added
|
### Added
|
||||||
|
- **Intro and Outro Skipping**:
|
||||||
- **YouTube Browser Window**:
|
- The AniSkip key now skips endings too, with its own prompt and chapter markers.
|
||||||
- Open it with `subminer youtube` (or `subminer yt`), or pick **Browse YouTube** from the tray. It stays logged in across restarts.
|
- Intros and outros are detected from the file's own chapters first, so skipping also works for Jellyfin and other streams.
|
||||||
- Clicking a video plays it in mpv. Middle-click, Shift-click, Ctrl-click, or the right-click menu adds it to mpv's playlist.
|
- AniSkip times now match your TV or Blu-ray cut.
|
||||||
- Queued videos get the same Japanese subtitle setup when they start.
|
- **Library Franchise Cards**: Seasons, movies, and OVAs of the same anime now share one library card, with each part's own stats listed inside. To fix the grouping, use **Move to Another Anime…**, **Show On Its Own**, or **Put Back Where AniList Has It** on a title's page.
|
||||||
- Closing the window quits SubMiner if you started it with `subminer youtube`. If a video is still playing, SubMiner waits until mpv closes.
|
- **FFmpeg Download in Setup**: First-run setup now shows whether FFmpeg and FFprobe are usable. If they are missing, click **Download FFmpeg** to install a verified build that SubMiner and the `subminer` command can use.
|
||||||
- **Whisper Subtitles for YouTube**:
|
|
||||||
- Set `youtube.subtitleSource` to `whisper` to make subtitles with Whisper instead of downloading YouTube's captions.
|
|
||||||
- The video stays paused while Whisper works, and progress shows in the subtitle generation modal. You can close the modal to keep watching, or cancel.
|
|
||||||
- The subtitle generation modal (`Ctrl+Shift+G`) now works on YouTube videos, including on Windows.
|
|
||||||
- **Mouse and Scroll Wheel Bindings**:
|
|
||||||
- You can now use scroll wheel keys (`WHEEL_UP`, `WHEEL_DOWN`, `WHEEL_LEFT`, `WHEEL_RIGHT`) in `keybindings` and record them in the settings key editor.
|
|
||||||
- mpv's mouse button and wheel bindings now work while the cursor is over the overlay. This matters most on Hyprland, where these bindings did nothing before.
|
|
||||||
- When a binding conflicts, SubMiner's own bindings and right-click pause take priority over mpv's.
|
|
||||||
- **Session Help Commands**: During playback, press `Enter` or double-click a row in session help to run that command. Hovering over a row makes it the target for `Enter`.
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
|
|
||||||
- **Release Assets**: Releases no longer include package-size JSON reports.
|
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
- **AniList Seasons**: Later seasons now match the right AniList entry when the series has split-season halves, specials, or movies. Episodes in the second half of a split season now update the right entry.
|
||||||
- **Jellyfin Subtitles**:
|
- **AniSkip**: Rate limits, server errors, and network failures are no longer remembered as "no intro" until restart. SubMiner retries them on the next load.
|
||||||
- The Japanese track is selected, and annotations start, as soon as it downloads. SubMiner no longer waits for the other tracks.
|
- **Jimaku**: The modal fills in the series name again for Jellyfin episodes whose name contains a "/".
|
||||||
- Japanese and English tracks are now picked automatically on episodes with image-based subtitles (PGS, DVD, DVB).
|
- **Windows Overlay**:
|
||||||
- If one track fails to download, the other tracks are still selected.
|
- The overlay now finds mpv more reliably, without relying on PowerShell lookups.
|
||||||
- **Jellyfin Audio Track**: On direct-play streams, timing review previews and mined card audio now use the audio track you're playing.
|
- You can now configure the IPC socket in `mpv.conf`.
|
||||||
- **Media Timing Review**:
|
- The overlay no longer stays attached to an unrelated window after mpv's process ID is reused.
|
||||||
- Trim handles are now thin lines centered on the clip edges.
|
- Stalled overlays now log diagnostic warnings without debug logging enabled.
|
||||||
- Original subtitle boundaries are now plain orange bars with no labels.
|
- **mpv Keys in the Overlay**: Keys bound in `input.conf` are no longer sent to a Yomitan popup that has already closed. They also no longer get dropped while the overlay reloads mpv's bindings after it regains focus.
|
||||||
- The preview cursor no longer stutters on macOS with Bluetooth headphones such as AirPods.
|
|
||||||
- **Hyprland Fullscreen**: The overlay stays visible when mpv enters or leaves fullscreen. With `mpv.backend: x11`, subtitles and the sidebar stay clickable after going fullscreen.
|
|
||||||
- **mpv Key Bindings in the Overlay**: mpv key bindings, such as `9`/`0` for volume, now work while the overlay has focus, even when the overlay loaded before mpv connected.
|
|
||||||
- **YouTube Japanese Subtitles**: Some videos also list a machine-translated Japanese track. On those, Japanese subtitles no longer fail with "HTTP 429". If YouTube refuses a direct download, SubMiner retries with yt-dlp.
|
|
||||||
- **Stats Accuracy**:
|
|
||||||
- Sentence mining no longer counts each card twice in session and lifetime stats.
|
|
||||||
- Overview totals, charts, the activity calendar, and the vocabulary summary now update after you delete sessions.
|
|
||||||
- Word and kanji dates stay correct after deleting sessions. New-word charts now match the vocabulary summary.
|
|
||||||
- **Dictionary Safety**: Automatic character dictionary changes now stop if a Yomitan profile that had dictionaries suddenly reports none. SubMiner also refuses to load Yomitan data after a downgrade to an older Electron version.
|
|
||||||
- **AppImage in Sandboxes**: The AppImage now opens its window in sandboxes that mount the image themselves, such as `firejail --appimage`.
|
|
||||||
- **Ctrl+C Crash**: Stopping the terminal command that started SubMiner with Ctrl+C no longer crashes it with a "write EPIPE" error.
|
|
||||||
- **Security Updates**: Electron is updated to 43.7.7 and undici to 7.29.1, which fixes known security advisories.
|
|
||||||
|
|
||||||
### Docs
|
### Docs
|
||||||
|
- **Windows Overlay Troubleshooting**: New guide to collecting and reading overlay attachment and readiness warnings without debug logging.
|
||||||
- **Docs Site Rewrite**: Pages are shorter and easier to scan. The configuration reference now has a short explanation and a table of keys and defaults for each config block. Pages that no longer matched current behavior are fixed.
|
|
||||||
- **Arch Linux Install**: The MeCab install command now uses the AUR package `mecab-git`. The README now matches the installation guide.
|
|
||||||
- **Stats**: The docs now cover the Overview refreshing after you delete sessions, and how first-seen dates are kept when old sessions are cleaned up.
|
|
||||||
|
|
||||||
## What's Changed
|
## What's Changed
|
||||||
|
|
||||||
- fix(storage): protect Yomitan profiles across Electron runtime changes by @ksyasuda in #211
|
- fix(overlay): identify Windows mpv windows through IPC PID by @ksyasuda in #330
|
||||||
- fix(jellyfin): select subtitles faster and survive failed track downloads by @ksyasuda in #270
|
- fix(overlay): keep forwarding mpv keys after a Yomitan popup closes by @ksyasuda in #332
|
||||||
- fix(jellyfin): use the current audio track for media generation by @ksyasuda in #271
|
- feat(setup): download FFmpeg from first-run setup when none is usable by @ksyasuda in #333
|
||||||
- feat(youtube): add YouTube browser window and Whisper subtitle source by @ksyasuda in #273
|
- feat(aniskip): detect intros and outros from file chapters and AniSkip v2 by @ksyasuda in #334
|
||||||
- fix(overlay): thin centered trim handles and label-free subtitle boundaries in timing review by @ksyasuda in #274
|
- fix(anilist): resolve later seasons past split-cour halves and specials by @ksyasuda in #335
|
||||||
- feat(overlay): run session help commands with Enter or double-click by @ksyasuda in #275
|
- feat(stats): group library seasons, movies and OVAs into franchise cards by @ksyasuda in #336
|
||||||
- fix(overlay): keep overlay mapped during Hyprland/Sway fullscreen by @ksyasuda in #276
|
- fix(jimaku): keep the series name for stream titles containing slashes by @ksyasuda in #337
|
||||||
- fix(linux): skip AppImage mount keepalive on sandbox squashfs mounts by @ksyasuda in #277
|
|
||||||
- fix(overlay): reload imported mpv keys after mpv connects by @ksyasuda in #278
|
|
||||||
- feat(overlay): forward mpv mouse button and wheel bindings by @ksyasuda in #279
|
|
||||||
- fix(stats): count mined cards once and keep lexical stats exact after deletes by @ksyasuda in #280
|
|
||||||
- fix(youtube): keep mpv queue when advancing to a queued video on Windows by @ksyasuda in #281
|
|
||||||
- fix(subtitles): allow Whisper generation during Windows YouTube stream playback by @ksyasuda in #282
|
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,38 @@
|
|||||||
## Highlights
|
## Highlights
|
||||||
### Changed
|
### Added
|
||||||
- **Stats Session View**: The expanded session view in the stats dashboard has been redesigned. It shows stat tiles for pace, lines, known-word rate, lookups, and paused time, plus a reading density chart of known and unknown words with lookup and card-mined markers.
|
- **Outro Skipping**:
|
||||||
|
- The AniSkip key now skips endings too, with its own prompt and chapter markers.
|
||||||
|
- Intro and outro detection reads the file's own chapters first, so it also works with Jellyfin and other streams.
|
||||||
|
- Skip times now match your TV or Blu-ray cut more closely.
|
||||||
|
- AniSkip rate limits and network errors no longer leave an episode marked as "no intro" until restart.
|
||||||
|
- **Anime Franchise Cards**:
|
||||||
|
- The stats Library now shows each anime once, with its related seasons, movies, and OVAs grouped on one card.
|
||||||
|
- Open a card to see each part in release order with its own stats.
|
||||||
|
- A title's page has options to move it to another anime, show it on its own, or restore AniList's grouping.
|
||||||
|
- **FFmpeg Download in Setup**: First-run setup now shows whether FFmpeg and FFprobe are available. If they're missing, **Download FFmpeg** installs a verified build that SubMiner and the `subminer` command use automatically.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- **Subtitle Delay**: Retiming subtitles in mpv (z/x or sub-step) now carries through SubMiner. Mined card audio, images, and timestamps match the retimed line, and so do the subtitle sidebar, subtitle navigation, and replay.
|
- **AniList Season Matching**: Later seasons now update the correct AniList entry when the series includes split seasons, specials, or movies, as with Mushoku Tensei S3 and Re:ZERO S4. Episodes in the second half of a split season update the right entry and episode number.
|
||||||
- **Subtitle Sidebar**: mpv keys and mouse buttons, such as volume keys and double-click fullscreen, work again while the sidebar is open.
|
- **Jimaku**: The Jimaku modal fills in the series name, season, and episode again for Jellyfin episodes whose titles contain a "/".
|
||||||
|
- **mpv Keys in the Overlay**: Keys bound in `input.conf`, such as arrow keys for subtitle seeking, are no longer sent to a Yomitan popup that has already closed. They are also no longer dropped when the overlay regains focus.
|
||||||
|
- **Windows Overlay**:
|
||||||
|
- The overlay attaches to mpv more reliably and no longer relies on PowerShell lookups.
|
||||||
|
- The mpv IPC socket can now be set in `mpv.conf`.
|
||||||
|
- The overlay can no longer stay attached to an unrelated window after mpv restarts.
|
||||||
|
- A stalled overlay now logs warnings by default, without debug logging.
|
||||||
|
|
||||||
### Docs
|
### Docs
|
||||||
- **README**: Refreshed the anime screenshots using the current build.
|
- **Windows Overlay Troubleshooting**: Added a guide to collecting and reading Windows overlay attachment and readiness warnings.
|
||||||
|
|
||||||
## What's Changed
|
## What's Changed
|
||||||
|
|
||||||
- fix(overlay): forward mpv input while subtitle sidebar is open by @ksyasuda in #300
|
- fix(overlay): identify Windows mpv windows through IPC PID by @ksyasuda in #330
|
||||||
- fix(subtitles): follow mpv sub-delay in mining, sidebar, and navigation by @ksyasuda in #302
|
- fix(overlay): keep forwarding mpv keys after a Yomitan popup closes by @ksyasuda in #332
|
||||||
- feat(stats): redesign expanded session view with density chart by @ksyasuda in #304
|
- feat(setup): download FFmpeg from first-run setup when none is usable by @ksyasuda in #333
|
||||||
|
- feat(aniskip): detect intros and outros from file chapters and AniSkip v2 by @ksyasuda in #334
|
||||||
|
- fix(anilist): resolve later seasons past split-cour halves and specials by @ksyasuda in #335
|
||||||
|
- feat(stats): group library seasons, movies and OVAs into franchise cards by @ksyasuda in #336
|
||||||
|
- fix(jimaku): keep the series name for stream titles containing slashes by @ksyasuda in #337
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
diff --git a/package.json b/package.json
|
|
||||||
index 02d2d8809a98c5d32b889fceba11458660f1fa6a..72cd7004d92809689daaeec1cd8a274e1cabdff5 100644
|
|
||||||
--- a/package.json
|
|
||||||
+++ b/package.json
|
|
||||||
@@ -77,7 +77,7 @@
|
|
||||||
"discord-api-types": "^0.38.40",
|
|
||||||
"magic-bytes.js": "^1.13.0",
|
|
||||||
"tslib": "^2.6.3",
|
|
||||||
- "undici": "6.24.1",
|
|
||||||
+ "undici": "6.27.0",
|
|
||||||
"@discordjs/collection": "^2.1.1",
|
|
||||||
"@discordjs/util": "^1.2.0"
|
|
||||||
},
|
|
||||||
@@ -108,6 +108,9 @@ function extractBuild() {
|
|||||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-'));
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-'));
|
||||||
try {
|
try {
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
|
// Call .NET directly instead of Expand-Archive: under a pwsh CI step, PSModulePath
|
||||||
|
// makes Windows PowerShell load PowerShell 7's Archive module, whose
|
||||||
|
// ExtractToDirectory overload does not exist on .NET Framework.
|
||||||
run(
|
run(
|
||||||
'powershell.exe',
|
'powershell.exe',
|
||||||
[
|
[
|
||||||
@@ -116,7 +119,7 @@ function extractBuild() {
|
|||||||
'-ExecutionPolicy',
|
'-ExecutionPolicy',
|
||||||
'Bypass',
|
'Bypass',
|
||||||
'-Command',
|
'-Command',
|
||||||
`Expand-Archive -LiteralPath '${escapePowerShellString(zipPath)}' -DestinationPath '${escapePowerShellString(tempDir)}' -Force`,
|
`$ErrorActionPreference = 'Stop'; Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapePowerShellString(zipPath)}', '${escapePowerShellString(tempDir)}')`,
|
||||||
],
|
],
|
||||||
repoRoot,
|
repoRoot,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ const http = require('node:http');
|
|||||||
const root = path.resolve(__dirname, '..');
|
const root = path.resolve(__dirname, '..');
|
||||||
const parser = require(path.join(root, 'dist/core/services/tokenizer/yomitan-parser-runtime.js'));
|
const parser = require(path.join(root, 'dist/core/services/tokenizer/yomitan-parser-runtime.js'));
|
||||||
const { writeStoredZip } = require(path.join(root, 'dist/shared/stored-zip.js'));
|
const { writeStoredZip } = require(path.join(root, 'dist/shared/stored-zip.js'));
|
||||||
|
const { HACHIDORI_POPUP_OPEN_SELECTOR } = require(
|
||||||
|
path.join(root, 'dist/renderer/yomitan-popup.js'),
|
||||||
|
);
|
||||||
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-hachidori-parser-'));
|
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-hachidori-parser-'));
|
||||||
|
|
||||||
protocol.registerSchemesAsPrivileged([
|
protocol.registerSchemesAsPrivileged([
|
||||||
@@ -43,6 +46,58 @@ function fixture(name, title, bankName, entries, frequencyMode = 'rank-based') {
|
|||||||
return zipPath;
|
return zipPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The renderer's popup auto-pause and key routing read this marker because the
|
||||||
|
// reader's shadow root is closed. Drives the real reader with real input, since
|
||||||
|
// stubbed DOM tests cannot notice an upstream merge that changes what it exposes.
|
||||||
|
async function assertPopupOpenMarkerFollowsPane(targetSession) {
|
||||||
|
const server = http.createServer((_request, response) => {
|
||||||
|
response.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||||||
|
response.end(
|
||||||
|
'<!doctype html><p id="word" style="font-size:48px;margin:300px 0 0 100px">食べた</p>',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||||
|
const page = new BrowserWindow({
|
||||||
|
width: 900,
|
||||||
|
height: 600,
|
||||||
|
show: true,
|
||||||
|
webPreferences: { session: targetSession, contextIsolation: true, nodeIntegration: false },
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await page.loadURL(`http://127.0.0.1:${server.address().port}/`);
|
||||||
|
const { webContents } = page;
|
||||||
|
const word = await webContents.executeJavaScript(
|
||||||
|
`(() => { const { x, y, height } = document.getElementById('word').getBoundingClientRect(); return { x, y, height }; })()`,
|
||||||
|
);
|
||||||
|
const repeatUntilMarker = async (expected, act) => {
|
||||||
|
const query = `document.querySelector(${JSON.stringify(HACHIDORI_POPUP_OPEN_SELECTOR)}) !== null`;
|
||||||
|
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||||
|
// Content scripts load asynchronously, so keep acting until the reader reacts.
|
||||||
|
act(attempt);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
if ((await webContents.executeJavaScript(query)) === expected) return;
|
||||||
|
}
|
||||||
|
assert.fail(`Hachidori popup-open marker never became ${expected}`);
|
||||||
|
};
|
||||||
|
page.focus();
|
||||||
|
webContents.focus();
|
||||||
|
await repeatUntilMarker(true, (attempt) =>
|
||||||
|
webContents.sendInputEvent({
|
||||||
|
type: 'mouseMove',
|
||||||
|
x: Math.round(word.x + 24) + (attempt % 2),
|
||||||
|
y: Math.round(word.y + word.height / 2),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await repeatUntilMarker(false, () => {
|
||||||
|
webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
|
||||||
|
webContents.sendInputEvent({ type: 'keyUp', keyCode: 'Escape' });
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
page.destroy();
|
||||||
|
await new Promise((resolve) => server.close(resolve));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
app
|
app
|
||||||
.whenReady()
|
.whenReady()
|
||||||
.then(async () => {
|
.then(async () => {
|
||||||
@@ -211,6 +266,7 @@ app
|
|||||||
assert.deepEqual(unmatched, []);
|
assert.deepEqual(unmatched, []);
|
||||||
assert.equal(await parser.getYomitanCurrentAnkiDeckName(deps, logger), 'Test Mining');
|
assert.equal(await parser.getYomitanCurrentAnkiDeckName(deps, logger), 'Test Mining');
|
||||||
assert.equal((await targetSession.extensions.getAllExtensions()).length, 1);
|
assert.equal((await targetSession.extensions.getAllExtensions()).length, 1);
|
||||||
|
await assertPopupOpenMarkerFollowsPane(targetSession);
|
||||||
assert.equal(
|
assert.equal(
|
||||||
await parser.syncYomitanDefaultAnkiServer('http://127.0.0.1:8765', deps, logger),
|
await parser.syncYomitanDefaultAnkiServer('http://127.0.0.1:8765', deps, logger),
|
||||||
true,
|
true,
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ const path = require('node:path');
|
|||||||
|
|
||||||
const LINUX_FFMPEG_LIBRARY = 'libffmpeg.so';
|
const LINUX_FFMPEG_LIBRARY = 'libffmpeg.so';
|
||||||
const MACOS_WINDOW_HELPER = 'get-mpv-window-macos';
|
const MACOS_WINDOW_HELPER = 'get-mpv-window-macos';
|
||||||
|
const MACOS_CONTROLLER_HELPER = 'macos-controller-watch';
|
||||||
|
const MACOS_HELPERS = [MACOS_WINDOW_HELPER, MACOS_CONTROLLER_HELPER];
|
||||||
const DEFAULT_MACOS_APP_BUNDLE = 'SubMiner.app';
|
const DEFAULT_MACOS_APP_BUNDLE = 'SubMiner.app';
|
||||||
|
|
||||||
function resolveMacOSAppBundlePath(context) {
|
function resolveMacOSAppBundlePath(context) {
|
||||||
@@ -52,7 +54,7 @@ async function stageLinuxAppImageSharedLibrary(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function verifyMacOSWindowHelper(
|
async function verifyMacOSHelpers(
|
||||||
context,
|
context,
|
||||||
deps = {
|
deps = {
|
||||||
access: (filePath, mode) => fs.access(filePath, mode),
|
access: (filePath, mode) => fs.access(filePath, mode),
|
||||||
@@ -60,27 +62,28 @@ async function verifyMacOSWindowHelper(
|
|||||||
) {
|
) {
|
||||||
if (context.electronPlatformName !== 'darwin') return false;
|
if (context.electronPlatformName !== 'darwin') return false;
|
||||||
|
|
||||||
const appBundlePath = resolveMacOSAppBundlePath(context);
|
const scriptsDir = path.join(
|
||||||
const helperPath = path.join(
|
resolveMacOSAppBundlePath(context),
|
||||||
appBundlePath,
|
|
||||||
'Contents',
|
'Contents',
|
||||||
'Resources',
|
'Resources',
|
||||||
'scripts',
|
'scripts',
|
||||||
MACOS_WINDOW_HELPER,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
try {
|
for (const helperName of MACOS_HELPERS) {
|
||||||
await deps.access(helperPath, fsSync.constants.X_OK);
|
const helperPath = path.join(scriptsDir, helperName);
|
||||||
} catch (error) {
|
try {
|
||||||
if (error && typeof error === 'object' && error.code === 'ENOENT') {
|
await deps.access(helperPath, fsSync.constants.X_OK);
|
||||||
throw new Error(
|
} catch (error) {
|
||||||
`macOS packaging requires ${MACOS_WINDOW_HELPER} at ${helperPath}. Run bun run build:assets on macOS with swiftc available before packaging.`,
|
if (error && typeof error === 'object' && error.code === 'ENOENT') {
|
||||||
);
|
throw new Error(
|
||||||
|
`macOS packaging requires ${helperName} at ${helperPath}. Run bun run build:assets on macOS with swiftc available before packaging.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (error && typeof error === 'object' && error.code === 'EACCES') {
|
||||||
|
throw new Error(`macOS helper is not executable: ${helperPath}`);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
if (error && typeof error === 'object' && error.code === 'EACCES') {
|
|
||||||
throw new Error(`macOS window helper is not executable: ${helperPath}`);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@@ -103,17 +106,17 @@ async function stageBundledBunRuntime(context, deps = {}) {
|
|||||||
|
|
||||||
async function afterPack(context, deps = {}) {
|
async function afterPack(context, deps = {}) {
|
||||||
await stageLinuxAppImageSharedLibrary(context);
|
await stageLinuxAppImageSharedLibrary(context);
|
||||||
await verifyMacOSWindowHelper(context);
|
await verifyMacOSHelpers(context);
|
||||||
await stageBundledBunRuntime(context, deps);
|
await stageBundledBunRuntime(context, deps);
|
||||||
await (deps.auditPackage ?? require('./package-audit.cjs').auditPackage)(context);
|
await (deps.auditPackage ?? require('./package-audit.cjs').auditPackage)(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
LINUX_FFMPEG_LIBRARY,
|
LINUX_FFMPEG_LIBRARY,
|
||||||
MACOS_WINDOW_HELPER,
|
MACOS_HELPERS,
|
||||||
resolveMacOSAppBundlePath,
|
resolveMacOSAppBundlePath,
|
||||||
stageBundledBunRuntime,
|
stageBundledBunRuntime,
|
||||||
stageLinuxAppImageSharedLibrary,
|
stageLinuxAppImageSharedLibrary,
|
||||||
verifyMacOSWindowHelper,
|
verifyMacOSHelpers,
|
||||||
default: afterPack,
|
default: afterPack,
|
||||||
};
|
};
|
||||||
@@ -6,13 +6,13 @@ import test from 'node:test';
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
LINUX_FFMPEG_LIBRARY,
|
LINUX_FFMPEG_LIBRARY,
|
||||||
MACOS_WINDOW_HELPER,
|
MACOS_HELPERS,
|
||||||
default: afterPack,
|
default: afterPack,
|
||||||
stageLinuxAppImageSharedLibrary,
|
stageLinuxAppImageSharedLibrary,
|
||||||
verifyMacOSWindowHelper,
|
verifyMacOSHelpers,
|
||||||
} = require('./electron-builder-after-pack.cjs') as {
|
} = require('./electron-builder-after-pack.cjs') as {
|
||||||
LINUX_FFMPEG_LIBRARY: string;
|
LINUX_FFMPEG_LIBRARY: string;
|
||||||
MACOS_WINDOW_HELPER: string;
|
MACOS_HELPERS: string[];
|
||||||
default: (
|
default: (
|
||||||
context: {
|
context: {
|
||||||
appOutDir: string;
|
appOutDir: string;
|
||||||
@@ -34,7 +34,7 @@ const {
|
|||||||
appOutDir: string;
|
appOutDir: string;
|
||||||
electronPlatformName: string;
|
electronPlatformName: string;
|
||||||
}) => Promise<boolean>;
|
}) => Promise<boolean>;
|
||||||
verifyMacOSWindowHelper: (context: {
|
verifyMacOSHelpers: (context: {
|
||||||
appOutDir: string;
|
appOutDir: string;
|
||||||
electronPlatformName: string;
|
electronPlatformName: string;
|
||||||
}) => Promise<boolean>;
|
}) => Promise<boolean>;
|
||||||
@@ -88,24 +88,19 @@ test('stageLinuxAppImageSharedLibrary skips non-Linux packaging contexts', async
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('verifyMacOSWindowHelper accepts packaged macOS helper binary', async () => {
|
test('verifyMacOSHelpers accepts packaged macOS helper binaries', async () => {
|
||||||
const workspace = createWorkspace('subminer-after-pack-macos-helper');
|
const workspace = createWorkspace('subminer-after-pack-macos-helper');
|
||||||
const appOutDir = path.join(workspace, 'SubMiner-darwin-arm64');
|
const appOutDir = path.join(workspace, 'SubMiner-darwin-arm64');
|
||||||
const helperPath = path.join(
|
const scriptsDir = path.join(appOutDir, 'SubMiner.app', 'Contents', 'Resources', 'scripts');
|
||||||
appOutDir,
|
|
||||||
'SubMiner.app',
|
|
||||||
'Contents',
|
|
||||||
'Resources',
|
|
||||||
'scripts',
|
|
||||||
MACOS_WINDOW_HELPER,
|
|
||||||
);
|
|
||||||
|
|
||||||
fs.mkdirSync(path.dirname(helperPath), { recursive: true });
|
fs.mkdirSync(scriptsDir, { recursive: true });
|
||||||
fs.writeFileSync(helperPath, 'compiled helper', 'utf8');
|
for (const helperName of MACOS_HELPERS) {
|
||||||
fs.chmodSync(helperPath, 0o755);
|
fs.writeFileSync(path.join(scriptsDir, helperName), 'compiled helper', 'utf8');
|
||||||
|
fs.chmodSync(path.join(scriptsDir, helperName), 0o755);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const verified = await verifyMacOSWindowHelper({
|
const verified = await verifyMacOSHelpers({
|
||||||
appOutDir,
|
appOutDir,
|
||||||
electronPlatformName: 'darwin',
|
electronPlatformName: 'darwin',
|
||||||
});
|
});
|
||||||
@@ -116,19 +111,22 @@ test('verifyMacOSWindowHelper accepts packaged macOS helper binary', async () =>
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('verifyMacOSWindowHelper throws when macOS helper binary is missing', async () => {
|
test('verifyMacOSHelpers throws when a macOS helper binary is missing', async () => {
|
||||||
const workspace = createWorkspace('subminer-after-pack-macos-helper-missing');
|
const workspace = createWorkspace('subminer-after-pack-macos-helper-missing');
|
||||||
const appOutDir = path.join(workspace, 'SubMiner-darwin-arm64');
|
const appOutDir = path.join(workspace, 'SubMiner-darwin-arm64');
|
||||||
|
const scriptsDir = path.join(appOutDir, 'SubMiner.app', 'Contents', 'Resources', 'scripts');
|
||||||
|
|
||||||
fs.mkdirSync(path.join(appOutDir, 'SubMiner.app', 'Contents', 'Resources'), { recursive: true });
|
fs.mkdirSync(scriptsDir, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(scriptsDir, 'get-mpv-window-macos'), 'compiled helper', 'utf8');
|
||||||
|
fs.chmodSync(path.join(scriptsDir, 'get-mpv-window-macos'), 0o755);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
verifyMacOSWindowHelper({
|
verifyMacOSHelpers({
|
||||||
appOutDir,
|
appOutDir,
|
||||||
electronPlatformName: 'darwin',
|
electronPlatformName: 'darwin',
|
||||||
}),
|
}),
|
||||||
/macOS packaging requires get-mpv-window-macos/,
|
/macOS packaging requires macos-controller-watch/,
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(workspace, { recursive: true, force: true });
|
fs.rmSync(workspace, { recursive: true, force: true });
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#!/usr/bin/env swift
|
||||||
|
//
|
||||||
|
// macos-controller-watch.swift
|
||||||
|
// SubMiner - Report controller button presses on macOS while SubMiner is in the background
|
||||||
|
//
|
||||||
|
// macOS only delivers GameController input to the frontmost app, so the overlay sees no
|
||||||
|
// presses while mpv is in front. This helper opts in to background events and prints one
|
||||||
|
// line per press so SubMiner can focus the overlay and replay the press there.
|
||||||
|
//
|
||||||
|
// Usage: macos-controller-watch (long-running; exits when stdin closes)
|
||||||
|
// Output: "press <index> <connected pads>" per button press, using the W3C standard gamepad
|
||||||
|
// button indices. SubMiner only replays a press when one pad is connected: nothing identifies
|
||||||
|
// a pad to both GameController and Chromium, so with several it could hit the wrong one.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Cocoa
|
||||||
|
import Foundation
|
||||||
|
import GameController
|
||||||
|
|
||||||
|
private func emit(_ line: String) {
|
||||||
|
FileHandle.standardOutput.write(Data((line + "\n").utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Standard gamepad mapping (https://w3c.github.io/gamepad/#remapping), matching the
|
||||||
|
/// indices Chromium reports for the same pad.
|
||||||
|
private func standardButtons(_ pad: GCExtendedGamepad) -> [(Int, GCControllerButtonInput?)] {
|
||||||
|
return [
|
||||||
|
(0, pad.buttonA),
|
||||||
|
(1, pad.buttonB),
|
||||||
|
(2, pad.buttonX),
|
||||||
|
(3, pad.buttonY),
|
||||||
|
(4, pad.leftShoulder),
|
||||||
|
(5, pad.rightShoulder),
|
||||||
|
(6, pad.leftTrigger),
|
||||||
|
(7, pad.rightTrigger),
|
||||||
|
(8, pad.buttonOptions),
|
||||||
|
(9, pad.buttonMenu),
|
||||||
|
(10, pad.leftThumbstickButton),
|
||||||
|
(11, pad.rightThumbstickButton),
|
||||||
|
(12, pad.dpad.up),
|
||||||
|
(13, pad.dpad.down),
|
||||||
|
(14, pad.dpad.left),
|
||||||
|
(15, pad.dpad.right),
|
||||||
|
(16, pad.buttonHome),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
private func connectedPadCount() -> Int {
|
||||||
|
return GCController.controllers().filter { $0.extendedGamepad != nil }.count
|
||||||
|
}
|
||||||
|
|
||||||
|
private func watch(_ controller: GCController) {
|
||||||
|
guard let pad = controller.extendedGamepad else { return }
|
||||||
|
for (index, button) in standardButtons(pad) {
|
||||||
|
button?.pressedChangedHandler = { _, _, pressed in
|
||||||
|
if pressed {
|
||||||
|
emit("press \(index) \(connectedPadCount())")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exit with SubMiner: it holds our stdin open for as long as it runs.
|
||||||
|
private func exitWhenStdinCloses() {
|
||||||
|
Thread.detachNewThread {
|
||||||
|
while !FileHandle.standardInput.availableData.isEmpty {}
|
||||||
|
exit(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let app = NSApplication.shared
|
||||||
|
app.setActivationPolicy(.prohibited)
|
||||||
|
GCController.shouldMonitorBackgroundEvents = true
|
||||||
|
|
||||||
|
NotificationCenter.default.addObserver(
|
||||||
|
forName: .GCControllerDidConnect,
|
||||||
|
object: nil,
|
||||||
|
queue: .main
|
||||||
|
) { notification in
|
||||||
|
if let controller = notification.object as? GCController {
|
||||||
|
watch(controller)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
GCController.controllers().forEach(watch)
|
||||||
|
|
||||||
|
exitWhenStdinCloses()
|
||||||
|
app.run()
|
||||||
@@ -14,9 +14,8 @@ const settingsOutputDir = path.join(repoRoot, 'dist', 'settings');
|
|||||||
const syncUiSourceDir = path.join(repoRoot, 'src', 'syncui');
|
const syncUiSourceDir = path.join(repoRoot, 'src', 'syncui');
|
||||||
const syncUiOutputDir = path.join(repoRoot, 'dist', 'syncui');
|
const syncUiOutputDir = path.join(repoRoot, 'dist', 'syncui');
|
||||||
const scriptsOutputDir = path.join(repoRoot, 'dist', 'scripts');
|
const scriptsOutputDir = path.join(repoRoot, 'dist', 'scripts');
|
||||||
const macosHelperSourcePath = path.join(scriptDir, 'get-mpv-window-macos.swift');
|
// Swift helpers compiled on macOS and shipped in Resources/scripts.
|
||||||
const macosHelperBinaryPath = path.join(scriptsOutputDir, 'get-mpv-window-macos');
|
const MACOS_HELPERS = ['get-mpv-window-macos', 'macos-controller-watch'];
|
||||||
const macosHelperSourceCopyPath = path.join(scriptsOutputDir, 'get-mpv-window-macos.swift');
|
|
||||||
|
|
||||||
function ensureDir(dirPath) {
|
function ensureDir(dirPath) {
|
||||||
fs.mkdirSync(dirPath, { recursive: true });
|
fs.mkdirSync(dirPath, { recursive: true });
|
||||||
@@ -45,9 +44,10 @@ function copySyncUiAssets() {
|
|||||||
copyAssets(syncUiSourceDir, syncUiOutputDir, 'syncui');
|
copyAssets(syncUiSourceDir, syncUiOutputDir, 'syncui');
|
||||||
}
|
}
|
||||||
|
|
||||||
function fallbackToMacosSource() {
|
function fallbackToMacosSource(helperName) {
|
||||||
copyFile(macosHelperSourcePath, macosHelperSourceCopyPath);
|
const sourceCopyPath = path.join(scriptsOutputDir, `${helperName}.swift`);
|
||||||
process.stdout.write(`Staged macOS helper source fallback: ${macosHelperSourceCopyPath}\n`);
|
copyFile(path.join(scriptDir, `${helperName}.swift`), sourceCopyPath);
|
||||||
|
process.stdout.write(`Staged macOS helper source fallback: ${sourceCopyPath}\n`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pin the minimum macOS to the app's own floor (Electron's `minos`). Without an
|
// Pin the minimum macOS to the app's own floor (Electron's `minos`). Without an
|
||||||
@@ -64,34 +64,34 @@ function shouldSkipMacosHelperBuild() {
|
|||||||
return process.env.SUBMINER_SKIP_MACOS_HELPER_BUILD === '1';
|
return process.env.SUBMINER_SKIP_MACOS_HELPER_BUILD === '1';
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildMacosHelper() {
|
function buildMacosHelper(helperName) {
|
||||||
if (shouldSkipMacosHelperBuild()) {
|
if (shouldSkipMacosHelperBuild()) {
|
||||||
process.stdout.write('Skipping macOS helper build (SUBMINER_SKIP_MACOS_HELPER_BUILD=1)\n');
|
process.stdout.write('Skipping macOS helper build (SUBMINER_SKIP_MACOS_HELPER_BUILD=1)\n');
|
||||||
fallbackToMacosSource();
|
fallbackToMacosSource(helperName);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.platform !== 'darwin') {
|
if (process.platform !== 'darwin') {
|
||||||
process.stdout.write('Skipping macOS helper build (not on macOS)\n');
|
process.stdout.write('Skipping macOS helper build (not on macOS)\n');
|
||||||
fallbackToMacosSource();
|
fallbackToMacosSource(helperName);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ensureDir(scriptsOutputDir);
|
ensureDir(scriptsOutputDir);
|
||||||
|
const sourcePath = path.join(scriptDir, `${helperName}.swift`);
|
||||||
|
const binaryPath = path.join(scriptsOutputDir, helperName);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
execFileSync(
|
execFileSync('swiftc', ['-O', '-target', macosHelperTarget(), sourcePath, '-o', binaryPath], {
|
||||||
'swiftc',
|
stdio: 'inherit',
|
||||||
['-O', '-target', macosHelperTarget(), macosHelperSourcePath, '-o', macosHelperBinaryPath],
|
});
|
||||||
{
|
fs.chmodSync(binaryPath, 0o755);
|
||||||
stdio: 'inherit',
|
process.stdout.write(`Built macOS helper: ${binaryPath}\n`);
|
||||||
},
|
|
||||||
);
|
|
||||||
fs.chmodSync(macosHelperBinaryPath, 0o755);
|
|
||||||
process.stdout.write(`Built macOS helper: ${macosHelperBinaryPath}\n`);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
process.stdout.write('Failed to compile macOS helper; using source fallback.\n');
|
process.stdout.write(`Failed to compile macOS helper ${helperName}; using source fallback.\n`);
|
||||||
fallbackToMacosSource();
|
// A binary from an earlier build would otherwise pass the after-pack check and ship stale.
|
||||||
|
fs.rmSync(binaryPath, { force: true });
|
||||||
|
fallbackToMacosSource(helperName);
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
process.stderr.write(`${error.message}\n`);
|
process.stderr.write(`${error.message}\n`);
|
||||||
}
|
}
|
||||||
@@ -117,7 +117,7 @@ function main() {
|
|||||||
copyRendererAssets();
|
copyRendererAssets();
|
||||||
copySettingsAssets();
|
copySettingsAssets();
|
||||||
copySyncUiAssets();
|
copySyncUiAssets();
|
||||||
buildMacosHelper();
|
MACOS_HELPERS.forEach(buildMacosHelper);
|
||||||
stageIntegrationKeys();
|
stageIntegrationKeys();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1297,7 +1297,6 @@ test('parses controller settings with logical bindings and tuning knobs', () =>
|
|||||||
"toggleMpvPause": "leftStickPress",
|
"toggleMpvPause": "leftStickPress",
|
||||||
"leftStickHorizontal": "rightStickX",
|
"leftStickHorizontal": "rightStickX",
|
||||||
"leftStickVertical": "rightStickY",
|
"leftStickVertical": "rightStickY",
|
||||||
"rightStickHorizontal": "leftStickX",
|
|
||||||
"rightStickVertical": "leftStickY"
|
"rightStickVertical": "leftStickY"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1383,6 +1382,59 @@ test('parses descriptor-based controller bindings', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('parses a hold input on discrete controller bindings and rejects an invalid one', () => {
|
||||||
|
const dir = makeTempDir();
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(dir, 'config.jsonc'),
|
||||||
|
`{
|
||||||
|
"controller": {
|
||||||
|
"bindings": {
|
||||||
|
"nextAudio": {
|
||||||
|
"kind": "button",
|
||||||
|
"buttonIndex": 15,
|
||||||
|
"hold": { "kind": "button", "buttonIndex": 4 }
|
||||||
|
},
|
||||||
|
"nextEntry": {
|
||||||
|
"kind": "axis",
|
||||||
|
"axisIndex": 0,
|
||||||
|
"direction": "positive",
|
||||||
|
"hold": { "kind": "axis", "axisIndex": 2, "direction": "positive" }
|
||||||
|
},
|
||||||
|
"mineCard": {
|
||||||
|
"kind": "button",
|
||||||
|
"buttonIndex": 12,
|
||||||
|
"hold": { "kind": "button" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
'utf-8',
|
||||||
|
);
|
||||||
|
|
||||||
|
const service = new ConfigService(dir);
|
||||||
|
const config = service.getConfig();
|
||||||
|
|
||||||
|
assert.deepEqual(config.controller.bindings.nextAudio, {
|
||||||
|
kind: 'button',
|
||||||
|
buttonIndex: 15,
|
||||||
|
hold: { kind: 'button', buttonIndex: 4 },
|
||||||
|
});
|
||||||
|
assert.deepEqual(config.controller.bindings.nextEntry, {
|
||||||
|
kind: 'axis',
|
||||||
|
axisIndex: 0,
|
||||||
|
direction: 'positive',
|
||||||
|
hold: { kind: 'axis', axisIndex: 2, direction: 'positive' },
|
||||||
|
});
|
||||||
|
// A broken hold must not silently become a plain press of button 12.
|
||||||
|
assert.deepEqual(
|
||||||
|
config.controller.bindings.mineCard,
|
||||||
|
DEFAULT_CONFIG.controller.bindings.mineCard,
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
service.getWarnings().some((warning) => warning.path === 'controller.bindings.mineCard'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test('parses controller profiles as per-gamepad binding overrides', () => {
|
test('parses controller profiles as per-gamepad binding overrides', () => {
|
||||||
const dir = makeTempDir();
|
const dir = makeTempDir();
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ const {
|
|||||||
discordPresence,
|
discordPresence,
|
||||||
ai,
|
ai,
|
||||||
} = INTEGRATIONS_DEFAULT_CONFIG;
|
} = INTEGRATIONS_DEFAULT_CONFIG;
|
||||||
const { subtitleStyle, subtitleSidebar } = SUBTITLE_DEFAULT_CONFIG;
|
const { subtitleStyle, subtitleSidebar, subtitleFilter } = SUBTITLE_DEFAULT_CONFIG;
|
||||||
const { immersionTracking } = IMMERSION_DEFAULT_CONFIG;
|
const { immersionTracking } = IMMERSION_DEFAULT_CONFIG;
|
||||||
const { stats } = STATS_DEFAULT_CONFIG;
|
const { stats } = STATS_DEFAULT_CONFIG;
|
||||||
|
|
||||||
@@ -78,6 +78,7 @@ export const DEFAULT_CONFIG: ResolvedConfig = {
|
|||||||
plugins,
|
plugins,
|
||||||
subtitleStyle,
|
subtitleStyle,
|
||||||
subtitleSidebar,
|
subtitleSidebar,
|
||||||
|
subtitleFilter,
|
||||||
auto_start_overlay,
|
auto_start_overlay,
|
||||||
jimaku,
|
jimaku,
|
||||||
tsukihime,
|
tsukihime,
|
||||||
|
|||||||
@@ -85,13 +85,13 @@ export const CORE_DEFAULT_CONFIG: Pick<
|
|||||||
holdSecondarySub: { kind: 'none' },
|
holdSecondarySub: { kind: 'none' },
|
||||||
previousEntry: { kind: 'none' },
|
previousEntry: { kind: 'none' },
|
||||||
nextEntry: { kind: 'none' },
|
nextEntry: { kind: 'none' },
|
||||||
|
toggleCharacterNavigation: { kind: 'none' },
|
||||||
previousSubtitle: { kind: 'none' },
|
previousSubtitle: { kind: 'none' },
|
||||||
nextSubtitle: { kind: 'none' },
|
nextSubtitle: { kind: 'none' },
|
||||||
replaySubtitle: { kind: 'none' },
|
replaySubtitle: { kind: 'none' },
|
||||||
playNextSubtitle: { kind: 'none' },
|
playNextSubtitle: { kind: 'none' },
|
||||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
|
||||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||||
},
|
},
|
||||||
reviewBindings: getDefaultControllerReviewBindings(),
|
reviewBindings: getDefaultControllerReviewBindings(),
|
||||||
|
|||||||
@@ -108,6 +108,7 @@ export const INTEGRATIONS_DEFAULT_CONFIG: Pick<
|
|||||||
apiKeyCommand: '',
|
apiKeyCommand: '',
|
||||||
languagePreference: 'ja',
|
languagePreference: 'ja',
|
||||||
maxEntryResults: 10,
|
maxEntryResults: 10,
|
||||||
|
autoOpenWhenPrimarySubtitleMissing: false,
|
||||||
},
|
},
|
||||||
tsukihime: {
|
tsukihime: {
|
||||||
apiBaseUrl: 'https://api.tsukihime.org/v1',
|
apiBaseUrl: 'https://api.tsukihime.org/v1',
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import { ResolvedConfig } from '../../types/config';
|
import { ResolvedConfig } from '../../types/config';
|
||||||
|
|
||||||
export const SUBTITLE_DEFAULT_CONFIG: Pick<ResolvedConfig, 'subtitleStyle' | 'subtitleSidebar'> = {
|
export const SUBTITLE_DEFAULT_CONFIG: Pick<
|
||||||
|
ResolvedConfig,
|
||||||
|
'subtitleStyle' | 'subtitleSidebar' | 'subtitleFilter'
|
||||||
|
> = {
|
||||||
subtitleStyle: {
|
subtitleStyle: {
|
||||||
primaryDefaultMode: 'visible',
|
primaryDefaultMode: 'visible',
|
||||||
css: {},
|
css: {},
|
||||||
@@ -94,4 +97,13 @@ export const SUBTITLE_DEFAULT_CONFIG: Pick<ResolvedConfig, 'subtitleStyle' | 'su
|
|||||||
activeLineBackgroundColor: 'rgba(138, 173, 244, 0.22)',
|
activeLineBackgroundColor: 'rgba(138, 173, 244, 0.22)',
|
||||||
hoverLineBackgroundColor: 'rgba(54, 58, 79, 0.84)',
|
hoverLineBackgroundColor: 'rgba(54, 58, 79, 0.84)',
|
||||||
},
|
},
|
||||||
|
subtitleFilter: {
|
||||||
|
presets: {
|
||||||
|
parentheses: false,
|
||||||
|
brackets: false,
|
||||||
|
speakerPrefix: false,
|
||||||
|
musicSymbols: false,
|
||||||
|
},
|
||||||
|
customRules: [],
|
||||||
|
},
|
||||||
};
|
};
|
||||||
@@ -82,6 +82,12 @@ export function buildCoreConfigOptionRegistry(
|
|||||||
description:
|
description:
|
||||||
'Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry.',
|
'Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry.',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'toggleCharacterNavigation',
|
||||||
|
defaultValue: defaultConfig.controller.bindings.toggleCharacterNavigation,
|
||||||
|
description:
|
||||||
|
'Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two.',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: 'previousSubtitle',
|
id: 'previousSubtitle',
|
||||||
defaultValue: defaultConfig.controller.bindings.previousSubtitle,
|
defaultValue: defaultConfig.controller.bindings.previousSubtitle,
|
||||||
@@ -119,11 +125,6 @@ export function buildCoreConfigOptionRegistry(
|
|||||||
defaultValue: defaultConfig.controller.bindings.leftStickVertical,
|
defaultValue: defaultConfig.controller.bindings.leftStickVertical,
|
||||||
description: 'Axis binding descriptor used for primary popup scrolling.',
|
description: 'Axis binding descriptor used for primary popup scrolling.',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: 'rightStickHorizontal',
|
|
||||||
defaultValue: defaultConfig.controller.bindings.rightStickHorizontal,
|
|
||||||
description: 'Axis binding descriptor reserved for alternate right-stick mappings.',
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
id: 'rightStickVertical',
|
id: 'rightStickVertical',
|
||||||
defaultValue: defaultConfig.controller.bindings.rightStickVertical,
|
defaultValue: defaultConfig.controller.bindings.rightStickVertical,
|
||||||
@@ -466,7 +467,7 @@ export function buildCoreConfigOptionRegistry(
|
|||||||
path: `controller.bindings.${binding.id}`,
|
path: `controller.bindings.${binding.id}`,
|
||||||
kind: 'object' as const,
|
kind: 'object' as const,
|
||||||
defaultValue: binding.defaultValue,
|
defaultValue: binding.defaultValue,
|
||||||
description: `${binding.description} Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.`,
|
description: `${binding.description} Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: `controller.bindings.${binding.id}.kind`,
|
path: `controller.bindings.${binding.id}.kind`,
|
||||||
@@ -499,6 +500,13 @@ export function buildCoreConfigOptionRegistry(
|
|||||||
description:
|
description:
|
||||||
'Axis direction captured for this discrete controller action. Required when kind is "axis".',
|
'Axis direction captured for this discrete controller action. Required when kind is "axis".',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: `controller.bindings.${binding.id}.hold`,
|
||||||
|
kind: 'object' as const,
|
||||||
|
defaultValue: undefined,
|
||||||
|
description:
|
||||||
|
'Optional button or axis input, in the same form, that must be held down while pressing this one.',
|
||||||
|
},
|
||||||
]),
|
]),
|
||||||
...axisBindings.flatMap((binding) => [
|
...axisBindings.flatMap((binding) => [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -467,6 +467,13 @@ export function buildIntegrationConfigOptionRegistry(
|
|||||||
defaultValue: defaultConfig.jimaku.maxEntryResults,
|
defaultValue: defaultConfig.jimaku.maxEntryResults,
|
||||||
description: 'Maximum Jimaku search results returned.',
|
description: 'Maximum Jimaku search results returned.',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'jimaku.autoOpenWhenPrimarySubtitleMissing',
|
||||||
|
kind: 'boolean',
|
||||||
|
defaultValue: defaultConfig.jimaku.autoOpenWhenPrimarySubtitleMissing,
|
||||||
|
description:
|
||||||
|
'Pause playback and open the Jimaku modal when a local video has no subtitle track in youtube.primarySubLanguages (Japanese by default).',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'tsukihime.apiBaseUrl',
|
path: 'tsukihime.apiBaseUrl',
|
||||||
kind: 'string',
|
kind: 'string',
|
||||||
@@ -609,13 +616,14 @@ export function buildIntegrationConfigOptionRegistry(
|
|||||||
path: 'mpv.aniskipEnabled',
|
path: 'mpv.aniskipEnabled',
|
||||||
kind: 'boolean',
|
kind: 'boolean',
|
||||||
defaultValue: defaultConfig.mpv.aniskipEnabled,
|
defaultValue: defaultConfig.mpv.aniskipEnabled,
|
||||||
description: 'Enable AniSkip intro detection, chapter markers, and the skip-intro key.',
|
description:
|
||||||
|
'Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'mpv.aniskipButtonKey',
|
path: 'mpv.aniskipButtonKey',
|
||||||
kind: 'string',
|
kind: 'string',
|
||||||
defaultValue: defaultConfig.mpv.aniskipButtonKey,
|
defaultValue: defaultConfig.mpv.aniskipButtonKey,
|
||||||
description: 'mpv key used to skip the detected intro while the skip prompt is visible.',
|
description: 'mpv key that skips the detected intro or outro while it plays.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'jellyfin.enabled',
|
path: 'jellyfin.enabled',
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { ResolvedConfig } from '../../types/config';
|
import { ResolvedConfig } from '../../types/config';
|
||||||
import { ConfigOptionRegistryEntry } from './shared';
|
import { ConfigOptionRegistryEntry } from './shared';
|
||||||
import { SUBTITLE_GENERATION_MODELS } from '../../shared/subtitle-generation-model-catalog';
|
import { SUBTITLE_GENERATION_MODELS } from '../../shared/subtitle-generation-model-catalog';
|
||||||
|
import {
|
||||||
|
SUBTITLE_FILTER_PRESET_IDS,
|
||||||
|
SUBTITLE_FILTER_PRESETS,
|
||||||
|
} from '../../shared/subtitle-text-filter';
|
||||||
|
|
||||||
export function buildSubtitleConfigOptionRegistry(
|
export function buildSubtitleConfigOptionRegistry(
|
||||||
defaultConfig: ResolvedConfig,
|
defaultConfig: ResolvedConfig,
|
||||||
@@ -340,5 +344,24 @@ export function buildSubtitleConfigOptionRegistry(
|
|||||||
defaultValue: defaultConfig.subtitleSidebar.hoverLineBackgroundColor,
|
defaultValue: defaultConfig.subtitleSidebar.hoverLineBackgroundColor,
|
||||||
description: 'Background color for hovered subtitle cues.',
|
description: 'Background color for hovered subtitle cues.',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'subtitleFilter.presets',
|
||||||
|
kind: 'object',
|
||||||
|
defaultValue: defaultConfig.subtitleFilter.presets,
|
||||||
|
description: 'Built-in filters. Each removes its matches and is off by default.',
|
||||||
|
},
|
||||||
|
...SUBTITLE_FILTER_PRESET_IDS.map((id) => ({
|
||||||
|
path: `subtitleFilter.presets.${id}`,
|
||||||
|
kind: 'boolean' as const,
|
||||||
|
defaultValue: defaultConfig.subtitleFilter.presets[id],
|
||||||
|
description: SUBTITLE_FILTER_PRESETS[id].description,
|
||||||
|
})),
|
||||||
|
{
|
||||||
|
path: 'subtitleFilter.customRules',
|
||||||
|
kind: 'array',
|
||||||
|
defaultValue: defaultConfig.subtitleFilter.customRules,
|
||||||
|
description:
|
||||||
|
'Your own regex rules, applied in order after the presets. Each rule is { name, pattern, replacement, enabled }; patterns use the gmu flags, so ^ and $ match per line. Leave replacement empty to remove the match.',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -153,6 +153,15 @@ const SUBTITLE_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
|
|||||||
notes: ['Hot-reload: subtitle sidebar changes apply live without restarting SubMiner.'],
|
notes: ['Hot-reload: subtitle sidebar changes apply live without restarting SubMiner.'],
|
||||||
key: 'subtitleSidebar',
|
key: 'subtitleSidebar',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: 'Subtitle Filters',
|
||||||
|
description: [
|
||||||
|
'Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.',
|
||||||
|
'Applies to the overlay, sidebar, mined sentences and stats.',
|
||||||
|
],
|
||||||
|
notes: ['Hot-reload: filter changes apply to the current subtitle file immediately.'],
|
||||||
|
key: 'subtitleFilter',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const INTEGRATION_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
|
const INTEGRATION_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ const HOT_RELOAD_ROOTS = [
|
|||||||
'shortcuts',
|
'shortcuts',
|
||||||
'subtitleSidebar',
|
'subtitleSidebar',
|
||||||
'subtitleSelection',
|
'subtitleSelection',
|
||||||
|
'subtitleFilter',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const HOT_RELOAD_EXACT_OR_PREFIX_PATHS = [
|
const HOT_RELOAD_EXACT_OR_PREFIX_PATHS = [
|
||||||
|
|||||||
@@ -7,12 +7,14 @@ import { applyIntegrationConfig } from './resolve/integrations';
|
|||||||
import { applyPluginsConfig } from './resolve/plugins';
|
import { applyPluginsConfig } from './resolve/plugins';
|
||||||
import { applyStatsConfig } from './resolve/stats';
|
import { applyStatsConfig } from './resolve/stats';
|
||||||
import { applySubtitleDomainConfig } from './resolve/subtitle-domains';
|
import { applySubtitleDomainConfig } from './resolve/subtitle-domains';
|
||||||
|
import { applySubtitleFilterConfig } from './resolve/subtitle-filter';
|
||||||
import { applyTopLevelConfig } from './resolve/top-level';
|
import { applyTopLevelConfig } from './resolve/top-level';
|
||||||
|
|
||||||
const APPLY_RESOLVE_STEPS = [
|
const APPLY_RESOLVE_STEPS = [
|
||||||
applyTopLevelConfig,
|
applyTopLevelConfig,
|
||||||
applyCoreDomainConfig,
|
applyCoreDomainConfig,
|
||||||
applySubtitleDomainConfig,
|
applySubtitleDomainConfig,
|
||||||
|
applySubtitleFilterConfig,
|
||||||
applyIntegrationConfig,
|
applyIntegrationConfig,
|
||||||
applyImmersionTrackingConfig,
|
applyImmersionTrackingConfig,
|
||||||
applyStatsConfig,
|
applyStatsConfig,
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import type {
|
import type {
|
||||||
ControllerAxisBinding,
|
ControllerAxisBinding,
|
||||||
ControllerAxisDirection,
|
|
||||||
ControllerButtonBinding,
|
ControllerButtonBinding,
|
||||||
ControllerButtonIndicesConfig,
|
ControllerButtonIndicesConfig,
|
||||||
ControllerDpadFallback,
|
ControllerDpadFallback,
|
||||||
@@ -11,6 +10,7 @@ import type {
|
|||||||
import {
|
import {
|
||||||
isControllerFaceButtonLabels,
|
isControllerFaceButtonLabels,
|
||||||
isControllerScreenAction,
|
isControllerScreenAction,
|
||||||
|
parseControllerDiscreteBinding,
|
||||||
parseControllerReviewBinding,
|
parseControllerReviewBinding,
|
||||||
type ControllerScreenBindings,
|
type ControllerScreenBindings,
|
||||||
type ControllerScreenDefinition,
|
type ControllerScreenDefinition,
|
||||||
@@ -70,7 +70,6 @@ const CONTROLLER_BUTTON_INDEX_KEY_BY_BINDING: Record<
|
|||||||
const CONTROLLER_AXIS_FALLBACK_BY_SLOT = {
|
const CONTROLLER_AXIS_FALLBACK_BY_SLOT = {
|
||||||
leftStickHorizontal: 'horizontal',
|
leftStickHorizontal: 'horizontal',
|
||||||
leftStickVertical: 'vertical',
|
leftStickVertical: 'vertical',
|
||||||
rightStickHorizontal: 'none',
|
|
||||||
rightStickVertical: 'none',
|
rightStickVertical: 'none',
|
||||||
} as const satisfies Record<string, ControllerDpadFallback>;
|
} as const satisfies Record<string, ControllerDpadFallback>;
|
||||||
|
|
||||||
@@ -101,6 +100,7 @@ const CONTROLLER_DISCRETE_BINDING_KEYS = [
|
|||||||
'holdSecondarySub',
|
'holdSecondarySub',
|
||||||
'previousEntry',
|
'previousEntry',
|
||||||
'nextEntry',
|
'nextEntry',
|
||||||
|
'toggleCharacterNavigation',
|
||||||
'previousSubtitle',
|
'previousSubtitle',
|
||||||
'nextSubtitle',
|
'nextSubtitle',
|
||||||
'replaySubtitle',
|
'replaySubtitle',
|
||||||
@@ -110,7 +110,6 @@ const CONTROLLER_DISCRETE_BINDING_KEYS = [
|
|||||||
const CONTROLLER_AXIS_BINDING_KEYS = [
|
const CONTROLLER_AXIS_BINDING_KEYS = [
|
||||||
'leftStickHorizontal',
|
'leftStickHorizontal',
|
||||||
'leftStickVertical',
|
'leftStickVertical',
|
||||||
'rightStickHorizontal',
|
|
||||||
'rightStickVertical',
|
'rightStickVertical',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
@@ -119,10 +118,6 @@ const RESERVED_CONTROLLER_PROFILE_IDS = new Set(['__proto__', 'constructor', 'pr
|
|||||||
type ControllerBindingsTarget = Required<ResolvedControllerBindingsConfig>;
|
type ControllerBindingsTarget = Required<ResolvedControllerBindingsConfig>;
|
||||||
type ControllerButtonIndicesTarget = Required<ControllerButtonIndicesConfig>;
|
type ControllerButtonIndicesTarget = Required<ControllerButtonIndicesConfig>;
|
||||||
|
|
||||||
function isControllerAxisDirection(value: unknown): value is ControllerAxisDirection {
|
|
||||||
return value === 'negative' || value === 'positive';
|
|
||||||
}
|
|
||||||
|
|
||||||
function isControllerDpadFallback(value: unknown): value is ControllerDpadFallback {
|
function isControllerDpadFallback(value: unknown): value is ControllerDpadFallback {
|
||||||
return value === 'none' || value === 'horizontal' || value === 'vertical';
|
return value === 'none' || value === 'horizontal' || value === 'vertical';
|
||||||
}
|
}
|
||||||
@@ -151,29 +146,6 @@ function resolveLegacyAxisBinding(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseDiscreteBindingObject(value: unknown): ResolvedControllerDiscreteBinding | null {
|
|
||||||
if (!isObject(value) || typeof value.kind !== 'string') return null;
|
|
||||||
if (value.kind === 'none') {
|
|
||||||
return { kind: 'none' };
|
|
||||||
}
|
|
||||||
if (value.kind === 'button') {
|
|
||||||
return typeof value.buttonIndex === 'number' &&
|
|
||||||
Number.isInteger(value.buttonIndex) &&
|
|
||||||
value.buttonIndex >= 0
|
|
||||||
? { kind: 'button', buttonIndex: value.buttonIndex }
|
|
||||||
: null;
|
|
||||||
}
|
|
||||||
if (value.kind === 'axis') {
|
|
||||||
return typeof value.axisIndex === 'number' &&
|
|
||||||
Number.isInteger(value.axisIndex) &&
|
|
||||||
value.axisIndex >= 0 &&
|
|
||||||
isControllerAxisDirection(value.direction)
|
|
||||||
? { kind: 'axis', axisIndex: value.axisIndex, direction: value.direction }
|
|
||||||
: null;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseAxisBindingObject(
|
function parseAxisBindingObject(
|
||||||
value: unknown,
|
value: unknown,
|
||||||
slot: keyof typeof CONTROLLER_AXIS_FALLBACK_BY_SLOT,
|
slot: keyof typeof CONTROLLER_AXIS_FALLBACK_BY_SLOT,
|
||||||
@@ -241,7 +213,7 @@ function applyControllerBindings(
|
|||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const parsedObject = parseDiscreteBindingObject(bindingValue);
|
const parsedObject = parseControllerDiscreteBinding(bindingValue);
|
||||||
if (parsedObject) {
|
if (parsedObject) {
|
||||||
target[key] = parsedObject;
|
target[key] = parsedObject;
|
||||||
} else if (bindingValue !== undefined) {
|
} else if (bindingValue !== undefined) {
|
||||||
@@ -249,7 +221,7 @@ function applyControllerBindings(
|
|||||||
`${pathPrefix}.${key}`,
|
`${pathPrefix}.${key}`,
|
||||||
bindingValue,
|
bindingValue,
|
||||||
target[key],
|
target[key],
|
||||||
"Expected legacy controller button name or binding object with kind 'none', 'button', or 'axis'.",
|
"Expected legacy controller button name or binding object with kind 'none', 'button', or 'axis', and an optional button or axis 'hold'.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,3 +57,18 @@ test('resolveConfig warns for invalid mpv launch mode', () => {
|
|||||||
message: "Expected one of: 'normal', 'maximized', 'fullscreen'.",
|
message: "Expected one of: 'normal', 'maximized', 'fullscreen'.",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('resolveConfig parses the Jimaku auto-open toggle and warns on non-boolean values', () => {
|
||||||
|
const enabled = resolveConfig({ jimaku: { autoOpenWhenPrimarySubtitleMissing: true } });
|
||||||
|
assert.equal(enabled.resolved.jimaku.autoOpenWhenPrimarySubtitleMissing, true);
|
||||||
|
assert.deepEqual(enabled.warnings, []);
|
||||||
|
|
||||||
|
const invalid = resolveConfig({
|
||||||
|
jimaku: { autoOpenWhenPrimarySubtitleMissing: 'sometimes' as never },
|
||||||
|
});
|
||||||
|
assert.equal(invalid.resolved.jimaku.autoOpenWhenPrimarySubtitleMissing, false);
|
||||||
|
assert.deepEqual(
|
||||||
|
invalid.warnings.map((warning) => warning.path),
|
||||||
|
['jimaku.autoOpenWhenPrimarySubtitleMissing'],
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -90,6 +90,18 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
|
|||||||
'Expected positive number.',
|
'Expected positive number.',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const autoOpen = asBoolean(src.jimaku.autoOpenWhenPrimarySubtitleMissing);
|
||||||
|
if (autoOpen !== undefined) {
|
||||||
|
resolved.jimaku.autoOpenWhenPrimarySubtitleMissing = autoOpen;
|
||||||
|
} else if (src.jimaku.autoOpenWhenPrimarySubtitleMissing !== undefined) {
|
||||||
|
warn(
|
||||||
|
'jimaku.autoOpenWhenPrimarySubtitleMissing',
|
||||||
|
src.jimaku.autoOpenWhenPrimarySubtitleMissing,
|
||||||
|
resolved.jimaku.autoOpenWhenPrimarySubtitleMissing,
|
||||||
|
'Expected boolean.',
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const currentTsukihimeSource = isObject(src.tsukihime) ? src.tsukihime : null;
|
const currentTsukihimeSource = isObject(src.tsukihime) ? src.tsukihime : null;
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { resolveConfig } from '../resolve';
|
||||||
|
|
||||||
|
test('subtitleFilter resolves presets and fills custom rule defaults', () => {
|
||||||
|
const { resolved, warnings } = resolveConfig({
|
||||||
|
subtitleFilter: {
|
||||||
|
presets: { parentheses: true },
|
||||||
|
customRules: [
|
||||||
|
{ pattern: '\\n' },
|
||||||
|
{ name: 'tag', pattern: '<i>', replacement: '', enabled: false },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.deepEqual(warnings, []);
|
||||||
|
assert.equal(resolved.subtitleFilter.presets.parentheses, true);
|
||||||
|
assert.equal(resolved.subtitleFilter.presets.brackets, false);
|
||||||
|
assert.deepEqual(resolved.subtitleFilter.customRules, [
|
||||||
|
{ name: '', pattern: '\\n', replacement: '', enabled: true },
|
||||||
|
{ name: 'tag', pattern: '<i>', replacement: '', enabled: false },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('subtitleFilter keeps empty and invalid patterns, warns on invalid, drops malformed rules', () => {
|
||||||
|
const { resolved, warnings } = resolveConfig({
|
||||||
|
subtitleFilter: {
|
||||||
|
presets: { brackets: 'yes' as unknown as boolean },
|
||||||
|
customRules: [
|
||||||
|
{ name: 'broken', pattern: '(' },
|
||||||
|
{ name: 'placeholder', pattern: '' },
|
||||||
|
{ name: 'no pattern' },
|
||||||
|
'oops' as never,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.deepEqual(
|
||||||
|
resolved.subtitleFilter.customRules.map((rule) => rule.name),
|
||||||
|
['broken', 'placeholder'],
|
||||||
|
);
|
||||||
|
assert.equal(resolved.subtitleFilter.presets.brackets, false);
|
||||||
|
assert.deepEqual(
|
||||||
|
warnings.map((warning) => warning.path),
|
||||||
|
[
|
||||||
|
'subtitleFilter.presets.brackets',
|
||||||
|
'subtitleFilter.customRules[0].pattern',
|
||||||
|
'subtitleFilter.customRules[2]',
|
||||||
|
'subtitleFilter.customRules[3]',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import type { SubtitleFilterRule } from '../../types/subtitle';
|
||||||
|
import {
|
||||||
|
SUBTITLE_FILTER_PRESET_IDS,
|
||||||
|
getSubtitleFilterPatternError,
|
||||||
|
} from '../../shared/subtitle-text-filter';
|
||||||
|
import { ResolveContext } from './context';
|
||||||
|
import { asBoolean, asString, isObject } from './shared';
|
||||||
|
|
||||||
|
function resolveCustomRule(
|
||||||
|
raw: unknown,
|
||||||
|
index: number,
|
||||||
|
warn: ResolveContext['warn'],
|
||||||
|
): SubtitleFilterRule | null {
|
||||||
|
const path = `subtitleFilter.customRules[${index}]`;
|
||||||
|
const pattern = isObject(raw) ? asString(raw.pattern) : undefined;
|
||||||
|
if (!isObject(raw) || pattern === undefined) {
|
||||||
|
warn(path, raw, null, 'Expected an object with a string pattern.');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty and invalid patterns stay in the config so the settings window can show and
|
||||||
|
// fix them; the filter skips both at runtime.
|
||||||
|
const patternError = pattern ? getSubtitleFilterPatternError(pattern) : null;
|
||||||
|
if (patternError !== null) {
|
||||||
|
warn(`${path}.pattern`, pattern, null, `Invalid regular expression: ${patternError}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: asString(raw.name) ?? '',
|
||||||
|
pattern,
|
||||||
|
replacement: asString(raw.replacement) ?? '',
|
||||||
|
enabled: asBoolean(raw.enabled) ?? true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applySubtitleFilterConfig(context: ResolveContext): void {
|
||||||
|
const { src, resolved, warn } = context;
|
||||||
|
if (src.subtitleFilter === undefined) return;
|
||||||
|
if (!isObject(src.subtitleFilter)) {
|
||||||
|
warn('subtitleFilter', src.subtitleFilter, resolved.subtitleFilter, 'Expected object.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { presets, customRules } = src.subtitleFilter;
|
||||||
|
if (isObject(presets)) {
|
||||||
|
for (const id of SUBTITLE_FILTER_PRESET_IDS) {
|
||||||
|
const enabled = asBoolean(presets[id]);
|
||||||
|
if (enabled !== undefined) {
|
||||||
|
resolved.subtitleFilter.presets[id] = enabled;
|
||||||
|
} else if (presets[id] !== undefined) {
|
||||||
|
warn(
|
||||||
|
`subtitleFilter.presets.${id}`,
|
||||||
|
presets[id],
|
||||||
|
resolved.subtitleFilter.presets[id],
|
||||||
|
'Expected boolean.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (presets !== undefined) {
|
||||||
|
warn('subtitleFilter.presets', presets, resolved.subtitleFilter.presets, 'Expected object.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(customRules)) {
|
||||||
|
resolved.subtitleFilter.customRules = customRules
|
||||||
|
.map((rule, index) => resolveCustomRule(rule, index, warn))
|
||||||
|
.filter((rule): rule is SubtitleFilterRule => rule !== null);
|
||||||
|
} else if (customRules !== undefined) {
|
||||||
|
warn(
|
||||||
|
'subtitleFilter.customRules',
|
||||||
|
customRules,
|
||||||
|
resolved.subtitleFilter.customRules,
|
||||||
|
'Expected an array of rules.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,10 @@ import type {
|
|||||||
ConfigSettingsField,
|
ConfigSettingsField,
|
||||||
} from '../../types/settings';
|
} from '../../types/settings';
|
||||||
import { CONFIG_OPTION_REGISTRY, DEFAULT_CONFIG } from '../definitions';
|
import { CONFIG_OPTION_REGISTRY, DEFAULT_CONFIG } from '../definitions';
|
||||||
|
import {
|
||||||
|
SUBTITLE_FILTER_PRESET_IDS,
|
||||||
|
SUBTITLE_FILTER_PRESETS,
|
||||||
|
} from '../../shared/subtitle-text-filter';
|
||||||
import {
|
import {
|
||||||
getSubtitleCssManagedConfigPaths,
|
getSubtitleCssManagedConfigPaths,
|
||||||
getSubtitleCssScopeForPath,
|
getSubtitleCssScopeForPath,
|
||||||
@@ -127,6 +131,7 @@ const SECTION_ORDER = new Map<string, number>(
|
|||||||
'Subtitle Sidebar Appearance',
|
'Subtitle Sidebar Appearance',
|
||||||
'Playback Behavior',
|
'Playback Behavior',
|
||||||
'Subtitle Behavior',
|
'Subtitle Behavior',
|
||||||
|
'Subtitle Filters',
|
||||||
'Subtitle Sidebar Behavior',
|
'Subtitle Sidebar Behavior',
|
||||||
'YouTube Playback Settings',
|
'YouTube Playback Settings',
|
||||||
'mpv Playback',
|
'mpv Playback',
|
||||||
@@ -203,6 +208,7 @@ const PATH_ORDER = new Map<string, number>(
|
|||||||
'logging.files.app',
|
'logging.files.app',
|
||||||
'logging.files.launcher',
|
'logging.files.launcher',
|
||||||
'logging.files.mpv',
|
'logging.files.mpv',
|
||||||
|
...SUBTITLE_FILTER_PRESET_IDS.map((id) => `subtitleFilter.presets.${id}`),
|
||||||
].map((path, index) => [path, index]),
|
].map((path, index) => [path, index]),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -253,6 +259,12 @@ const LABEL_OVERRIDES: Record<string, string> = {
|
|||||||
'ankiConnect.media.mirrorMpvVolume': 'Mirror mpv Volume',
|
'ankiConnect.media.mirrorMpvVolume': 'Mirror mpv Volume',
|
||||||
'ankiConnect.media.reviewTiming': 'Review Media Timing',
|
'ankiConnect.media.reviewTiming': 'Review Media Timing',
|
||||||
'discordPresence.updateIntervalMs': 'Update Interval (ms)',
|
'discordPresence.updateIntervalMs': 'Update Interval (ms)',
|
||||||
|
...Object.fromEntries(
|
||||||
|
SUBTITLE_FILTER_PRESET_IDS.map((id) => [
|
||||||
|
`subtitleFilter.presets.${id}`,
|
||||||
|
SUBTITLE_FILTER_PRESETS[id].label,
|
||||||
|
]),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
const DESCRIPTION_OVERRIDES: Record<string, string> = {
|
const DESCRIPTION_OVERRIDES: Record<string, string> = {
|
||||||
@@ -280,6 +292,8 @@ const DESCRIPTION_OVERRIDES: Record<string, string> = {
|
|||||||
'Built-in subtitle WebSocket server mode. Auto starts the built-in server only when mpv_websocket is not detected; otherwise it defers to the plugin.',
|
'Built-in subtitle WebSocket server mode. Auto starts the built-in server only when mpv_websocket is not detected; otherwise it defers to the plugin.',
|
||||||
'discordPresence.updateIntervalMs':
|
'discordPresence.updateIntervalMs':
|
||||||
'Minimum interval between presence payload updates, in milliseconds.',
|
'Minimum interval between presence payload updates, in milliseconds.',
|
||||||
|
'subtitleFilter.customRules':
|
||||||
|
'Your own regex rules, applied in order after the presets. ^ and $ match each line. Leave the replacement empty to remove the match.',
|
||||||
};
|
};
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
@@ -353,6 +367,9 @@ function categoryAndSection(path: string): { category: ConfigSettingsCategory; s
|
|||||||
if (path === 'subtitleStyle.preserveLineBreaks') {
|
if (path === 'subtitleStyle.preserveLineBreaks') {
|
||||||
return { category: 'behavior', section: 'Subtitle Behavior' };
|
return { category: 'behavior', section: 'Subtitle Behavior' };
|
||||||
}
|
}
|
||||||
|
if (path.startsWith('subtitleFilter.')) {
|
||||||
|
return { category: 'behavior', section: 'Subtitle Filters' };
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
path === 'ankiConnect.knownWords.addMinedWordsImmediately' ||
|
path === 'ankiConnect.knownWords.addMinedWordsImmediately' ||
|
||||||
path === 'ankiConnect.knownWords.decks' ||
|
path === 'ankiConnect.knownWords.decks' ||
|
||||||
@@ -557,6 +574,7 @@ function controlForPath(path: string, value: unknown): ConfigSettingsControl {
|
|||||||
if (path.startsWith('subtitleStyle.jlptColors.')) return 'color';
|
if (path.startsWith('subtitleStyle.jlptColors.')) return 'color';
|
||||||
if (path.startsWith('subtitleStyle.knownWordMaturityColors.')) return 'color';
|
if (path.startsWith('subtitleStyle.knownWordMaturityColors.')) return 'color';
|
||||||
if (path === 'subtitleStyle.frequencyDictionary.bandedColors') return 'color-list';
|
if (path === 'subtitleStyle.frequencyDictionary.bandedColors') return 'color-list';
|
||||||
|
if (path === 'subtitleFilter.customRules') return 'subtitle-filter-rules';
|
||||||
if (OPTION_BY_PATH.get(path)?.enumValues?.length) return 'select';
|
if (OPTION_BY_PATH.get(path)?.enumValues?.length) return 'select';
|
||||||
if (JSON_OBJECT_FIELDS.has(path)) return 'json';
|
if (JSON_OBJECT_FIELDS.has(path)) return 'json';
|
||||||
if (Array.isArray(value)) return 'string-list';
|
if (Array.isArray(value)) return 'string-list';
|
||||||
|
|||||||
@@ -155,15 +155,20 @@ const WATCH_TIME_PER_ANIME = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const TRENDS_DASHBOARD = {
|
const TRENDS_DASHBOARD = {
|
||||||
|
window: { startDay: 20_000, endDay: 20_000 },
|
||||||
|
buckets: [{ label: 'Mar 1', startDay: 20_000, endDay: 20_000 }],
|
||||||
|
summary: {
|
||||||
|
current: { watchTimeMin: 25, words: 300, newWords: 12, cards: 5, episodes: 2, activeDays: 1 },
|
||||||
|
previous: null,
|
||||||
|
},
|
||||||
activity: {
|
activity: {
|
||||||
watchTime: [{ label: 'Mar 1', value: 25 }],
|
watchTime: [{ label: 'Mar 1', value: 25 }],
|
||||||
cards: [{ label: 'Mar 1', value: 5 }],
|
cards: [{ label: 'Mar 1', value: 5 }],
|
||||||
words: [{ label: 'Mar 1', value: 300 }],
|
words: [{ label: 'Mar 1', value: 300 }],
|
||||||
sessions: [{ label: 'Mar 1', value: 3 }],
|
episodes: [{ label: 'Mar 1', value: 2 }],
|
||||||
},
|
},
|
||||||
progress: {
|
progress: {
|
||||||
watchTime: [{ label: 'Mar 1', value: 25 }],
|
watchTime: [{ label: 'Mar 1', value: 25 }],
|
||||||
sessions: [{ label: 'Mar 1', value: 3 }],
|
|
||||||
words: [{ label: 'Mar 1', value: 300 }],
|
words: [{ label: 'Mar 1', value: 300 }],
|
||||||
newWords: [{ label: 'Mar 1', value: 12 }],
|
newWords: [{ label: 'Mar 1', value: 12 }],
|
||||||
cards: [{ label: 'Mar 1', value: 5 }],
|
cards: [{ label: 'Mar 1', value: 5 }],
|
||||||
@@ -175,11 +180,19 @@ const TRENDS_DASHBOARD = {
|
|||||||
cardsPerHour: [{ label: 'Mar 1', value: 12 }],
|
cardsPerHour: [{ label: 'Mar 1', value: 12 }],
|
||||||
readingSpeed: [{ label: 'Mar 1', value: 180 }],
|
readingSpeed: [{ label: 'Mar 1', value: 180 }],
|
||||||
},
|
},
|
||||||
|
learning: {
|
||||||
|
newWordsPerThousand: [{ label: 'Mar 1', value: null }],
|
||||||
|
frequencyBands: [],
|
||||||
|
},
|
||||||
|
watchTimeByDayHour: [],
|
||||||
librarySummary: [
|
librarySummary: [
|
||||||
{
|
{
|
||||||
title: 'Little Witch Academia',
|
title: 'Little Witch Academia',
|
||||||
|
animeId: 1,
|
||||||
|
videoId: 1,
|
||||||
watchTimeMin: 25,
|
watchTimeMin: 25,
|
||||||
videos: 1,
|
videos: 1,
|
||||||
|
episodesFinished: 1,
|
||||||
sessions: 1,
|
sessions: 1,
|
||||||
cards: 5,
|
cards: 5,
|
||||||
words: 300,
|
words: 300,
|
||||||
@@ -189,16 +202,7 @@ const TRENDS_DASHBOARD = {
|
|||||||
lastWatched: 20_000,
|
lastWatched: 20_000,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
animeCumulative: {
|
titleTimeline: [{ epochDay: 20_000, animeTitle: 'Little Witch Academia', value: 25 }],
|
||||||
watchTime: [{ epochDay: 20_000, animeTitle: 'Little Witch Academia', value: 25 }],
|
|
||||||
episodes: [{ epochDay: 20_000, animeTitle: 'Little Witch Academia', value: 1 }],
|
|
||||||
cards: [{ epochDay: 20_000, animeTitle: 'Little Witch Academia', value: 5 }],
|
|
||||||
words: [{ epochDay: 20_000, animeTitle: 'Little Witch Academia', value: 300 }],
|
|
||||||
},
|
|
||||||
patterns: {
|
|
||||||
watchTimeByDayOfWeek: [{ label: 'Sun', value: 25 }],
|
|
||||||
watchTimeByHour: [{ label: '12:00', value: 25 }],
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const ANIME_EPISODES = [
|
const ANIME_EPISODES = [
|
||||||
@@ -227,6 +231,12 @@ const WORD_DETAIL = {
|
|||||||
pos2: '一般',
|
pos2: '一般',
|
||||||
pos3: null,
|
pos3: null,
|
||||||
frequency: 42,
|
frequency: 42,
|
||||||
|
frequencyRank: 100,
|
||||||
|
dictionaryReading: 'ねこ',
|
||||||
|
formCount: 1,
|
||||||
|
forms: [{ wordId: 1, word: '猫', reading: 'ねこ', seen: 42 }],
|
||||||
|
lineCount: 40,
|
||||||
|
streamLineCount: 0,
|
||||||
firstSeen: Date.now() - 100_000,
|
firstSeen: Date.now() - 100_000,
|
||||||
lastSeen: Date.now(),
|
lastSeen: Date.now(),
|
||||||
};
|
};
|
||||||
@@ -313,11 +323,11 @@ function createMockTracker(
|
|||||||
}),
|
}),
|
||||||
getVocabularyChartData: async () => ({
|
getVocabularyChartData: async () => ({
|
||||||
ready: true,
|
ready: true,
|
||||||
topWords: [{ wordId: 1, headword: 'する', frequency: 50 }],
|
|
||||||
topWordsWithoutNames: [{ wordId: 1, headword: 'する', frequency: 50 }],
|
|
||||||
newWordsTimeline: [{ epochDay: 20_000, wordCount: 3 }],
|
newWordsTimeline: [{ epochDay: 20_000, wordCount: 3 }],
|
||||||
newWordsTimelineWithoutNames: [{ epochDay: 20_000, wordCount: 3 }],
|
newWordsTimelineWithoutNames: [{ epochDay: 20_000, wordCount: 3 }],
|
||||||
}),
|
}),
|
||||||
|
getDictionaryWords: async () => ({ rows: [], total: 0, maxSeen: 0 }),
|
||||||
|
getVocabularyCoverage: async () => [],
|
||||||
getStatsExcludedWords: async () => [],
|
getStatsExcludedWords: async () => [],
|
||||||
replaceStatsExcludedWords: async () => {},
|
replaceStatsExcludedWords: async () => {},
|
||||||
getKanjiStats: async () => KANJI_STATS,
|
getKanjiStats: async () => KANJI_STATS,
|
||||||
@@ -328,6 +338,7 @@ function createMockTracker(
|
|||||||
hasAnime: async (animeId: number) => animeId === 1,
|
hasAnime: async (animeId: number) => animeId === 1,
|
||||||
getAnimeEpisodes: async () => ANIME_EPISODES,
|
getAnimeEpisodes: async () => ANIME_EPISODES,
|
||||||
getAnimeAnilistEntries: async () => [],
|
getAnimeAnilistEntries: async () => [],
|
||||||
|
getAnimeGroupPlacement: async () => null,
|
||||||
getAnimeWords: async () => ANIME_WORDS,
|
getAnimeWords: async () => ANIME_WORDS,
|
||||||
getAnimeDailyRollups: async () => DAILY_ROLLUPS,
|
getAnimeDailyRollups: async () => DAILY_ROLLUPS,
|
||||||
getEpisodesPerDay: async () => EPISODES_PER_DAY,
|
getEpisodesPerDay: async () => EPISODES_PER_DAY,
|
||||||
@@ -674,9 +685,16 @@ const CLAMPED_QUERIES: Array<{
|
|||||||
];
|
];
|
||||||
|
|
||||||
const TRENDS_DASHBOARD_QUERIES = [
|
const TRENDS_DASHBOARD_QUERIES = [
|
||||||
{ query: 'range=90d&groupBy=month', expectedArgs: ['90d', 'month', true] },
|
{ query: 'range=90d&groupBy=month', expectedArgs: ['90d', 'month', true, null] },
|
||||||
{ query: 'range=weird&groupBy=year', expectedArgs: ['30d', 'day', true] },
|
{ query: 'range=90d&groupBy=week', expectedArgs: ['90d', 'week', true, null] },
|
||||||
{ query: 'range=30d&groupBy=day&fillEmpty=false', expectedArgs: ['30d', 'day', false] },
|
{ query: 'range=weird&groupBy=year', expectedArgs: ['30d', 'day', true, null] },
|
||||||
|
{ query: 'range=30d&groupBy=day&fillEmpty=false', expectedArgs: ['30d', 'day', false, null] },
|
||||||
|
{
|
||||||
|
query: 'range=custom&fromDay=20000&toDay=20010',
|
||||||
|
expectedArgs: [{ startDay: 20000, endDay: 20010 }, 'day', true, null],
|
||||||
|
},
|
||||||
|
{ query: 'range=custom&fromDay=20010&toDay=20000', expectedArgs: ['30d', 'day', true, null] },
|
||||||
|
{ query: 'range=30d&title=Bocchi%20%26%20Co', expectedArgs: ['30d', 'day', true, 'Bocchi & Co'] },
|
||||||
];
|
];
|
||||||
|
|
||||||
const MALFORMED_IDS = [
|
const MALFORMED_IDS = [
|
||||||
@@ -695,7 +713,7 @@ const MALFORMED_IDS = [
|
|||||||
|
|
||||||
/** Every route that takes a positive resource id; `:id` is replaced per request. */
|
/** Every route that takes a positive resource id; `:id` is replaced per request. */
|
||||||
const ID_ROUTES: Array<{
|
const ID_ROUTES: Array<{
|
||||||
method: 'GET' | 'DELETE' | 'PATCH' | 'POST';
|
method: 'GET' | 'DELETE' | 'PATCH' | 'POST' | 'PUT';
|
||||||
path: string;
|
path: string;
|
||||||
body?: unknown;
|
body?: unknown;
|
||||||
}> = [
|
}> = [
|
||||||
@@ -722,6 +740,7 @@ const ID_ROUTES: Array<{
|
|||||||
{ method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } },
|
{ method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } },
|
||||||
{ method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } },
|
{ method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } },
|
||||||
{ method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } },
|
{ method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } },
|
||||||
|
{ method: 'PUT', path: '/api/stats/anime/:id/group', body: { mode: 'standalone' } },
|
||||||
{ method: 'POST', path: '/api/stats/anki/browse?noteId=:id' },
|
{ method: 'POST', path: '/api/stats/anki/browse?noteId=:id' },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -991,7 +1010,7 @@ describe('stats server API routes', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
for (const { query, expectedArgs } of TRENDS_DASHBOARD_QUERIES) {
|
for (const { query, expectedArgs } of TRENDS_DASHBOARD_QUERIES) {
|
||||||
it(`GET /api/stats/trends/dashboard?${query} requests ${expectedArgs.join('/')}`, async () => {
|
it(`GET /api/stats/trends/dashboard?${query} requests ${JSON.stringify(expectedArgs)}`, async () => {
|
||||||
let seenArgs: unknown[] = [];
|
let seenArgs: unknown[] = [];
|
||||||
const app = createStatsApp(
|
const app = createStatsApp(
|
||||||
createMockTracker({
|
createMockTracker({
|
||||||
@@ -1008,6 +1027,69 @@ describe('stats server API routes', () => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
it('GET /api/stats/vocabulary/words passes a parsed query and ignores unknown values', async () => {
|
||||||
|
const seenQueries: unknown[] = [];
|
||||||
|
const app = createStatsApp(
|
||||||
|
createMockTracker({
|
||||||
|
getDictionaryWords: async (_knownWords: unknown, query: unknown) => {
|
||||||
|
seenQueries.push(query);
|
||||||
|
return { rows: [], total: 0, maxSeen: 0 };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await app.request(
|
||||||
|
'/api/stats/vocabulary/words?search=%20%E7%8C%AB%20&sort=rank&order=asc&hideKnown=true&hideNames=true&pos=verb&maxRank=10000&minTitles=2&limit=25&offset=50',
|
||||||
|
);
|
||||||
|
await app.request('/api/stats/vocabulary/words?sort=bogus&pos=bogus&maxRank=-1&limit=99999');
|
||||||
|
|
||||||
|
assert.deepEqual(seenQueries, [
|
||||||
|
{
|
||||||
|
search: '猫',
|
||||||
|
sort: 'rank',
|
||||||
|
descending: false,
|
||||||
|
hideKnown: true,
|
||||||
|
hideNames: true,
|
||||||
|
hideKana: false,
|
||||||
|
partOfSpeech: 'verb',
|
||||||
|
maxRank: 10000,
|
||||||
|
minTitles: 2,
|
||||||
|
limit: 25,
|
||||||
|
offset: 50,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
search: undefined,
|
||||||
|
sort: 'seen',
|
||||||
|
descending: true,
|
||||||
|
hideKnown: false,
|
||||||
|
hideNames: false,
|
||||||
|
hideKana: false,
|
||||||
|
partOfSpeech: undefined,
|
||||||
|
maxRank: undefined,
|
||||||
|
minTitles: undefined,
|
||||||
|
limit: 200,
|
||||||
|
offset: 0,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/stats/sessions narrows to a valid day range and ignores a reversed one', async () => {
|
||||||
|
const seenRanges: unknown[] = [];
|
||||||
|
const app = createStatsApp(
|
||||||
|
createMockTracker({
|
||||||
|
getSessionSummaries: async (_limit?: number, dayRange?: unknown) => {
|
||||||
|
seenRanges.push(dayRange);
|
||||||
|
return SESSION_SUMMARIES;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await app.request('/api/stats/sessions?limit=500&fromDay=20000&toDay=20006');
|
||||||
|
await app.request('/api/stats/sessions?fromDay=20006&toDay=20000');
|
||||||
|
|
||||||
|
assert.deepEqual(seenRanges, [{ startDay: 20000, endDay: 20006 }, undefined]);
|
||||||
|
});
|
||||||
|
|
||||||
it('GET /api/stats/vocabulary/occurrences returns recent occurrence rows for a word', async () => {
|
it('GET /api/stats/vocabulary/occurrences returns recent occurrence rows for a word', async () => {
|
||||||
let seenArgs: unknown[] = [];
|
let seenArgs: unknown[] = [];
|
||||||
const app = createStatsApp(
|
const app = createStatsApp(
|
||||||
@@ -1026,7 +1108,7 @@ describe('stats server API routes', () => {
|
|||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
assert.ok(Array.isArray(body));
|
assert.ok(Array.isArray(body));
|
||||||
assert.equal(body[0].animeTitle, 'Little Witch Academia');
|
assert.equal(body[0].animeTitle, 'Little Witch Academia');
|
||||||
assert.deepEqual(seenArgs, ['猫', '猫', 'ねこ', 500, 25]);
|
assert.deepEqual(seenArgs, ['猫', '猫', 'ねこ', 500, 25, false]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('GET /api/stats/kanji/occurrences returns recent occurrence rows for a kanji', async () => {
|
it('GET /api/stats/kanji/occurrences returns recent occurrence rows for a kanji', async () => {
|
||||||
@@ -1056,6 +1138,33 @@ describe('stats server API routes', () => {
|
|||||||
assert.equal(res.status, 400);
|
assert.equal(res.status, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('GET /api/stats/vocabulary/occurrences finds all forms of legacy words missing text', async () => {
|
||||||
|
const seenHeadwords: unknown[] = [];
|
||||||
|
const app = createStatsApp(
|
||||||
|
createMockTracker({
|
||||||
|
getWordOccurrences: async (...args: unknown[]) => {
|
||||||
|
seenHeadwords.push(args[0]);
|
||||||
|
return OCCURRENCES;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const request = (params: string) =>
|
||||||
|
app.request(`/api/stats/vocabulary/occurrences?allForms=true&${params}`);
|
||||||
|
|
||||||
|
assert.equal((await request('headword=&word=%E7%8C%AB&reading=')).status, 200);
|
||||||
|
assert.equal((await request('headword=%E7%8A%AC&word=&reading=')).status, 200);
|
||||||
|
assert.equal((await request('headword=&word=&reading=%E3%81%AD%E3%81%93')).status, 200);
|
||||||
|
assert.deepEqual(seenHeadwords, ['猫', '犬', 'ねこ']);
|
||||||
|
|
||||||
|
assert.equal((await request('headword=%20&word=&reading=')).status, 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/stats/vocabulary/occurrences needs a headword and form for an exact lookup', async () => {
|
||||||
|
const app = createStatsApp(createMockTracker());
|
||||||
|
const res = await app.request('/api/stats/vocabulary/occurrences?headword=&word=%E7%8C%AB');
|
||||||
|
assert.equal(res.status, 400);
|
||||||
|
});
|
||||||
|
|
||||||
it('PUT /api/stats/excluded-words replaces tracker exclusion rows', async () => {
|
it('PUT /api/stats/excluded-words replaces tracker exclusion rows', async () => {
|
||||||
let seenWords: unknown = null;
|
let seenWords: unknown = null;
|
||||||
const app = createStatsApp(
|
const app = createStatsApp(
|
||||||
@@ -2322,6 +2431,50 @@ describe('stats server API routes', () => {
|
|||||||
assert.equal(mergeCalls, 0);
|
assert.equal(mergeCalls, 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('PUT /api/stats/anime/:animeId/group validates the body and maps refusals', async () => {
|
||||||
|
const calls: unknown[] = [];
|
||||||
|
const app = createStatsApp(
|
||||||
|
createMockTracker({
|
||||||
|
setAnimeGroupOverride: async (animeId, target) => {
|
||||||
|
calls.push([animeId, target]);
|
||||||
|
if (target.mode === 'join' && target.targetAnimeId === 9) {
|
||||||
|
return { ok: false, reason: 'target-not-grouped' };
|
||||||
|
}
|
||||||
|
if (animeId === 404) return { ok: false, reason: 'not-found' };
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const put = (path: string, body: unknown) =>
|
||||||
|
app.request(path, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(body) });
|
||||||
|
|
||||||
|
for (const body of [
|
||||||
|
{},
|
||||||
|
{ mode: 'join' },
|
||||||
|
{ mode: 'join', targetAnimeId: 0 },
|
||||||
|
{ mode: 'join', targetAnimeId: '8' },
|
||||||
|
{ mode: 'join', targetAnimeId: 3 },
|
||||||
|
{ mode: 'reset' },
|
||||||
|
]) {
|
||||||
|
assert.equal((await put('/api/stats/anime/3/group', body)).status, 400, JSON.stringify(body));
|
||||||
|
}
|
||||||
|
assert.deepEqual(calls, []);
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
(await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 8 })).status,
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
assert.equal((await put('/api/stats/anime/3/group', { mode: 'anilist' })).status, 200);
|
||||||
|
assert.equal((await put('/api/stats/anime/404/group', { mode: 'standalone' })).status, 404);
|
||||||
|
const refused = await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 9 });
|
||||||
|
assert.equal(refused.status, 409);
|
||||||
|
assert.match((await refused.json()).error, /no AniList entry/);
|
||||||
|
assert.deepEqual(calls.slice(0, 2), [
|
||||||
|
[3, { mode: 'join', targetAnimeId: 8 }],
|
||||||
|
[3, { mode: 'anilist' }],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => {
|
it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => {
|
||||||
let moved: { videoId: number; animeId: number } | null = null;
|
let moved: { videoId: number; animeId: number } | null = null;
|
||||||
const app = createStatsApp(
|
const app = createStatsApp(
|
||||||
|
|||||||
@@ -0,0 +1,651 @@
|
|||||||
|
// Captured from live AniList responses on 2026-11-22, trimmed to the fields the resolver reads.
|
||||||
|
// Each chain is in SEQUEL order: entry i's only SEQUEL is entry i + 1.
|
||||||
|
import type { AnilistSeasonMedia } from '../season-resolver';
|
||||||
|
|
||||||
|
/** Mushoku Tensei: S1 -> "Cour 2" -> S2 -> "Season 2 Part 2" -> S3 -> S3 Part 2. */
|
||||||
|
export const MUSHOKU_CHAIN: AnilistSeasonMedia[] = [
|
||||||
|
{
|
||||||
|
id: 108465,
|
||||||
|
episodes: 11,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2021,
|
||||||
|
synonyms: [
|
||||||
|
'Jobless Reincarnation: I Will Seriously Try If I Go To Another World',
|
||||||
|
'无职转生 ~到了异世界就拿出真本事~',
|
||||||
|
'เกิดชาตินี้พี่ต้องเทพ',
|
||||||
|
'Thất nghiệp chuyển sinh',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu',
|
||||||
|
english: 'Mushoku Tensei: Jobless Reincarnation',
|
||||||
|
native: '無職転生 ~異世界行ったら本気だす~',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 127720,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2021,
|
||||||
|
synonyms: ['Mushoku Tensei: Jobless Reincarnation Part 2', 'เกิดชาตินี้พี่ต้องเทพ พาร์ท 2'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu Part 2',
|
||||||
|
english: 'Mushoku Tensei: Jobless Reincarnation Cour 2',
|
||||||
|
native: '無職転生 ~異世界行ったら本気だす~ 第2クール',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 146065,
|
||||||
|
episodes: 13,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2023,
|
||||||
|
synonyms: [
|
||||||
|
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2',
|
||||||
|
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season',
|
||||||
|
'Mushoku Tensei II: Jobless Reincarnation',
|
||||||
|
'Mushoku Tensei II: Reencarnación desde cero',
|
||||||
|
'无职转生~到了异世界就拿出真本事~第2季',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu',
|
||||||
|
english: 'Mushoku Tensei: Jobless Reincarnation Season 2',
|
||||||
|
native: '無職転生Ⅱ ~異世界行ったら本気だす~',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 166873,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2024,
|
||||||
|
synonyms: [
|
||||||
|
'Mushoku Tensei: Jobless Reincarnation Season 2 Cour 2',
|
||||||
|
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2 ครึ่งหลัง',
|
||||||
|
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season Part 2',
|
||||||
|
'Mushoku Tensei II: Jobless Reincarnation Part 2',
|
||||||
|
'Mushoku Tensei II: Reencarnación desde cero',
|
||||||
|
'无职转生~到了异世界就拿出真本事~第2季',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu Part 2',
|
||||||
|
english: 'Mushoku Tensei: Jobless Reincarnation Season 2 Part 2',
|
||||||
|
native: '無職転生Ⅱ ~異世界行ったら本気だす~ 第2クール',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 178789,
|
||||||
|
episodes: 14,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2026,
|
||||||
|
synonyms: [
|
||||||
|
'無職転生 ~異世界行ったら本気だす~ 第3期',
|
||||||
|
'Mushoku Tensei: Isekai Ittara Honki Dasu 3rd Season',
|
||||||
|
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 3',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu',
|
||||||
|
english: 'Mushoku Tensei: Jobless Reincarnation Season 3',
|
||||||
|
native: '無職転生Ⅲ ~異世界行ったら本気だす~',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 217434,
|
||||||
|
episodes: null,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2027,
|
||||||
|
synonyms: ['Mushoku Tensei: Jobless Reincarnation Season 3 Part 2'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu Part 2',
|
||||||
|
english: null,
|
||||||
|
native: '無職転生Ⅲ ~異世界行ったら本気だす~ 第2クール',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Re:ZERO: S1 -> S2 -> "Season 2 Part 2" -> S3 -> S4 -> S5 (unaired). */
|
||||||
|
export const REZERO_CHAIN: AnilistSeasonMedia[] = [
|
||||||
|
{
|
||||||
|
id: 21355,
|
||||||
|
episodes: 25,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2016,
|
||||||
|
synonyms: [
|
||||||
|
'Re: Life in a different world from zero',
|
||||||
|
'ReZero',
|
||||||
|
'Re Zero',
|
||||||
|
'Re:从零开始的异世界生活',
|
||||||
|
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก',
|
||||||
|
'Re:Zero — жизнь с нуля в другом мире',
|
||||||
|
'Re:Zero Empezar de cero en un mundo diferente',
|
||||||
|
'Re:Zero – Bắt đầu lại ở thế giới khác',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu',
|
||||||
|
english: 'Re:ZERO -Starting Life in Another World-',
|
||||||
|
native: 'Re:ゼロから始める異世界生活',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 108632,
|
||||||
|
episodes: 13,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2020,
|
||||||
|
synonyms: [
|
||||||
|
'Re:Zero kara Hajimeru Isekai Seikatsu (2020)',
|
||||||
|
'Re: 제로부터 시작하는 이세계 생활 2기',
|
||||||
|
'Re:从零开始的异世界生活第二季(上半)',
|
||||||
|
'Re:从零开始的异世界生活 2 上半',
|
||||||
|
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2',
|
||||||
|
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season',
|
||||||
|
english: 'Re:ZERO -Starting Life in Another World- Season 2',
|
||||||
|
native: 'Re:ゼロから始める異世界生活 2nd Season',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 119661,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2021,
|
||||||
|
synonyms: [
|
||||||
|
'Re:Zero kara Hajimeru Isekai Seikatsu (2021)',
|
||||||
|
'Re: 제로부터 시작하는 이세계 생활 2기 파트 2',
|
||||||
|
'Re:从零开始的异世界生活第二季(下半)',
|
||||||
|
'Re:从零开始的异世界生活 2 下半',
|
||||||
|
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2 พาร์ท 2',
|
||||||
|
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season Part 2',
|
||||||
|
english: 'Re:ZERO -Starting Life in Another World- Season 2 Part 2',
|
||||||
|
native: 'Re:ゼロから始める異世界生活 2nd Season Part 2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 163134,
|
||||||
|
episodes: 16,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2024,
|
||||||
|
synonyms: ['Re:ZERO – Жизнь с нуля в альтернативном мире 3'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 3rd Season',
|
||||||
|
english: 'Re:ZERO -Starting Life in Another World- Season 3',
|
||||||
|
native: 'Re:ゼロから始める異世界生活 3rd season',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 189046,
|
||||||
|
episodes: 19,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2026,
|
||||||
|
synonyms: [
|
||||||
|
'Re:ZERO รีเซทชีวิต ฝ่าวิกฤตต่างโลก ซีซั่น 4',
|
||||||
|
'Re:ZERO – Жизнь с нуля в альтернативном мире 4',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 4th Season',
|
||||||
|
english: 'Re:ZERO -Starting Life in Another World- Season 4',
|
||||||
|
native: 'Re:ゼロから始める異世界生活 4th season',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 219904,
|
||||||
|
episodes: null,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: null,
|
||||||
|
synonyms: ['Re:ZERO -Starting Life in Another World- Season 5'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 5th Season',
|
||||||
|
english: null,
|
||||||
|
native: 'Re:ゼロから始める異世界生活 5th season',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Dr. STONE: STONE WARS reaches NEW WORLD through a one-episode SPECIAL. */
|
||||||
|
export const DR_STONE_CHAIN: AnilistSeasonMedia[] = [
|
||||||
|
{
|
||||||
|
id: 105333,
|
||||||
|
episodes: 24,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2019,
|
||||||
|
synonyms: [
|
||||||
|
'Dcst',
|
||||||
|
'石纪元',
|
||||||
|
'ドクターストーン',
|
||||||
|
'ดร.สโตน เจ้าแห่งวิทยาศาสตร์กู้คืนอารยธรรมโลก',
|
||||||
|
'Доктор Стоун',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Dr. STONE',
|
||||||
|
english: 'Dr. STONE',
|
||||||
|
native: 'Dr.STONE',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 113936,
|
||||||
|
episodes: 11,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2021,
|
||||||
|
synonyms: [
|
||||||
|
'ドクターストーン STONE WARS',
|
||||||
|
'Dr.STONE第2期',
|
||||||
|
'Dr. STONE 2',
|
||||||
|
'닥터 스톤 STONE WARS',
|
||||||
|
'石纪元第二季',
|
||||||
|
'DR.STONE ภาค 2',
|
||||||
|
'Доктор Стоун: Каменные войны',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Dr. STONE: STONE WARS',
|
||||||
|
english: 'Dr. STONE: STONE WARS',
|
||||||
|
native: 'Dr.STONE STONE WARS',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 142876,
|
||||||
|
episodes: 1,
|
||||||
|
format: 'SPECIAL',
|
||||||
|
seasonYear: 2022,
|
||||||
|
synonyms: ['Dr. STONE: Ryusui', 'Доктор Стоун: Рюсуй'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Dr. STONE: Ryuusui',
|
||||||
|
english: 'Dr. STONE Special Episode – RYUSUI',
|
||||||
|
native: 'Dr.STONE 龍水',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 131518,
|
||||||
|
episodes: 11,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2023,
|
||||||
|
synonyms: [
|
||||||
|
'石纪元第三季',
|
||||||
|
'Dr.STONE Season 3',
|
||||||
|
'DR.STONE ภาค 3',
|
||||||
|
'Dr.STONE 第3期',
|
||||||
|
'Dr. STONE 新石紀(第三季)',
|
||||||
|
'Доктор Стоун: Новый Свет',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Dr. STONE: NEW WORLD',
|
||||||
|
english: 'Dr. STONE New World',
|
||||||
|
native: 'Dr.STONE NEW WORLD',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 162670,
|
||||||
|
episodes: 11,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2023,
|
||||||
|
synonyms: [
|
||||||
|
'石纪元第三季',
|
||||||
|
'Dr.STONE Season 3 Part 2',
|
||||||
|
'DR.STONE ภาค 3',
|
||||||
|
'Dr.STONE 第3期 第2クール',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Dr. STONE: NEW WORLD Part 2',
|
||||||
|
english: 'Dr. STONE New World Part 2',
|
||||||
|
native: 'Dr.STONE NEW WORLD 第2クール',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 172019,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2025,
|
||||||
|
synonyms: ['Dr.STONE Season 4', 'Dr.STONE 第4期', 'ドクターストーン'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Dr. STONE: SCIENCE FUTURE',
|
||||||
|
english: 'Dr. STONE SCIENCE FUTURE',
|
||||||
|
native: 'Dr.STONE SCIENCE FUTURE',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Bleach TYBW: cours named after arcs; "Part N" only in synonyms, spelled "Thousand Year". */
|
||||||
|
export const BLEACH_TYBW_CHAIN: AnilistSeasonMedia[] = [
|
||||||
|
{
|
||||||
|
id: 116674,
|
||||||
|
episodes: 13,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2022,
|
||||||
|
synonyms: [
|
||||||
|
'بليتش: حرب الألف سنة الدموية',
|
||||||
|
'Bleach: La guerre sanglante de mille ans',
|
||||||
|
'BLEACH TYBW',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'BLEACH: Sennen Kessen-hen',
|
||||||
|
english: 'BLEACH: Thousand-Year Blood War',
|
||||||
|
native: 'BLEACH 千年血戦篇',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 159322,
|
||||||
|
episodes: 13,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2023,
|
||||||
|
synonyms: [
|
||||||
|
'BLEACH: Thousand Year Blood War Part 2',
|
||||||
|
'BLEACH 千年血戦篇 第2クール',
|
||||||
|
'BLEACH TYBW',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'BLEACH: Sennen Kessen-hen - Ketsubetsu-tan',
|
||||||
|
english: 'BLEACH: Thousand-Year Blood War - The Separation',
|
||||||
|
native: 'BLEACH 千年血戦篇-訣別譚-',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 169755,
|
||||||
|
episodes: 14,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2024,
|
||||||
|
synonyms: [
|
||||||
|
'BLEACH: Thousand Year Blood War Part 3',
|
||||||
|
'BLEACH 千年血戦篇 第3クール',
|
||||||
|
'BLEACH TYBW',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'BLEACH: Sennen Kessen-hen - Soukoku-tan',
|
||||||
|
english: 'BLEACH: Thousand-Year Blood War - The Conflict',
|
||||||
|
native: 'BLEACH 千年血戦篇-相剋譚-',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 185874,
|
||||||
|
episodes: 10,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2026,
|
||||||
|
synonyms: [
|
||||||
|
'BLEACH: Thousand-Year Blood War Part 4',
|
||||||
|
'BLEACH 千年血戦篇 第4クール',
|
||||||
|
'BLEACH: Thousand-Year Blood War The Final Season',
|
||||||
|
'BLEACH TYBW',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'BLEACH: Sennen Kessen-hen - Kashin-tan',
|
||||||
|
english: 'BLEACH: Thousand-Year Blood War - The Calamity',
|
||||||
|
native: 'BLEACH 千年血戦篇-禍進譚-',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Attack on Titan: season 3 carries the Thai synonym "... ภาค 3 Part 1"; the chain ends in SPECIALs. */
|
||||||
|
export const AOT_CHAIN: AnilistSeasonMedia[] = [
|
||||||
|
{
|
||||||
|
id: 16498,
|
||||||
|
episodes: 25,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2013,
|
||||||
|
synonyms: [
|
||||||
|
'SnK',
|
||||||
|
'AoT',
|
||||||
|
'Ataque a los Titanes',
|
||||||
|
'Ataque dos Titãs',
|
||||||
|
"L'Attacco dei Giganti",
|
||||||
|
'מתקפת הטיטאנים',
|
||||||
|
'进击的巨人',
|
||||||
|
'L’Attaque des Titans',
|
||||||
|
'الهجوم على العمالقة',
|
||||||
|
'ผ่าพิภพไททัน',
|
||||||
|
'حمله به تایتان',
|
||||||
|
'Ataque de Titãs',
|
||||||
|
'Atak Tytanów',
|
||||||
|
'Атака титанов',
|
||||||
|
'Đại Chiến Titan',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Shingeki no Kyojin',
|
||||||
|
english: 'Attack on Titan',
|
||||||
|
native: '進撃の巨人',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 20958,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2017,
|
||||||
|
synonyms: [
|
||||||
|
'SnK 2',
|
||||||
|
'AoT 2',
|
||||||
|
'+מתקפת הטיטאנים עונה 2',
|
||||||
|
"L'Attacco dei Giganti 2",
|
||||||
|
"L'Attacco dei Giganti - Seconda Stagione",
|
||||||
|
'ผ่าพิภพไททัน ภาค 2',
|
||||||
|
'حمله به تایتان فصل 2',
|
||||||
|
'Атака титанов 2',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Shingeki no Kyojin Season 2',
|
||||||
|
english: 'Attack on Titan Season 2',
|
||||||
|
native: '進撃の巨人 Season2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 99147,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2018,
|
||||||
|
synonyms: [
|
||||||
|
'SnK 3',
|
||||||
|
'AoT 3',
|
||||||
|
'מתקפת הטיטאנים עונה 3',
|
||||||
|
"L'Attacco dei Giganti 3",
|
||||||
|
"L'Attacco dei Giganti - Terza Stagione",
|
||||||
|
'ผ่าพิภพไททัน ภาค 3',
|
||||||
|
'حمله به تایتان فصل 3',
|
||||||
|
'ผ่าพิภพไททัน ภาค 3 Part 1',
|
||||||
|
'Атака титанов 3',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Shingeki no Kyojin Season 3',
|
||||||
|
english: 'Attack on Titan Season 3',
|
||||||
|
native: '進撃の巨人 Season3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 104578,
|
||||||
|
episodes: 10,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2019,
|
||||||
|
synonyms: [
|
||||||
|
'SnK 3',
|
||||||
|
'AoT 3',
|
||||||
|
'Shingeki no Kyojin Season 3 (2019)',
|
||||||
|
"L'Attaco dei Giganti 3 Parte 2",
|
||||||
|
"L'Attacco dei Giganti - Terza Stagione Parte 2",
|
||||||
|
'מתקפת הטיטאנים עונה 3 חלק 2',
|
||||||
|
"L'Attaque des Titans Saison 3 Partie 2 ",
|
||||||
|
'ผ่าพิภพไททัน ภาค 3 Part 2',
|
||||||
|
'ผ่าพิภพไททัน ภาค 3 พาร์ท 2',
|
||||||
|
'حمله به تایتان فصل 3',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Shingeki no Kyojin Season 3 Part 2',
|
||||||
|
english: 'Attack on Titan Season 3 Part 2',
|
||||||
|
native: '進撃の巨人 Season3 Part.2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 110277,
|
||||||
|
episodes: 16,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2021,
|
||||||
|
synonyms: [
|
||||||
|
'SnK 4',
|
||||||
|
'AoT 4',
|
||||||
|
'Shingeki no Kyojin 4',
|
||||||
|
'進撃の巨人4',
|
||||||
|
'Attack on Titan Season 4',
|
||||||
|
'진격의 거인 더 파이널 시즌',
|
||||||
|
'מתקפת הטיטאנים העונה האחרונה',
|
||||||
|
"L'Attaque des Titans Saison Finale",
|
||||||
|
"L'Attacco dei Giganti 4",
|
||||||
|
"L'Attacco dei Giganti - La Stagione Finale",
|
||||||
|
'حمله به تایتان فصل 4 ',
|
||||||
|
' ผ่าพิภพไททัน ไฟนอล ซีซั่น',
|
||||||
|
'ผ่าพิภพไททัน Final Season',
|
||||||
|
'ผ่าพิภพไททัน ภาค 4',
|
||||||
|
'هجوم العملاقة الجزء الأخير',
|
||||||
|
'Атака Титанов: Финал',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Shingeki no Kyojin: The Final Season',
|
||||||
|
english: 'Attack on Titan Final Season',
|
||||||
|
native: '進撃の巨人 The Final Season',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 131681,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2022,
|
||||||
|
synonyms: [
|
||||||
|
'SnK 4',
|
||||||
|
'AoT 4',
|
||||||
|
"L'attaque des titans Saison Finale Partie 2",
|
||||||
|
'Shingeki no Kyojin: The Final Season (2022)',
|
||||||
|
'اتک عن تایتان',
|
||||||
|
'حمله به غول ها',
|
||||||
|
'حمله به تایتان فصل 4 ',
|
||||||
|
' ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 2',
|
||||||
|
'ผ่าพิภพไททัน ภาค 4',
|
||||||
|
"L'Attacco dei Giganti 4 Parte 2",
|
||||||
|
'Атака титанов: Финал. Часть 2',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Shingeki no Kyojin: The Final Season Part 2',
|
||||||
|
english: 'Attack on Titan Final Season Part 2',
|
||||||
|
native: '進撃の巨人 The Final Season Part 2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 146984,
|
||||||
|
episodes: 1,
|
||||||
|
format: 'SPECIAL',
|
||||||
|
seasonYear: 2023,
|
||||||
|
synonyms: [
|
||||||
|
'Shingeki no Kyojin: The Final Season Final Edition',
|
||||||
|
'Shingeki no Kyojin: The Final Season Part 3',
|
||||||
|
'ผ่าพิภพไททัน ภาค 4',
|
||||||
|
'ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 3',
|
||||||
|
'Attack on Titan Final Season Part 3 Final Arc Part 1',
|
||||||
|
'Attack on Titan The Final Season The Final Part Special',
|
||||||
|
'Attack on Titan The Final Season The Final Part Part 1',
|
||||||
|
'حمله به تایتان فصل آخر قسمت ویژه 1 ',
|
||||||
|
'SnK 4',
|
||||||
|
'AoT 4',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'Shingeki no Kyojin: The Final Season - Kanketsu-hen Zenpen',
|
||||||
|
english: 'Attack on Titan Final Season THE FINAL CHAPTERS Special 1',
|
||||||
|
native: '進撃の巨人 The Final Season完結編 前編',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Overlord: seasons named only by a trailing roman numeral. */
|
||||||
|
export const OVERLORD_CHAIN: AnilistSeasonMedia[] = [
|
||||||
|
{
|
||||||
|
id: 20832,
|
||||||
|
episodes: 13,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2015,
|
||||||
|
synonyms: ['Over Lord', 'โอเวอร์ลอร์ด', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Overlord',
|
||||||
|
english: 'Overlord',
|
||||||
|
native: 'オーバーロード',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 98437,
|
||||||
|
episodes: 13,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2018,
|
||||||
|
synonyms: ['Over Lord 2', 'โอเวอร์ลอร์ด ภาค 2', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 2'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Overlord II',
|
||||||
|
english: 'Overlord II',
|
||||||
|
native: 'オーバーロードⅡ',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 101474,
|
||||||
|
episodes: 13,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2018,
|
||||||
|
synonyms: ['Over Lord 3', 'โอเวอร์ลอร์ด ภาค 3', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 3'],
|
||||||
|
title: {
|
||||||
|
romaji: 'Overlord III',
|
||||||
|
english: 'Overlord III',
|
||||||
|
native: 'オーバーロードⅢ',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** JoJo: Golden Wind ends in the synonym "Part 5", Stone Ocean in "Part 6"; both are new seasons. */
|
||||||
|
export const JOJO_CHAIN: AnilistSeasonMedia[] = [
|
||||||
|
{
|
||||||
|
id: 21450,
|
||||||
|
episodes: 39,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2016,
|
||||||
|
synonyms: [
|
||||||
|
'JoJo no Kimyou na Bouken Part 4: Diamond wa Kudakenai',
|
||||||
|
"JoJo's Bizarre Adventure Part 4: Diamond is Unbreakable",
|
||||||
|
'مغامرات جوجو العجيبة: الألماس غير قابل للكسر',
|
||||||
|
'Le bizzarre avventure di JoJo: Diamond is Unbreakable',
|
||||||
|
'Невероятные приключения ДжоДжо: Diamond is Unbreakable',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'JoJo no Kimyou na Bouken: Diamond wa Kudakenai',
|
||||||
|
english: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
|
||||||
|
native: 'ジョジョの奇妙な冒険 ダイヤモンドは砕けない',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 102883,
|
||||||
|
episodes: 39,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2018,
|
||||||
|
synonyms: [
|
||||||
|
"JoJo's Bizarre Adventure Part 5",
|
||||||
|
"JoJo's Bizarre Adventure: Vento Aureo",
|
||||||
|
'Le Bizzarre Avventure Di GioGio: Vento Aureo',
|
||||||
|
'مغامرات جوجو العجيبة: الرياح الذهبية',
|
||||||
|
'Невероятные приключения ДжоДжо: Золотой ветер',
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'JoJo no Kimyou na Bouken: Ougon no Kaze',
|
||||||
|
english: "JoJo's Bizarre Adventure: Golden Wind",
|
||||||
|
native: 'ジョジョの奇妙な冒険 黄金の風',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 131942,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'ONA',
|
||||||
|
seasonYear: 2021,
|
||||||
|
synonyms: [
|
||||||
|
"JoJo's Bizarre Adventure: Stone Ocean",
|
||||||
|
"JoJo's Bizarre Adventure Part 6",
|
||||||
|
'JoJo no Kimyou na Bouken Part 6',
|
||||||
|
'Le bizzarre avventure di JoJo: Stone Ocean',
|
||||||
|
'โจโจ้ ล่าข้ามศตวรรษ: สโตนโอเชียน ',
|
||||||
|
'โจโจ้ ล่าข้ามศตวรรษ ภาค 6',
|
||||||
|
'مغامرات جوجو العجيبة: محيط الأحجار',
|
||||||
|
"ההרפתקה המוזרה של ג'וג'ו: אוקיינוס האבן",
|
||||||
|
'Невероятные приключения ДжоДжо: Каменный океан ',
|
||||||
|
"Химерні пригоди ДжоДжо: Кам'яний океан",
|
||||||
|
],
|
||||||
|
title: {
|
||||||
|
romaji: 'JoJo no Kimyou na Bouken: Stone Ocean',
|
||||||
|
english: "JoJo's Bizarre Adventure: STONE OCEAN",
|
||||||
|
native: 'ジョジョの奇妙な冒険 ストーンオーシャン',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import type { AnilistRateLimiter } from './rate-limiter';
|
||||||
|
|
||||||
|
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
|
||||||
|
|
||||||
|
export class AnilistRateLimitedError extends Error {
|
||||||
|
constructor() {
|
||||||
|
super('Anilist rate limit reached');
|
||||||
|
this.name = 'AnilistRateLimitedError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs one anonymous AniList GraphQL query through the shared rate limiter.
|
||||||
|
* Throws AnilistRateLimitedError on HTTP 429 (the limiter has already recorded
|
||||||
|
* the retry window) and a plain Error for other HTTP or GraphQL failures.
|
||||||
|
*/
|
||||||
|
export async function executeAnilistQuery<T>(
|
||||||
|
rateLimiter: AnilistRateLimiter,
|
||||||
|
query: string,
|
||||||
|
variables: Record<string, unknown>,
|
||||||
|
): Promise<T> {
|
||||||
|
await rateLimiter.acquire();
|
||||||
|
|
||||||
|
const res = await fetch(ANILIST_GRAPHQL_URL, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||||
|
body: JSON.stringify({ query, variables }),
|
||||||
|
});
|
||||||
|
|
||||||
|
rateLimiter.recordResponse(res.headers);
|
||||||
|
|
||||||
|
if (res.status === 429) {
|
||||||
|
throw new AnilistRateLimitedError();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
|
||||||
|
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
|
||||||
|
if (firstError?.message) {
|
||||||
|
throw new Error(firstError.message);
|
||||||
|
}
|
||||||
|
if (!json.data) {
|
||||||
|
throw new Error('Anilist response missing data');
|
||||||
|
}
|
||||||
|
return json.data;
|
||||||
|
}
|
||||||
@@ -34,6 +34,21 @@ test('guessAnilistMediaInfo fills missing guessit episode from filename parser',
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('guessAnilistMediaInfo fallback keeps the series of a stream title with slashes', async () => {
|
||||||
|
const title = 'Seitokai Yakuindomo S01E01 Under the Cherry Tree / For Now, Lets Try Stripping';
|
||||||
|
const result = await guessAnilistMediaInfo('jellyfin://host/item/abc', title, {
|
||||||
|
runGuessit: async () => {
|
||||||
|
throw new Error('guessit unavailable');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.deepEqual(result, {
|
||||||
|
title: 'Seitokai Yakuindomo',
|
||||||
|
season: 1,
|
||||||
|
episode: 1,
|
||||||
|
source: 'fallback',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test('guessAnilistMediaInfo keeps season directory scope when guessit omits details', async () => {
|
test('guessAnilistMediaInfo keeps season directory scope when guessit omits details', async () => {
|
||||||
const result = await guessAnilistMediaInfo('/tmp/Season 2/Guessit Title.mkv', null, {
|
const result = await guessAnilistMediaInfo('/tmp/Season 2/Guessit Title.mkv', null, {
|
||||||
runGuessit: async () => JSON.stringify({ title: 'Guessit Title' }),
|
runGuessit: async () => JSON.stringify({ title: 'Guessit Title' }),
|
||||||
@@ -585,6 +600,11 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (call === 3) {
|
if (call === 3) {
|
||||||
|
// Looks one season past the count for an entry naming season 2; there is none.
|
||||||
|
assert.equal(body.variables?.id, 202);
|
||||||
|
return createJsonResponse({ data: { Media: { relations: { edges: [] } } } });
|
||||||
|
}
|
||||||
|
if (call === 4) {
|
||||||
assert.equal(body.variables?.mediaId, 202);
|
assert.equal(body.variables?.mediaId, 202);
|
||||||
return createJsonResponse({
|
return createJsonResponse({
|
||||||
data: {
|
data: {
|
||||||
@@ -608,7 +628,68 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
|
|||||||
assert.deepEqual(searchTerms, ['Demo Show']);
|
assert.deepEqual(searchTerms, ['Demo Show']);
|
||||||
assert.equal(result.status, 'updated');
|
assert.equal(result.status, 'updated');
|
||||||
assert.match(result.message, /Demo Show Sequel/);
|
assert.match(result.message, /Demo Show Sequel/);
|
||||||
assert.equal(call, 4);
|
assert.equal(call, 5);
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('updateAnilistPostWatchProgress writes a split-cour episode to the part that airs it', async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
const saved: Array<Record<string, unknown> | undefined> = [];
|
||||||
|
globalThis.fetch = (async (_input, init) => {
|
||||||
|
const body = JSON.parse(String(init?.body)) as {
|
||||||
|
query: string;
|
||||||
|
variables?: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
if (body.query.includes('Page(')) {
|
||||||
|
return createJsonResponse({
|
||||||
|
data: {
|
||||||
|
Page: {
|
||||||
|
media: [{ id: 101, episodes: 11, format: 'TV', title: { english: 'Demo Show' } }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (body.query.includes('relations')) {
|
||||||
|
assert.equal(body.variables?.id, 101);
|
||||||
|
return createJsonResponse({
|
||||||
|
data: {
|
||||||
|
Media: {
|
||||||
|
relations: {
|
||||||
|
edges: [
|
||||||
|
{
|
||||||
|
relationType: 'SEQUEL',
|
||||||
|
node: {
|
||||||
|
id: 202,
|
||||||
|
type: 'ANIME',
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
title: { english: 'Demo Show Cour 2' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (body.query.includes('SaveMediaListEntry')) {
|
||||||
|
saved.push(body.variables);
|
||||||
|
return createJsonResponse({ data: { SaveMediaListEntry: { progress: 4 } } });
|
||||||
|
}
|
||||||
|
assert.equal(body.variables?.mediaId, 202);
|
||||||
|
return createJsonResponse({
|
||||||
|
data: { Media: { id: 202, mediaListEntry: { progress: 3, status: 'CURRENT' } } },
|
||||||
|
});
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Episode 15 of an 11 + 12 season is episode 4 of the second cour's entry.
|
||||||
|
const result = await updateAnilistPostWatchProgress('token', 'Demo Show', 15, { season: 1 });
|
||||||
|
assert.equal(result.status, 'updated');
|
||||||
|
assert.match(result.message, /Demo Show Cour 2.*episode 4/);
|
||||||
|
assert.deepEqual(saved, [{ mediaId: 202, progress: 4, status: 'CURRENT' }]);
|
||||||
} finally {
|
} finally {
|
||||||
globalThis.fetch = originalFetch;
|
globalThis.fetch = originalFetch;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import * as childProcess from 'child_process';
|
import * as childProcess from 'child_process';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
|
|
||||||
import { parseMediaInfo } from '../../../jimaku/utils';
|
import { parseMediaLookupInfo } from '../../../jimaku/utils';
|
||||||
import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../../../shared/media-identity';
|
import { resolveMediaLookupTarget, sanitizeMediaTitle } from '../../../shared/media-identity';
|
||||||
import type { AnilistRateLimiter } from './rate-limiter';
|
import type { AnilistRateLimiter } from './rate-limiter';
|
||||||
import { resolveAnilistSeasonMedia, stripSeasonSuffix } from './season-resolver';
|
import { resolveAnilistSeasonMedia, stripSeasonSuffix } from './season-resolver';
|
||||||
@@ -231,7 +231,7 @@ export async function guessAnilistMediaInfo(
|
|||||||
const season = firstPositiveInteger(parsed.season);
|
const season = firstPositiveInteger(parsed.season);
|
||||||
const year = firstYear(parsed.year);
|
const year = firstYear(parsed.year);
|
||||||
if (title) {
|
if (title) {
|
||||||
const fallback = parseMediaInfo(target);
|
const fallback = parseMediaLookupInfo(mediaPath, mediaTitle);
|
||||||
const canUseFallbackDetails = fallback.confidence !== 'low';
|
const canUseFallbackDetails = fallback.confidence !== 'low';
|
||||||
return {
|
return {
|
||||||
title: buildGuessitTitle(title, alternativeTitle),
|
title: buildGuessitTitle(title, alternativeTitle),
|
||||||
@@ -247,7 +247,7 @@ export async function guessAnilistMediaInfo(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parsed = parseMediaInfo(target);
|
const parsed = parseMediaLookupInfo(mediaPath, mediaTitle);
|
||||||
if (!parsed.title.trim()) {
|
if (!parsed.title.trim()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -273,6 +273,9 @@ export async function updateAnilistPostWatchProgress(
|
|||||||
let mediaId = pinnedMediaId;
|
let mediaId = pinnedMediaId;
|
||||||
let resolvedTitle: string | null = null;
|
let resolvedTitle: string | null = null;
|
||||||
let resolvedEpisodes: number | null = null;
|
let resolvedEpisodes: number | null = null;
|
||||||
|
// Episode number within the entry being updated; differs from `episode` only for a
|
||||||
|
// split-cour back half.
|
||||||
|
let progress = episode;
|
||||||
// A missing list entry is only created when we trust the match; otherwise a fuzzy
|
// A missing list entry is only created when we trust the match; otherwise a fuzzy
|
||||||
// search hit would add an unrelated show to the user's list.
|
// search hit would add an unrelated show to the user's list.
|
||||||
let confidentMatch = pinnedMediaId !== null;
|
let confidentMatch = pinnedMediaId !== null;
|
||||||
@@ -312,14 +315,18 @@ export async function updateAnilistPostWatchProgress(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
mediaId = resolution.id;
|
// A split-cour back half is its own AniList entry with its own episode numbering:
|
||||||
resolvedTitle = resolution.title;
|
// "S1E15" of an 11 + 12 season is progress 4 on the second entry.
|
||||||
resolvedEpisodes = resolution.episodes;
|
const target = resolution.episodeEntry ?? resolution;
|
||||||
|
mediaId = target.id;
|
||||||
|
resolvedTitle = target.title;
|
||||||
|
resolvedEpisodes = target.episodes;
|
||||||
|
progress = resolution.episodeEntry?.episode ?? episode;
|
||||||
// With no parsed season, an exact match on a season-stripped title ("Show S2" ->
|
// With no parsed season, an exact match on a season-stripped title ("Show S2" ->
|
||||||
// "Show") only certifies the season 1 anchor, not the entry being watched.
|
// "Show") only certifies the season 1 anchor, not the entry being watched.
|
||||||
const seasonMarkerStripped = stripSeasonSuffix(title).trim() !== title.trim();
|
const seasonMarkerStripped = stripSeasonSuffix(title).trim() !== title.trim();
|
||||||
confidentMatch =
|
confidentMatch =
|
||||||
resolution.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
|
target.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
|
||||||
}
|
}
|
||||||
|
|
||||||
const entryResponse = await anilistGraphQl<AnilistMediaEntryData>(
|
const entryResponse = await anilistGraphQl<AnilistMediaEntryData>(
|
||||||
@@ -376,8 +383,8 @@ export async function updateAnilistPostWatchProgress(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const currentProgress = entry?.progress ?? 0;
|
const currentProgress = entry?.progress ?? 0;
|
||||||
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, episode);
|
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, progress);
|
||||||
if (typeof currentProgress === 'number' && currentProgress >= episode && !shouldMarkCompleted) {
|
if (typeof currentProgress === 'number' && currentProgress >= progress && !shouldMarkCompleted) {
|
||||||
return {
|
return {
|
||||||
status: 'skipped',
|
status: 'skipped',
|
||||||
message: `AniList already at episode ${currentProgress} (${pickedTitle}).`,
|
message: `AniList already at episode ${currentProgress} (${pickedTitle}).`,
|
||||||
@@ -396,7 +403,7 @@ export async function updateAnilistPostWatchProgress(
|
|||||||
`,
|
`,
|
||||||
{
|
{
|
||||||
mediaId,
|
mediaId,
|
||||||
progress: episode,
|
progress,
|
||||||
status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT',
|
status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT',
|
||||||
},
|
},
|
||||||
options,
|
options,
|
||||||
@@ -410,15 +417,15 @@ export async function updateAnilistPostWatchProgress(
|
|||||||
return {
|
return {
|
||||||
status: 'updated',
|
status: 'updated',
|
||||||
message: shouldMarkCompleted
|
message: shouldMarkCompleted
|
||||||
? `AniList added "${pickedTitle}" at episode ${episode} and marked it completed.`
|
? `AniList added "${pickedTitle}" at episode ${progress} and marked it completed.`
|
||||||
: `AniList added "${pickedTitle}" to Watching at episode ${episode}.`,
|
: `AniList added "${pickedTitle}" to Watching at episode ${progress}.`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
status: 'updated',
|
status: 'updated',
|
||||||
message: shouldMarkCompleted
|
message: shouldMarkCompleted
|
||||||
? `AniList updated "${pickedTitle}" to episode ${episode} and marked it completed.`
|
? `AniList updated "${pickedTitle}" to episode ${progress} and marked it completed.`
|
||||||
: `AniList updated "${pickedTitle}" to episode ${episode}.`,
|
: `AniList updated "${pickedTitle}" to episode ${progress}.`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { AnilistRateLimiter } from './rate-limiter';
|
import type { AnilistRateLimiter } from './rate-limiter';
|
||||||
|
import { AnilistRateLimitedError, executeAnilistQuery } from './anilist-graphql';
|
||||||
import type { DatabaseSync } from '../immersion-tracker/sqlite';
|
import type { DatabaseSync } from '../immersion-tracker/sqlite';
|
||||||
import {
|
import {
|
||||||
getAnimeCoverArt,
|
getAnimeCoverArt,
|
||||||
@@ -20,7 +21,6 @@ import { getVideoTmdbLink, linkAnimeToTmdbTitle } from '../immersion-tracker/liv
|
|||||||
import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver';
|
import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver';
|
||||||
import type { TmdbTitleDetails } from '../tmdb/tmdb-client';
|
import type { TmdbTitleDetails } from '../tmdb/tmdb-client';
|
||||||
|
|
||||||
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
|
|
||||||
const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
|
const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
|
||||||
|
|
||||||
export interface CoverArtFetcher {
|
export interface CoverArtFetcher {
|
||||||
@@ -76,47 +76,6 @@ export function stripFilenameTags(raw: string): string {
|
|||||||
return title.trim().replace(/\s{2,}/g, ' ');
|
return title.trim().replace(/\s{2,}/g, ' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
class AnilistRateLimitedError extends Error {
|
|
||||||
constructor() {
|
|
||||||
super('Anilist rate limit reached');
|
|
||||||
this.name = 'AnilistRateLimitedError';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function executeAnilistQuery<T>(
|
|
||||||
rateLimiter: AnilistRateLimiter,
|
|
||||||
query: string,
|
|
||||||
variables: Record<string, unknown>,
|
|
||||||
): Promise<T> {
|
|
||||||
await rateLimiter.acquire();
|
|
||||||
|
|
||||||
const res = await fetch(ANILIST_GRAPHQL_URL, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
||||||
body: JSON.stringify({ query, variables }),
|
|
||||||
});
|
|
||||||
|
|
||||||
rateLimiter.recordResponse(res.headers);
|
|
||||||
|
|
||||||
if (res.status === 429) {
|
|
||||||
throw new AnilistRateLimitedError();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
|
|
||||||
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
|
|
||||||
if (firstError?.message) {
|
|
||||||
throw new Error(firstError.message);
|
|
||||||
}
|
|
||||||
if (!json.data) {
|
|
||||||
throw new Error('Anilist response missing data');
|
|
||||||
}
|
|
||||||
return json.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadImage(url: string): Promise<Buffer | null> {
|
async function downloadImage(url: string): Promise<Buffer | null> {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(url);
|
const res = await fetch(url);
|
||||||
|
|||||||
@@ -0,0 +1,261 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import {
|
||||||
|
buildFranchiseGraph,
|
||||||
|
walkFranchiseRelations,
|
||||||
|
type AnilistMediaNode,
|
||||||
|
type FranchiseWalkOptions,
|
||||||
|
} from './franchise-graph';
|
||||||
|
|
||||||
|
function entry(
|
||||||
|
anilistId: number,
|
||||||
|
format: string | null,
|
||||||
|
startDate: number | null,
|
||||||
|
relations: Array<[string, number]> = [],
|
||||||
|
): AnilistMediaNode {
|
||||||
|
return {
|
||||||
|
anilistId,
|
||||||
|
format,
|
||||||
|
titleRomaji: `romaji ${anilistId}`,
|
||||||
|
titleEnglish: null,
|
||||||
|
titleNative: null,
|
||||||
|
startDate,
|
||||||
|
episodes: null,
|
||||||
|
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
|
||||||
|
fetchedAtMs: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overlord: two recap films sit between seasons one and two; Isekai Quartet only shares characters.
|
||||||
|
const overlord = [
|
||||||
|
entry(20832, 'TV', 20150707, [
|
||||||
|
['SEQUEL', 98437],
|
||||||
|
['SUMMARY', 98873],
|
||||||
|
['CHARACTER', 104454],
|
||||||
|
]),
|
||||||
|
entry(98873, 'MOVIE', 20170225, [
|
||||||
|
['PARENT', 20832],
|
||||||
|
['SEQUEL', 98874],
|
||||||
|
]),
|
||||||
|
entry(98874, 'MOVIE', 20170311, [
|
||||||
|
['PREQUEL', 98873],
|
||||||
|
['SEQUEL', 98437],
|
||||||
|
]),
|
||||||
|
entry(98437, 'TV', 20180109, [
|
||||||
|
['PREQUEL', 20832],
|
||||||
|
['PREQUEL', 98874],
|
||||||
|
]),
|
||||||
|
entry(104454, 'TV_SHORT', 20190410, [['CHARACTER', 20832]]),
|
||||||
|
];
|
||||||
|
|
||||||
|
test('seasons, films and recaps share a root named after the first TV series', () => {
|
||||||
|
const graph = buildFranchiseGraph(overlord);
|
||||||
|
for (const id of [20832, 98873, 98874, 98437]) assert.equal(graph.rootOf(id), 20832);
|
||||||
|
assert.equal(graph.rootOf(104454), 104454);
|
||||||
|
assert.equal(graph.rootOf(1), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('excluded relation types keep franchises apart even when the other end says PARENT', () => {
|
||||||
|
const graph = buildFranchiseGraph([
|
||||||
|
entry(1, 'TV', 20060101, [
|
||||||
|
['SPIN_OFF', 2],
|
||||||
|
['ALTERNATIVE', 3],
|
||||||
|
['ADAPTATION', 4],
|
||||||
|
['OTHER', 5],
|
||||||
|
]),
|
||||||
|
// A spin-off pointing back at its original as PARENT.
|
||||||
|
entry(2, 'TV', 20130101, [['PARENT', 1]]),
|
||||||
|
entry(3, 'TV', 20140101, [['ALTERNATIVE', 1]]),
|
||||||
|
]);
|
||||||
|
assert.deepEqual(
|
||||||
|
[1, 2, 3, 4, 5].map((id) => graph.rootOf(id)),
|
||||||
|
[1, 2, 3, undefined, undefined],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('root falls back to episodic formats, then earliest entry, then lowest id', () => {
|
||||||
|
const ona = buildFranchiseGraph([
|
||||||
|
entry(10, 'MOVIE', 20000101, [['SEQUEL', 11]]),
|
||||||
|
entry(11, 'ONA', 20050101, [['PREQUEL', 10]]),
|
||||||
|
]);
|
||||||
|
assert.equal(ona.rootOf(10), 11);
|
||||||
|
const films = buildFranchiseGraph([
|
||||||
|
entry(20, 'MOVIE', 20100101, [['PREQUEL', 21]]),
|
||||||
|
entry(21, 'MOVIE', 20090101, [['SEQUEL', 20]]),
|
||||||
|
entry(22, 'OVA', null, [['PARENT', 20]]),
|
||||||
|
]);
|
||||||
|
assert.equal(films.rootOf(22), 21);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('owned films join through an unowned, uncached TV entry they both point at', () => {
|
||||||
|
const graph = buildFranchiseGraph([
|
||||||
|
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
|
||||||
|
entry(1526, 'MOVIE', 20050716, [['PARENT', 527]]),
|
||||||
|
]);
|
||||||
|
assert.equal(graph.rootOf(528), graph.rootOf(1526));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('relation cycles terminate and form one franchise', () => {
|
||||||
|
const graph = buildFranchiseGraph([
|
||||||
|
entry(1, 'TV', 20000101, [['SEQUEL', 2]]),
|
||||||
|
entry(2, 'TV', 20010101, [['SEQUEL', 3]]),
|
||||||
|
entry(3, 'TV', 20020101, [['SEQUEL', 1]]),
|
||||||
|
]);
|
||||||
|
assert.deepEqual(
|
||||||
|
[1, 2, 3].map((id) => graph.rootOf(id)),
|
||||||
|
[1, 1, 1],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
function walkHarness(all: AnilistMediaNode[], overrides: Partial<FranchiseWalkOptions> = {}) {
|
||||||
|
const asked: number[][] = [];
|
||||||
|
const known = new Map<number, AnilistMediaNode>();
|
||||||
|
const options: FranchiseWalkOptions = {
|
||||||
|
seeds: [],
|
||||||
|
known,
|
||||||
|
isFresh: () => true,
|
||||||
|
fetchNodes: async (ids) => {
|
||||||
|
asked.push([...ids].sort((a, b) => a - b));
|
||||||
|
return all.filter((node) => ids.includes(node.anilistId));
|
||||||
|
},
|
||||||
|
onBatch: () => {},
|
||||||
|
now: () => 5,
|
||||||
|
maxDepth: 6,
|
||||||
|
maxFetch: 500,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
return { asked, known, options };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('walk follows franchise links through entries the user does not own', async () => {
|
||||||
|
const pokemon = [
|
||||||
|
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
|
||||||
|
entry(527, 'TV', 19970401, [
|
||||||
|
['SIDE_STORY', 528],
|
||||||
|
['SEQUEL', 1564],
|
||||||
|
]),
|
||||||
|
entry(1564, 'TV', 20021121, [
|
||||||
|
['PREQUEL', 527],
|
||||||
|
['SIDE_STORY', 1526],
|
||||||
|
['OTHER', 9],
|
||||||
|
]),
|
||||||
|
entry(1526, 'MOVIE', 20050716, [['PARENT', 1564]]),
|
||||||
|
entry(9, 'TV', 20000101),
|
||||||
|
];
|
||||||
|
const { asked, known, options } = walkHarness(pokemon, { seeds: [528, 1526, 404] });
|
||||||
|
await walkFranchiseRelations(options);
|
||||||
|
assert.deepEqual(asked, [
|
||||||
|
[404, 528, 1526],
|
||||||
|
[527, 1564],
|
||||||
|
]);
|
||||||
|
const graph = buildFranchiseGraph(known.values());
|
||||||
|
assert.equal(graph.rootOf(528), 527);
|
||||||
|
assert.equal(graph.rootOf(1526), 527);
|
||||||
|
// Missing ids are remembered so they are not asked about again; OTHER links are not followed.
|
||||||
|
assert.equal(known.get(404)?.format, null);
|
||||||
|
assert.equal(known.has(9), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('walk does not follow the links of an entry that vetoes how it was reached', async () => {
|
||||||
|
const { asked, options } = walkHarness(
|
||||||
|
[
|
||||||
|
entry(2, 'TV', 20130101, [['PARENT', 1]]),
|
||||||
|
entry(1, 'TV', 20060101, [
|
||||||
|
['SPIN_OFF', 2],
|
||||||
|
['SEQUEL', 3],
|
||||||
|
]),
|
||||||
|
entry(3, 'TV', 20070101),
|
||||||
|
],
|
||||||
|
{ seeds: [2] },
|
||||||
|
);
|
||||||
|
await walkFranchiseRelations(options);
|
||||||
|
assert.deepEqual(asked, [[2], [1]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('walk follows an entry reached through any link it accepts, whatever the seed order', async () => {
|
||||||
|
const nodes = [
|
||||||
|
entry(1, 'TV', 20100101, [['SEQUEL', 3]]),
|
||||||
|
entry(2, 'TV', 20110101, [['SEQUEL', 3]]),
|
||||||
|
// Rejects seed 1 but accepts seed 2, so its own links are still followed.
|
||||||
|
entry(3, 'TV', 20120101, [
|
||||||
|
['SPIN_OFF', 1],
|
||||||
|
['PREQUEL', 2],
|
||||||
|
['PARENT', 4],
|
||||||
|
]),
|
||||||
|
entry(4, 'TV', 20000101),
|
||||||
|
];
|
||||||
|
for (const seeds of [
|
||||||
|
[1, 2],
|
||||||
|
[2, 1],
|
||||||
|
]) {
|
||||||
|
const { asked, options } = walkHarness(nodes, { seeds });
|
||||||
|
await walkFranchiseRelations(options);
|
||||||
|
assert.deepEqual(asked, [[1, 2], [3], [4]]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a cancelled walk starts no further request and drops the in-flight result', async () => {
|
||||||
|
const seeds = Array.from({ length: 51 }, (_, index) => index + 1);
|
||||||
|
let cancelled = false;
|
||||||
|
const batches: number[] = [];
|
||||||
|
const { asked, known, options } = walkHarness(
|
||||||
|
seeds.map((id) => entry(id, 'TV', 20200101)),
|
||||||
|
{
|
||||||
|
seeds,
|
||||||
|
isFresh: () => false,
|
||||||
|
onBatch: (nodes) => batches.push(nodes.length),
|
||||||
|
isCancelled: () => cancelled,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const fetchNodes = options.fetchNodes;
|
||||||
|
options.fetchNodes = async (ids) => {
|
||||||
|
cancelled = true;
|
||||||
|
return fetchNodes(ids);
|
||||||
|
};
|
||||||
|
const result = await walkFranchiseRelations(options);
|
||||||
|
assert.equal(asked.length, 1);
|
||||||
|
assert.deepEqual(batches, []);
|
||||||
|
assert.equal(known.size, 0);
|
||||||
|
assert.equal(result.truncated, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('walk respects the depth and fetch bounds', async () => {
|
||||||
|
const chain = Array.from({ length: 10 }, (_, i) =>
|
||||||
|
entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []),
|
||||||
|
);
|
||||||
|
const deep = walkHarness(chain, { seeds: [1], maxDepth: 3 });
|
||||||
|
await walkFranchiseRelations(deep.options);
|
||||||
|
assert.deepEqual([...deep.known.keys()], [1, 2, 3, 4]);
|
||||||
|
|
||||||
|
const budget = walkHarness(chain, { seeds: [1], maxFetch: 2 });
|
||||||
|
const result = await walkFranchiseRelations(budget.options);
|
||||||
|
assert.deepEqual(result, { fetched: 2, truncated: true });
|
||||||
|
assert.deepEqual([...budget.known.keys()], [1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('walk follows fresh cached entries without asking and keeps old data on a failed fetch', async () => {
|
||||||
|
const cached = entry(1, 'TV', 20000101, [['SEQUEL', 2]]);
|
||||||
|
const stale = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
|
||||||
|
const { known, options } = walkHarness([], {
|
||||||
|
seeds: [1],
|
||||||
|
isFresh: (node) => node.fetchedAtMs >= 0,
|
||||||
|
fetchNodes: async () => {
|
||||||
|
throw new Error('AniList unavailable');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
known.set(1, cached);
|
||||||
|
known.set(2, stale);
|
||||||
|
await assert.rejects(walkFranchiseRelations(options), /AniList unavailable/);
|
||||||
|
assert.deepEqual(known.get(2), stale);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an entry AniList stops returning keeps its cached links', async () => {
|
||||||
|
const previous = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
|
||||||
|
const { known, options } = walkHarness([], {
|
||||||
|
seeds: [2],
|
||||||
|
isFresh: (node) => node.fetchedAtMs >= 0,
|
||||||
|
});
|
||||||
|
known.set(2, previous);
|
||||||
|
await walkFranchiseRelations(options);
|
||||||
|
assert.deepEqual(known.get(2), { ...previous, fetchedAtMs: 5 });
|
||||||
|
});
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
/**
|
||||||
|
* Franchise grouping over AniList's relation graph. AniList keeps every
|
||||||
|
* season, movie and OVA as its own entry and says how entries relate; the
|
||||||
|
* stats library lists a franchise once by following those links, including
|
||||||
|
* through entries the user does not own (two movies meet at a TV series that
|
||||||
|
* is not in the library). Nothing here touches the database or the network.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relation types that make two entries parts of one franchise. SPIN_OFF,
|
||||||
|
* ALTERNATIVE, CHARACTER, OTHER, ADAPTATION and SOURCE are left out on purpose:
|
||||||
|
* following them collapses Gundam or Fate into a single card.
|
||||||
|
*/
|
||||||
|
export const FRANCHISE_RELATION_TYPES: ReadonlySet<string> = new Set([
|
||||||
|
'PREQUEL',
|
||||||
|
'SEQUEL',
|
||||||
|
'PARENT',
|
||||||
|
'SIDE_STORY',
|
||||||
|
'SUMMARY',
|
||||||
|
'COMPILATION',
|
||||||
|
'CONTAINS',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export interface AnilistRelationEdge {
|
||||||
|
relationType: string;
|
||||||
|
targetId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One cached AniList entry and its links to other anime entries. */
|
||||||
|
export interface AnilistMediaNode {
|
||||||
|
anilistId: number;
|
||||||
|
/** TV, MOVIE, OVA...; null when AniList did not return the entry. */
|
||||||
|
format: string | null;
|
||||||
|
titleRomaji: string | null;
|
||||||
|
titleEnglish: string | null;
|
||||||
|
titleNative: string | null;
|
||||||
|
/** First air date as yyyymmdd (month/day 0 when unknown); null when AniList has no year. */
|
||||||
|
startDate: number | null;
|
||||||
|
episodes: number | null;
|
||||||
|
relations: AnilistRelationEdge[];
|
||||||
|
fetchedAtMs: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FranchiseGraph {
|
||||||
|
node(anilistId: number): AnilistMediaNode | undefined;
|
||||||
|
/** AniList id the franchise containing `anilistId` is named after; undefined when unknown. */
|
||||||
|
rootOf(anilistId: number): number | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function anilistNodeTitle(node: AnilistMediaNode): string | null {
|
||||||
|
return node.titleEnglish ?? node.titleRomaji ?? node.titleNative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when `node` names `targetId` only through relations that do not join a
|
||||||
|
* franchise. AniList records most links from both ends; a spin-off can point
|
||||||
|
* back at its original as PARENT, so the original's SPIN_OFF edge has to veto
|
||||||
|
* the join or excluding SPIN_OFF would not keep the two apart.
|
||||||
|
*/
|
||||||
|
function vetoes(node: AnilistMediaNode, targetId: number): boolean {
|
||||||
|
const edges = node.relations.filter((edge) => edge.targetId === targetId);
|
||||||
|
return edges.length > 0 && !edges.some((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType));
|
||||||
|
}
|
||||||
|
|
||||||
|
function franchiseTargets(node: AnilistMediaNode): number[] {
|
||||||
|
return node.relations
|
||||||
|
.filter((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType))
|
||||||
|
.map((edge) => edge.targetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TV first, then other episodic formats, then films/OVAs/specials, then entries with no data.
|
||||||
|
function formatRank(format: string | null): number {
|
||||||
|
if (format === 'TV') return 0;
|
||||||
|
if (format === 'TV_SHORT' || format === 'ONA') return 1;
|
||||||
|
return format === null ? 3 : 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildFranchiseGraph(nodes: Iterable<AnilistMediaNode>): FranchiseGraph {
|
||||||
|
const byId = new Map<number, AnilistMediaNode>();
|
||||||
|
for (const node of nodes) byId.set(node.anilistId, node);
|
||||||
|
|
||||||
|
const parent = new Map<number, number>();
|
||||||
|
const find = (id: number): number => {
|
||||||
|
let top = parent.get(id) ?? id;
|
||||||
|
if (!parent.has(id)) parent.set(id, id);
|
||||||
|
while (parent.get(top) !== top) top = parent.get(top)!;
|
||||||
|
// Path compression keeps long sequel chains cheap.
|
||||||
|
let at = id;
|
||||||
|
while (at !== top) {
|
||||||
|
const next = parent.get(at)!;
|
||||||
|
parent.set(at, top);
|
||||||
|
at = next;
|
||||||
|
}
|
||||||
|
return top;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const node of byId.values()) {
|
||||||
|
find(node.anilistId);
|
||||||
|
for (const targetId of franchiseTargets(node)) {
|
||||||
|
const target = byId.get(targetId);
|
||||||
|
if (target && vetoes(target, node.anilistId)) continue;
|
||||||
|
const a = find(node.anilistId);
|
||||||
|
const b = find(targetId);
|
||||||
|
if (a !== b) parent.set(b, a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const members = new Map<number, number[]>();
|
||||||
|
for (const id of parent.keys()) {
|
||||||
|
const top = find(id);
|
||||||
|
const list = members.get(top);
|
||||||
|
if (list) list.push(id);
|
||||||
|
else members.set(top, [id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A franchise is named after its first TV series, else its first episodic
|
||||||
|
// entry, else its earliest entry; ties go to the lower id.
|
||||||
|
const compareRoots = (a: number, b: number): number => {
|
||||||
|
const left = byId.get(a);
|
||||||
|
const right = byId.get(b);
|
||||||
|
return (
|
||||||
|
formatRank(left?.format ?? null) - formatRank(right?.format ?? null) ||
|
||||||
|
(left?.startDate ?? Number.MAX_SAFE_INTEGER) -
|
||||||
|
(right?.startDate ?? Number.MAX_SAFE_INTEGER) ||
|
||||||
|
a - b
|
||||||
|
);
|
||||||
|
};
|
||||||
|
const roots = new Map<number, number>();
|
||||||
|
for (const ids of members.values()) {
|
||||||
|
const root = [...ids].sort(compareRoots)[0]!;
|
||||||
|
for (const id of ids) roots.set(id, root);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
node: (anilistId) => byId.get(anilistId),
|
||||||
|
rootOf: (anilistId) => roots.get(anilistId),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const FETCH_CHUNK_SIZE = 50;
|
||||||
|
|
||||||
|
export interface FranchiseWalkOptions {
|
||||||
|
/** AniList ids the walk starts from (the library's own entries). */
|
||||||
|
seeds: readonly number[];
|
||||||
|
/** Cached entries; updated in place with everything fetched. */
|
||||||
|
known: Map<number, AnilistMediaNode>;
|
||||||
|
isFresh: (node: AnilistMediaNode) => boolean;
|
||||||
|
/** Entries AniList returned for `ids` (at most 50). Throws on transport or API failure. */
|
||||||
|
fetchNodes: (ids: number[]) => Promise<AnilistMediaNode[]>;
|
||||||
|
/** Called once per fetched batch so progress survives a later failure. */
|
||||||
|
onBatch: (nodes: AnilistMediaNode[]) => void;
|
||||||
|
now: () => number;
|
||||||
|
/** Hops from a seed; entries at this depth are fetched but not followed. */
|
||||||
|
maxDepth: number;
|
||||||
|
/** Most entries fetched in one walk; the rest wait for the next walk. */
|
||||||
|
maxFetch: number;
|
||||||
|
/** When true, the walk starts no further request and drops an in-flight result. */
|
||||||
|
isCancelled?: () => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FranchiseWalkResult {
|
||||||
|
fetched: number;
|
||||||
|
/** True when the fetch budget ran out before every stale entry was refreshed. */
|
||||||
|
truncated: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Breadth-first walk from the seeds along franchise relations, fetching
|
||||||
|
* entries that are missing or stale. Fresh cached entries are followed without
|
||||||
|
* a request. An entry AniList does not return keeps its previous data (or gets
|
||||||
|
* an empty placeholder) so it is not asked about again until it goes stale; a
|
||||||
|
* thrown fetch error stops the walk and leaves the cache as it was.
|
||||||
|
*/
|
||||||
|
export async function walkFranchiseRelations(
|
||||||
|
options: FranchiseWalkOptions,
|
||||||
|
): Promise<FranchiseWalkResult> {
|
||||||
|
const { known } = options;
|
||||||
|
const visited = new Set<number>();
|
||||||
|
// `from` lists every entry the walk reached this one through at this depth
|
||||||
|
// (empty for a seed), so the order seeds are given in cannot change the result.
|
||||||
|
let frontier: Array<{ id: number; from: number[] }> = [...new Set(options.seeds)].map((id) => ({
|
||||||
|
id,
|
||||||
|
from: [],
|
||||||
|
}));
|
||||||
|
let fetched = 0;
|
||||||
|
let truncated = false;
|
||||||
|
|
||||||
|
for (let depth = 0; frontier.length > 0; depth += 1) {
|
||||||
|
for (const step of frontier) visited.add(step.id);
|
||||||
|
|
||||||
|
const stale = frontier
|
||||||
|
.map((step) => step.id)
|
||||||
|
.filter((id) => {
|
||||||
|
const node = known.get(id);
|
||||||
|
return !node || !options.isFresh(node);
|
||||||
|
});
|
||||||
|
const allowed = stale.slice(0, Math.max(0, options.maxFetch - fetched));
|
||||||
|
if (allowed.length < stale.length) truncated = true;
|
||||||
|
|
||||||
|
for (let start = 0; start < allowed.length; start += FETCH_CHUNK_SIZE) {
|
||||||
|
if (options.isCancelled?.()) return { fetched, truncated: true };
|
||||||
|
const chunk = allowed.slice(start, start + FETCH_CHUNK_SIZE);
|
||||||
|
const fetchedNodes = await options.fetchNodes(chunk);
|
||||||
|
if (options.isCancelled?.()) return { fetched, truncated: true };
|
||||||
|
const found = new Map(fetchedNodes.map((node) => [node.anilistId, node] as const));
|
||||||
|
const fetchedAtMs = options.now();
|
||||||
|
const batch = chunk.map((id): AnilistMediaNode => {
|
||||||
|
const node = found.get(id);
|
||||||
|
if (node) return node;
|
||||||
|
const previous = known.get(id);
|
||||||
|
if (previous) return { ...previous, fetchedAtMs };
|
||||||
|
return {
|
||||||
|
anilistId: id,
|
||||||
|
format: null,
|
||||||
|
titleRomaji: null,
|
||||||
|
titleEnglish: null,
|
||||||
|
titleNative: null,
|
||||||
|
startDate: null,
|
||||||
|
episodes: null,
|
||||||
|
relations: [],
|
||||||
|
fetchedAtMs,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
for (const node of batch) known.set(node.anilistId, node);
|
||||||
|
options.onBatch(batch);
|
||||||
|
fetched += chunk.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (depth >= options.maxDepth) break;
|
||||||
|
|
||||||
|
const next = new Map<number, number[]>();
|
||||||
|
for (const step of frontier) {
|
||||||
|
const node = known.get(step.id);
|
||||||
|
if (!node) continue;
|
||||||
|
// Reached only through links the entry itself rejects (a spin-off's
|
||||||
|
// original): it is not part of the franchise, so its own links are not
|
||||||
|
// followed. One accepted incoming link is enough.
|
||||||
|
if (step.from.length > 0 && step.from.every((fromId) => vetoes(node, fromId))) continue;
|
||||||
|
for (const targetId of franchiseTargets(node)) {
|
||||||
|
if (visited.has(targetId)) continue;
|
||||||
|
const from = next.get(targetId);
|
||||||
|
if (from) from.push(node.anilistId);
|
||||||
|
else next.set(targetId, [node.anilistId]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
frontier = [...next].map(([id, from]) => ({ id, from }));
|
||||||
|
}
|
||||||
|
|
||||||
|
return { fetched, truncated };
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { executeAnilistQuery } from './anilist-graphql';
|
||||||
|
import type { AnilistMediaNode, AnilistRelationEdge } from './franchise-graph';
|
||||||
|
import type { AnilistRateLimiter } from './rate-limiter';
|
||||||
|
|
||||||
|
/** Loads AniList entries with their relations, for the library's franchise grouping. */
|
||||||
|
export interface AnilistRelationFetcher {
|
||||||
|
/** Entries AniList returned for `ids` (at most 50); ids it does not know are absent. */
|
||||||
|
fetchMedia(ids: number[]): Promise<AnilistMediaNode[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const RELATIONS_QUERY = `
|
||||||
|
query ($ids: [Int], $perPage: Int) {
|
||||||
|
Page(page: 1, perPage: $perPage) {
|
||||||
|
media(id_in: $ids, type: ANIME) {
|
||||||
|
id
|
||||||
|
format
|
||||||
|
episodes
|
||||||
|
title { romaji english native }
|
||||||
|
startDate { year month day }
|
||||||
|
relations { edges { relationType(version: 2) node { id type } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`;
|
||||||
|
|
||||||
|
interface RelationsMedia {
|
||||||
|
id: number;
|
||||||
|
format: string | null;
|
||||||
|
episodes: number | null;
|
||||||
|
title: { romaji: string | null; english: string | null; native: string | null } | null;
|
||||||
|
startDate: { year: number | null; month: number | null; day: number | null } | null;
|
||||||
|
relations: {
|
||||||
|
edges: Array<{
|
||||||
|
relationType: string | null;
|
||||||
|
node: { id: number; type: string | null } | null;
|
||||||
|
} | null> | null;
|
||||||
|
} | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RelationsResponse {
|
||||||
|
Page: { media: Array<RelationsMedia | null> | null } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toAnilistMediaNode(media: RelationsMedia, fetchedAtMs: number): AnilistMediaNode {
|
||||||
|
const start = media.startDate;
|
||||||
|
const relations: AnilistRelationEdge[] = [];
|
||||||
|
for (const edge of media.relations?.edges ?? []) {
|
||||||
|
// Manga and novels are not part of a watch library.
|
||||||
|
if (!edge?.relationType || edge.node?.type !== 'ANIME') continue;
|
||||||
|
relations.push({ relationType: edge.relationType, targetId: edge.node.id });
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
anilistId: media.id,
|
||||||
|
format: media.format,
|
||||||
|
titleRomaji: media.title?.romaji ?? null,
|
||||||
|
titleEnglish: media.title?.english ?? null,
|
||||||
|
titleNative: media.title?.native ?? null,
|
||||||
|
startDate: start?.year
|
||||||
|
? start.year * 10_000 + (start.month ?? 0) * 100 + (start.day ?? 0)
|
||||||
|
: null,
|
||||||
|
episodes: media.episodes,
|
||||||
|
relations,
|
||||||
|
fetchedAtMs,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAnilistRelationFetcher(
|
||||||
|
rateLimiter: AnilistRateLimiter,
|
||||||
|
now: () => number = Date.now,
|
||||||
|
): AnilistRelationFetcher {
|
||||||
|
return {
|
||||||
|
async fetchMedia(ids) {
|
||||||
|
if (ids.length === 0) return [];
|
||||||
|
const data = await executeAnilistQuery<RelationsResponse>(rateLimiter, RELATIONS_QUERY, {
|
||||||
|
ids,
|
||||||
|
perPage: ids.length,
|
||||||
|
});
|
||||||
|
const fetchedAtMs = now();
|
||||||
|
return (data.Page?.media ?? [])
|
||||||
|
.filter((media): media is RelationsMedia => media !== null)
|
||||||
|
.map((media) => toAnilistMediaNode(media, fetchedAtMs));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -4,11 +4,22 @@ import assert from 'node:assert/strict';
|
|||||||
import {
|
import {
|
||||||
ANILIST_SEASON_RELATIONS_QUERY,
|
ANILIST_SEASON_RELATIONS_QUERY,
|
||||||
ANILIST_SEASON_SEARCH_QUERY,
|
ANILIST_SEASON_SEARCH_QUERY,
|
||||||
|
namedSeasons,
|
||||||
pickByAirOrder,
|
pickByAirOrder,
|
||||||
resolveAnilistSeasonMedia,
|
resolveAnilistSeasonMedia,
|
||||||
|
splitPartMarker,
|
||||||
stripSeasonSuffix,
|
stripSeasonSuffix,
|
||||||
type AnilistSeasonMedia,
|
type AnilistSeasonMedia,
|
||||||
} from './season-resolver';
|
} from './season-resolver';
|
||||||
|
import {
|
||||||
|
AOT_CHAIN,
|
||||||
|
BLEACH_TYBW_CHAIN,
|
||||||
|
DR_STONE_CHAIN,
|
||||||
|
JOJO_CHAIN,
|
||||||
|
MUSHOKU_CHAIN,
|
||||||
|
OVERLORD_CHAIN,
|
||||||
|
REZERO_CHAIN,
|
||||||
|
} from './__fixtures__/anilist-season-chains';
|
||||||
|
|
||||||
/** Real AniList payloads for "My Teen Romantic Comedy SNAFU", trimmed to used fields. */
|
/** Real AniList payloads for "My Teen Romantic Comedy SNAFU", trimmed to used fields. */
|
||||||
const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [
|
const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [
|
||||||
@@ -161,7 +172,8 @@ test('resolves season 3 by walking sequel relations', async () => {
|
|||||||
assert.equal(result?.via, 'sequel-chain');
|
assert.equal(result?.via, 'sequel-chain');
|
||||||
// Searches the bare title only; "Season 3" returns nothing on AniList.
|
// Searches the bare title only; "Season 3" returns nothing on AniList.
|
||||||
assert.deepEqual(searches, ['My Teen Romantic Comedy SNAFU']);
|
assert.deepEqual(searches, ['My Teen Romantic Comedy SNAFU']);
|
||||||
assert.deepEqual(relationLookups, [14813, 20698]);
|
// The last lookup checks one season past the count for an entry naming season 3.
|
||||||
|
assert.deepEqual(relationLookups, [14813, 20698, 108489]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('season 1 resolves to the anchor without relation lookups', async () => {
|
test('season 1 resolves to the anchor without relation lookups', async () => {
|
||||||
@@ -215,7 +227,7 @@ test('a sequel resolution whose own title matches the parsed title stays exact',
|
|||||||
);
|
);
|
||||||
|
|
||||||
assert.equal(result?.id, 2);
|
assert.equal(result?.id, 2);
|
||||||
assert.equal(result?.via, 'sequel-chain');
|
assert.equal(result?.via, 'named-season');
|
||||||
assert.equal(result?.exactTitleMatch, true);
|
assert.equal(result?.exactTitleMatch, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -325,7 +337,7 @@ test('prefers the TV sequel when a franchise branches into other formats', async
|
|||||||
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
|
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
|
||||||
|
|
||||||
assert.equal(result?.id, 2);
|
assert.equal(result?.id, 2);
|
||||||
assert.equal(result?.via, 'sequel-chain');
|
assert.equal(result?.via, 'named-season');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('air-order fallback refuses when the anchor is not the earliest entry', () => {
|
test('air-order fallback refuses when the anchor is not the earliest entry', () => {
|
||||||
@@ -399,3 +411,288 @@ test('air-order fallback declines when a franchise entry has no air year', async
|
|||||||
assert.equal(result?.seasonResolved, false);
|
assert.equal(result?.seasonResolved, false);
|
||||||
assert.equal(result?.via, 'anchor');
|
assert.equal(result?.via, 'anchor');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** Executor over a fixture chain: search returns the whole chain, entry i's SEQUEL is i + 1. */
|
||||||
|
function createChainExecutor(chain: AnilistSeasonMedia[]) {
|
||||||
|
const relations: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {};
|
||||||
|
chain.forEach((entry, index) => {
|
||||||
|
const next = chain[index + 1];
|
||||||
|
relations[entry.id] = next ? [{ relationType: 'SEQUEL', node: next }] : [];
|
||||||
|
});
|
||||||
|
return createExecutor(chain, relations);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveInChain(
|
||||||
|
chain: AnilistSeasonMedia[],
|
||||||
|
input: { title: string; season?: number | null; episode?: number | null },
|
||||||
|
) {
|
||||||
|
const executor = createChainExecutor(chain);
|
||||||
|
const result = await resolveAnilistSeasonMedia(input, { execute: executor.execute });
|
||||||
|
return { result, relationLookups: executor.relationLookups };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('split-cour back halves do not count as seasons', async () => {
|
||||||
|
const title = 'Mushoku Tensei: Jobless Reincarnation';
|
||||||
|
const s2 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 2, episode: 1 });
|
||||||
|
assert.equal(s2.result?.id, 146065);
|
||||||
|
assert.equal(s2.result?.seasonResolved, true);
|
||||||
|
|
||||||
|
const s3 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 3, episode: 1 });
|
||||||
|
assert.equal(s3.result?.id, 178789);
|
||||||
|
// Four hops for two seasons: "Cour 2" and "Season 2 Part 2" were walked through.
|
||||||
|
assert.deepEqual(s3.relationLookups, [108465, 127720, 146065, 166873]);
|
||||||
|
|
||||||
|
const reZeroS3 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 3 });
|
||||||
|
assert.equal(reZeroS3.result?.id, 163134);
|
||||||
|
const reZeroS4 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 4 });
|
||||||
|
assert.equal(reZeroS4.result?.id, 189046);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a special in the sequel chain is walked through without counting', async () => {
|
||||||
|
const s3 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 3 });
|
||||||
|
assert.equal(s3.result?.id, 131518);
|
||||||
|
const s4 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 4 });
|
||||||
|
assert.equal(s4.result?.id, 172019);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('season names ignore part and cour numbers, including localized ones', () => {
|
||||||
|
// "Cour 2" carries the Thai synonym "... พาร์ท 2" ("part 2").
|
||||||
|
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[1]!)], []);
|
||||||
|
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[3]!)], [2]);
|
||||||
|
assert.deepEqual([...namedSeasons(OVERLORD_CHAIN[1]!)], [2]);
|
||||||
|
assert.deepEqual([...namedSeasons(DR_STONE_CHAIN[1]!)], [2]);
|
||||||
|
assert.deepEqual([...namedSeasons(AOT_CHAIN[4]!)], [4]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an entry naming the requested season beats the hop count', async () => {
|
||||||
|
// The second cour has no marker anywhere, so counting alone would call it season 2.
|
||||||
|
const chain: AnilistSeasonMedia[] = [
|
||||||
|
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
|
||||||
|
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show: Arc Two' } },
|
||||||
|
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
|
||||||
|
];
|
||||||
|
const { result } = await resolveInChain(chain, { title: 'Show', season: 2 });
|
||||||
|
assert.equal(result?.id, 3);
|
||||||
|
assert.equal(result?.via, 'named-season');
|
||||||
|
|
||||||
|
const overlord = await resolveInChain(OVERLORD_CHAIN, { title: 'Overlord', season: 2 });
|
||||||
|
assert.equal(overlord.result?.id, 98437);
|
||||||
|
assert.equal(overlord.result?.via, 'named-season');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a counted entry whose title names another season is not accepted', async () => {
|
||||||
|
const chain: AnilistSeasonMedia[] = [
|
||||||
|
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
|
||||||
|
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2021, title: { english: 'Show: Arc Two' } },
|
||||||
|
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
|
||||||
|
];
|
||||||
|
// Counting lands on id 3 for season 3, but it says it is season 2.
|
||||||
|
const { result } = await resolveInChain(chain, { title: 'Show', season: 3 });
|
||||||
|
assert.equal(result?.seasonResolved, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('JoJo parts are seasons, not split-cour continuations', async () => {
|
||||||
|
assert.equal(splitPartMarker('JoJo no Kimyou na Bouken Part 5: Ougon no Kaze'), null);
|
||||||
|
assert.deepEqual(splitPartMarker("JoJo's Bizarre Adventure Part 5"), {
|
||||||
|
base: 'jojo s bizarre adventure',
|
||||||
|
part: 5,
|
||||||
|
});
|
||||||
|
// Golden Wind ends in "Part 5" and Stone Ocean in "Part 6": same base, different
|
||||||
|
// parts, so Stone Ocean must still count as the next season.
|
||||||
|
const { result } = await resolveInChain(JOJO_CHAIN, {
|
||||||
|
title: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
|
||||||
|
season: 3,
|
||||||
|
});
|
||||||
|
assert.equal(result?.id, 131942);
|
||||||
|
assert.equal(result?.via, 'sequel-chain');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Attack on Titan resolves its final season past the season 3 back half', async () => {
|
||||||
|
const { result } = await resolveInChain(AOT_CHAIN, { title: 'Attack on Titan', season: 4 });
|
||||||
|
assert.equal(result?.id, 110277);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('air-order fallback drops back halves but keeps a season spelled "Part 1"', () => {
|
||||||
|
// AoT season 3 carries the synonym "ผ่าพิภพไททัน ภาค 3 Part 1".
|
||||||
|
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 3, AOT_CHAIN)?.id, 99147);
|
||||||
|
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 4, AOT_CHAIN)?.id, 110277);
|
||||||
|
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 3, MUSHOKU_CHAIN)?.id, 178789);
|
||||||
|
// Only three real seasons have aired, so a fourth must not fall out of the list.
|
||||||
|
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 4, MUSHOKU_CHAIN.slice(0, 5)), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a TYBW cour marked only in a differently spelled synonym is not season 2', async () => {
|
||||||
|
const { result } = await resolveInChain(BLEACH_TYBW_CHAIN, {
|
||||||
|
title: 'BLEACH: Thousand-Year Blood War',
|
||||||
|
season: 2,
|
||||||
|
});
|
||||||
|
// Every sequel is a later cour of the same season, so there is no season 2 to find.
|
||||||
|
assert.equal(result?.seasonResolved, false);
|
||||||
|
assert.equal(result?.id, 116674);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an episode past the season entry lands on the split-cour part that airs it', async () => {
|
||||||
|
const mushoku = await resolveInChain(MUSHOKU_CHAIN, {
|
||||||
|
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||||
|
season: 1,
|
||||||
|
episode: 15,
|
||||||
|
});
|
||||||
|
assert.equal(mushoku.result?.id, 108465);
|
||||||
|
assert.equal(mushoku.result?.episodeEntry?.id, 127720);
|
||||||
|
assert.equal(mushoku.result?.episodeEntry?.episode, 4);
|
||||||
|
|
||||||
|
const mushokuS2 = await resolveInChain(MUSHOKU_CHAIN, {
|
||||||
|
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||||
|
season: 2,
|
||||||
|
episode: 20,
|
||||||
|
});
|
||||||
|
assert.equal(mushokuS2.result?.id, 146065);
|
||||||
|
assert.equal(mushokuS2.result?.episodeEntry?.id, 166873);
|
||||||
|
assert.equal(mushokuS2.result?.episodeEntry?.episode, 7);
|
||||||
|
|
||||||
|
// Three cours of 13 + 13 + 14: episode 28 is the third cour's second.
|
||||||
|
const bleach = await resolveInChain(BLEACH_TYBW_CHAIN, {
|
||||||
|
title: 'BLEACH: Thousand-Year Blood War',
|
||||||
|
episode: 28,
|
||||||
|
});
|
||||||
|
assert.equal(bleach.result?.id, 116674);
|
||||||
|
assert.equal(bleach.result?.episodeEntry?.id, 169755);
|
||||||
|
assert.equal(bleach.result?.episodeEntry?.episode, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an episode inside the season entry needs no remap or relation lookup', async () => {
|
||||||
|
const { result, relationLookups } = await resolveInChain(MUSHOKU_CHAIN, {
|
||||||
|
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||||
|
season: 1,
|
||||||
|
episode: 5,
|
||||||
|
});
|
||||||
|
assert.equal(result?.id, 108465);
|
||||||
|
assert.equal(result?.episodeEntry, null);
|
||||||
|
assert.deepEqual(relationLookups, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an episode past a season with no continuation is not moved into the next season', async () => {
|
||||||
|
const { result } = await resolveInChain(OVERLORD_CHAIN, {
|
||||||
|
title: 'Overlord',
|
||||||
|
season: 1,
|
||||||
|
episode: 20,
|
||||||
|
});
|
||||||
|
assert.equal(result?.id, 20832);
|
||||||
|
assert.equal(result?.episodeEntry, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a sequel naming its own season is not a back half, even with a part synonym', async () => {
|
||||||
|
const sequel: AnilistSeasonMedia = {
|
||||||
|
id: 2,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2022,
|
||||||
|
title: { english: 'Part Synonym Show Season 2' },
|
||||||
|
synonyms: ['Part Synonym Show Part 2'],
|
||||||
|
};
|
||||||
|
// The anchor names season 1 itself...
|
||||||
|
const named = await resolveInChain(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2020,
|
||||||
|
title: { english: 'Part Synonym Show' },
|
||||||
|
synonyms: ['Part Synonym Show Season 1'],
|
||||||
|
},
|
||||||
|
sequel,
|
||||||
|
],
|
||||||
|
{ title: 'Part Synonym Show', season: 2 },
|
||||||
|
);
|
||||||
|
assert.equal(named.result?.id, 2);
|
||||||
|
// ...or is season 1 because the walk starts there.
|
||||||
|
const unnamed = await resolveInChain(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2020,
|
||||||
|
title: { english: 'Part Synonym Show' },
|
||||||
|
},
|
||||||
|
sequel,
|
||||||
|
],
|
||||||
|
{ title: 'Part Synonym Show', season: 2 },
|
||||||
|
);
|
||||||
|
assert.equal(unnamed.result?.id, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('air order keeps a sequel naming its own season despite a part synonym', () => {
|
||||||
|
const anchor: AnilistSeasonMedia = {
|
||||||
|
id: 1,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2020,
|
||||||
|
title: { english: 'Air Order Show' },
|
||||||
|
};
|
||||||
|
const sequel: AnilistSeasonMedia = {
|
||||||
|
id: 2,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2022,
|
||||||
|
title: { english: 'Air Order Show Season 2' },
|
||||||
|
synonyms: ['Air Order Show Part 2'],
|
||||||
|
};
|
||||||
|
assert.equal(pickByAirOrder(anchor, 2, [anchor, sequel])?.id, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a season 1 episode past its length does not move to a longer later season', async () => {
|
||||||
|
const { result } = await resolveInChain(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
episodes: 12,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2020,
|
||||||
|
title: { english: 'Long Later Show' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
episodes: 24,
|
||||||
|
format: 'TV',
|
||||||
|
seasonYear: 2022,
|
||||||
|
title: { english: 'Long Later Show Season 2' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ title: 'Long Later Show', season: 1, episode: 20 },
|
||||||
|
);
|
||||||
|
assert.equal(result?.id, 1);
|
||||||
|
assert.equal(result?.episodeEntry, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a sequel that repeats its predecessor name is still a new season', async () => {
|
||||||
|
// No part marker, so the identical title must not be read as a continuation.
|
||||||
|
const chain: AnilistSeasonMedia[] = [
|
||||||
|
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Same Name Show' } },
|
||||||
|
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Same Name Show' } },
|
||||||
|
];
|
||||||
|
const { result } = await resolveInChain(chain, { title: 'Same Name Show', season: 2 });
|
||||||
|
assert.equal(result?.id, 2);
|
||||||
|
assert.equal(result?.seasonResolved, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a rate limit mid-walk is surfaced instead of answered from air order', async () => {
|
||||||
|
const { execute } = createChainExecutor(MUSHOKU_CHAIN);
|
||||||
|
let relationCalls = 0;
|
||||||
|
const failing = async <T>(query: string, variables: Record<string, unknown>): Promise<T> => {
|
||||||
|
if (query === ANILIST_SEASON_RELATIONS_QUERY && ++relationCalls === 2) {
|
||||||
|
throw new Error('AniList rate limited (429)');
|
||||||
|
}
|
||||||
|
return execute<T>(query, variables);
|
||||||
|
};
|
||||||
|
// Air order alone would answer season 3 correctly from this search result, but it must
|
||||||
|
// not answer from a franchise picture the failed walk never confirmed.
|
||||||
|
await assert.rejects(
|
||||||
|
resolveAnilistSeasonMedia(
|
||||||
|
{ title: 'Mushoku Tensei: Jobless Reincarnation', season: 3 },
|
||||||
|
{ execute: failing },
|
||||||
|
),
|
||||||
|
/429/,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -9,6 +9,14 @@ import { sanitizeMediaTitle } from '../../../shared/media-identity';
|
|||||||
* season 1 anchor and then walking AniList SEQUEL relations, with an air-order fallback
|
* season 1 anchor and then walking AniList SEQUEL relations, with an air-order fallback
|
||||||
* when the relation chain is incomplete. When the seasonal entry cannot be located it
|
* when the relation chain is incomplete. When the seasonal entry cannot be located it
|
||||||
* reports `seasonResolved: false` so callers can refuse to act instead of guessing.
|
* reports `seasonResolved: false` so callers can refuse to act instead of guessing.
|
||||||
|
*
|
||||||
|
* Not every SEQUEL hop is a new season. Along the chain:
|
||||||
|
* - the back half of a split cour ("Part 2", "Cour 2", "第2クール") is its own entry,
|
||||||
|
* - movies, specials and OVAs sit between seasons,
|
||||||
|
* so the walk only counts entries that start a new TV season, and prefers an entry whose
|
||||||
|
* title names the requested season ("Season 3", "3rd Season", "III", "第3期") over the
|
||||||
|
* count. A continuation with no marker anywhere is indistinguishable from a new season;
|
||||||
|
* the manual AniList override covers those.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { normalizeTitleIdentity } from '../../utils/title-normalization';
|
import { normalizeTitleIdentity } from '../../utils/title-normalization';
|
||||||
@@ -35,9 +43,29 @@ export type AnilistQueryExecutor = <T>(
|
|||||||
variables: Record<string, unknown>,
|
variables: Record<string, unknown>,
|
||||||
) => Promise<T>;
|
) => Promise<T>;
|
||||||
|
|
||||||
export type AnilistSeasonResolutionVia = 'anchor' | 'sequel-chain' | 'air-order';
|
export type AnilistSeasonResolutionVia = 'anchor' | 'named-season' | 'sequel-chain' | 'air-order';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The entry that actually airs the parsed episode when it runs past the season entry
|
||||||
|
* into a later part of the same season ("S1E15" of an 11 + 12 split cour is episode 4
|
||||||
|
* of the "Cour 2" entry).
|
||||||
|
*/
|
||||||
|
export interface AnilistEpisodeEntry {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
episodes: number | null;
|
||||||
|
media: AnilistSeasonMedia;
|
||||||
|
/** Episode number within this entry. */
|
||||||
|
episode: number;
|
||||||
|
exactTitleMatch: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AnilistSeasonResolution {
|
export interface AnilistSeasonResolution {
|
||||||
|
/**
|
||||||
|
* The season's own entry (its first part). Season-level consumers (cover art, the
|
||||||
|
* anime row's AniList link, the character dictionary) use this so every episode of a
|
||||||
|
* split-cour season agrees on one id.
|
||||||
|
*/
|
||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
episodes: number | null;
|
episodes: number | null;
|
||||||
@@ -48,6 +76,8 @@ export interface AnilistSeasonResolution {
|
|||||||
via: AnilistSeasonResolutionVia;
|
via: AnilistSeasonResolutionVia;
|
||||||
/** Exact normalized match against an AniList title or synonym. */
|
/** Exact normalized match against an AniList title or synonym. */
|
||||||
exactTitleMatch: boolean;
|
exactTitleMatch: boolean;
|
||||||
|
/** Set only when the parsed episode belongs to a later part of the season. */
|
||||||
|
episodeEntry: AnilistEpisodeEntry | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ResolveAnilistSeasonMediaInput {
|
export interface ResolveAnilistSeasonMediaInput {
|
||||||
@@ -119,8 +149,79 @@ interface AnilistSeasonRelationsResponse {
|
|||||||
/** Formats that can carry a numbered TV season, best first. */
|
/** Formats that can carry a numbered TV season, best first. */
|
||||||
const SEASONAL_FORMAT_PRIORITY = ['TV', 'TV_SHORT', 'ONA'];
|
const SEASONAL_FORMAT_PRIORITY = ['TV', 'TV_SHORT', 'ONA'];
|
||||||
|
|
||||||
|
/** An ONA this short is a special released online, not a season. */
|
||||||
|
const MIN_ONA_SEASON_EPISODES = 3;
|
||||||
|
|
||||||
|
/** Largest season the chain walk will count to. */
|
||||||
const MAX_SEQUEL_HOPS = 12;
|
const MAX_SEQUEL_HOPS = 12;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hops the walk may take in total. Continuations and specials add hops without adding
|
||||||
|
* seasons, so this has to leave room beyond the season number.
|
||||||
|
*/
|
||||||
|
const MAX_SEQUEL_STEPS = 24;
|
||||||
|
|
||||||
|
/** Parts a single season can be split into before the episode remap gives up. */
|
||||||
|
const MAX_SEASON_PARTS = 6;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Markers AniList appends when one broadcast season is listed as several entries,
|
||||||
|
* matched against normalized titles. Anchored to the end so a numbered *work*
|
||||||
|
* ("JoJo no Kimyou na Bouken Part 5: Ougon no Kaze") is not read as a continuation:
|
||||||
|
* those carry a subtitle after the number and really are separate seasons.
|
||||||
|
*/
|
||||||
|
const PART_MARKER_PATTERNS: RegExp[] = [
|
||||||
|
/\bpart\s*(\d{1,2}|i{1,3}|iv|v)$/u,
|
||||||
|
/\bcour\s*(\d{1,2})$/u,
|
||||||
|
/\b(\d{1,2})(?:st|nd|rd|th)\s+(?:part|cour)$/u,
|
||||||
|
/\b(second|final)\s+(?:part|cour)$/u,
|
||||||
|
/第\s*(\d{1,2})\s*(?:部|クール)$/u,
|
||||||
|
];
|
||||||
|
|
||||||
|
const NUMBER_WORDS: Record<string, number> = {
|
||||||
|
i: 1,
|
||||||
|
ii: 2,
|
||||||
|
iii: 3,
|
||||||
|
iv: 4,
|
||||||
|
v: 5,
|
||||||
|
vi: 6,
|
||||||
|
second: 2,
|
||||||
|
third: 3,
|
||||||
|
fourth: 4,
|
||||||
|
fifth: 5,
|
||||||
|
sixth: 6,
|
||||||
|
一: 1,
|
||||||
|
二: 2,
|
||||||
|
三: 3,
|
||||||
|
四: 4,
|
||||||
|
五: 5,
|
||||||
|
六: 6,
|
||||||
|
七: 7,
|
||||||
|
八: 8,
|
||||||
|
九: 9,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patterns that state a season outright. Safe on any title or synonym, because none of
|
||||||
|
* them can be confused with a part or cour number.
|
||||||
|
*/
|
||||||
|
const EXPLICIT_SEASON_PATTERNS: RegExp[] = [
|
||||||
|
/\bseason\s*(\d{1,2})\b/u,
|
||||||
|
/\b(\d{1,2})(?:st|nd|rd|th)\s+season\b/u,
|
||||||
|
/\b(second|third|fourth|fifth|sixth)\s+season\b/u,
|
||||||
|
/\bs(\d{1,2})\b/u,
|
||||||
|
/第\s*(\d{1,2}|[二三四五六七八九])\s*[期季]/u,
|
||||||
|
/(\d{1,2})\s*(?:期|기)/u,
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Words after which a trailing number counts parts, not seasons. */
|
||||||
|
const PART_WORDS = new Set(['part', 'cour', 'parte', 'partie']);
|
||||||
|
|
||||||
|
function parseNumberToken(token: string): number | null {
|
||||||
|
if (/^\d{1,2}$/.test(token)) return Number(token);
|
||||||
|
return NUMBER_WORDS[token] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Drops season markers a release name carries but AniList titles never do,
|
* Drops season markers a release name carries but AniList titles never do,
|
||||||
* so "Some Show Season 3" and "Some Show S3" both search as "Some Show".
|
* so "Some Show Season 3" and "Some Show S3" both search as "Some Show".
|
||||||
@@ -134,13 +235,65 @@ export function stripSeasonSuffix(title: string): string {
|
|||||||
.trim();
|
.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
function mediaTitles(media: AnilistSeasonMedia): string[] {
|
/**
|
||||||
const synonyms = Array.isArray(media.synonyms) ? media.synonyms : [];
|
* Splits a trailing part/cour marker off a title, or returns null when it has none.
|
||||||
return [media.title?.english, media.title?.romaji, media.title?.native, ...synonyms]
|
*
|
||||||
|
* "Mushoku Tensei: Jobless Reincarnation Season 2 Part 2" is the back half of season 2,
|
||||||
|
* not season 3. `part` is null for an unnumbered marker ("Final Cour").
|
||||||
|
*/
|
||||||
|
export function splitPartMarker(title: string): { base: string; part: number | null } | null {
|
||||||
|
const normalized = normalizeTitleIdentity(title);
|
||||||
|
for (const pattern of PART_MARKER_PATTERNS) {
|
||||||
|
const match = normalized.match(pattern);
|
||||||
|
if (!match || match.index === undefined) continue;
|
||||||
|
const base = normalized.slice(0, match.index).trim();
|
||||||
|
if (!base) continue;
|
||||||
|
const token = match[1] ?? '';
|
||||||
|
return { base, part: token === 'final' ? null : parseNumberToken(token) };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mainTitles(media: AnilistSeasonMedia): string[] {
|
||||||
|
return [media.title?.english, media.title?.romaji, media.title?.native]
|
||||||
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||||
.map((value) => normalizeTitleIdentity(value));
|
.map((value) => normalizeTitleIdentity(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mediaTitles(media: AnilistSeasonMedia): string[] {
|
||||||
|
const synonyms = (Array.isArray(media.synonyms) ? media.synonyms : [])
|
||||||
|
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||||
|
.map((value) => normalizeTitleIdentity(value));
|
||||||
|
return [...mainTitles(media), ...synonyms].filter((value) => value.length > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Season numbers an entry's titles name.
|
||||||
|
*
|
||||||
|
* A bare trailing number ("Overlord II", "Konosuba 2") is only trusted on the main
|
||||||
|
* titles: localized synonyms end in part numbers spelled in other scripts (Mushoku
|
||||||
|
* Tensei's "Cour 2" carries the Thai "... พาร์ท 2", "part 2").
|
||||||
|
*/
|
||||||
|
export function namedSeasons(media: AnilistSeasonMedia): Set<number> {
|
||||||
|
const seasons = new Set<number>();
|
||||||
|
for (const title of mediaTitles(media)) {
|
||||||
|
for (const pattern of EXPLICIT_SEASON_PATTERNS) {
|
||||||
|
const token = title.match(pattern)?.[1];
|
||||||
|
const value = token ? parseNumberToken(token) : null;
|
||||||
|
if (value !== null && value > 0) seasons.add(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const title of mainTitles(media)) {
|
||||||
|
const words = title.split(' ');
|
||||||
|
const last = words.at(-1) ?? '';
|
||||||
|
const before = words.at(-2) ?? '';
|
||||||
|
if (PART_WORDS.has(before)) continue;
|
||||||
|
const value = parseNumberToken(last);
|
||||||
|
if (value !== null && value > 1) seasons.add(value);
|
||||||
|
}
|
||||||
|
return seasons;
|
||||||
|
}
|
||||||
|
|
||||||
function displayTitle(media: AnilistSeasonMedia, fallback: string): string {
|
function displayTitle(media: AnilistSeasonMedia, fallback: string): string {
|
||||||
return (
|
return (
|
||||||
media.title?.english?.trim() ||
|
media.title?.english?.trim() ||
|
||||||
@@ -167,29 +320,64 @@ function isSeasonalFormat(media: AnilistSeasonMedia): boolean {
|
|||||||
return SEASONAL_FORMAT_PRIORITY.includes(format);
|
return SEASONAL_FORMAT_PRIORITY.includes(format);
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatRank(media: AnilistSeasonMedia): number {
|
/** Whether an entry can be a season: a TV series, or an ONA long enough not to be a special. */
|
||||||
const index = SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
|
function isSeasonEntry(media: AnilistSeasonMedia): boolean {
|
||||||
return index < 0 ? SEASONAL_FORMAT_PRIORITY.length : index;
|
if (!isSeasonalFormat(media)) return false;
|
||||||
|
if ((media.format || '').toUpperCase() !== 'ONA') return true;
|
||||||
|
const episodes = episodeCount(media);
|
||||||
|
return episodes === null || episodes >= MIN_ONA_SEASON_EPISODES;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toResolution(
|
function formatRank(media: AnilistSeasonMedia): number {
|
||||||
media: AnilistSeasonMedia,
|
if (!isSeasonEntry(media)) return SEASONAL_FORMAT_PRIORITY.length;
|
||||||
fallbackTitle: string,
|
return SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
|
||||||
season: number | null,
|
}
|
||||||
via: AnilistSeasonResolutionVia,
|
|
||||||
seasonResolved: boolean,
|
/**
|
||||||
exactTitleMatch: boolean,
|
* Whether `next` continues the season `seasonStart` began rather than starting a new one.
|
||||||
): AnilistSeasonResolution {
|
*
|
||||||
return {
|
* Compared against the season's first entry, not the previous hop, so a special between
|
||||||
id: media.id,
|
* a season and its second cour cannot hide the link. The marker is required, not just a
|
||||||
title: displayTitle(media, fallbackTitle),
|
* matching base: a sequel that repeats its predecessor's name exactly is a new season
|
||||||
episodes: episodeCount(media),
|
* AniList did not number. "Part 1" never marks a back half, and a season's own marker is
|
||||||
media,
|
* only stripped when it is "Part 1" (AoT season 3 carries "... ภาค 3 Part 1"); stripping
|
||||||
seasonResolved,
|
* any number would read JoJo's "Part 6" as a continuation of its "Part 5".
|
||||||
requestedSeason: season,
|
*
|
||||||
via,
|
* An entry naming a season never continues a different one: "Show Season 2" with the
|
||||||
exactTitleMatch,
|
* synonym "Show Part 2" is season 2, not a back half of "Show". The season `seasonStart`
|
||||||
};
|
* stands for is taken from its own titles, else from `startSeason` when the caller
|
||||||
|
* knows it (the chain walk counts it, the episode remap was asked for it).
|
||||||
|
*/
|
||||||
|
function isSeasonContinuation(
|
||||||
|
seasonStart: AnilistSeasonMedia,
|
||||||
|
next: AnilistSeasonMedia,
|
||||||
|
startSeason: number | null = null,
|
||||||
|
): boolean {
|
||||||
|
const markers = mediaTitles(next)
|
||||||
|
.map((title) => splitPartMarker(title))
|
||||||
|
.filter((marker): marker is NonNullable<typeof marker> => marker !== null && marker.part !== 1);
|
||||||
|
if (markers.length === 0) return false;
|
||||||
|
|
||||||
|
const nextSeasons = namedSeasons(next);
|
||||||
|
if (nextSeasons.size > 0) {
|
||||||
|
const startNamed = namedSeasons(seasonStart);
|
||||||
|
const startSeasons =
|
||||||
|
startNamed.size > 0 ? startNamed : startSeason !== null ? new Set([startSeason]) : null;
|
||||||
|
if (startSeasons && ![...nextSeasons].some((value) => startSeasons.has(value))) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const seasonKeys = new Set<string>();
|
||||||
|
for (const title of mediaTitles(seasonStart)) {
|
||||||
|
seasonKeys.add(title);
|
||||||
|
const own = splitPartMarker(title);
|
||||||
|
if (own?.part === 1) seasonKeys.add(own.base);
|
||||||
|
}
|
||||||
|
return markers.some((marker) => seasonKeys.has(marker.base));
|
||||||
|
}
|
||||||
|
|
||||||
|
function exactMatchFor(candidate: AnilistSeasonMedia, titles: string[]): boolean {
|
||||||
|
const candidateTitles = mediaTitles(candidate);
|
||||||
|
return titles.some((title) => candidateTitles.includes(normalizeTitleIdentity(title)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -250,49 +438,31 @@ export function pickAnchorMedia(
|
|||||||
return scored[0]?.entry ?? null;
|
return scored[0]?.entry ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function walkSequelChain(
|
/** SEQUEL entries of a media id, minus those already visited, best continuation first. */
|
||||||
anchor: AnilistSeasonMedia,
|
type SequelLookup = (id: number, visited: Set<number>) => Promise<AnilistSeasonMedia[]>;
|
||||||
season: number,
|
|
||||||
deps: ResolveAnilistSeasonMediaDeps,
|
|
||||||
): Promise<AnilistSeasonMedia | null> {
|
|
||||||
// Walking fewer hops than requested would land on the wrong season and report it as
|
|
||||||
// resolved, so refuse instead and let the caller fall through to its guarded fallback.
|
|
||||||
const hops = season - 1;
|
|
||||||
if (hops > MAX_SEQUEL_HOPS) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const visited = new Set<number>([anchor.id]);
|
|
||||||
let current = anchor;
|
|
||||||
|
|
||||||
for (let hop = 0; hop < hops; hop += 1) {
|
/**
|
||||||
// Transport errors propagate: a failed hop must not be mistaken for "no sequel exists".
|
* Relation lookups for one resolution, memoized so the episode remap does not refetch
|
||||||
|
* what the chain walk already loaded. Sorted with a season over a special, then the TV
|
||||||
|
* line over other formats, then the earliest. Transport errors propagate: a failed lookup
|
||||||
|
* must not be mistaken for "no sequel exists".
|
||||||
|
*/
|
||||||
|
function createSequelLookup(deps: ResolveAnilistSeasonMediaDeps): SequelLookup {
|
||||||
|
const cache = new Map<number, Promise<AnilistSeasonMedia[]>>();
|
||||||
|
const load = async (id: number): Promise<AnilistSeasonMedia[]> => {
|
||||||
const response = await deps.execute<AnilistSeasonRelationsResponse>(
|
const response = await deps.execute<AnilistSeasonRelationsResponse>(
|
||||||
ANILIST_SEASON_RELATIONS_QUERY,
|
ANILIST_SEASON_RELATIONS_QUERY,
|
||||||
{ id: current.id },
|
{ id },
|
||||||
);
|
);
|
||||||
|
const sequels: AnilistSeasonMedia[] = [];
|
||||||
const sequels = (response.Media?.relations?.edges ?? [])
|
for (const edge of response.Media?.relations?.edges ?? []) {
|
||||||
.map((edge) => edge ?? null)
|
const node = edge?.node;
|
||||||
.filter(
|
if (!node || typeof node.id !== 'number') continue;
|
||||||
(
|
if ((edge.relationType || '').toUpperCase() !== 'SEQUEL') continue;
|
||||||
edge,
|
if ((node.type || 'ANIME').toUpperCase() !== 'ANIME') continue;
|
||||||
): edge is {
|
sequels.push(node);
|
||||||
relationType?: string | null;
|
|
||||||
node: AnilistSeasonMedia & { type?: string | null };
|
|
||||||
} =>
|
|
||||||
Boolean(edge?.node) &&
|
|
||||||
(edge?.relationType || '').toUpperCase() === 'SEQUEL' &&
|
|
||||||
(edge?.node?.type || 'ANIME').toUpperCase() === 'ANIME',
|
|
||||||
)
|
|
||||||
.map((edge) => edge.node)
|
|
||||||
.filter((node) => !visited.has(node.id));
|
|
||||||
|
|
||||||
if (sequels.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
return sequels.sort((a, b) => {
|
||||||
// A franchise can branch (a TV sequel plus an ONA spinoff); prefer the TV line.
|
|
||||||
sequels.sort((a, b) => {
|
|
||||||
const rankDelta = formatRank(a) - formatRank(b);
|
const rankDelta = formatRank(a) - formatRank(b);
|
||||||
if (rankDelta !== 0) return rankDelta;
|
if (rankDelta !== 0) return rankDelta;
|
||||||
const yearDelta =
|
const yearDelta =
|
||||||
@@ -300,12 +470,121 @@ async function walkSequelChain(
|
|||||||
if (yearDelta !== 0) return yearDelta;
|
if (yearDelta !== 0) return yearDelta;
|
||||||
return a.id - b.id;
|
return a.id - b.id;
|
||||||
});
|
});
|
||||||
|
};
|
||||||
|
return async (id, visited) => {
|
||||||
|
let pending = cache.get(id);
|
||||||
|
if (!pending) {
|
||||||
|
pending = load(id);
|
||||||
|
cache.set(id, pending);
|
||||||
|
// A failed lookup is retried by the next caller rather than cached.
|
||||||
|
pending.catch(() => cache.delete(id));
|
||||||
|
}
|
||||||
|
return (await pending).filter((node) => !visited.has(node.id));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
current = sequels[0]!;
|
type ChainResult = { media: AnilistSeasonMedia; via: 'named-season' | 'sequel-chain' };
|
||||||
visited.add(current.id);
|
|
||||||
|
async function walkSequelChain(
|
||||||
|
anchor: AnilistSeasonMedia,
|
||||||
|
season: number,
|
||||||
|
sequelsOf: SequelLookup,
|
||||||
|
): Promise<ChainResult | null> {
|
||||||
|
// Advancing fewer seasons than requested would land on the wrong one and report it as
|
||||||
|
// resolved, so refuse instead and let the caller fall through to its guarded fallback.
|
||||||
|
const targetAdvances = season - 1;
|
||||||
|
if (targetAdvances > MAX_SEQUEL_HOPS) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const visited = new Set<number>([anchor.id]);
|
||||||
|
let current = anchor;
|
||||||
|
// The last entry that counted as a season.
|
||||||
|
let seasonStart = anchor;
|
||||||
|
let advances = 0;
|
||||||
|
// The unnamed entry the count landed on. The walk looks one season further before
|
||||||
|
// accepting it, because an entry naming the requested season outranks the count: the
|
||||||
|
// counted entry may be a continuation with no marker.
|
||||||
|
let counted: AnilistSeasonMedia | null = null;
|
||||||
|
// Set once counting reached the requested season on an entry whose title names a
|
||||||
|
// different one. Only a named match can answer after that.
|
||||||
|
let countContradicted = false;
|
||||||
|
|
||||||
|
for (let step = 0; step < MAX_SEQUEL_STEPS; step += 1) {
|
||||||
|
const next = (await sequelsOf(current.id, visited))[0];
|
||||||
|
if (!next) break;
|
||||||
|
current = next;
|
||||||
|
visited.add(next.id);
|
||||||
|
|
||||||
|
// Specials, movies and OVAs are walked through, because the rest of the franchise
|
||||||
|
// hangs off them, but never counted.
|
||||||
|
if (!isSeasonEntry(next)) continue;
|
||||||
|
|
||||||
|
const named = namedSeasons(next);
|
||||||
|
if (isSeasonContinuation(seasonStart, next, advances + 1)) {
|
||||||
|
// A back half naming the requested season ("Season 3 Part 2") vouches for the
|
||||||
|
// entry its season started on.
|
||||||
|
if (named.has(season)) return { media: seasonStart, via: 'named-season' };
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (named.has(season)) return { media: next, via: 'named-season' };
|
||||||
|
// The season after the counted one does not claim the requested number either.
|
||||||
|
if (counted) break;
|
||||||
|
if (countContradicted) {
|
||||||
|
// Past the requested season by name: it is not on this chain.
|
||||||
|
if ([...named].some((value) => value > season)) return null;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
advances += 1;
|
||||||
|
seasonStart = next;
|
||||||
|
if (advances === targetAdvances) {
|
||||||
|
if (named.size === 0) counted = next;
|
||||||
|
else countContradicted = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return current.id === anchor.id ? null : current;
|
return counted ? { media: counted, via: 'sequel-chain' } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the parsed episode runs past `seasonEntry` into a later part of the same season,
|
||||||
|
* and if so, which entry airs it and at what episode number. Null when the episode fits
|
||||||
|
* the season entry, its length is unknown, or no continuation covers the episode (e.g.
|
||||||
|
* absolute numbering across seasons).
|
||||||
|
*/
|
||||||
|
async function findEpisodeEntry(
|
||||||
|
seasonEntry: AnilistSeasonMedia,
|
||||||
|
season: number,
|
||||||
|
episode: number,
|
||||||
|
sequelsOf: SequelLookup,
|
||||||
|
): Promise<{ media: AnilistSeasonMedia; episode: number } | null> {
|
||||||
|
const seasonLength = episodeCount(seasonEntry);
|
||||||
|
if (seasonLength === null || episode <= seasonLength) return null;
|
||||||
|
|
||||||
|
const visited = new Set<number>([seasonEntry.id]);
|
||||||
|
let current = seasonEntry;
|
||||||
|
// The last part whose episodes are still counted in `remaining`; its length is known.
|
||||||
|
let lastPart = seasonEntry;
|
||||||
|
let remaining = episode;
|
||||||
|
let parts = 1;
|
||||||
|
|
||||||
|
for (let step = 0; step < MAX_SEQUEL_STEPS; step += 1) {
|
||||||
|
const next = (await sequelsOf(current.id, visited))[0];
|
||||||
|
if (!next) return null;
|
||||||
|
visited.add(next.id);
|
||||||
|
current = next;
|
||||||
|
// A recap special between the two halves airs none of the season's episodes.
|
||||||
|
if (!isSeasonEntry(next)) continue;
|
||||||
|
if (!isSeasonContinuation(seasonEntry, next, season)) return null;
|
||||||
|
|
||||||
|
remaining -= episodeCount(lastPart) ?? 0;
|
||||||
|
lastPart = next;
|
||||||
|
parts += 1;
|
||||||
|
const length = episodeCount(next);
|
||||||
|
if (length === null || remaining <= length) return { media: next, episode: remaining };
|
||||||
|
if (parts >= MAX_SEASON_PARTS) return null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -317,24 +596,45 @@ export function pickByAirOrder(
|
|||||||
season: number,
|
season: number,
|
||||||
media: AnilistSeasonMedia[],
|
media: AnilistSeasonMedia[],
|
||||||
): AnilistSeasonMedia | null {
|
): AnilistSeasonMedia | null {
|
||||||
const anchorTitles = mediaTitles(anchor).map((value) => stripSeasonSuffix(value));
|
// Any of the anchor's main titles, matched on word boundaries. Synonyms are too short
|
||||||
const anchorBase = anchorTitles.sort((a, b) => a.length - b.length)[0];
|
// and loose ("SnK", "ReZero") to define a franchise, and a single title misses entries
|
||||||
if (!anchorBase) return null;
|
// that only spell another one out (Mushoku Tensei II's native title adds "Ⅱ" to the
|
||||||
|
// word the season 1 native title ends on).
|
||||||
|
const anchorBases = mainTitles(anchor)
|
||||||
|
.map((value) => stripSeasonSuffix(value))
|
||||||
|
.filter((value) => value.length > 0);
|
||||||
|
if (anchorBases.length === 0) return null;
|
||||||
|
|
||||||
const franchise = media.filter((entry) => {
|
const franchise = media.filter((entry) => {
|
||||||
if (!isSeasonalFormat(entry)) return false;
|
if (!isSeasonEntry(entry)) return false;
|
||||||
if (entry.id === anchor.id) return true;
|
if (entry.id === anchor.id) return true;
|
||||||
return mediaTitles(entry).some((candidate) =>
|
return mediaTitles(entry).some((candidate) => {
|
||||||
stripSeasonSuffix(candidate).includes(anchorBase),
|
const padded = ` ${stripSeasonSuffix(candidate)} `;
|
||||||
|
return anchorBases.some((base) => padded.includes(` ${base} `));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Drop the back halves of split-cour seasons, which are separate entries here but not
|
||||||
|
// separate seasons: counting them shifts every later season index. An entry is only
|
||||||
|
// compared against the *other* entries' titles, so a season whose own localized synonym
|
||||||
|
// spells it "<season> Part 1" is kept.
|
||||||
|
const seasons = franchise.filter((entry) => {
|
||||||
|
if (entry.id === anchor.id) return true;
|
||||||
|
// The anchor is season 1 here, which lets the continuation check reject an entry
|
||||||
|
// naming another season even when the anchor's own titles name none.
|
||||||
|
return !franchise.some(
|
||||||
|
(other) =>
|
||||||
|
other.id !== entry.id &&
|
||||||
|
isSeasonContinuation(other, entry, other.id === anchor.id ? 1 : null),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
if (franchise.length < season) return null;
|
if (seasons.length < season) return null;
|
||||||
|
|
||||||
// Ordering by air date is only meaningful when every entry has one: an unknown year
|
// Ordering by air date is only meaningful when every entry has one: an unknown year
|
||||||
// would sort last and shift the season index while still reporting a resolved match.
|
// would sort last and shift the season index while still reporting a resolved match.
|
||||||
if (franchise.some((entry) => airYear(entry) === null)) return null;
|
if (seasons.some((entry) => airYear(entry) === null)) return null;
|
||||||
|
|
||||||
const ordered = [...franchise].sort((a, b) => {
|
const ordered = [...seasons].sort((a, b) => {
|
||||||
const yearDelta = (airYear(a) ?? 0) - (airYear(b) ?? 0);
|
const yearDelta = (airYear(a) ?? 0) - (airYear(b) ?? 0);
|
||||||
if (yearDelta !== 0) return yearDelta;
|
if (yearDelta !== 0) return yearDelta;
|
||||||
return a.id - b.id;
|
return a.id - b.id;
|
||||||
@@ -343,7 +643,12 @@ export function pickByAirOrder(
|
|||||||
// The anchor has to be the first entry, otherwise this ordering is not a season list.
|
// The anchor has to be the first entry, otherwise this ordering is not a season list.
|
||||||
if (ordered[0]?.id !== anchor.id) return null;
|
if (ordered[0]?.id !== anchor.id) return null;
|
||||||
|
|
||||||
return ordered[season - 1] ?? null;
|
const picked = ordered[season - 1] ?? null;
|
||||||
|
if (!picked) return null;
|
||||||
|
// An entry that names some other season shows this ordering is off.
|
||||||
|
const named = namedSeasons(picked);
|
||||||
|
if (named.size > 0 && !named.has(season)) return null;
|
||||||
|
return picked;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resolveAnilistSeasonMedia(
|
export async function resolveAnilistSeasonMedia(
|
||||||
@@ -359,6 +664,10 @@ export async function resolveAnilistSeasonMedia(
|
|||||||
typeof input.season === 'number' && Number.isInteger(input.season) && input.season > 0
|
typeof input.season === 'number' && Number.isInteger(input.season) && input.season > 0
|
||||||
? input.season
|
? input.season
|
||||||
: null;
|
: null;
|
||||||
|
const episode =
|
||||||
|
typeof input.episode === 'number' && Number.isInteger(input.episode) && input.episode > 0
|
||||||
|
? input.episode
|
||||||
|
: null;
|
||||||
|
|
||||||
const response = await deps.execute<AnilistSeasonSearchResponse>(ANILIST_SEASON_SEARCH_QUERY, {
|
const response = await deps.execute<AnilistSeasonSearchResponse>(ANILIST_SEASON_SEARCH_QUERY, {
|
||||||
search: searchTitle,
|
search: searchTitle,
|
||||||
@@ -368,72 +677,83 @@ export async function resolveAnilistSeasonMedia(
|
|||||||
);
|
);
|
||||||
if (media.length === 0) return null;
|
if (media.length === 0) return null;
|
||||||
|
|
||||||
// Season 1 (or unknown) resolves against the episode count; later seasons must not,
|
// Certifies the media actually returned, never the anchor on its behalf: a hop can land
|
||||||
// because the anchor is season 1 and may be shorter than the requested episode.
|
// on the wrong entry while the anchor title still matches perfectly, and that certainty
|
||||||
const anchor = pickAnchorMedia(searchTitle, media, {
|
// must not carry over to the hopped-to entry.
|
||||||
episode: season === null || season <= 1 ? input.episode : null,
|
const parsedTitles = [searchTitle, input.title];
|
||||||
});
|
const sequelsOf = createSequelLookup(deps);
|
||||||
if (!anchor) return null;
|
|
||||||
// Certifies the media actually returned, never the anchor on its behalf: a
|
const finish = (
|
||||||
// sequel-chain hop can land one season short (split-cour entries) while the
|
seasonEntry: AnilistSeasonMedia,
|
||||||
// anchor title still matches perfectly, and that certainty must not carry
|
via: AnilistSeasonResolutionVia,
|
||||||
// over to the hopped-to entry.
|
split: { media: AnilistSeasonMedia; episode: number } | null = null,
|
||||||
const exactMatchFor = (candidate: AnilistSeasonMedia): boolean => {
|
seasonResolved = true,
|
||||||
const titles = mediaTitles(candidate);
|
): AnilistSeasonResolution => {
|
||||||
return (
|
if (split) {
|
||||||
titles.includes(normalizeTitleIdentity(searchTitle)) ||
|
deps.logInfo?.(
|
||||||
titles.includes(normalizeTitleIdentity(input.title))
|
`[anilist] episode ${episode} of "${searchTitle}" is episode ${split.episode} of ${displayTitle(split.media, searchTitle)} (${split.media.id})`,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: seasonEntry.id,
|
||||||
|
title: displayTitle(seasonEntry, searchTitle),
|
||||||
|
episodes: episodeCount(seasonEntry),
|
||||||
|
media: seasonEntry,
|
||||||
|
seasonResolved,
|
||||||
|
requestedSeason: season,
|
||||||
|
via,
|
||||||
|
exactTitleMatch: exactMatchFor(seasonEntry, parsedTitles),
|
||||||
|
episodeEntry: split
|
||||||
|
? {
|
||||||
|
id: split.media.id,
|
||||||
|
title: displayTitle(split.media, searchTitle),
|
||||||
|
episodes: episodeCount(split.media),
|
||||||
|
media: split.media,
|
||||||
|
episode: split.episode,
|
||||||
|
exactTitleMatch: exactMatchFor(split.media, parsedTitles),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
if (season === null || season <= 1) {
|
if (season === null || season <= 1) {
|
||||||
return toResolution(anchor, searchTitle, season, 'anchor', true, exactMatchFor(anchor));
|
// The best title match first. If the episode runs past it, a split-cour continuation
|
||||||
|
// may air it ("S1E15" of 11 + 12). Only when none does, and the title match is not a
|
||||||
|
// season itself (a same-titled movie or special), is the episode count used to pick
|
||||||
|
// a longer entry; it must not swap season 1 for a later, longer season.
|
||||||
|
const titleAnchor = pickAnchorMedia(searchTitle, media);
|
||||||
|
if (!titleAnchor) return null;
|
||||||
|
if (episode === null) return finish(titleAnchor, 'anchor');
|
||||||
|
const split = await findEpisodeEntry(titleAnchor, 1, episode, sequelsOf);
|
||||||
|
if (split) return finish(titleAnchor, 'anchor', split);
|
||||||
|
if (isSeasonEntry(titleAnchor)) return finish(titleAnchor, 'anchor');
|
||||||
|
const fitted = pickAnchorMedia(searchTitle, media, { episode });
|
||||||
|
const laterSeason = fitted !== null && [...namedSeasons(fitted)].some((value) => value > 1);
|
||||||
|
return finish(fitted && !laterSeason ? fitted : titleAnchor, 'anchor');
|
||||||
}
|
}
|
||||||
|
|
||||||
let chainError: unknown = null;
|
// Later seasons must not filter by episode, because the anchor is season 1 and may be
|
||||||
let viaChain: AnilistSeasonMedia | null = null;
|
// shorter than the requested episode.
|
||||||
try {
|
const anchor = pickAnchorMedia(searchTitle, media);
|
||||||
viaChain = await walkSequelChain(anchor, season, deps);
|
if (!anchor) return null;
|
||||||
} catch (error) {
|
|
||||||
chainError = error;
|
// Transport failures propagate from here: the air-order fallback is for a chain that
|
||||||
}
|
// answered and had no edge to follow, and running it after a failed hop would turn a
|
||||||
if (viaChain) {
|
// rate limit into a confident wrong season.
|
||||||
|
const viaChain = await walkSequelChain(anchor, season, sequelsOf);
|
||||||
|
const seasonEntry = viaChain?.media ?? pickByAirOrder(anchor, season, media);
|
||||||
|
if (seasonEntry) {
|
||||||
|
const via = viaChain?.via ?? 'air-order';
|
||||||
deps.logInfo?.(
|
deps.logInfo?.(
|
||||||
`[anilist] season ${season} of "${searchTitle}" resolved via sequel chain: ${displayTitle(viaChain, searchTitle)} (${viaChain.id})`,
|
`[anilist] season ${season} of "${searchTitle}" resolved via ${via}: ${displayTitle(seasonEntry, searchTitle)} (${seasonEntry.id})`,
|
||||||
);
|
);
|
||||||
return toResolution(
|
const split =
|
||||||
viaChain,
|
episode === null ? null : await findEpisodeEntry(seasonEntry, season, episode, sequelsOf);
|
||||||
searchTitle,
|
return finish(seasonEntry, via, split);
|
||||||
season,
|
|
||||||
'sequel-chain',
|
|
||||||
true,
|
|
||||||
exactMatchFor(viaChain),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const viaAirOrder = pickByAirOrder(anchor, season, media);
|
|
||||||
if (viaAirOrder) {
|
|
||||||
deps.logInfo?.(
|
|
||||||
`[anilist] season ${season} of "${searchTitle}" resolved via air order: ${displayTitle(viaAirOrder, searchTitle)} (${viaAirOrder.id})`,
|
|
||||||
);
|
|
||||||
return toResolution(
|
|
||||||
viaAirOrder,
|
|
||||||
searchTitle,
|
|
||||||
season,
|
|
||||||
'air-order',
|
|
||||||
true,
|
|
||||||
exactMatchFor(viaAirOrder),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The chain failed for transport reasons rather than because the season is absent;
|
|
||||||
// surface that so callers retry instead of reporting an unresolvable season.
|
|
||||||
if (chainError) {
|
|
||||||
throw chainError;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
deps.logInfo?.(
|
deps.logInfo?.(
|
||||||
`[anilist] could not resolve season ${season} of "${searchTitle}"; falling back to ${displayTitle(anchor, searchTitle)} (${anchor.id})`,
|
`[anilist] could not resolve season ${season} of "${searchTitle}"; falling back to ${displayTitle(anchor, searchTitle)} (${anchor.id})`,
|
||||||
);
|
);
|
||||||
return toResolution(anchor, searchTitle, season, 'anchor', false, exactMatchFor(anchor));
|
return finish(anchor, 'anchor', null, false);
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,18 @@ import { createLogger } from '../../logger';
|
|||||||
import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity';
|
import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity';
|
||||||
import { MediaGenerator } from '../../media-generator';
|
import { MediaGenerator } from '../../media-generator';
|
||||||
import type { CoverArtFetcher } from './anilist/cover-art-fetcher';
|
import type { CoverArtFetcher } from './anilist/cover-art-fetcher';
|
||||||
|
import type { AnilistRelationFetcher } from './anilist/franchise-relation-fetcher';
|
||||||
|
import {
|
||||||
|
createFranchiseRelationRefresher,
|
||||||
|
type FranchiseRelationRefresher,
|
||||||
|
} from './immersion-tracker/franchise-relation-refresher';
|
||||||
|
import {
|
||||||
|
getAnimeGroupPlacement,
|
||||||
|
getAnimeLibraryGroups,
|
||||||
|
setAnimeGroupOverride,
|
||||||
|
type AnimeGroupOverrideResult,
|
||||||
|
type AnimeGroupOverrideTarget,
|
||||||
|
} from './immersion-tracker/query-library-groups';
|
||||||
import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata';
|
import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata';
|
||||||
import {
|
import {
|
||||||
pruneRawRetention,
|
pruneRawRetention,
|
||||||
@@ -51,6 +63,17 @@ import {
|
|||||||
getSessionWordsByLine,
|
getSessionWordsByLine,
|
||||||
} from './immersion-tracker/query-sessions';
|
} from './immersion-tracker/query-sessions';
|
||||||
import { getTrendsDashboard } from './immersion-tracker/query-trends';
|
import { getTrendsDashboard } from './immersion-tracker/query-trends';
|
||||||
|
import {
|
||||||
|
getDictionaryWordPage,
|
||||||
|
getVocabularyCoverage,
|
||||||
|
} from './immersion-tracker/query-vocabulary-words';
|
||||||
|
import type {
|
||||||
|
StatsDayRange,
|
||||||
|
StatsDictionaryWordQuery,
|
||||||
|
StatsTrendGroupBy,
|
||||||
|
StatsTrendRange,
|
||||||
|
} from '../../types/stats-http-contract';
|
||||||
|
import type { AnimeGroupPlacement, AnimeLibraryGroup } from '../../types/stats-wire';
|
||||||
import {
|
import {
|
||||||
getKanjiAnimeAppearances,
|
getKanjiAnimeAppearances,
|
||||||
getKanjiDetail,
|
getKanjiDetail,
|
||||||
@@ -442,6 +465,7 @@ export class ImmersionTrackerService {
|
|||||||
private readonly mediaGenerator = new MediaGenerator();
|
private readonly mediaGenerator = new MediaGenerator();
|
||||||
private readonly preparedStatements: TrackerPreparedStatements;
|
private readonly preparedStatements: TrackerPreparedStatements;
|
||||||
private coverArtFetcher: CoverArtFetcher | null = null;
|
private coverArtFetcher: CoverArtFetcher | null = null;
|
||||||
|
private franchiseRelations: FranchiseRelationRefresher | null = null;
|
||||||
private readonly pendingCoverFetches = new Map<number, Promise<boolean>>();
|
private readonly pendingCoverFetches = new Map<number, Promise<boolean>>();
|
||||||
private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>();
|
private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>();
|
||||||
private readonly recordedSubtitleKeys = new Set<string>();
|
private readonly recordedSubtitleKeys = new Set<string>();
|
||||||
@@ -611,6 +635,7 @@ export class ImmersionTrackerService {
|
|||||||
}
|
}
|
||||||
this.finalizeActiveSession();
|
this.finalizeActiveSession();
|
||||||
this.isDestroyed = true;
|
this.isDestroyed = true;
|
||||||
|
this.franchiseRelations?.stop();
|
||||||
this.deleteMaintenanceScheduler.destroy();
|
this.deleteMaintenanceScheduler.destroy();
|
||||||
this.destroyDeleteMaintenanceRunner();
|
this.destroyDeleteMaintenanceRunner();
|
||||||
this.destroyVocabularySummaryRunner();
|
this.destroyVocabularySummaryRunner();
|
||||||
@@ -618,8 +643,11 @@ export class ImmersionTrackerService {
|
|||||||
this.db.close();
|
this.db.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
async getSessionSummaries(limit = 50): Promise<SessionSummaryQueryRow[]> {
|
async getSessionSummaries(
|
||||||
return getSessionSummaries(this.db, limit);
|
limit = 50,
|
||||||
|
dayRange?: StatsDayRange,
|
||||||
|
): Promise<SessionSummaryQueryRow[]> {
|
||||||
|
return getSessionSummaries(this.db, limit, dayRange);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getSessionTimeline(sessionId: number, limit?: number): Promise<SessionTimelineRow[]> {
|
async getSessionTimeline(sessionId: number, limit?: number): Promise<SessionTimelineRow[]> {
|
||||||
@@ -673,11 +701,12 @@ export class ImmersionTrackerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getTrendsDashboard(
|
async getTrendsDashboard(
|
||||||
range: '7d' | '30d' | '90d' | '365d' | 'all' = '30d',
|
range: StatsTrendRange = '30d',
|
||||||
groupBy: 'day' | 'month' = 'day',
|
groupBy: StatsTrendGroupBy = 'day',
|
||||||
fillEmptyBuckets = true,
|
fillEmptyBuckets = true,
|
||||||
|
title: string | null = null,
|
||||||
) {
|
) {
|
||||||
return getTrendsDashboard(this.db, range, groupBy, fillEmptyBuckets);
|
return getTrendsDashboard(this.db, range, groupBy, fillEmptyBuckets, title);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getVocabularyStats(limit = 100, excludePos?: string[]): Promise<VocabularyStatsRow[]> {
|
async getVocabularyStats(limit = 100, excludePos?: string[]): Promise<VocabularyStatsRow[]> {
|
||||||
@@ -703,6 +732,17 @@ export class ImmersionTrackerService {
|
|||||||
return getVocabularyChartData(this.db);
|
return getVocabularyChartData(this.db);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getDictionaryWords(
|
||||||
|
knownWords: ReadonlySet<string> | null,
|
||||||
|
query: StatsDictionaryWordQuery,
|
||||||
|
) {
|
||||||
|
return getDictionaryWordPage(this.db, knownWords, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getVocabularyCoverage(knownWords: ReadonlySet<string>) {
|
||||||
|
return getVocabularyCoverage(this.db, knownWords);
|
||||||
|
}
|
||||||
|
|
||||||
async getStatsExcludedWords(): Promise<StatsExcludedWordRow[]> {
|
async getStatsExcludedWords(): Promise<StatsExcludedWordRow[]> {
|
||||||
return getStatsExcludedWords(this.db);
|
return getStatsExcludedWords(this.db);
|
||||||
}
|
}
|
||||||
@@ -754,8 +794,9 @@ export class ImmersionTrackerService {
|
|||||||
reading: string,
|
reading: string,
|
||||||
limit = 100,
|
limit = 100,
|
||||||
offset = 0,
|
offset = 0,
|
||||||
|
allForms = false,
|
||||||
): Promise<WordOccurrenceRow[]> {
|
): Promise<WordOccurrenceRow[]> {
|
||||||
return getWordOccurrences(this.db, headword, word, reading, limit, offset);
|
return getWordOccurrences(this.db, headword, word, reading, limit, offset, allForms);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getKanjiOccurrences(kanji: string, limit = 100, offset = 0): Promise<KanjiOccurrenceRow[]> {
|
async getKanjiOccurrences(kanji: string, limit = 100, offset = 0): Promise<KanjiOccurrenceRow[]> {
|
||||||
@@ -807,6 +848,27 @@ export class ImmersionTrackerService {
|
|||||||
return getAnimeLibrary(this.db);
|
return getAnimeLibrary(this.db);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The library as franchise cards; also schedules a background AniList relation refresh. */
|
||||||
|
async getAnimeLibraryGroups(): Promise<AnimeLibraryGroup[]> {
|
||||||
|
this.relinkYoutubeAnimeLibrary();
|
||||||
|
const groups = getAnimeLibraryGroups(this.db);
|
||||||
|
this.franchiseRelations?.requestRefresh();
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAnimeGroupPlacement(animeId: number): Promise<AnimeGroupPlacement | null> {
|
||||||
|
return getAnimeGroupPlacement(this.db, animeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async setAnimeGroupOverride(
|
||||||
|
animeId: number,
|
||||||
|
target: AnimeGroupOverrideTarget,
|
||||||
|
): Promise<AnimeGroupOverrideResult> {
|
||||||
|
const result = setAnimeGroupOverride(this.db, animeId, target);
|
||||||
|
if (result.ok) this.franchiseRelations?.requestRefresh({ force: true });
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> {
|
async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> {
|
||||||
return getAnimeMergeRecommendations(this.db);
|
return getAnimeMergeRecommendations(this.db);
|
||||||
}
|
}
|
||||||
@@ -1096,6 +1158,7 @@ export class ImmersionTrackerService {
|
|||||||
this.db.exec('ROLLBACK');
|
this.db.exec('ROLLBACK');
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
this.franchiseRelations?.requestRefresh({ force: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1222,6 +1285,19 @@ export class ImmersionTrackerService {
|
|||||||
this.coverArtFetcher = fetcher;
|
this.coverArtFetcher = fetcher;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Enables franchise grouping refreshes; null disables them (tests, offline runs). */
|
||||||
|
setAnilistRelationFetcher(fetcher: AnilistRelationFetcher | null): void {
|
||||||
|
this.franchiseRelations?.stop();
|
||||||
|
this.franchiseRelations = fetcher
|
||||||
|
? createFranchiseRelationRefresher({
|
||||||
|
db: this.db,
|
||||||
|
fetcher,
|
||||||
|
logger: createLogger('immersion-tracker:franchise-relations'),
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
this.franchiseRelations?.requestRefresh();
|
||||||
|
}
|
||||||
|
|
||||||
async ensureAnimeCoverArt(animeId: number): Promise<boolean> {
|
async ensureAnimeCoverArt(animeId: number): Promise<boolean> {
|
||||||
const existing = await this.getAnimeCoverArt(animeId);
|
const existing = await this.getAnimeCoverArt(animeId);
|
||||||
if (existing?.coverBlob) {
|
if (existing?.coverBlob) {
|
||||||
@@ -1274,6 +1350,8 @@ export class ImmersionTrackerService {
|
|||||||
if (!fetched) {
|
if (!fetched) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
// A fresh AniList link may join this entry to a franchise card.
|
||||||
|
this.franchiseRelations?.requestRefresh({ force: true });
|
||||||
const cover = await this.getCoverArt(videoId);
|
const cover = await this.getCoverArt(videoId);
|
||||||
return cover?.coverBlob != null;
|
return cover?.coverBlob != null;
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -704,7 +704,7 @@ test('getTrendsDashboard returns chart-ready aggregated series', () => {
|
|||||||
total_tokens_seen, total_cards
|
total_tokens_seen, total_cards
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
`,
|
`,
|
||||||
).run(Math.floor(dayOneStart / 86_400_000), videoId, 1, 30, 10, 120, 2);
|
).run(getLocalEpochDay(db, dayOneStart), videoId, 1, 30, 10, 120, 2);
|
||||||
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`
|
`
|
||||||
@@ -713,7 +713,7 @@ test('getTrendsDashboard returns chart-ready aggregated series', () => {
|
|||||||
total_tokens_seen, total_cards
|
total_tokens_seen, total_cards
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
`,
|
`,
|
||||||
).run(Math.floor(dayTwoStart / 86_400_000), videoId, 1, 45, 10, 140, 3);
|
).run(getLocalEpochDay(db, dayTwoStart), videoId, 1, 45, 10, 140, 3);
|
||||||
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`
|
`
|
||||||
@@ -739,15 +739,17 @@ test('getTrendsDashboard returns chart-ready aggregated series', () => {
|
|||||||
assert.equal(dashboard.activity.watchTime[0]?.value, 30);
|
assert.equal(dashboard.activity.watchTime[0]?.value, 30);
|
||||||
assert.equal(dashboard.progress.watchTime[1]?.value, 75);
|
assert.equal(dashboard.progress.watchTime[1]?.value, 75);
|
||||||
assert.equal(dashboard.progress.lookups[1]?.value, 18);
|
assert.equal(dashboard.progress.lookups[1]?.value, 18);
|
||||||
assert.equal(dashboard.ratios.lookupsPerHundred[0]?.value, +((8 / 120) * 100).toFixed(1));
|
|
||||||
assert.equal(dashboard.ratios.cardsPerHour[0]?.value, +(2 / (30 / 60)).toFixed(1));
|
assert.equal(dashboard.ratios.cardsPerHour[0]?.value, +(2 / (30 / 60)).toFixed(1));
|
||||||
assert.equal(dashboard.ratios.cardsPerHour[1]?.value, +(3 / (45 / 60)).toFixed(1));
|
assert.equal(dashboard.ratios.cardsPerHour[1]?.value, +(5 / (75 / 60)).toFixed(1));
|
||||||
assert.equal(dashboard.ratios.readingSpeed[0]?.value, +(120 / 30).toFixed(1));
|
assert.equal(dashboard.ratios.readingSpeed[0]?.value, +(120 / 30).toFixed(1));
|
||||||
assert.equal(dashboard.ratios.readingSpeed[1]?.value, +(140 / 45).toFixed(1));
|
assert.equal(dashboard.ratios.readingSpeed[1]?.value, +(260 / 75).toFixed(1));
|
||||||
assert.equal(dashboard.librarySummary[0]?.title, 'Trend Dashboard Anime');
|
assert.equal(dashboard.librarySummary[0]?.title, 'Trend Dashboard Anime');
|
||||||
assert.equal(dashboard.animeCumulative.watchTime[1]?.value, 75);
|
assert.deepEqual(
|
||||||
|
dashboard.titleTimeline.map((point) => point.value).sort((a, b) => a - b),
|
||||||
|
[30, 45],
|
||||||
|
);
|
||||||
assert.equal(
|
assert.equal(
|
||||||
dashboard.patterns.watchTimeByDayOfWeek.reduce((sum, point) => sum + point.value, 0),
|
dashboard.watchTimeByDayHour.flat().reduce((sum, minutes) => sum + minutes, 0),
|
||||||
75,
|
75,
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -819,7 +821,7 @@ test('getTrendsDashboard redacts legacy Jellyfin stream titles', () => {
|
|||||||
|
|
||||||
const dashboard = getTrendsDashboard(db, 'all', 'day');
|
const dashboard = getTrendsDashboard(db, 'all', 'day');
|
||||||
const titles = [
|
const titles = [
|
||||||
...dashboard.animeCumulative.watchTime.map((point) => point.animeTitle),
|
...dashboard.titleTimeline.map((point) => point.animeTitle),
|
||||||
...dashboard.librarySummary.map((row) => row.title),
|
...dashboard.librarySummary.map((row) => row.title),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -1521,6 +1523,8 @@ test('word-count read models use filtered persisted occurrences with raw fallbac
|
|||||||
const startedAtMs = 1_700_000_000_000;
|
const startedAtMs = 1_700_000_000_000;
|
||||||
const withOccurrences = startSessionRecord(db, videoId, startedAtMs);
|
const withOccurrences = startSessionRecord(db, videoId, startedAtMs);
|
||||||
const fallbackOnly = startSessionRecord(db, videoId, startedAtMs + 60_000);
|
const fallbackOnly = startSessionRecord(db, videoId, startedAtMs + 60_000);
|
||||||
|
// Still running, so its words stay out of the all-time total.
|
||||||
|
const stillActive = startSessionRecord(db, videoId, startedAtMs + 120_000);
|
||||||
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`
|
`
|
||||||
@@ -1543,6 +1547,14 @@ test('word-count read models use filtered persisted occurrences with raw fallbac
|
|||||||
occurrenceCount: 2,
|
occurrenceCount: 2,
|
||||||
startedAtMs,
|
startedAtMs,
|
||||||
});
|
});
|
||||||
|
insertFilteredWordOccurrence(db, {
|
||||||
|
sessionId: stillActive.sessionId,
|
||||||
|
videoId,
|
||||||
|
lineIndex: 3,
|
||||||
|
occurrenceCount: 4,
|
||||||
|
startedAtMs: startedAtMs + 120_000,
|
||||||
|
headword: '犬',
|
||||||
|
});
|
||||||
insertFilteredWordOccurrence(db, {
|
insertFilteredWordOccurrence(db, {
|
||||||
sessionId: withOccurrences.sessionId,
|
sessionId: withOccurrences.sessionId,
|
||||||
videoId,
|
videoId,
|
||||||
@@ -4738,7 +4750,7 @@ test('deleteSession removes zero-session media from library and trends', () => {
|
|||||||
|
|
||||||
const trends = getTrendsDashboard(db, 'all', 'day');
|
const trends = getTrendsDashboard(db, 'all', 'day');
|
||||||
assert.deepEqual(trends.activity.watchTime, []);
|
assert.deepEqual(trends.activity.watchTime, []);
|
||||||
assert.deepEqual(trends.activity.sessions, []);
|
assert.deepEqual(trends.activity.cards, []);
|
||||||
|
|
||||||
const dailyRollups = getDailyRollups(db, 30);
|
const dailyRollups = getDailyRollups(db, 30);
|
||||||
const monthlyRollups = getMonthlyRollups(db, 30);
|
const monthlyRollups = getMonthlyRollups(db, 30);
|
||||||
@@ -5060,7 +5072,7 @@ test('getTrendsDashboard rollup word metrics keep persisted totals over partial
|
|||||||
total_tokens_seen, total_cards
|
total_tokens_seen, total_cards
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
`,
|
`,
|
||||||
).run(Math.floor(row.start / 86_400_000), videoId, 1, 10, 1, row.rawWords, 0);
|
).run(getLocalEpochDay(db, row.start), videoId, 1, 10, 1, row.rawWords, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
const dashboard = getTrendsDashboard(db, 'all', 'day');
|
const dashboard = getTrendsDashboard(db, 'all', 'day');
|
||||||
@@ -5072,10 +5084,8 @@ test('getTrendsDashboard rollup word metrics keep persisted totals over partial
|
|||||||
dashboard.progress.words.map((point) => point.value),
|
dashboard.progress.words.map((point) => point.value),
|
||||||
[10, 30],
|
[10, 30],
|
||||||
);
|
);
|
||||||
assert.equal(dashboard.ratios.lookupsPerHundred[0]?.value, 200);
|
|
||||||
assert.equal(dashboard.librarySummary[0]?.words, 30);
|
assert.equal(dashboard.librarySummary[0]?.words, 30);
|
||||||
assert.equal(dashboard.librarySummary[0]?.lookupsPerHundred, 33.3);
|
assert.equal(dashboard.librarySummary[0]?.lookupsPerHundred, 33.3);
|
||||||
assert.equal(dashboard.animeCumulative.words.at(-1)?.value, 30);
|
|
||||||
} finally {
|
} finally {
|
||||||
db.close();
|
db.close();
|
||||||
cleanupDbPath(dbPath);
|
cleanupDbPath(dbPath);
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import type { AnilistMediaNode } from '../anilist/franchise-graph';
|
||||||
|
import type { DatabaseSync } from './sqlite';
|
||||||
|
import { fromDbTimestamp, toDbTimestamp } from './query-shared';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Franchise grouping state. `imm_anilist_media` and `imm_anilist_relations`
|
||||||
|
* cache AniList entries (owned or reached through relations) and every
|
||||||
|
* anime-to-anime edge, whatever its type, so the grouping rule can change
|
||||||
|
* without a refetch. The cache is rebuildable from AniList and is not synced.
|
||||||
|
*
|
||||||
|
* `imm_anime.group_override` is the user's choice for one library entry:
|
||||||
|
* NULL follows AniList, 0 keeps the entry on its own, and a positive value is
|
||||||
|
* an AniList id whose franchise the entry joins. `group_override_updated_at`
|
||||||
|
* records when it was set (or cleared) so sync can keep the newer choice.
|
||||||
|
*/
|
||||||
|
export function ensureAnimeGroupingSchema(db: DatabaseSync): void {
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS imm_anilist_media(
|
||||||
|
anilist_id INTEGER PRIMARY KEY,
|
||||||
|
format TEXT,
|
||||||
|
title_romaji TEXT,
|
||||||
|
title_english TEXT,
|
||||||
|
title_native TEXT,
|
||||||
|
start_date INTEGER,
|
||||||
|
episodes INTEGER,
|
||||||
|
fetched_at_ms TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS imm_anilist_relations(
|
||||||
|
anilist_id INTEGER NOT NULL,
|
||||||
|
relation_type TEXT NOT NULL,
|
||||||
|
target_anilist_id INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY(anilist_id, relation_type, target_anilist_id),
|
||||||
|
FOREIGN KEY(anilist_id) REFERENCES imm_anilist_media(anilist_id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
const columns = new Set(
|
||||||
|
(db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>).map(
|
||||||
|
(column) => column.name,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (!columns.has('group_override')) {
|
||||||
|
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override INTEGER');
|
||||||
|
}
|
||||||
|
if (!columns.has('group_override_updated_at')) {
|
||||||
|
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override_updated_at TEXT');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readAnilistRelationCache(db: DatabaseSync): Map<number, AnilistMediaNode> {
|
||||||
|
const nodes = new Map<number, AnilistMediaNode>();
|
||||||
|
const mediaRows = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT anilist_id AS anilistId, format, title_romaji AS titleRomaji,
|
||||||
|
title_english AS titleEnglish, title_native AS titleNative,
|
||||||
|
start_date AS startDate, episodes, fetched_at_ms AS fetchedAtMs
|
||||||
|
FROM imm_anilist_media`,
|
||||||
|
)
|
||||||
|
.all() as Array<Omit<AnilistMediaNode, 'relations' | 'fetchedAtMs'> & { fetchedAtMs: string }>;
|
||||||
|
for (const row of mediaRows) {
|
||||||
|
nodes.set(row.anilistId, {
|
||||||
|
...row,
|
||||||
|
relations: [],
|
||||||
|
fetchedAtMs: fromDbTimestamp(row.fetchedAtMs) ?? 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const edgeRows = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT anilist_id AS anilistId, relation_type AS relationType, target_anilist_id AS targetId
|
||||||
|
FROM imm_anilist_relations
|
||||||
|
ORDER BY anilist_id, relation_type, target_anilist_id`,
|
||||||
|
)
|
||||||
|
.all() as Array<{ anilistId: number; relationType: string; targetId: number }>;
|
||||||
|
for (const edge of edgeRows) {
|
||||||
|
nodes.get(edge.anilistId)?.relations.push({
|
||||||
|
relationType: edge.relationType,
|
||||||
|
targetId: edge.targetId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return nodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces each node's cached row and edges in one transaction. */
|
||||||
|
export function writeAnilistRelationNodes(db: DatabaseSync, nodes: AnilistMediaNode[]): void {
|
||||||
|
if (nodes.length === 0) return;
|
||||||
|
const upsertMedia = db.prepare(`
|
||||||
|
INSERT INTO imm_anilist_media(anilist_id, format, title_romaji, title_english, title_native,
|
||||||
|
start_date, episodes, fetched_at_ms)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(anilist_id) DO UPDATE SET
|
||||||
|
format = excluded.format,
|
||||||
|
title_romaji = excluded.title_romaji,
|
||||||
|
title_english = excluded.title_english,
|
||||||
|
title_native = excluded.title_native,
|
||||||
|
start_date = excluded.start_date,
|
||||||
|
episodes = excluded.episodes,
|
||||||
|
fetched_at_ms = excluded.fetched_at_ms
|
||||||
|
`);
|
||||||
|
const deleteEdges = db.prepare('DELETE FROM imm_anilist_relations WHERE anilist_id = ?');
|
||||||
|
const insertEdge = db.prepare(`
|
||||||
|
INSERT OR IGNORE INTO imm_anilist_relations(anilist_id, relation_type, target_anilist_id)
|
||||||
|
VALUES (?, ?, ?)
|
||||||
|
`);
|
||||||
|
db.exec('BEGIN IMMEDIATE');
|
||||||
|
try {
|
||||||
|
for (const node of nodes) {
|
||||||
|
upsertMedia.run(
|
||||||
|
node.anilistId,
|
||||||
|
node.format,
|
||||||
|
node.titleRomaji,
|
||||||
|
node.titleEnglish,
|
||||||
|
node.titleNative,
|
||||||
|
node.startDate,
|
||||||
|
node.episodes,
|
||||||
|
toDbTimestamp(node.fetchedAtMs),
|
||||||
|
);
|
||||||
|
deleteEdges.run(node.anilistId);
|
||||||
|
for (const edge of node.relations) {
|
||||||
|
insertEdge.run(node.anilistId, edge.relationType, edge.targetId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
db.exec('COMMIT');
|
||||||
|
} catch (error) {
|
||||||
|
db.exec('ROLLBACK');
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import type { AnilistMediaNode } from '../anilist/franchise-graph';
|
||||||
|
import { readAnilistRelationCache } from './anilist-relation-cache';
|
||||||
|
import {
|
||||||
|
createFranchiseRelationRefresher,
|
||||||
|
FRANCHISE_RELATION_STALE_MS,
|
||||||
|
} from './franchise-relation-refresher';
|
||||||
|
import { Database } from './sqlite';
|
||||||
|
import { ensureSchema } from './storage';
|
||||||
|
|
||||||
|
const silent = { info: () => {}, warn: () => {} };
|
||||||
|
|
||||||
|
function media(anilistId: number, relations: Array<[string, number]>, fetchedAtMs: number) {
|
||||||
|
return {
|
||||||
|
anilistId,
|
||||||
|
format: 'TV',
|
||||||
|
titleRomaji: null,
|
||||||
|
titleEnglish: null,
|
||||||
|
titleNative: null,
|
||||||
|
startDate: null,
|
||||||
|
episodes: null,
|
||||||
|
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
|
||||||
|
fetchedAtMs,
|
||||||
|
} satisfies AnilistMediaNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('refresh walks from linked entries and override targets, then keeps the cache on failure', async () => {
|
||||||
|
const db = new Database(':memory:');
|
||||||
|
try {
|
||||||
|
ensureSchema(db);
|
||||||
|
db.exec(`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, media_kind)
|
||||||
|
VALUES ('a', 'A', 1, 'anime'), ('c', 'C', 77, 'youtube');
|
||||||
|
INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override)
|
||||||
|
VALUES ('b', 'B', 50)`);
|
||||||
|
let clock = 1_000;
|
||||||
|
let failing = false;
|
||||||
|
const asked: number[][] = [];
|
||||||
|
const refresher = createFranchiseRelationRefresher({
|
||||||
|
db,
|
||||||
|
logger: silent,
|
||||||
|
now: () => clock,
|
||||||
|
fetcher: {
|
||||||
|
fetchMedia: async (ids) => {
|
||||||
|
if (failing) throw new Error('AniList down');
|
||||||
|
asked.push([...ids].sort((a, b) => a - b));
|
||||||
|
return ids.map((id) => media(id, id === 1 ? [['SEQUEL', 2]] : [], clock));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
refresher.requestRefresh();
|
||||||
|
await refresher.whenIdle();
|
||||||
|
assert.deepEqual(asked, [[1, 50], [2]]);
|
||||||
|
assert.deepEqual(
|
||||||
|
[...readAnilistRelationCache(db).keys()].sort((a, b) => a - b),
|
||||||
|
[1, 2, 50],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Throttled until forced; everything is fresh, so a forced run asks nothing.
|
||||||
|
refresher.requestRefresh({ force: true });
|
||||||
|
await refresher.whenIdle();
|
||||||
|
assert.equal(asked.length, 2);
|
||||||
|
|
||||||
|
clock += FRANCHISE_RELATION_STALE_MS;
|
||||||
|
failing = true;
|
||||||
|
refresher.requestRefresh({ force: true });
|
||||||
|
await refresher.whenIdle();
|
||||||
|
assert.deepEqual(readAnilistRelationCache(db).get(1)?.relations, [
|
||||||
|
{ relationType: 'SEQUEL', targetId: 2 },
|
||||||
|
]);
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { walkFranchiseRelations } from '../anilist/franchise-graph';
|
||||||
|
import type { AnilistRelationFetcher } from '../anilist/franchise-relation-fetcher';
|
||||||
|
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
|
||||||
|
import type { DatabaseSync } from './sqlite';
|
||||||
|
|
||||||
|
/** Cached AniList entries are asked about again after a week. */
|
||||||
|
export const FRANCHISE_RELATION_STALE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||||
|
/** Hops followed from a library entry; keeps long-running franchises bounded. */
|
||||||
|
export const FRANCHISE_WALK_MAX_DEPTH = 6;
|
||||||
|
/** Entries fetched per refresh (five AniList requests); the rest wait for the next refresh. */
|
||||||
|
export const FRANCHISE_WALK_MAX_FETCH = 250;
|
||||||
|
/** Unforced refreshes (library polls) run at most this often. */
|
||||||
|
const MIN_INTERVAL_MS = 10 * 60 * 1000;
|
||||||
|
|
||||||
|
interface RefresherLogger {
|
||||||
|
info(message: string, ...args: unknown[]): void;
|
||||||
|
warn(message: string, ...args: unknown[]): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FranchiseRelationRefresherDeps {
|
||||||
|
db: DatabaseSync;
|
||||||
|
fetcher: AnilistRelationFetcher;
|
||||||
|
logger: RefresherLogger;
|
||||||
|
now?: () => number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FranchiseRelationRefresher {
|
||||||
|
/**
|
||||||
|
* Starts a background refresh unless one ran recently. `force` skips that
|
||||||
|
* throttle, for when an entry has just been linked to AniList.
|
||||||
|
*/
|
||||||
|
requestRefresh(options?: { force?: boolean }): void;
|
||||||
|
/** Resolves once no refresh is running; for tests and shutdown. */
|
||||||
|
whenIdle(): Promise<void>;
|
||||||
|
/** Stops writing; a running refresh finishes its request and discards the result. */
|
||||||
|
stop(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readSeeds(db: DatabaseSync): number[] {
|
||||||
|
return (
|
||||||
|
db
|
||||||
|
.prepare(
|
||||||
|
`SELECT anilist_id AS id FROM imm_anime WHERE media_kind = 'anime' AND anilist_id IS NOT NULL
|
||||||
|
UNION
|
||||||
|
SELECT group_override AS id FROM imm_anime WHERE group_override > 0`,
|
||||||
|
)
|
||||||
|
.all() as Array<{ id: number }>
|
||||||
|
).map((row) => row.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createFranchiseRelationRefresher(
|
||||||
|
deps: FranchiseRelationRefresherDeps,
|
||||||
|
): FranchiseRelationRefresher {
|
||||||
|
const now = deps.now ?? Date.now;
|
||||||
|
let running: Promise<void> | null = null;
|
||||||
|
let pending = false;
|
||||||
|
let stopped = false;
|
||||||
|
let lastStartedAtMs: number | null = null;
|
||||||
|
|
||||||
|
const refreshOnce = async (): Promise<void> => {
|
||||||
|
const known = readAnilistRelationCache(deps.db);
|
||||||
|
const result = await walkFranchiseRelations({
|
||||||
|
seeds: readSeeds(deps.db),
|
||||||
|
known,
|
||||||
|
isFresh: (node) => now() - node.fetchedAtMs < FRANCHISE_RELATION_STALE_MS,
|
||||||
|
fetchNodes: (ids) => deps.fetcher.fetchMedia(ids),
|
||||||
|
onBatch: (nodes) => writeAnilistRelationNodes(deps.db, nodes),
|
||||||
|
isCancelled: () => stopped,
|
||||||
|
now,
|
||||||
|
maxDepth: FRANCHISE_WALK_MAX_DEPTH,
|
||||||
|
maxFetch: FRANCHISE_WALK_MAX_FETCH,
|
||||||
|
});
|
||||||
|
if (result.fetched > 0) {
|
||||||
|
deps.logger.info(
|
||||||
|
'franchise-relations: refreshed %d AniList entries%s',
|
||||||
|
result.fetched,
|
||||||
|
result.truncated ? ' (more next time)' : '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const run = (): void => {
|
||||||
|
lastStartedAtMs = now();
|
||||||
|
running = (async () => {
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
pending = false;
|
||||||
|
await refreshOnce();
|
||||||
|
} while (pending && !stopped);
|
||||||
|
} catch (error) {
|
||||||
|
// Cached rows stay as they were; the next request (after the throttle) retries.
|
||||||
|
deps.logger.warn(
|
||||||
|
'franchise-relations: refresh failed: %s',
|
||||||
|
error instanceof Error ? error.message : String(error),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
running = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
requestRefresh(options = {}) {
|
||||||
|
if (stopped) return;
|
||||||
|
if (running) {
|
||||||
|
if (options.force) pending = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!options.force && lastStartedAtMs !== null && now() - lastStartedAtMs < MIN_INTERVAL_MS) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
run();
|
||||||
|
},
|
||||||
|
async whenIdle() {
|
||||||
|
while (running) await running;
|
||||||
|
},
|
||||||
|
stop() {
|
||||||
|
stopped = true;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -8,15 +8,16 @@ import {
|
|||||||
getLexicalDailyRollups,
|
getLexicalDailyRollups,
|
||||||
rebuildLexicalDailyRollups,
|
rebuildLexicalDailyRollups,
|
||||||
} from './lexical-rollups';
|
} from './lexical-rollups';
|
||||||
import { getTrendsDashboard } from './query-trends';
|
|
||||||
import {
|
import {
|
||||||
getVocabularyChartData,
|
getVocabularyChartData,
|
||||||
getVocabularySummary,
|
getVocabularySummary,
|
||||||
replaceStatsExcludedWords,
|
replaceStatsExcludedWords,
|
||||||
} from './query-lexical';
|
} from './query-lexical';
|
||||||
|
import { cleanupVocabularyStats } from './query-maintenance';
|
||||||
import { Database } from './sqlite';
|
import { Database } from './sqlite';
|
||||||
import type { DatabaseSync } from './sqlite';
|
import type { DatabaseSync } from './sqlite';
|
||||||
import { createTrackerPreparedStatements, ensureSchema, executeQueuedWrite } from './storage';
|
import { createTrackerPreparedStatements, ensureSchema, executeQueuedWrite } from './storage';
|
||||||
|
import { isVocabularyStatsRowVisible, type VocabularyVisibilityRow } from './vocabulary-visibility';
|
||||||
import { BASE_MS, createDb, seedEndedSession, seedVideo } from './__tests__/lifetime-test-fixtures';
|
import { BASE_MS, createDb, seedEndedSession, seedVideo } from './__tests__/lifetime-test-fixtures';
|
||||||
|
|
||||||
function makeDbPath(): string {
|
function makeDbPath(): string {
|
||||||
@@ -260,7 +261,7 @@ test('lexical rollup rebuild tolerates nullable legacy vocabulary text', () => {
|
|||||||
assert.equal(areLexicalDailyRollupsReady(db), true);
|
assert.equal(areLexicalDailyRollupsReady(db), true);
|
||||||
assert.equal(getVocabularySummary(db, null).uniqueWords, 1);
|
assert.equal(getVocabularySummary(db, null).uniqueWords, 1);
|
||||||
assert.equal(getVocabularySummary(db, new Set(['猫'])).knownWordCount, 1);
|
assert.equal(getVocabularySummary(db, new Set(['猫'])).knownWordCount, 1);
|
||||||
assert.equal(getVocabularyChartData(db).topWords[0]?.headword, '猫');
|
assert.equal(getVocabularyChartData(db).newWordsTimeline[0]?.wordCount, 1);
|
||||||
} finally {
|
} finally {
|
||||||
db.close();
|
db.close();
|
||||||
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
|
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
|
||||||
@@ -384,7 +385,7 @@ test('current lexical rollup readiness accepts legacy integer state storage', ()
|
|||||||
state_value INTEGER NOT NULL
|
state_value INTEGER NOT NULL
|
||||||
);
|
);
|
||||||
INSERT INTO imm_rollup_state(state_key, state_value)
|
INSERT INTO imm_rollup_state(state_key, state_value)
|
||||||
VALUES ('lexical_daily_rollups_version', 3);
|
VALUES ('lexical_daily_rollups_version', 4);
|
||||||
`);
|
`);
|
||||||
|
|
||||||
assert.equal(areLexicalDailyRollupsReady(db), true);
|
assert.equal(areLexicalDailyRollupsReady(db), true);
|
||||||
@@ -394,6 +395,185 @@ test('current lexical rollup readiness accepts legacy integer state storage', ()
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function insertWord(
|
||||||
|
db: DatabaseSync,
|
||||||
|
word: {
|
||||||
|
headword: string;
|
||||||
|
word: string;
|
||||||
|
reading: string;
|
||||||
|
partOfSpeech: string;
|
||||||
|
pos1: string;
|
||||||
|
pos2: string;
|
||||||
|
},
|
||||||
|
firstSeen: number,
|
||||||
|
): number {
|
||||||
|
const result = db
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO imm_words(
|
||||||
|
headword, word, reading, part_of_speech, pos1, pos2, pos3, first_seen, last_seen, frequency
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, '', ?, ?, 1)`,
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
word.headword,
|
||||||
|
word.word,
|
||||||
|
word.reading,
|
||||||
|
word.partOfSpeech,
|
||||||
|
word.pos1,
|
||||||
|
word.pos2,
|
||||||
|
firstSeen,
|
||||||
|
firstSeen,
|
||||||
|
);
|
||||||
|
return Number(result.lastInsertRowid);
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertPersistedVisibilityMatchesPredicate(db: DatabaseSync): void {
|
||||||
|
const rows = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT headword, word, reading, part_of_speech AS partOfSpeech, pos1, pos2, pos3,
|
||||||
|
frequency_rank AS frequencyRank, vocabulary_visible AS vocabularyVisible
|
||||||
|
FROM imm_words`,
|
||||||
|
)
|
||||||
|
.all() as Array<VocabularyVisibilityRow & { vocabularyVisible: number }>;
|
||||||
|
assert.ok(rows.length > 0);
|
||||||
|
assert.deepEqual(
|
||||||
|
rows.map((row) => [row.headword, row.vocabularyVisible === 1]),
|
||||||
|
rows.map((row) => [row.headword, isVocabularyStatsRowVisible(row)]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('cleanupVocabularyStats re-derives visibility for a repaired word', async () => {
|
||||||
|
const dbPath = makeDbPath();
|
||||||
|
const db = new Database(dbPath);
|
||||||
|
|
||||||
|
try {
|
||||||
|
ensureSchema(db);
|
||||||
|
const epochDay = 19_500;
|
||||||
|
const firstSeen = epochDay * 86_400 + 43_200;
|
||||||
|
const legacyWord = {
|
||||||
|
headword: '旧',
|
||||||
|
word: '旧',
|
||||||
|
reading: '',
|
||||||
|
partOfSpeech: 'particle',
|
||||||
|
pos1: '助詞',
|
||||||
|
pos2: '係助詞',
|
||||||
|
};
|
||||||
|
const legacyId = insertWord(db, legacyWord, firstSeen);
|
||||||
|
rebuildLexicalDailyRollups(db);
|
||||||
|
assert.equal(getVocabularySummary(db, null).uniqueWords, 0);
|
||||||
|
|
||||||
|
await cleanupVocabularyStats(db, {
|
||||||
|
resolveLegacyPos: async (row) =>
|
||||||
|
row.id === legacyId
|
||||||
|
? {
|
||||||
|
headword: '旧',
|
||||||
|
reading: 'きゅう',
|
||||||
|
partOfSpeech: 'noun',
|
||||||
|
pos1: '名詞',
|
||||||
|
pos2: '一般',
|
||||||
|
pos3: '',
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
assertPersistedVisibilityMatchesPredicate(db);
|
||||||
|
assert.equal(getVocabularySummary(db, null).uniqueWords, 1);
|
||||||
|
assert.equal(getLexicalDailyRollups(db)[0]?.wordCount, 1);
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cleanupVocabularyStats re-derives visibility for a merged duplicate', async () => {
|
||||||
|
const dbPath = makeDbPath();
|
||||||
|
const db = new Database(dbPath);
|
||||||
|
|
||||||
|
try {
|
||||||
|
ensureSchema(db);
|
||||||
|
const firstSeen = 19_500 * 86_400 + 43_200;
|
||||||
|
// The merge fills these blank POS fields from the repair, which hides the word.
|
||||||
|
insertWord(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
headword: '知る',
|
||||||
|
word: '知っている',
|
||||||
|
reading: 'しっている',
|
||||||
|
partOfSpeech: 'noun',
|
||||||
|
pos1: '',
|
||||||
|
pos2: '',
|
||||||
|
},
|
||||||
|
firstSeen,
|
||||||
|
);
|
||||||
|
const legacyId = insertWord(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
headword: '知っている',
|
||||||
|
word: '知っている',
|
||||||
|
reading: '',
|
||||||
|
partOfSpeech: 'verb',
|
||||||
|
pos1: '動詞',
|
||||||
|
pos2: '自立',
|
||||||
|
},
|
||||||
|
firstSeen,
|
||||||
|
);
|
||||||
|
rebuildLexicalDailyRollups(db);
|
||||||
|
assert.equal(getVocabularySummary(db, null).uniqueWords, 2);
|
||||||
|
|
||||||
|
await cleanupVocabularyStats(db, {
|
||||||
|
resolveLegacyPos: async (row) =>
|
||||||
|
row.id === legacyId
|
||||||
|
? {
|
||||||
|
headword: '知る',
|
||||||
|
reading: 'しっている',
|
||||||
|
partOfSpeech: 'particle',
|
||||||
|
pos1: '助詞',
|
||||||
|
pos2: '係助詞',
|
||||||
|
pos3: '',
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
assertPersistedVisibilityMatchesPredicate(db);
|
||||||
|
assert.equal(getVocabularySummary(db, null).uniqueWords, 0);
|
||||||
|
assert.deepEqual(getLexicalDailyRollups(db), []);
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a queued word write persists visibility from the stored row', () => {
|
||||||
|
const dbPath = makeDbPath();
|
||||||
|
const db = new Database(dbPath);
|
||||||
|
|
||||||
|
try {
|
||||||
|
ensureSchema(db);
|
||||||
|
const firstSeen = 19_500 * 86_400 + 43_200;
|
||||||
|
executeQueuedWrite(
|
||||||
|
{
|
||||||
|
kind: 'word',
|
||||||
|
headword: 'は',
|
||||||
|
word: 'は',
|
||||||
|
reading: 'は',
|
||||||
|
partOfSpeech: 'particle',
|
||||||
|
pos1: '助詞',
|
||||||
|
pos2: '係助詞',
|
||||||
|
pos3: '',
|
||||||
|
firstSeen,
|
||||||
|
lastSeen: firstSeen,
|
||||||
|
frequencyRank: null,
|
||||||
|
},
|
||||||
|
createTrackerPreparedStatements(db),
|
||||||
|
);
|
||||||
|
|
||||||
|
assertPersistedVisibilityMatchesPredicate(db);
|
||||||
|
assert.equal(getVocabularySummary(db, null).uniqueWords, 0);
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('imm_words persists vocabulary visibility for rollup maintenance', () => {
|
test('imm_words persists vocabulary visibility for rollup maintenance', () => {
|
||||||
const dbPath = makeDbPath();
|
const dbPath = makeDbPath();
|
||||||
const db = new Database(dbPath);
|
const db = new Database(dbPath);
|
||||||
@@ -412,7 +592,7 @@ test('imm_words persists vocabulary visibility for rollup maintenance', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('vocabulary charts use complete top-word and lexical rollup data', () => {
|
test('vocabulary charts count every word in new-word history', () => {
|
||||||
const dbPath = makeDbPath();
|
const dbPath = makeDbPath();
|
||||||
const db = new Database(dbPath);
|
const db = new Database(dbPath);
|
||||||
|
|
||||||
@@ -430,8 +610,6 @@ test('vocabulary charts use complete top-word and lexical rollup data', () => {
|
|||||||
|
|
||||||
const charts = getVocabularyChartData(db);
|
const charts = getVocabularyChartData(db);
|
||||||
|
|
||||||
assert.equal(charts.topWords[0]?.headword, '語500');
|
|
||||||
assert.equal(charts.topWords[0]?.frequency, 10_000);
|
|
||||||
assert.equal(charts.newWordsTimeline[0]?.wordCount, 501);
|
assert.equal(charts.newWordsTimeline[0]?.wordCount, 501);
|
||||||
} finally {
|
} finally {
|
||||||
db.close();
|
db.close();
|
||||||
@@ -439,41 +617,6 @@ test('vocabulary charts use complete top-word and lexical rollup data', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('vocabulary charts find full top-word sets beyond excluded and name rows', () => {
|
|
||||||
const dbPath = makeDbPath();
|
|
||||||
const db = new Database(dbPath);
|
|
||||||
|
|
||||||
try {
|
|
||||||
ensureSchema(db);
|
|
||||||
const insertWord = db.prepare(
|
|
||||||
`INSERT INTO imm_words(headword, word, reading, pos2, first_seen, last_seen, frequency)
|
|
||||||
VALUES (?, ?, '', ?, 1700000000, 1700000000, ?)`,
|
|
||||||
);
|
|
||||||
const exclusions = [];
|
|
||||||
for (let index = 0; index < 100; index += 1) {
|
|
||||||
const headword = `語${index}`;
|
|
||||||
insertWord.run(
|
|
||||||
headword,
|
|
||||||
headword,
|
|
||||||
index < 80 && index >= 60 ? '固有名詞' : '一般',
|
|
||||||
100 - index,
|
|
||||||
);
|
|
||||||
if (index < 60) exclusions.push({ headword, word: headword, reading: '' });
|
|
||||||
}
|
|
||||||
replaceStatsExcludedWords(db, exclusions);
|
|
||||||
|
|
||||||
const charts = getVocabularyChartData(db);
|
|
||||||
|
|
||||||
assert.equal(charts.topWords.length, 12);
|
|
||||||
assert.equal(charts.topWords[0]?.headword, '語60');
|
|
||||||
assert.equal(charts.topWordsWithoutNames.length, 12);
|
|
||||||
assert.equal(charts.topWordsWithoutNames[0]?.headword, '語80');
|
|
||||||
} finally {
|
|
||||||
db.close();
|
|
||||||
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('vocabulary charts handle exclusion lists above one SQLite variable batch', () => {
|
test('vocabulary charts handle exclusion lists above one SQLite variable batch', () => {
|
||||||
const dbPath = makeDbPath();
|
const dbPath = makeDbPath();
|
||||||
const db = new Database(dbPath);
|
const db = new Database(dbPath);
|
||||||
@@ -493,7 +636,6 @@ test('vocabulary charts handle exclusion lists above one SQLite variable batch',
|
|||||||
|
|
||||||
const charts = getVocabularyChartData(db);
|
const charts = getVocabularyChartData(db);
|
||||||
|
|
||||||
assert.deepEqual(charts.topWords, []);
|
|
||||||
assert.deepEqual(charts.newWordsTimeline, []);
|
assert.deepEqual(charts.newWordsTimeline, []);
|
||||||
} finally {
|
} finally {
|
||||||
db.close();
|
db.close();
|
||||||
@@ -516,24 +658,3 @@ test('lexical rollup rebuild preserves the original error when rollback also fai
|
|||||||
|
|
||||||
assert.throws(() => rebuildLexicalDailyRollups(db), originalError);
|
assert.throws(() => rebuildLexicalDailyRollups(db), originalError);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('trends read historical new-word buckets from lexical rollups', () => {
|
|
||||||
const dbPath = makeDbPath();
|
|
||||||
const db = new Database(dbPath);
|
|
||||||
|
|
||||||
try {
|
|
||||||
ensureSchema(db);
|
|
||||||
db.prepare(
|
|
||||||
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
|
|
||||||
VALUES ('海', '海', 'うみ', 1700000000, 1700000000, 1)`,
|
|
||||||
).run();
|
|
||||||
db.prepare(`UPDATE imm_lexical_daily_rollups SET word_count = 9`).run();
|
|
||||||
|
|
||||||
const dashboard = getTrendsDashboard(db, 'all', 'day', false);
|
|
||||||
|
|
||||||
assert.equal(dashboard.progress.newWords[0]?.value, 9);
|
|
||||||
} finally {
|
|
||||||
db.close();
|
|
||||||
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -19,8 +19,9 @@ const LOCAL_EPOCH_DAY_SQL = `
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
// v3 re-derives visibility for rows a re-seen word forced visible and repairs
|
// v3 re-derives visibility for rows a re-seen word forced visible and repairs
|
||||||
// last_seen values left behind by session deletes.
|
// last_seen values left behind by session deletes. v4 re-derives visibility for
|
||||||
const LEXICAL_DAILY_ROLLUP_VERSION = '3';
|
// rows vocabulary cleanup repaired without updating it.
|
||||||
|
const LEXICAL_DAILY_ROLLUP_VERSION = '4';
|
||||||
const LEXICAL_DAILY_ROLLUP_VERSION_KEY = 'lexical_daily_rollups_version';
|
const LEXICAL_DAILY_ROLLUP_VERSION_KEY = 'lexical_daily_rollups_version';
|
||||||
const VOCABULARY_VISIBILITY_SCAN_BATCH_SIZE = 5_000;
|
const VOCABULARY_VISIBILITY_SCAN_BATCH_SIZE = 5_000;
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 313 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user