Compare commits

..
Author SHA1 Message Date
sudacode 4a78b946d9 fix(stats): address review findings on franchise walk and group view
- The relation walk keeps every incoming link to an entry and follows it when
  any link is accepted, so a veto on one seed no longer hides a franchise root
  reached through another (and seed order no longer changes the result).
- A stopped refresher starts no further AniList request; the in-flight result
  is dropped and the walk ends.
- An open franchise that is left with one part closes once the library has
  loaded, so a later refresh cannot reopen it on its own.
2026-11-22 14:37:03 -08:00
sudacode 55110fd592 docs(stats): note schema 27 in the immersion schema version comment 2026-11-22 02:34:05 -08:00
sudacode 2edf56541c feat(stats): group library seasons, movies and OVAs into franchise cards
The stats library now lists each anime once. Grouping is a view over
imm_anime rows computed from a cached AniList relation graph; no rows are
merged and identity keys are unchanged.

- Schema 27: imm_anilist_media + imm_anilist_relations cache every AniList
  entry reached from the library and all its anime edges. A background
  refresher walks from owned AniList ids (depth 6, 250 fetches per run,
  7-day staleness) through the shared AniList rate limiter; a failed fetch
  leaves cached rows untouched.
- FRANCHISE_RELATION_TYPES (PREQUEL, SEQUEL, PARENT, SIDE_STORY, SUMMARY,
  COMPILATION, CONTAINS) joins entries; an entry that names the other only
  through an excluded type (a spin-off's original) vetoes the join.
- GET /api/stats/anime/groups returns cards with summed totals, the root
  entry's title, and parts in release order. Entries without cached
  relations stay single cards identical to before.
- imm_anime.group_override (NULL = AniList, 0 = on its own, positive =
  join the franchise containing that AniList id) with
  PUT /api/stats/anime/:id/group and Move to Another Anime / Show On Its
  Own / Put Back Where AniList Has It on the title page.
- SSH sync merges the override last-writer-wins on
  group_override_updated_at and skips the rebuildable relation cache.
2026-11-22 02:33:44 -08:00
55 changed files with 2346 additions and 680 deletions

No files matched your search

+1 -1
View File
@@ -121,7 +121,7 @@ SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to
| mpv | Required | The video player SubMiner draws over | | mpv | Required | The video player SubMiner draws over |
| fuse2 | Required (Linux) | Running the AppImage | | fuse2 | Required (Linux) | Running the AppImage |
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup | | Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
| ffmpeg | Recommended | Card audio and screenshots (first-run setup can download it) | | ffmpeg | Recommended | Audio clips and screenshots on cards |
| MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting | | MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting |
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway | | xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
| yt-dlp | Optional | YouTube playback | | yt-dlp | Optional | YouTube playback |
+5
View File
@@ -0,0 +1,5 @@
type: added
area: stats
- Library lists each anime once: seasons, movies, and OVAs that AniList links as sequels, prequels, side stories, summaries, or compilations share one card, named after the first TV series. Opening it lists the parts in release order with their own stats. Spin-offs and alternative versions keep their own cards.
- A title's page has **Move to Another Anime…**, **Show On Its Own**, and **Put Back Where AniList Has It** to correct the grouping. `subminer sync` keeps the most recent choice.
-4
View File
@@ -1,4 +0,0 @@
type: added
area: setup
- First-run setup now shows whether FFmpeg and FFprobe are usable. When they are missing from `PATH`, **Download FFmpeg** saves a verified static build next to your config, and SubMiner and the `subminer` command use it whenever no system FFmpeg is found.
+1 -1
View File
@@ -8,7 +8,7 @@ For the day-to-day flow, see [Mining workflow](/mining-workflow). Every key on t
1. Install [Anki](https://apps.ankiweb.net/). 1. Install [Anki](https://apps.ankiweb.net/).
2. Install AnkiConnect (add-on code `2055492159`). 2. Install AnkiConnect (add-on code `2055492159`).
3. Install FFmpeg and make sure it is on your `PATH`, or download it from first-run setup. SubMiner uses it for audio and images. 3. Install FFmpeg and make sure it is on your `PATH`. SubMiner uses it for audio and images.
4. Keep Anki running while you mine. 4. Keep Anki running while you mine.
If you changed AnkiConnect's port, set `ankiConnect.url` to match. If you changed AnkiConnect's port, set `ankiConnect.url` to match.
+6 -2
View File
@@ -50,11 +50,15 @@ Deleting a session or session group refreshes the Overview totals, charts, calen
Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel. Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel.
Seasons get separate cards when a season number is detected. Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand. Seasons, movies, and OVAs of one anime share a card. SubMiner follows AniList's sequel, prequel, parent, side-story, summary, and compilation links, including through entries you have not watched, so two films can meet at a TV series you never played. Spin-offs and alternative versions keep their own cards. A shared card is named after the anime's first TV series, shows the cover of the earliest part you have, and opens to a list of its parts in release order. Relations come from AniList in the background and refresh weekly, so a newly linked show can take a minute to join its card.
If a part lands on the wrong card, open it and choose **Move to Another Anime…** (the target must be linked to AniList) or **Show On Its Own**. **Put Back Where AniList Has It** undoes either. This only changes how the library is listed; duplicate entries for the same season still need a merge.
Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
The same show can end up on several cards when release names disagree. To fix that: The same show can end up on several cards when release names disagree. To fix that:
- Merge: click **Select**, tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry. - Merge: click **Select** (the grid then lists every entry on its own), tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction. - Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction.
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**. - Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
+4 -5
View File
@@ -12,7 +12,7 @@ Getting started takes three steps:
## 1. Install requirements ## 1. Install requirements
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. If you skip it, first-run setup can download a copy for SubMiner. Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot.
| Dependency | Needed for | Platforms | | Dependency | Needed for | Platforms |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ | | ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
@@ -124,7 +124,7 @@ mpv --version
ffmpeg -version ffmpeg -version
``` ```
ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. Otherwise, use the FFmpeg download in first-run setup. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`). ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`).
<details> <details>
<summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary> <summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary>
@@ -262,9 +262,8 @@ Setup walks you through:
1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows). 1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows).
2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser. 2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser.
3. **FFmpeg** (optional). If `ffmpeg` and `ffprobe` are on your `PATH` and run, there is nothing to do. Otherwise **Download FFmpeg** saves a static build to `tools/ffmpeg/` next to your config file. SubMiner and the `subminer` command use it only when FFmpeg is missing from `PATH`, so a system install always takes priority. 3. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`.
4. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`. 4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
5. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
**Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`. **Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`.
+1 -1
View File
@@ -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.
+2
View File
@@ -64,8 +64,10 @@ 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`
- 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.
-7
View File
@@ -1,11 +1,6 @@
import path from 'node:path'; import path from 'node:path';
import packageJson from '../package.json'; import packageJson from '../package.json';
import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js'; import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js';
import { getDefaultConfigDir } from '../src/shared/setup-state.js';
import {
appendManagedFfmpegToPath,
getManagedFfmpegDir,
} from '../src/core/services/managed-ffmpeg.js';
import { import {
loadLauncherJellyfinConfig, loadLauncherJellyfinConfig,
loadLauncherLoggingConfig, loadLauncherLoggingConfig,
@@ -70,8 +65,6 @@ function ensureAppPath(context: LauncherCommandContext): string {
async function main(): Promise<void> { async function main(): Promise<void> {
const scriptPath = process.argv[1] || 'subminer'; const scriptPath = process.argv[1] || 'subminer';
const scriptName = path.basename(scriptPath); const scriptName = path.basename(scriptPath);
// Same PATH rule as the app: dependency checks and spawned tools see a setup-page FFmpeg.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(getDefaultConfigDir()));
const launcherConfig = loadLauncherYoutubeSubgenConfig(); const launcherConfig = loadLauncherYoutubeSubgenConfig();
const launcherMpvConfig = loadLauncherMpvConfig(); const launcherMpvConfig = loadLauncherMpvConfig();
const launcherLoggingConfig = loadLauncherLoggingConfig(); const launcherLoggingConfig = loadLauncherLoggingConfig();
+3 -1
View File
@@ -25,7 +25,9 @@ export const IMMERSION_DB_FIXTURE_DDL = `
tmdb_type TEXT, tmdb_type TEXT,
metadata_json TEXT, metadata_json TEXT,
CREATED_DATE TEXT, CREATED_DATE TEXT,
LAST_UPDATE_DATE TEXT LAST_UPDATE_DATE TEXT,
group_override INTEGER,
group_override_updated_at TEXT
); );
CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key); CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key);
CREATE TABLE imm_videos( CREATE TABLE imm_videos(
@@ -338,6 +338,7 @@ function createMockTracker(
hasAnime: async (animeId: number) => animeId === 1, hasAnime: async (animeId: number) => animeId === 1,
getAnimeEpisodes: async () => ANIME_EPISODES, getAnimeEpisodes: async () => ANIME_EPISODES,
getAnimeAnilistEntries: async () => [], getAnimeAnilistEntries: async () => [],
getAnimeGroupPlacement: async () => null,
getAnimeWords: async () => ANIME_WORDS, getAnimeWords: async () => ANIME_WORDS,
getAnimeDailyRollups: async () => DAILY_ROLLUPS, getAnimeDailyRollups: async () => DAILY_ROLLUPS,
getEpisodesPerDay: async () => EPISODES_PER_DAY, getEpisodesPerDay: async () => EPISODES_PER_DAY,
@@ -712,7 +713,7 @@ const MALFORMED_IDS = [
/** Every route that takes a positive resource id; `:id` is replaced per request. */ /** Every route that takes a positive resource id; `:id` is replaced per request. */
const ID_ROUTES: Array<{ const ID_ROUTES: Array<{
method: 'GET' | 'DELETE' | 'PATCH' | 'POST'; method: 'GET' | 'DELETE' | 'PATCH' | 'POST' | 'PUT';
path: string; path: string;
body?: unknown; body?: unknown;
}> = [ }> = [
@@ -739,6 +740,7 @@ const ID_ROUTES: Array<{
{ method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } }, { method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } },
{ method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } }, { method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } },
{ method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } }, { method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } },
{ method: 'PUT', path: '/api/stats/anime/:id/group', body: { mode: 'standalone' } },
{ method: 'POST', path: '/api/stats/anki/browse?noteId=:id' }, { method: 'POST', path: '/api/stats/anki/browse?noteId=:id' },
]; ];
@@ -2429,6 +2431,50 @@ describe('stats server API routes', () => {
assert.equal(mergeCalls, 0); assert.equal(mergeCalls, 0);
}); });
it('PUT /api/stats/anime/:animeId/group validates the body and maps refusals', async () => {
const calls: unknown[] = [];
const app = createStatsApp(
createMockTracker({
setAnimeGroupOverride: async (animeId, target) => {
calls.push([animeId, target]);
if (target.mode === 'join' && target.targetAnimeId === 9) {
return { ok: false, reason: 'target-not-grouped' };
}
if (animeId === 404) return { ok: false, reason: 'not-found' };
return { ok: true };
},
}),
);
const put = (path: string, body: unknown) =>
app.request(path, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(body) });
for (const body of [
{},
{ mode: 'join' },
{ mode: 'join', targetAnimeId: 0 },
{ mode: 'join', targetAnimeId: '8' },
{ mode: 'join', targetAnimeId: 3 },
{ mode: 'reset' },
]) {
assert.equal((await put('/api/stats/anime/3/group', body)).status, 400, JSON.stringify(body));
}
assert.deepEqual(calls, []);
assert.equal(
(await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 8 })).status,
200,
);
assert.equal((await put('/api/stats/anime/3/group', { mode: 'anilist' })).status, 200);
assert.equal((await put('/api/stats/anime/404/group', { mode: 'standalone' })).status, 404);
const refused = await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 9 });
assert.equal(refused.status, 409);
assert.match((await refused.json()).error, /no AniList entry/);
assert.deepEqual(calls.slice(0, 2), [
[3, { mode: 'join', targetAnimeId: 8 }],
[3, { mode: 'anilist' }],
]);
});
it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => { it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => {
let moved: { videoId: number; animeId: number } | null = null; let moved: { videoId: number; animeId: number } | null = null;
const app = createStatsApp( const app = createStatsApp(
@@ -0,0 +1,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;
}
+1 -42
View File
@@ -1,4 +1,5 @@
import type { AnilistRateLimiter } from './rate-limiter'; import type { AnilistRateLimiter } from './rate-limiter';
import { AnilistRateLimitedError, executeAnilistQuery } from './anilist-graphql';
import type { DatabaseSync } from '../immersion-tracker/sqlite'; import type { DatabaseSync } from '../immersion-tracker/sqlite';
import { import {
getAnimeCoverArt, getAnimeCoverArt,
@@ -20,7 +21,6 @@ import { getVideoTmdbLink, linkAnimeToTmdbTitle } from '../immersion-tracker/liv
import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver'; import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver';
import type { TmdbTitleDetails } from '../tmdb/tmdb-client'; import type { TmdbTitleDetails } from '../tmdb/tmdb-client';
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
const NO_MATCH_RETRY_MS = 5 * 60 * 1000; const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
export interface CoverArtFetcher { export interface CoverArtFetcher {
@@ -76,47 +76,6 @@ export function stripFilenameTags(raw: string): string {
return title.trim().replace(/\s{2,}/g, ' '); return title.trim().replace(/\s{2,}/g, ' ');
} }
class AnilistRateLimitedError extends Error {
constructor() {
super('Anilist rate limit reached');
this.name = 'AnilistRateLimitedError';
}
}
async function executeAnilistQuery<T>(
rateLimiter: AnilistRateLimiter,
query: string,
variables: Record<string, unknown>,
): Promise<T> {
await rateLimiter.acquire();
const res = await fetch(ANILIST_GRAPHQL_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query, variables }),
});
rateLimiter.recordResponse(res.headers);
if (res.status === 429) {
throw new AnilistRateLimitedError();
}
if (!res.ok) {
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
}
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
if (firstError?.message) {
throw new Error(firstError.message);
}
if (!json.data) {
throw new Error('Anilist response missing data');
}
return json.data;
}
async function downloadImage(url: string): Promise<Buffer | null> { async function downloadImage(url: string): Promise<Buffer | null> {
try { try {
const res = await fetch(url); const res = await fetch(url);
@@ -0,0 +1,261 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildFranchiseGraph,
walkFranchiseRelations,
type AnilistMediaNode,
type FranchiseWalkOptions,
} from './franchise-graph';
function entry(
anilistId: number,
format: string | null,
startDate: number | null,
relations: Array<[string, number]> = [],
): AnilistMediaNode {
return {
anilistId,
format,
titleRomaji: `romaji ${anilistId}`,
titleEnglish: null,
titleNative: null,
startDate,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs: 0,
};
}
// Overlord: two recap films sit between seasons one and two; Isekai Quartet only shares characters.
const overlord = [
entry(20832, 'TV', 20150707, [
['SEQUEL', 98437],
['SUMMARY', 98873],
['CHARACTER', 104454],
]),
entry(98873, 'MOVIE', 20170225, [
['PARENT', 20832],
['SEQUEL', 98874],
]),
entry(98874, 'MOVIE', 20170311, [
['PREQUEL', 98873],
['SEQUEL', 98437],
]),
entry(98437, 'TV', 20180109, [
['PREQUEL', 20832],
['PREQUEL', 98874],
]),
entry(104454, 'TV_SHORT', 20190410, [['CHARACTER', 20832]]),
];
test('seasons, films and recaps share a root named after the first TV series', () => {
const graph = buildFranchiseGraph(overlord);
for (const id of [20832, 98873, 98874, 98437]) assert.equal(graph.rootOf(id), 20832);
assert.equal(graph.rootOf(104454), 104454);
assert.equal(graph.rootOf(1), undefined);
});
test('excluded relation types keep franchises apart even when the other end says PARENT', () => {
const graph = buildFranchiseGraph([
entry(1, 'TV', 20060101, [
['SPIN_OFF', 2],
['ALTERNATIVE', 3],
['ADAPTATION', 4],
['OTHER', 5],
]),
// A spin-off pointing back at its original as PARENT.
entry(2, 'TV', 20130101, [['PARENT', 1]]),
entry(3, 'TV', 20140101, [['ALTERNATIVE', 1]]),
]);
assert.deepEqual(
[1, 2, 3, 4, 5].map((id) => graph.rootOf(id)),
[1, 2, 3, undefined, undefined],
);
});
test('root falls back to episodic formats, then earliest entry, then lowest id', () => {
const ona = buildFranchiseGraph([
entry(10, 'MOVIE', 20000101, [['SEQUEL', 11]]),
entry(11, 'ONA', 20050101, [['PREQUEL', 10]]),
]);
assert.equal(ona.rootOf(10), 11);
const films = buildFranchiseGraph([
entry(20, 'MOVIE', 20100101, [['PREQUEL', 21]]),
entry(21, 'MOVIE', 20090101, [['SEQUEL', 20]]),
entry(22, 'OVA', null, [['PARENT', 20]]),
]);
assert.equal(films.rootOf(22), 21);
});
test('owned films join through an unowned, uncached TV entry they both point at', () => {
const graph = buildFranchiseGraph([
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
entry(1526, 'MOVIE', 20050716, [['PARENT', 527]]),
]);
assert.equal(graph.rootOf(528), graph.rootOf(1526));
});
test('relation cycles terminate and form one franchise', () => {
const graph = buildFranchiseGraph([
entry(1, 'TV', 20000101, [['SEQUEL', 2]]),
entry(2, 'TV', 20010101, [['SEQUEL', 3]]),
entry(3, 'TV', 20020101, [['SEQUEL', 1]]),
]);
assert.deepEqual(
[1, 2, 3].map((id) => graph.rootOf(id)),
[1, 1, 1],
);
});
function walkHarness(all: AnilistMediaNode[], overrides: Partial<FranchiseWalkOptions> = {}) {
const asked: number[][] = [];
const known = new Map<number, AnilistMediaNode>();
const options: FranchiseWalkOptions = {
seeds: [],
known,
isFresh: () => true,
fetchNodes: async (ids) => {
asked.push([...ids].sort((a, b) => a - b));
return all.filter((node) => ids.includes(node.anilistId));
},
onBatch: () => {},
now: () => 5,
maxDepth: 6,
maxFetch: 500,
...overrides,
};
return { asked, known, options };
}
test('walk follows franchise links through entries the user does not own', async () => {
const pokemon = [
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
entry(527, 'TV', 19970401, [
['SIDE_STORY', 528],
['SEQUEL', 1564],
]),
entry(1564, 'TV', 20021121, [
['PREQUEL', 527],
['SIDE_STORY', 1526],
['OTHER', 9],
]),
entry(1526, 'MOVIE', 20050716, [['PARENT', 1564]]),
entry(9, 'TV', 20000101),
];
const { asked, known, options } = walkHarness(pokemon, { seeds: [528, 1526, 404] });
await walkFranchiseRelations(options);
assert.deepEqual(asked, [
[404, 528, 1526],
[527, 1564],
]);
const graph = buildFranchiseGraph(known.values());
assert.equal(graph.rootOf(528), 527);
assert.equal(graph.rootOf(1526), 527);
// Missing ids are remembered so they are not asked about again; OTHER links are not followed.
assert.equal(known.get(404)?.format, null);
assert.equal(known.has(9), false);
});
test('walk does not follow the links of an entry that vetoes how it was reached', async () => {
const { asked, options } = walkHarness(
[
entry(2, 'TV', 20130101, [['PARENT', 1]]),
entry(1, 'TV', 20060101, [
['SPIN_OFF', 2],
['SEQUEL', 3],
]),
entry(3, 'TV', 20070101),
],
{ seeds: [2] },
);
await walkFranchiseRelations(options);
assert.deepEqual(asked, [[2], [1]]);
});
test('walk follows an entry reached through any link it accepts, whatever the seed order', async () => {
const nodes = [
entry(1, 'TV', 20100101, [['SEQUEL', 3]]),
entry(2, 'TV', 20110101, [['SEQUEL', 3]]),
// Rejects seed 1 but accepts seed 2, so its own links are still followed.
entry(3, 'TV', 20120101, [
['SPIN_OFF', 1],
['PREQUEL', 2],
['PARENT', 4],
]),
entry(4, 'TV', 20000101),
];
for (const seeds of [
[1, 2],
[2, 1],
]) {
const { asked, options } = walkHarness(nodes, { seeds });
await walkFranchiseRelations(options);
assert.deepEqual(asked, [[1, 2], [3], [4]]);
}
});
test('a cancelled walk starts no further request and drops the in-flight result', async () => {
const seeds = Array.from({ length: 51 }, (_, index) => index + 1);
let cancelled = false;
const batches: number[] = [];
const { asked, known, options } = walkHarness(
seeds.map((id) => entry(id, 'TV', 20200101)),
{
seeds,
isFresh: () => false,
onBatch: (nodes) => batches.push(nodes.length),
isCancelled: () => cancelled,
},
);
const fetchNodes = options.fetchNodes;
options.fetchNodes = async (ids) => {
cancelled = true;
return fetchNodes(ids);
};
const result = await walkFranchiseRelations(options);
assert.equal(asked.length, 1);
assert.deepEqual(batches, []);
assert.equal(known.size, 0);
assert.equal(result.truncated, true);
});
test('walk respects the depth and fetch bounds', async () => {
const chain = Array.from({ length: 10 }, (_, i) =>
entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []),
);
const deep = walkHarness(chain, { seeds: [1], maxDepth: 3 });
await walkFranchiseRelations(deep.options);
assert.deepEqual([...deep.known.keys()], [1, 2, 3, 4]);
const budget = walkHarness(chain, { seeds: [1], maxFetch: 2 });
const result = await walkFranchiseRelations(budget.options);
assert.deepEqual(result, { fetched: 2, truncated: true });
assert.deepEqual([...budget.known.keys()], [1, 2]);
});
test('walk follows fresh cached entries without asking and keeps old data on a failed fetch', async () => {
const cached = entry(1, 'TV', 20000101, [['SEQUEL', 2]]);
const stale = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
const { known, options } = walkHarness([], {
seeds: [1],
isFresh: (node) => node.fetchedAtMs >= 0,
fetchNodes: async () => {
throw new Error('AniList unavailable');
},
});
known.set(1, cached);
known.set(2, stale);
await assert.rejects(walkFranchiseRelations(options), /AniList unavailable/);
assert.deepEqual(known.get(2), stale);
});
test('an entry AniList stops returning keeps its cached links', async () => {
const previous = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
const { known, options } = walkHarness([], {
seeds: [2],
isFresh: (node) => node.fetchedAtMs >= 0,
});
known.set(2, previous);
await walkFranchiseRelations(options);
assert.deepEqual(known.get(2), { ...previous, fetchedAtMs: 5 });
});
@@ -0,0 +1,250 @@
/**
* Franchise grouping over AniList's relation graph. AniList keeps every
* season, movie and OVA as its own entry and says how entries relate; the
* stats library lists a franchise once by following those links, including
* through entries the user does not own (two movies meet at a TV series that
* is not in the library). Nothing here touches the database or the network.
*/
/**
* Relation types that make two entries parts of one franchise. SPIN_OFF,
* ALTERNATIVE, CHARACTER, OTHER, ADAPTATION and SOURCE are left out on purpose:
* following them collapses Gundam or Fate into a single card.
*/
export const FRANCHISE_RELATION_TYPES: ReadonlySet<string> = new Set([
'PREQUEL',
'SEQUEL',
'PARENT',
'SIDE_STORY',
'SUMMARY',
'COMPILATION',
'CONTAINS',
]);
export interface AnilistRelationEdge {
relationType: string;
targetId: number;
}
/** One cached AniList entry and its links to other anime entries. */
export interface AnilistMediaNode {
anilistId: number;
/** TV, MOVIE, OVA...; null when AniList did not return the entry. */
format: string | null;
titleRomaji: string | null;
titleEnglish: string | null;
titleNative: string | null;
/** First air date as yyyymmdd (month/day 0 when unknown); null when AniList has no year. */
startDate: number | null;
episodes: number | null;
relations: AnilistRelationEdge[];
fetchedAtMs: number;
}
export interface FranchiseGraph {
node(anilistId: number): AnilistMediaNode | undefined;
/** AniList id the franchise containing `anilistId` is named after; undefined when unknown. */
rootOf(anilistId: number): number | undefined;
}
export function anilistNodeTitle(node: AnilistMediaNode): string | null {
return node.titleEnglish ?? node.titleRomaji ?? node.titleNative;
}
/**
* True when `node` names `targetId` only through relations that do not join a
* franchise. AniList records most links from both ends; a spin-off can point
* back at its original as PARENT, so the original's SPIN_OFF edge has to veto
* the join or excluding SPIN_OFF would not keep the two apart.
*/
function vetoes(node: AnilistMediaNode, targetId: number): boolean {
const edges = node.relations.filter((edge) => edge.targetId === targetId);
return edges.length > 0 && !edges.some((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType));
}
function franchiseTargets(node: AnilistMediaNode): number[] {
return node.relations
.filter((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType))
.map((edge) => edge.targetId);
}
// TV first, then other episodic formats, then films/OVAs/specials, then entries with no data.
function formatRank(format: string | null): number {
if (format === 'TV') return 0;
if (format === 'TV_SHORT' || format === 'ONA') return 1;
return format === null ? 3 : 2;
}
export function buildFranchiseGraph(nodes: Iterable<AnilistMediaNode>): FranchiseGraph {
const byId = new Map<number, AnilistMediaNode>();
for (const node of nodes) byId.set(node.anilistId, node);
const parent = new Map<number, number>();
const find = (id: number): number => {
let top = parent.get(id) ?? id;
if (!parent.has(id)) parent.set(id, id);
while (parent.get(top) !== top) top = parent.get(top)!;
// Path compression keeps long sequel chains cheap.
let at = id;
while (at !== top) {
const next = parent.get(at)!;
parent.set(at, top);
at = next;
}
return top;
};
for (const node of byId.values()) {
find(node.anilistId);
for (const targetId of franchiseTargets(node)) {
const target = byId.get(targetId);
if (target && vetoes(target, node.anilistId)) continue;
const a = find(node.anilistId);
const b = find(targetId);
if (a !== b) parent.set(b, a);
}
}
const members = new Map<number, number[]>();
for (const id of parent.keys()) {
const top = find(id);
const list = members.get(top);
if (list) list.push(id);
else members.set(top, [id]);
}
// A franchise is named after its first TV series, else its first episodic
// entry, else its earliest entry; ties go to the lower id.
const compareRoots = (a: number, b: number): number => {
const left = byId.get(a);
const right = byId.get(b);
return (
formatRank(left?.format ?? null) - formatRank(right?.format ?? null) ||
(left?.startDate ?? Number.MAX_SAFE_INTEGER) -
(right?.startDate ?? Number.MAX_SAFE_INTEGER) ||
a - b
);
};
const roots = new Map<number, number>();
for (const ids of members.values()) {
const root = [...ids].sort(compareRoots)[0]!;
for (const id of ids) roots.set(id, root);
}
return {
node: (anilistId) => byId.get(anilistId),
rootOf: (anilistId) => roots.get(anilistId),
};
}
const FETCH_CHUNK_SIZE = 50;
export interface FranchiseWalkOptions {
/** AniList ids the walk starts from (the library's own entries). */
seeds: readonly number[];
/** Cached entries; updated in place with everything fetched. */
known: Map<number, AnilistMediaNode>;
isFresh: (node: AnilistMediaNode) => boolean;
/** Entries AniList returned for `ids` (at most 50). Throws on transport or API failure. */
fetchNodes: (ids: number[]) => Promise<AnilistMediaNode[]>;
/** Called once per fetched batch so progress survives a later failure. */
onBatch: (nodes: AnilistMediaNode[]) => void;
now: () => number;
/** Hops from a seed; entries at this depth are fetched but not followed. */
maxDepth: number;
/** Most entries fetched in one walk; the rest wait for the next walk. */
maxFetch: number;
/** When true, the walk starts no further request and drops an in-flight result. */
isCancelled?: () => boolean;
}
export interface FranchiseWalkResult {
fetched: number;
/** True when the fetch budget ran out before every stale entry was refreshed. */
truncated: boolean;
}
/**
* Breadth-first walk from the seeds along franchise relations, fetching
* entries that are missing or stale. Fresh cached entries are followed without
* a request. An entry AniList does not return keeps its previous data (or gets
* an empty placeholder) so it is not asked about again until it goes stale; a
* thrown fetch error stops the walk and leaves the cache as it was.
*/
export async function walkFranchiseRelations(
options: FranchiseWalkOptions,
): Promise<FranchiseWalkResult> {
const { known } = options;
const visited = new Set<number>();
// `from` lists every entry the walk reached this one through at this depth
// (empty for a seed), so the order seeds are given in cannot change the result.
let frontier: Array<{ id: number; from: number[] }> = [...new Set(options.seeds)].map((id) => ({
id,
from: [],
}));
let fetched = 0;
let truncated = false;
for (let depth = 0; frontier.length > 0; depth += 1) {
for (const step of frontier) visited.add(step.id);
const stale = frontier
.map((step) => step.id)
.filter((id) => {
const node = known.get(id);
return !node || !options.isFresh(node);
});
const allowed = stale.slice(0, Math.max(0, options.maxFetch - fetched));
if (allowed.length < stale.length) truncated = true;
for (let start = 0; start < allowed.length; start += FETCH_CHUNK_SIZE) {
if (options.isCancelled?.()) return { fetched, truncated: true };
const chunk = allowed.slice(start, start + FETCH_CHUNK_SIZE);
const fetchedNodes = await options.fetchNodes(chunk);
if (options.isCancelled?.()) return { fetched, truncated: true };
const found = new Map(fetchedNodes.map((node) => [node.anilistId, node] as const));
const fetchedAtMs = options.now();
const batch = chunk.map((id): AnilistMediaNode => {
const node = found.get(id);
if (node) return node;
const previous = known.get(id);
if (previous) return { ...previous, fetchedAtMs };
return {
anilistId: id,
format: null,
titleRomaji: null,
titleEnglish: null,
titleNative: null,
startDate: null,
episodes: null,
relations: [],
fetchedAtMs,
};
});
for (const node of batch) known.set(node.anilistId, node);
options.onBatch(batch);
fetched += chunk.length;
}
if (depth >= options.maxDepth) break;
const next = new Map<number, number[]>();
for (const step of frontier) {
const node = known.get(step.id);
if (!node) continue;
// Reached only through links the entry itself rejects (a spin-off's
// original): it is not part of the franchise, so its own links are not
// followed. One accepted incoming link is enough.
if (step.from.length > 0 && step.from.every((fromId) => vetoes(node, fromId))) continue;
for (const targetId of franchiseTargets(node)) {
if (visited.has(targetId)) continue;
const from = next.get(targetId);
if (from) from.push(node.anilistId);
else next.set(targetId, [node.anilistId]);
}
}
frontier = [...next].map(([id, from]) => ({ id, from }));
}
return { fetched, truncated };
}
@@ -0,0 +1,83 @@
import { executeAnilistQuery } from './anilist-graphql';
import type { AnilistMediaNode, AnilistRelationEdge } from './franchise-graph';
import type { AnilistRateLimiter } from './rate-limiter';
/** Loads AniList entries with their relations, for the library's franchise grouping. */
export interface AnilistRelationFetcher {
/** Entries AniList returned for `ids` (at most 50); ids it does not know are absent. */
fetchMedia(ids: number[]): Promise<AnilistMediaNode[]>;
}
const RELATIONS_QUERY = `
query ($ids: [Int], $perPage: Int) {
Page(page: 1, perPage: $perPage) {
media(id_in: $ids, type: ANIME) {
id
format
episodes
title { romaji english native }
startDate { year month day }
relations { edges { relationType(version: 2) node { id type } } }
}
}
}`;
interface RelationsMedia {
id: number;
format: string | null;
episodes: number | null;
title: { romaji: string | null; english: string | null; native: string | null } | null;
startDate: { year: number | null; month: number | null; day: number | null } | null;
relations: {
edges: Array<{
relationType: string | null;
node: { id: number; type: string | null } | null;
} | null> | null;
} | null;
}
interface RelationsResponse {
Page: { media: Array<RelationsMedia | null> | null } | null;
}
export function toAnilistMediaNode(media: RelationsMedia, fetchedAtMs: number): AnilistMediaNode {
const start = media.startDate;
const relations: AnilistRelationEdge[] = [];
for (const edge of media.relations?.edges ?? []) {
// Manga and novels are not part of a watch library.
if (!edge?.relationType || edge.node?.type !== 'ANIME') continue;
relations.push({ relationType: edge.relationType, targetId: edge.node.id });
}
return {
anilistId: media.id,
format: media.format,
titleRomaji: media.title?.romaji ?? null,
titleEnglish: media.title?.english ?? null,
titleNative: media.title?.native ?? null,
startDate: start?.year
? start.year * 10_000 + (start.month ?? 0) * 100 + (start.day ?? 0)
: null,
episodes: media.episodes,
relations,
fetchedAtMs,
};
}
export function createAnilistRelationFetcher(
rateLimiter: AnilistRateLimiter,
now: () => number = Date.now,
): AnilistRelationFetcher {
return {
async fetchMedia(ids) {
if (ids.length === 0) return [];
const data = await executeAnilistQuery<RelationsResponse>(rateLimiter, RELATIONS_QUERY, {
ids,
perPage: ids.length,
});
const fetchedAtMs = now();
return (data.Page?.media ?? [])
.filter((media): media is RelationsMedia => media !== null)
.map((media) => toAnilistMediaNode(media, fetchedAtMs));
},
};
}
@@ -4,6 +4,18 @@ import { createLogger } from '../../logger';
import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity'; import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity';
import { MediaGenerator } from '../../media-generator'; import { MediaGenerator } from '../../media-generator';
import type { CoverArtFetcher } from './anilist/cover-art-fetcher'; import type { CoverArtFetcher } from './anilist/cover-art-fetcher';
import type { AnilistRelationFetcher } from './anilist/franchise-relation-fetcher';
import {
createFranchiseRelationRefresher,
type FranchiseRelationRefresher,
} from './immersion-tracker/franchise-relation-refresher';
import {
getAnimeGroupPlacement,
getAnimeLibraryGroups,
setAnimeGroupOverride,
type AnimeGroupOverrideResult,
type AnimeGroupOverrideTarget,
} from './immersion-tracker/query-library-groups';
import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata'; import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata';
import { import {
pruneRawRetention, pruneRawRetention,
@@ -61,6 +73,7 @@ import type {
StatsTrendGroupBy, StatsTrendGroupBy,
StatsTrendRange, StatsTrendRange,
} from '../../types/stats-http-contract'; } from '../../types/stats-http-contract';
import type { AnimeGroupPlacement, AnimeLibraryGroup } from '../../types/stats-wire';
import { import {
getKanjiAnimeAppearances, getKanjiAnimeAppearances,
getKanjiDetail, getKanjiDetail,
@@ -452,6 +465,7 @@ export class ImmersionTrackerService {
private readonly mediaGenerator = new MediaGenerator(); private readonly mediaGenerator = new MediaGenerator();
private readonly preparedStatements: TrackerPreparedStatements; private readonly preparedStatements: TrackerPreparedStatements;
private coverArtFetcher: CoverArtFetcher | null = null; private coverArtFetcher: CoverArtFetcher | null = null;
private franchiseRelations: FranchiseRelationRefresher | null = null;
private readonly pendingCoverFetches = new Map<number, Promise<boolean>>(); private readonly pendingCoverFetches = new Map<number, Promise<boolean>>();
private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>(); private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>();
private readonly recordedSubtitleKeys = new Set<string>(); private readonly recordedSubtitleKeys = new Set<string>();
@@ -621,6 +635,7 @@ export class ImmersionTrackerService {
} }
this.finalizeActiveSession(); this.finalizeActiveSession();
this.isDestroyed = true; this.isDestroyed = true;
this.franchiseRelations?.stop();
this.deleteMaintenanceScheduler.destroy(); this.deleteMaintenanceScheduler.destroy();
this.destroyDeleteMaintenanceRunner(); this.destroyDeleteMaintenanceRunner();
this.destroyVocabularySummaryRunner(); this.destroyVocabularySummaryRunner();
@@ -833,6 +848,27 @@ export class ImmersionTrackerService {
return getAnimeLibrary(this.db); return getAnimeLibrary(this.db);
} }
/** The library as franchise cards; also schedules a background AniList relation refresh. */
async getAnimeLibraryGroups(): Promise<AnimeLibraryGroup[]> {
this.relinkYoutubeAnimeLibrary();
const groups = getAnimeLibraryGroups(this.db);
this.franchiseRelations?.requestRefresh();
return groups;
}
async getAnimeGroupPlacement(animeId: number): Promise<AnimeGroupPlacement | null> {
return getAnimeGroupPlacement(this.db, animeId);
}
async setAnimeGroupOverride(
animeId: number,
target: AnimeGroupOverrideTarget,
): Promise<AnimeGroupOverrideResult> {
const result = setAnimeGroupOverride(this.db, animeId, target);
if (result.ok) this.franchiseRelations?.requestRefresh({ force: true });
return result;
}
async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> { async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> {
return getAnimeMergeRecommendations(this.db); return getAnimeMergeRecommendations(this.db);
} }
@@ -1122,6 +1158,7 @@ export class ImmersionTrackerService {
this.db.exec('ROLLBACK'); this.db.exec('ROLLBACK');
throw error; throw error;
} }
this.franchiseRelations?.requestRefresh({ force: true });
} }
/** /**
@@ -1248,6 +1285,19 @@ export class ImmersionTrackerService {
this.coverArtFetcher = fetcher; this.coverArtFetcher = fetcher;
} }
/** Enables franchise grouping refreshes; null disables them (tests, offline runs). */
setAnilistRelationFetcher(fetcher: AnilistRelationFetcher | null): void {
this.franchiseRelations?.stop();
this.franchiseRelations = fetcher
? createFranchiseRelationRefresher({
db: this.db,
fetcher,
logger: createLogger('immersion-tracker:franchise-relations'),
})
: null;
this.franchiseRelations?.requestRefresh();
}
async ensureAnimeCoverArt(animeId: number): Promise<boolean> { async ensureAnimeCoverArt(animeId: number): Promise<boolean> {
const existing = await this.getAnimeCoverArt(animeId); const existing = await this.getAnimeCoverArt(animeId);
if (existing?.coverBlob) { if (existing?.coverBlob) {
@@ -1300,6 +1350,8 @@ export class ImmersionTrackerService {
if (!fetched) { if (!fetched) {
return false; return false;
} }
// A fresh AniList link may join this entry to a franchise card.
this.franchiseRelations?.requestRefresh({ force: true });
const cover = await this.getCoverArt(videoId); const cover = await this.getCoverArt(videoId);
return cover?.coverBlob != null; return cover?.coverBlob != null;
})(); })();
@@ -0,0 +1,126 @@
import type { AnilistMediaNode } from '../anilist/franchise-graph';
import type { DatabaseSync } from './sqlite';
import { fromDbTimestamp, toDbTimestamp } from './query-shared';
/**
* Franchise grouping state. `imm_anilist_media` and `imm_anilist_relations`
* cache AniList entries (owned or reached through relations) and every
* anime-to-anime edge, whatever its type, so the grouping rule can change
* without a refetch. The cache is rebuildable from AniList and is not synced.
*
* `imm_anime.group_override` is the user's choice for one library entry:
* NULL follows AniList, 0 keeps the entry on its own, and a positive value is
* an AniList id whose franchise the entry joins. `group_override_updated_at`
* records when it was set (or cleared) so sync can keep the newer choice.
*/
export function ensureAnimeGroupingSchema(db: DatabaseSync): void {
db.exec(`
CREATE TABLE IF NOT EXISTS imm_anilist_media(
anilist_id INTEGER PRIMARY KEY,
format TEXT,
title_romaji TEXT,
title_english TEXT,
title_native TEXT,
start_date INTEGER,
episodes INTEGER,
fetched_at_ms TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS imm_anilist_relations(
anilist_id INTEGER NOT NULL,
relation_type TEXT NOT NULL,
target_anilist_id INTEGER NOT NULL,
PRIMARY KEY(anilist_id, relation_type, target_anilist_id),
FOREIGN KEY(anilist_id) REFERENCES imm_anilist_media(anilist_id) ON DELETE CASCADE
);
`);
const columns = new Set(
(db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>).map(
(column) => column.name,
),
);
if (!columns.has('group_override')) {
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override INTEGER');
}
if (!columns.has('group_override_updated_at')) {
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override_updated_at TEXT');
}
}
export function readAnilistRelationCache(db: DatabaseSync): Map<number, AnilistMediaNode> {
const nodes = new Map<number, AnilistMediaNode>();
const mediaRows = db
.prepare(
`SELECT anilist_id AS anilistId, format, title_romaji AS titleRomaji,
title_english AS titleEnglish, title_native AS titleNative,
start_date AS startDate, episodes, fetched_at_ms AS fetchedAtMs
FROM imm_anilist_media`,
)
.all() as Array<Omit<AnilistMediaNode, 'relations' | 'fetchedAtMs'> & { fetchedAtMs: string }>;
for (const row of mediaRows) {
nodes.set(row.anilistId, {
...row,
relations: [],
fetchedAtMs: fromDbTimestamp(row.fetchedAtMs) ?? 0,
});
}
const edgeRows = db
.prepare(
`SELECT anilist_id AS anilistId, relation_type AS relationType, target_anilist_id AS targetId
FROM imm_anilist_relations
ORDER BY anilist_id, relation_type, target_anilist_id`,
)
.all() as Array<{ anilistId: number; relationType: string; targetId: number }>;
for (const edge of edgeRows) {
nodes.get(edge.anilistId)?.relations.push({
relationType: edge.relationType,
targetId: edge.targetId,
});
}
return nodes;
}
/** Replaces each node's cached row and edges in one transaction. */
export function writeAnilistRelationNodes(db: DatabaseSync, nodes: AnilistMediaNode[]): void {
if (nodes.length === 0) return;
const upsertMedia = db.prepare(`
INSERT INTO imm_anilist_media(anilist_id, format, title_romaji, title_english, title_native,
start_date, episodes, fetched_at_ms)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(anilist_id) DO UPDATE SET
format = excluded.format,
title_romaji = excluded.title_romaji,
title_english = excluded.title_english,
title_native = excluded.title_native,
start_date = excluded.start_date,
episodes = excluded.episodes,
fetched_at_ms = excluded.fetched_at_ms
`);
const deleteEdges = db.prepare('DELETE FROM imm_anilist_relations WHERE anilist_id = ?');
const insertEdge = db.prepare(`
INSERT OR IGNORE INTO imm_anilist_relations(anilist_id, relation_type, target_anilist_id)
VALUES (?, ?, ?)
`);
db.exec('BEGIN IMMEDIATE');
try {
for (const node of nodes) {
upsertMedia.run(
node.anilistId,
node.format,
node.titleRomaji,
node.titleEnglish,
node.titleNative,
node.startDate,
node.episodes,
toDbTimestamp(node.fetchedAtMs),
);
deleteEdges.run(node.anilistId);
for (const edge of node.relations) {
insertEdge.run(node.anilistId, edge.relationType, edge.targetId);
}
}
db.exec('COMMIT');
} catch (error) {
db.exec('ROLLBACK');
throw error;
}
}
@@ -0,0 +1,75 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { AnilistMediaNode } from '../anilist/franchise-graph';
import { readAnilistRelationCache } from './anilist-relation-cache';
import {
createFranchiseRelationRefresher,
FRANCHISE_RELATION_STALE_MS,
} from './franchise-relation-refresher';
import { Database } from './sqlite';
import { ensureSchema } from './storage';
const silent = { info: () => {}, warn: () => {} };
function media(anilistId: number, relations: Array<[string, number]>, fetchedAtMs: number) {
return {
anilistId,
format: 'TV',
titleRomaji: null,
titleEnglish: null,
titleNative: null,
startDate: null,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs,
} satisfies AnilistMediaNode;
}
test('refresh walks from linked entries and override targets, then keeps the cache on failure', async () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
db.exec(`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, media_kind)
VALUES ('a', 'A', 1, 'anime'), ('c', 'C', 77, 'youtube');
INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override)
VALUES ('b', 'B', 50)`);
let clock = 1_000;
let failing = false;
const asked: number[][] = [];
const refresher = createFranchiseRelationRefresher({
db,
logger: silent,
now: () => clock,
fetcher: {
fetchMedia: async (ids) => {
if (failing) throw new Error('AniList down');
asked.push([...ids].sort((a, b) => a - b));
return ids.map((id) => media(id, id === 1 ? [['SEQUEL', 2]] : [], clock));
},
},
});
refresher.requestRefresh();
await refresher.whenIdle();
assert.deepEqual(asked, [[1, 50], [2]]);
assert.deepEqual(
[...readAnilistRelationCache(db).keys()].sort((a, b) => a - b),
[1, 2, 50],
);
// Throttled until forced; everything is fresh, so a forced run asks nothing.
refresher.requestRefresh({ force: true });
await refresher.whenIdle();
assert.equal(asked.length, 2);
clock += FRANCHISE_RELATION_STALE_MS;
failing = true;
refresher.requestRefresh({ force: true });
await refresher.whenIdle();
assert.deepEqual(readAnilistRelationCache(db).get(1)?.relations, [
{ relationType: 'SEQUEL', targetId: 2 },
]);
} finally {
db.close();
}
});
@@ -0,0 +1,121 @@
import { walkFranchiseRelations } from '../anilist/franchise-graph';
import type { AnilistRelationFetcher } from '../anilist/franchise-relation-fetcher';
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
import type { DatabaseSync } from './sqlite';
/** Cached AniList entries are asked about again after a week. */
export const FRANCHISE_RELATION_STALE_MS = 7 * 24 * 60 * 60 * 1000;
/** Hops followed from a library entry; keeps long-running franchises bounded. */
export const FRANCHISE_WALK_MAX_DEPTH = 6;
/** Entries fetched per refresh (five AniList requests); the rest wait for the next refresh. */
export const FRANCHISE_WALK_MAX_FETCH = 250;
/** Unforced refreshes (library polls) run at most this often. */
const MIN_INTERVAL_MS = 10 * 60 * 1000;
interface RefresherLogger {
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
}
export interface FranchiseRelationRefresherDeps {
db: DatabaseSync;
fetcher: AnilistRelationFetcher;
logger: RefresherLogger;
now?: () => number;
}
export interface FranchiseRelationRefresher {
/**
* Starts a background refresh unless one ran recently. `force` skips that
* throttle, for when an entry has just been linked to AniList.
*/
requestRefresh(options?: { force?: boolean }): void;
/** Resolves once no refresh is running; for tests and shutdown. */
whenIdle(): Promise<void>;
/** Stops writing; a running refresh finishes its request and discards the result. */
stop(): void;
}
function readSeeds(db: DatabaseSync): number[] {
return (
db
.prepare(
`SELECT anilist_id AS id FROM imm_anime WHERE media_kind = 'anime' AND anilist_id IS NOT NULL
UNION
SELECT group_override AS id FROM imm_anime WHERE group_override > 0`,
)
.all() as Array<{ id: number }>
).map((row) => row.id);
}
export function createFranchiseRelationRefresher(
deps: FranchiseRelationRefresherDeps,
): FranchiseRelationRefresher {
const now = deps.now ?? Date.now;
let running: Promise<void> | null = null;
let pending = false;
let stopped = false;
let lastStartedAtMs: number | null = null;
const refreshOnce = async (): Promise<void> => {
const known = readAnilistRelationCache(deps.db);
const result = await walkFranchiseRelations({
seeds: readSeeds(deps.db),
known,
isFresh: (node) => now() - node.fetchedAtMs < FRANCHISE_RELATION_STALE_MS,
fetchNodes: (ids) => deps.fetcher.fetchMedia(ids),
onBatch: (nodes) => writeAnilistRelationNodes(deps.db, nodes),
isCancelled: () => stopped,
now,
maxDepth: FRANCHISE_WALK_MAX_DEPTH,
maxFetch: FRANCHISE_WALK_MAX_FETCH,
});
if (result.fetched > 0) {
deps.logger.info(
'franchise-relations: refreshed %d AniList entries%s',
result.fetched,
result.truncated ? ' (more next time)' : '',
);
}
};
const run = (): void => {
lastStartedAtMs = now();
running = (async () => {
try {
do {
pending = false;
await refreshOnce();
} while (pending && !stopped);
} catch (error) {
// Cached rows stay as they were; the next request (after the throttle) retries.
deps.logger.warn(
'franchise-relations: refresh failed: %s',
error instanceof Error ? error.message : String(error),
);
} finally {
running = null;
}
})();
};
return {
requestRefresh(options = {}) {
if (stopped) return;
if (running) {
if (options.force) pending = true;
return;
}
if (!options.force && lastStartedAtMs !== null && now() - lastStartedAtMs < MIN_INTERVAL_MS) {
return;
}
run();
},
async whenIdle() {
while (running) await running;
},
stop() {
stopped = true;
},
};
}
@@ -0,0 +1,226 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildFranchiseGraph, type AnilistMediaNode } from '../anilist/franchise-graph';
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
import {
getAnimeGroupPlacement,
getAnimeLibraryGroups,
groupAnimeLibrary,
setAnimeGroupOverride,
type GroupableLibraryRow,
} from './query-library-groups';
import { Database, type DatabaseSync } from './sqlite';
import { ensureSchema } from './storage';
import { SCHEMA_VERSION } from './types';
function node(
anilistId: number,
format: string,
startDate: number,
relations: Array<[string, number]>,
titleEnglish: string | null = null,
): AnilistMediaNode {
return {
anilistId,
format,
titleRomaji: `romaji ${anilistId}`,
titleEnglish,
titleNative: null,
startDate,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs: 1,
};
}
// Owned: season 2 and a film. The first season (the root) is not in the library.
const overlordNodes = [
node(
20832,
'TV',
20150707,
[
['SEQUEL', 98437],
['SUMMARY', 98873],
],
'Overlord',
),
node(98873, 'MOVIE', 20170225, [['PARENT', 20832]]),
node(98437, 'TV', 20180109, [['PREQUEL', 20832]]),
];
function row(
animeId: number,
anilistId: number | null,
overrides: Partial<GroupableLibraryRow> = {},
): GroupableLibraryRow {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: `Entry ${animeId}`,
anilistId,
tmdbId: null,
tmdbType: null,
totalSessions: 1,
totalActiveMs: 1000 * animeId,
totalCards: animeId,
totalTokensSeen: 10,
episodeCount: 2,
episodesTotal: null,
lastWatchedMs: 100 * animeId,
groupOverride: null,
...overrides,
};
}
test('owned parts join under the unowned root, in release order, with summed totals', () => {
const graph = buildFranchiseGraph(overlordNodes);
const groups = groupAnimeLibrary([row(1, 98437), row(2, 98873), row(3, null)], graph);
assert.equal(groups.length, 2);
const overlord = groups.find((group) => group.groupKey === 20832)!;
assert.equal(overlord.title, 'Overlord');
assert.deepEqual(
overlord.parts.map((part) => [part.animeId, part.format, part.startDate]),
[
[2, 'MOVIE', 20170225],
[1, 'TV', 20180109],
],
);
assert.equal(overlord.coverAnimeId, 2);
assert.deepEqual(
[overlord.totalActiveMs, overlord.totalCards, overlord.episodeCount, overlord.lastWatchedMs],
[3000, 3, 4, 200],
);
});
test('entries without AniList data stay single cards that look like the entry', () => {
const graph = buildFranchiseGraph([]);
const lone = row(7, 555, { canonicalTitle: 'Bocchi the Rock!' });
const [linked, unlinked, channel] = groupAnimeLibrary(
[lone, row(3, null), row(2, null, { mediaKind: 'youtube', groupOverride: 555 })],
graph,
);
assert.deepEqual(
[linked!.groupKey, linked!.title, linked!.coverAnimeId, linked!.parts.length],
[555, 'Bocchi the Rock!', 7, 1],
);
const { groupOverride: _override, ...item } = lone;
assert.deepEqual(linked!.parts[0], { ...item, format: null, startDate: null });
assert.equal(unlinked!.groupKey, -3);
// Overrides never apply to YouTube or live-action entries.
assert.equal(channel!.groupKey, -2);
});
test('overrides move an entry to another franchise or keep it on its own', () => {
const graph = buildFranchiseGraph(overlordNodes);
const groups = groupAnimeLibrary(
[
row(1, 98437),
row(2, 98873, { groupOverride: 0 }),
// Unlinked specials moved in by the user, pointing at any part of the franchise.
row(3, null, { groupOverride: 98437 }),
],
graph,
);
assert.deepEqual(
groups
.map((group) => [group.groupKey, group.parts.map((part) => part.animeId)] as const)
.sort((a, b) => a[0] - b[0]),
[
[-2, [2]],
[20832, [1, 3]],
],
);
});
function seed(db: DatabaseSync, title: string, anilistId: number | null): number {
const animeId = Number(
db
.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id) VALUES (?, ?, ?)`,
)
.run(title.toLowerCase(), title, anilistId).lastInsertRowid,
);
db.prepare(
`INSERT INTO imm_videos(video_key, anime_id, canonical_title, source_type, duration_ms)
VALUES (?, ?, ?, 1, 0)`,
).run(`key:${title}`, animeId, title);
db.prepare(
'INSERT INTO imm_lifetime_anime(anime_id, total_active_ms, total_cards) VALUES (?, 60000, 1)',
).run(animeId);
return animeId;
}
test('library groups and overrides round-trip through the database', () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
const season2 = seed(db, 'Overlord II', 98437);
const film = seed(db, 'The Undead King', 98873);
const specials = seed(db, 'Overlord specials', null);
const other = seed(db, 'Bocchi the Rock!', 130003);
// No cached relations yet: every entry is its own card.
assert.equal(getAnimeLibraryGroups(db).length, 4);
writeAnilistRelationNodes(db, overlordNodes);
assert.deepEqual(readAnilistRelationCache(db).get(20832), overlordNodes[0]);
assert.deepEqual(getAnimeGroupPlacement(db, film), {
groupKey: 20832,
title: 'Overlord',
partCount: 2,
overrideMode: 'anilist',
});
assert.deepEqual(
setAnimeGroupOverride(db, specials, { mode: 'join', targetAnimeId: season2 }),
{
ok: true,
},
);
assert.deepEqual(setAnimeGroupOverride(db, film, { mode: 'standalone' }), { ok: true });
assert.deepEqual(setAnimeGroupOverride(db, other, { mode: 'join', targetAnimeId: film }), {
ok: false,
reason: 'target-not-grouped',
});
assert.deepEqual(setAnimeGroupOverride(db, 999, { mode: 'standalone' }), {
ok: false,
reason: 'not-found',
});
const stored = db
.prepare('SELECT group_override AS value FROM imm_anime WHERE anime_id = ?')
.get(specials) as { value: number };
assert.equal(stored.value, 20832);
assert.deepEqual(getAnimeGroupPlacement(db, specials), {
groupKey: 20832,
title: 'Overlord',
partCount: 2,
overrideMode: 'joined',
});
assert.equal(getAnimeGroupPlacement(db, film)?.overrideMode, 'standalone');
setAnimeGroupOverride(db, film, { mode: 'anilist' });
assert.equal(getAnimeGroupPlacement(db, film)?.partCount, 3);
} finally {
db.close();
}
});
test('schema 27 upgrade adds the relation cache and override columns', () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
db.exec(`DROP TABLE imm_anilist_relations; DROP TABLE imm_anilist_media;
ALTER TABLE imm_anime DROP COLUMN group_override;
ALTER TABLE imm_anime DROP COLUMN group_override_updated_at;`);
db.prepare('UPDATE imm_schema_version SET schema_version = ?').run(SCHEMA_VERSION - 1);
ensureSchema(db);
const columns = (db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>)
.map((column) => column.name)
.filter((name) => name.startsWith('group_override'));
assert.deepEqual(columns, ['group_override', 'group_override_updated_at']);
assert.equal(readAnilistRelationCache(db).size, 0);
} finally {
db.close();
}
});
@@ -0,0 +1,192 @@
import type {
AnimeGroupOverrideMode,
AnimeGroupPlacement,
AnimeLibraryGroup,
AnimeLibraryGroupPart,
} from '../../../types/stats-wire';
import {
anilistNodeTitle,
buildFranchiseGraph,
type FranchiseGraph,
} from '../anilist/franchise-graph';
import { readAnilistRelationCache } from './anilist-relation-cache';
import { toDbTimestamp } from './query-shared';
import { getAnimeLibrary } from './query-library';
import type { DatabaseSync } from './sqlite';
import { nowMs } from './time';
import type { AnimeLibraryRow } from './types';
/** `imm_anime.group_override` value that keeps an entry on its own. */
export const GROUP_OVERRIDE_STANDALONE = 0;
export interface GroupableLibraryRow extends AnimeLibraryRow {
groupOverride: number | null;
}
function overrideMode(row: GroupableLibraryRow): AnimeGroupOverrideMode {
if (row.mediaKind !== 'anime' || row.groupOverride === null || row.groupOverride < 0) {
return 'anilist';
}
return row.groupOverride === GROUP_OVERRIDE_STANDALONE ? 'standalone' : 'joined';
}
/**
* The card an entry belongs to: positive keys are AniList ids (the franchise
* root once its relations are cached, the entry's own id until then), negative
* keys are `-animeId` for entries listed on their own. Overrides only apply to
* anime entries; live-action and YouTube rows always stand alone.
*/
function groupKeyFor(row: GroupableLibraryRow, graph: FranchiseGraph): number {
const mode = overrideMode(row);
if (mode === 'standalone') return -row.animeId;
if (mode === 'joined') return graph.rootOf(row.groupOverride!) ?? row.groupOverride!;
if (row.mediaKind === 'anime' && row.anilistId !== null) {
return graph.rootOf(row.anilistId) ?? row.anilistId;
}
return -row.animeId;
}
function toPart(row: GroupableLibraryRow, graph: FranchiseGraph): AnimeLibraryGroupPart {
const { groupOverride: _groupOverride, ...item } = row;
const node =
row.mediaKind === 'anime' && row.anilistId !== null ? graph.node(row.anilistId) : undefined;
return { ...item, format: node?.format ?? null, startDate: node?.startDate ?? null };
}
// Release order; entries AniList has no date for go last, in library order.
function compareParts(a: AnimeLibraryGroupPart, b: AnimeLibraryGroupPart): number {
return (
(a.startDate ?? Number.MAX_SAFE_INTEGER) - (b.startDate ?? Number.MAX_SAFE_INTEGER) ||
a.animeId - b.animeId
);
}
/**
* Groups library rows into franchise cards. A card with one part keeps that
* entry's own title, so ungrouped entries render exactly as before; a card with
* several parts is named after the franchise root, even when the root itself
* is not in the library.
*/
export function groupAnimeLibrary(
rows: GroupableLibraryRow[],
graph: FranchiseGraph,
): AnimeLibraryGroup[] {
const byKey = new Map<number, GroupableLibraryRow[]>();
for (const row of rows) {
const key = groupKeyFor(row, graph);
const members = byKey.get(key);
if (members) members.push(row);
else byKey.set(key, [row]);
}
const groups: AnimeLibraryGroup[] = [];
for (const [groupKey, members] of byKey) {
const parts = members.map((row) => toPart(row, graph)).sort(compareParts);
const first = parts[0]!;
const rootNode = groupKey > 0 ? graph.node(groupKey) : undefined;
const title =
parts.length === 1
? first.canonicalTitle
: ((rootNode ? anilistNodeTitle(rootNode) : null) ??
parts.find((part) => part.anilistId === groupKey)?.canonicalTitle ??
first.canonicalTitle);
groups.push({
groupKey,
title,
mediaKind: first.mediaKind,
coverAnimeId: first.animeId,
totalSessions: parts.reduce((sum, part) => sum + part.totalSessions, 0),
totalActiveMs: parts.reduce((sum, part) => sum + part.totalActiveMs, 0),
totalCards: parts.reduce((sum, part) => sum + part.totalCards, 0),
totalTokensSeen: parts.reduce((sum, part) => sum + part.totalTokensSeen, 0),
episodeCount: parts.reduce((sum, part) => sum + part.episodeCount, 0),
lastWatchedMs: Math.max(...parts.map((part) => part.lastWatchedMs)),
parts,
});
}
return groups.sort((a, b) => b.totalActiveMs - a.totalActiveMs || a.groupKey - b.groupKey);
}
function readGroupableLibrary(db: DatabaseSync): GroupableLibraryRow[] {
const overrides = new Map(
(
db
.prepare(
'SELECT anime_id AS animeId, group_override AS groupOverride FROM imm_anime WHERE group_override IS NOT NULL',
)
.all() as Array<{ animeId: number; groupOverride: number }>
).map((row) => [row.animeId, row.groupOverride] as const),
);
return getAnimeLibrary(db).map((row) => ({
...row,
groupOverride: overrides.get(row.animeId) ?? null,
}));
}
export function getAnimeLibraryGroups(db: DatabaseSync): AnimeLibraryGroup[] {
return groupAnimeLibrary(
readGroupableLibrary(db),
buildFranchiseGraph(readAnilistRelationCache(db).values()),
);
}
/** The card an entry is listed under, or null when the entry is not in the library list. */
export function getAnimeGroupPlacement(
db: DatabaseSync,
animeId: number,
): AnimeGroupPlacement | null {
const rows = readGroupableLibrary(db);
const row = rows.find((candidate) => candidate.animeId === animeId);
if (!row) return null;
const group = groupAnimeLibrary(
rows,
buildFranchiseGraph(readAnilistRelationCache(db).values()),
).find((candidate) => candidate.parts.some((part) => part.animeId === animeId));
if (!group) return null;
return {
groupKey: group.groupKey,
title: group.title,
partCount: group.parts.length,
overrideMode: overrideMode(row),
};
}
/** Where to put an entry: with another entry's franchise, on its own, or where AniList has it. */
export type AnimeGroupOverrideTarget =
| { mode: 'join'; targetAnimeId: number }
| { mode: 'standalone' }
| { mode: 'anilist' };
export type AnimeGroupOverrideResult =
| { ok: true }
| { ok: false; reason: 'not-found' | 'unsupported-kind' | 'target-not-grouped' };
/**
* Stores the user's grouping choice for one anime entry. Joining stores the
* target's current card key, which is always an AniList id: entries without
* one cannot be joined (merge them instead).
*/
export function setAnimeGroupOverride(
db: DatabaseSync,
animeId: number,
target: AnimeGroupOverrideTarget,
): AnimeGroupOverrideResult {
const row = db
.prepare('SELECT media_kind AS mediaKind FROM imm_anime WHERE anime_id = ?')
.get(animeId) as { mediaKind: string } | undefined;
if (!row) return { ok: false, reason: 'not-found' };
if (row.mediaKind !== 'anime') return { ok: false, reason: 'unsupported-kind' };
let value: number | null = null;
if (target.mode === 'standalone') value = GROUP_OVERRIDE_STANDALONE;
if (target.mode === 'join') {
const placement = getAnimeGroupPlacement(db, target.targetAnimeId);
if (!placement) return { ok: false, reason: 'not-found' };
if (placement.groupKey <= 0) return { ok: false, reason: 'target-not-grouped' };
value = placement.groupKey;
}
db.prepare(
'UPDATE imm_anime SET group_override = ?, group_override_updated_at = ? WHERE anime_id = ?',
).run(value, toDbTimestamp(nowMs()), animeId);
return { ok: true };
}
@@ -10,6 +10,7 @@ import { isVocabularyStatsRowVisible, type VocabularyVisibilityRow } from './voc
import { SCHEMA_VERSION } from './types'; import { SCHEMA_VERSION } from './types';
import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types'; import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types';
import { toDbTimestamp } from './query-shared'; import { toDbTimestamp } from './query-shared';
import { ensureAnimeGroupingSchema } from './anilist-relation-cache';
export interface TrackerPreparedStatements { export interface TrackerPreparedStatements {
telemetryInsertStmt: ReturnType<DatabaseSync['prepare']>; telemetryInsertStmt: ReturnType<DatabaseSync['prepare']>;
@@ -998,6 +999,7 @@ export function ensureSchema(db: DatabaseSync): void {
ensureLifetimeSummaryTables(db); ensureLifetimeSummaryTables(db);
ensureStatsExcludedWordsTable(db); ensureStatsExcludedWordsTable(db);
ensureAnimeMergeTables(db); ensureAnimeMergeTables(db);
ensureAnimeGroupingSchema(db);
ensureSubtitleLineEventIndex(db); ensureSubtitleLineEventIndex(db);
return; return;
} }
@@ -1064,6 +1066,8 @@ export function ensureSchema(db: DatabaseSync): void {
'INTEGER NOT NULL DEFAULT 0 CHECK(anime_assignment_locked IN (0, 1))', 'INTEGER NOT NULL DEFAULT 0 CHECK(anime_assignment_locked IN (0, 1))',
); );
ensureAnimeMergeTables(db); ensureAnimeMergeTables(db);
// Schema 27: franchise grouping (AniList relation cache + per-entry override).
ensureAnimeGroupingSchema(db);
db.exec(` db.exec(`
CREATE TABLE IF NOT EXISTS imm_sessions( CREATE TABLE IF NOT EXISTS imm_sessions(
session_id INTEGER PRIMARY KEY AUTOINCREMENT, session_id INTEGER PRIMARY KEY AUTOINCREMENT,
+2 -1
View File
@@ -1,7 +1,8 @@
import type { MediaKind, TmdbMediaType } from '../../../shared/media-kind'; import type { MediaKind, TmdbMediaType } from '../../../shared/media-kind';
// 26: live-action entries (TMDB link) and YouTube channels share the media_kind column. // 26: live-action entries (TMDB link) and YouTube channels share the media_kind column.
export const SCHEMA_VERSION = 26; // 27: AniList relation cache and imm_anime.group_override for franchise grouping.
export const SCHEMA_VERSION = 27;
export const DEFAULT_QUEUE_CAP = 1_000; export const DEFAULT_QUEUE_CAP = 1_000;
export const DEFAULT_BATCH_SIZE = 25; export const DEFAULT_BATCH_SIZE = 25;
export const DEFAULT_FLUSH_INTERVAL_MS = 500; export const DEFAULT_FLUSH_INTERVAL_MS = 500;
-154
View File
@@ -1,154 +0,0 @@
import assert from 'node:assert/strict';
import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
appendManagedFfmpegToPath,
detectFfmpeg,
getManagedFfmpegDir,
installManagedFfmpeg,
} from './managed-ffmpeg';
async function withTempDirs(run: (dirs: { system: string; managed: string }) => Promise<void>) {
const root = await mkdtemp(path.join(tmpdir(), 'managed-ffmpeg-'));
const dirs = { system: path.join(root, 'bin'), managed: getManagedFfmpegDir(root) };
await mkdir(dirs.system, { recursive: true });
await mkdir(dirs.managed, { recursive: true });
try {
await run(dirs);
} finally {
await rm(root, { recursive: true, force: true });
}
}
async function writeExecutable(directory: string, name: string): Promise<void> {
const filePath = path.join(directory, name);
await writeFile(filePath, '#!/bin/sh\n');
await chmod(filePath, 0o755);
}
const passVersionCheck = async () => undefined;
test('managed FFmpeg is appended to PATH once, behind system entries, only when downloaded', async () => {
await withTempDirs(async ({ system, managed }) => {
const env: NodeJS.ProcessEnv = { Path: system };
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), false);
await writeExecutable(managed, 'ffmpeg');
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), true);
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), false);
// Writes the existing key (Windows spells it Path) instead of adding a second one.
assert.deepEqual(env, { Path: [system, managed].join(path.delimiter) });
});
});
test('detectFfmpeg prefers system tools and fills gaps from the managed copy', async () => {
await withTempDirs(async ({ system, managed }) => {
const env = { PATH: [system, managed].join(path.delimiter) };
const detect = () =>
detectFfmpeg({
managedDir: managed,
env,
platform: 'linux',
arch: 'x64',
runVersionCheck: passVersionCheck,
});
assert.deepEqual(await detect(), {
kind: 'missing',
missing: ['ffmpeg', 'ffprobe'],
downloadable: true,
});
await writeExecutable(system, 'ffmpeg');
await writeExecutable(managed, 'ffprobe');
assert.deepEqual(await detect(), {
kind: 'ready',
source: 'managed',
ffmpegPath: path.join(system, 'ffmpeg'),
ffprobePath: path.join(managed, 'ffprobe'),
});
await writeExecutable(system, 'ffprobe');
const status = await detect();
assert.equal(status.kind === 'ready' ? status.source : status.kind, 'system');
});
});
test('detectFfmpeg reports a tool that is found but fails to run', async () => {
await withTempDirs(async ({ managed }) => {
await writeExecutable(managed, 'ffmpeg');
await writeExecutable(managed, 'ffprobe');
const status = await detectFfmpeg({
managedDir: managed,
env: { PATH: managed },
platform: 'freebsd',
arch: 'x64',
runVersionCheck: async () => {
throw new Error('Killed: 9');
},
});
assert.deepEqual(status, {
kind: 'broken',
path: path.join(managed, 'ffmpeg'),
message: 'Killed: 9',
managed: true,
downloadable: false,
});
});
});
test('detectFfmpeg reports a broken system tool before offering a download for its companion', async () => {
await withTempDirs(async ({ system, managed }) => {
await writeExecutable(system, 'ffmpeg');
const detect = (runVersionCheck: (executablePath: string) => Promise<void>) =>
detectFfmpeg({
managedDir: managed,
env: { PATH: system },
platform: 'linux',
arch: 'x64',
runVersionCheck,
});
// A download would only add ffprobe; the broken system ffmpeg would still shadow it.
assert.deepEqual(
await detect(async () => {
throw new Error('exit 127');
}),
{
kind: 'broken',
path: path.join(system, 'ffmpeg'),
message: 'exit 127',
managed: false,
downloadable: true,
},
);
assert.deepEqual(await detect(passVersionCheck), {
kind: 'missing',
missing: ['ffprobe'],
downloadable: true,
});
});
});
test('installManagedFfmpeg rejects unsupported platforms and never publishes a failed download', async () => {
await withTempDirs(async ({ managed }) => {
await assert.rejects(
installManagedFfmpeg({ managedDir: managed, platform: 'freebsd', arch: 'x64' }),
/no FFmpeg download for freebsd-x64/,
);
const originalFetch = globalThis.fetch;
globalThis.fetch = Object.assign(async () => new Response('not ffmpeg'), originalFetch);
try {
await assert.rejects(
installManagedFfmpeg({ managedDir: managed, platform: 'linux', arch: 'x64' }),
/FFmpeg failed integrity verification/,
);
} finally {
globalThis.fetch = originalFetch;
}
assert.deepEqual(await readdir(managed), []);
});
});
-222
View File
@@ -1,222 +0,0 @@
import { execFile } from 'node:child_process';
import { createReadStream, createWriteStream, existsSync } from 'node:fs';
import { chmod, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';
import { createGunzip } from 'node:zlib';
import { downloadSubtitleGenerationArtifact } from './subtitle-generation-download';
import { findOnPath } from './subtitle-generation-tools';
/**
* SubMiner can download its own FFmpeg when none is usable on PATH. The copy lives in
* `<configDir>/tools/ffmpeg` and is appended to PATH at startup, so a system FFmpeg always
* wins and every bare `ffmpeg`/`ffprobe` spawn picks up the download otherwise.
*/
export type FfmpegTool = 'ffmpeg' | 'ffprobe';
const FFMPEG_TOOLS: readonly FfmpegTool[] = ['ffmpeg', 'ffprobe'];
/** Pinned ffmpeg-static release: single gzipped static binaries per platform. */
const MANAGED_FFMPEG_RELEASE_URL =
'https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1';
type ManagedAsset = { size: number; sha256: string };
const MANAGED_FFMPEG_ASSETS = {
'linux-x64': {
ffmpeg: {
size: 29354986,
sha256: 'bfe8a8fc511530457b528c48d77b5737527b504a3797a9bc4866aeca69c2dffa',
},
ffprobe: {
size: 29276839,
sha256: '25d9b6ccb05e3d9de9e04e31e2506d8dd7f9f0418981965ac6df12e8d3afd067',
},
},
'linux-arm64': {
ffmpeg: {
size: 25568691,
sha256: '754a678672298bc68156adff58aa7385a592c2b30b1d0ae8750c45c915c4bac0',
},
ffprobe: {
size: 25493573,
sha256: '2ab6aba60ee84412dff9188720703376cb4e7aaf7e0b5e43aa8249f2acae5bf8',
},
},
'darwin-x64': {
ffmpeg: {
size: 25296431,
sha256: '929b375c1182d956c51f7ac25e0b2b0411fb01f6f407aa15c9758efeb4242106',
},
ffprobe: {
size: 25239438,
sha256: 'd4da574d6e2e197bd259b47d69cf262df9e312af24ad960444f6d806d3d4c186',
},
},
'darwin-arm64': {
ffmpeg: {
size: 19246198,
sha256: '8923876afa8db5585022d7860ec7e589af192f441c56793971276d450ed3bbfa',
},
ffprobe: {
size: 19207077,
sha256: 'd986a8ec7b030899fe66a8a288ed809a3543338705a3ce178cfb85869c5d80be',
},
},
'win32-x64': {
ffmpeg: {
size: 29581307,
sha256: '8883a3dffbd0a16cf4ef95206ea05283f78908dbfb118f73c83f4951dcc06d77',
},
ffprobe: {
size: 29521644,
sha256: 'f309e6223ad89d2fe54bccd420a7709b66fd27540674e92309578ed491a43c8d',
},
},
} as const satisfies Record<string, Record<FfmpegTool, ManagedAsset>>;
type ManagedFfmpegTarget = keyof typeof MANAGED_FFMPEG_ASSETS;
function getManagedFfmpegTarget(
platform: NodeJS.Platform,
arch: string,
): ManagedFfmpegTarget | null {
// Windows on ARM runs the x64 build through emulation; there is no native arm64 build.
const key = platform === 'win32' && arch === 'arm64' ? 'win32-x64' : `${platform}-${arch}`;
return key in MANAGED_FFMPEG_ASSETS ? (key as ManagedFfmpegTarget) : null;
}
export function getManagedFfmpegDir(configDir: string): string {
return path.join(configDir, 'tools', 'ffmpeg');
}
function managedBinaryPath(
managedDir: string,
tool: FfmpegTool,
platform: NodeJS.Platform,
): string {
return path.join(managedDir, platform === 'win32' ? `${tool}.exe` : tool);
}
function pathKey(env: NodeJS.ProcessEnv): string {
return Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'PATH';
}
/**
* Appends the managed FFmpeg directory to `env`'s PATH when a download exists there.
* Appending keeps a system FFmpeg in front. Returns whether PATH changed.
*/
export function appendManagedFfmpegToPath(
env: NodeJS.ProcessEnv,
managedDir: string,
platform: NodeJS.Platform = process.platform,
): boolean {
if (!existsSync(managedBinaryPath(managedDir, 'ffmpeg', platform))) return false;
const key = pathKey(env);
const entries = (env[key] ?? '').split(path.delimiter).filter(Boolean);
if (entries.some((entry) => path.resolve(entry) === path.resolve(managedDir))) return false;
env[key] = [...entries, managedDir].join(path.delimiter);
return true;
}
export type FfmpegSetupStatus =
| { kind: 'ready'; source: 'system' | 'managed'; ffmpegPath: string; ffprobePath: string }
| { kind: 'missing'; missing: FfmpegTool[]; downloadable: boolean }
/** Found on PATH but `-version` failed. Only a broken managed copy is fixed by downloading. */
| { kind: 'broken'; path: string; message: string; managed: boolean; downloadable: boolean };
export type RunVersionCheck = (executablePath: string) => Promise<void>;
const runVersionCheckDefault: RunVersionCheck = (executablePath) =>
new Promise((resolve, reject) => {
// Generous timeout: Windows Defender scans a fresh 80 MB exe on first launch.
execFile(executablePath, ['-version'], { timeout: 15_000 }, (error) =>
error ? reject(error) : resolve(),
);
});
/** Whether SubMiner can run FFmpeg and FFprobe from the current PATH, and where they come from. */
export async function detectFfmpeg(options: {
managedDir: string;
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
arch?: string;
runVersionCheck?: RunVersionCheck;
}): Promise<FfmpegSetupStatus> {
const env = options.env ?? process.env;
const platform = options.platform ?? process.platform;
const runVersionCheck = options.runVersionCheck ?? runVersionCheckDefault;
const downloadable = getManagedFfmpegTarget(platform, options.arch ?? process.arch) !== null;
const isManaged = (filePath: string) =>
path.resolve(path.dirname(filePath)) === path.resolve(options.managedDir);
const found = await Promise.all(FFMPEG_TOOLS.map((tool) => findOnPath([tool], env)));
// Check what was found before reporting gaps: a broken system tool shadows any download.
for (const executablePath of found.filter(Boolean)) {
try {
await runVersionCheck(executablePath);
} catch (error) {
return {
kind: 'broken',
path: executablePath,
message: error instanceof Error ? error.message : String(error),
managed: isManaged(executablePath),
downloadable,
};
}
}
const missing = FFMPEG_TOOLS.filter((_, index) => !found[index]);
if (missing.length > 0) return { kind: 'missing', missing, downloadable };
const [ffmpegPath, ffprobePath] = found as [string, string];
return {
kind: 'ready',
source: isManaged(ffmpegPath) || isManaged(ffprobePath) ? 'managed' : 'system',
ffmpegPath,
ffprobePath,
};
}
/**
* Downloads, verifies, and unpacks FFmpeg and FFprobe into `managedDir`, replacing any
* earlier download. Callers append `managedDir` to PATH afterwards.
*/
export async function installManagedFfmpeg(options: {
managedDir: string;
platform?: NodeJS.Platform;
arch?: string;
}): Promise<void> {
const platform = options.platform ?? process.platform;
const arch = options.arch ?? process.arch;
const target = getManagedFfmpegTarget(platform, arch);
if (!target) {
throw new Error(
`SubMiner has no FFmpeg download for ${platform}-${arch}. Install FFmpeg yourself.`,
);
}
await mkdir(options.managedDir, { recursive: true });
const staging = await mkdtemp(path.join(options.managedDir, '.install-'));
try {
const unpacked: Array<[string, string]> = [];
for (const tool of FFMPEG_TOOLS) {
const asset = MANAGED_FFMPEG_ASSETS[target][tool];
const archivePath = path.join(staging, `${tool}.gz`);
await downloadSubtitleGenerationArtifact({
url: `${MANAGED_FFMPEG_RELEASE_URL}/${tool}-${target}.gz`,
size: asset.size,
sha256: asset.sha256,
destination: archivePath,
label: tool === 'ffmpeg' ? 'FFmpeg' : 'FFprobe',
});
const binaryPath = managedBinaryPath(staging, tool, platform);
await pipeline(createReadStream(archivePath), createGunzip(), createWriteStream(binaryPath));
await chmod(binaryPath, 0o755);
unpacked.push([binaryPath, managedBinaryPath(options.managedDir, tool, platform)]);
}
// Publish only after both tools verified, so a failed download never leaves half a pair.
for (const [from, to] of unpacked) await rename(from, to);
} finally {
await rm(staging, { recursive: true, force: true });
}
}
@@ -11,6 +11,7 @@ import {
enrichSessionsWithKnownWordMetrics, enrichSessionsWithKnownWordMetrics,
isPositiveSafeInteger, isPositiveSafeInteger,
loadKnownWordsSet, loadKnownWordsSet,
parseAnimeGroupOverrideBody,
parseBooleanQuery, parseBooleanQuery,
parseDuplicateLineCleanupBody, parseDuplicateLineCleanupBody,
parseExcludedWordsBody, parseExcludedWordsBody,
@@ -190,6 +191,11 @@ export function registerStatsLibraryRoutes(
return c.json(statsJson('animeLibrary', rows)); return c.json(statsJson('animeLibrary', rows));
}); });
// Registered before `/api/stats/anime/:animeId` so `groups` is not read as an id.
app.get('/api/stats/anime/groups', async (c) => {
return c.json(statsJson('animeLibraryGroups', await tracker.getAnimeLibraryGroups()));
});
app.get('/api/stats/anime/merge-recommendations', async (c) => { app.get('/api/stats/anime/merge-recommendations', async (c) => {
const recommendations = await tracker.getAnimeMergeRecommendations(); const recommendations = await tracker.getAnimeMergeRecommendations();
return c.json(statsJson('animeMergeRecommendations', { recommendations })); return c.json(statsJson('animeMergeRecommendations', { recommendations }));
@@ -208,11 +214,12 @@ export function registerStatsLibraryRoutes(
if (animeId === null) return c.body(null, 400); if (animeId === null) return c.body(null, 400);
const detail = await tracker.getAnimeDetail(animeId); const detail = await tracker.getAnimeDetail(animeId);
if (!detail) return c.body(null, 404); if (!detail) return c.body(null, 404);
const [episodes, anilistEntries] = await Promise.all([ const [episodes, anilistEntries, group] = await Promise.all([
tracker.getAnimeEpisodes(animeId), tracker.getAnimeEpisodes(animeId),
tracker.getAnimeAnilistEntries(animeId), tracker.getAnimeAnilistEntries(animeId),
tracker.getAnimeGroupPlacement(animeId),
]); ]);
return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries })); return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries, group }));
}); });
app.get('/api/stats/anime/:animeId/words', async (c) => { app.get('/api/stats/anime/:animeId/words', async (c) => {
@@ -267,6 +274,22 @@ export function registerStatsLibraryRoutes(
return c.json(statsJson('deleteAnime', { ok: true })); return c.json(statsJson('deleteAnime', { ok: true }));
}); });
app.put('/api/stats/anime/:animeId/group', async (c) => {
const animeId = parsePositiveId(c.req.param('animeId'));
if (animeId === null) return c.body(null, 400);
const request = parseAnimeGroupOverrideBody(await c.req.json().catch(() => null));
if (!request) return c.body(null, 400);
if (request.mode === 'join' && request.targetAnimeId === animeId) return c.body(null, 400);
const result = await tracker.setAnimeGroupOverride(animeId, request);
if (result.ok) return c.json(statsJson('setAnimeGroupOverride', { ok: true }));
if (result.reason === 'not-found') return c.body(null, 404);
const error =
result.reason === 'unsupported-kind'
? 'Only anime entries can be grouped.'
: 'That title has no AniList entry to group with. Link it to AniList or merge the entries instead.';
return c.json(statsJson('error', { error }), 409);
});
app.post('/api/stats/anime/:animeId/merge', async (c) => { app.post('/api/stats/anime/:animeId/merge', async (c) => {
const animeId = parsePositiveId(c.req.param('animeId')); const animeId = parsePositiveId(c.req.param('animeId'));
if (animeId === null) return c.body(null, 400); if (animeId === null) return c.body(null, 400);
@@ -13,6 +13,7 @@ import {
import { createLogger } from '../../../logger.js'; import { createLogger } from '../../../logger.js';
import type { AnkiConnectConfig } from '../../../types.js'; import type { AnkiConnectConfig } from '../../../types.js';
import type { import type {
StatsAnimeGroupOverrideRequest,
StatsDayRange, StatsDayRange,
StatsDictionaryWordQuery, StatsDictionaryWordQuery,
StatsDictionaryWordSort, StatsDictionaryWordSort,
@@ -59,6 +60,15 @@ export function isPositiveSafeInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0; return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
} }
/** Validates a `PUT /api/stats/anime/:animeId/group` body; null for anything malformed. */
export function parseAnimeGroupOverrideBody(body: unknown): StatsAnimeGroupOverrideRequest | null {
if (!body || typeof body !== 'object') return null;
const { mode, targetAnimeId } = body as Record<string, unknown>;
if (mode === 'standalone' || mode === 'anilist') return { mode };
if (mode === 'join' && isPositiveSafeInteger(targetAnimeId)) return { mode, targetAnimeId };
return null;
}
export function parsePositiveId(raw: string | undefined): number | null { export function parsePositiveId(raw: string | undefined): number | null {
if (raw === undefined) return null; if (raw === undefined) return null;
const value = Number(raw); const value = Number(raw);
@@ -58,3 +58,78 @@ for (const [localKind, remoteKind, sameEntry] of [
} }
}); });
} }
test('franchise override follows whichever side set or cleared it last', () => {
const adapt = (db: DatabaseSync) => ({
query: (sql: string) => db.prepare(sql),
exec: (sql: string) => {
db.exec(sql);
},
close: () => {
db.close();
},
});
const cases: Array<{
name: string;
local: [number | null, string | null];
remote: [number | null, string | null];
expected: number | null;
}> = [
{
name: 'newer remote join wins',
local: [null, null],
remote: [20832, '2000'],
expected: 20832,
},
{ name: 'newer remote clear wins', local: [0, '1000'], remote: [null, '2000'], expected: null },
{ name: 'older remote loses', local: [0, '3000'], remote: [20832, '2000'], expected: 0 },
{ name: 'untouched remote keeps local', local: [0, '1000'], remote: [null, null], expected: 0 },
];
for (const c of cases) {
const local = new Database(':memory:');
const remote = new Database(':memory:');
try {
for (const [db, [override, updatedAt]] of [
[local, c.local],
[remote, c.remote],
] as const) {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, group_override, group_override_updated_at)
VALUES ('overlord ii', 'Overlord II', 98437, ?, ?)`,
).run(override, updatedAt);
}
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
const row = local.prepare('SELECT group_override AS value FROM imm_anime').get() as {
value: number | null;
};
assert.equal(row.value, c.expected, c.name);
} finally {
local.close();
remote.close();
}
}
const local = new Database(':memory:');
const remote = new Database(':memory:');
try {
ensureSchema(local);
ensureSchema(remote);
remote
.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override, group_override_updated_at)
VALUES ('specials', 'Specials', 20832, '1000')`,
)
.run();
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
const row = local
.prepare(
'SELECT group_override AS value, group_override_updated_at AS updatedAt FROM imm_anime',
)
.get() as { value: number | null; updatedAt: string | null };
assert.deepEqual([row.value, row.updatedAt], [20832, '1000']);
} finally {
local.close();
remote.close();
}
});
@@ -15,6 +15,8 @@ const ANIME_COPY_COLUMNS = [
'tmdb_id', 'tmdb_id',
'tmdb_type', 'tmdb_type',
'metadata_json', 'metadata_json',
'group_override',
'group_override_updated_at',
'CREATED_DATE', 'CREATED_DATE',
'LAST_UPDATE_DATE', 'LAST_UPDATE_DATE',
] as const; ] as const;
@@ -146,6 +148,13 @@ export function mergeAnime(
END END
WHERE anime_id = ?`, WHERE anime_id = ?`,
); );
// The franchise override holds AniList ids (or 0 / NULL), so it needs no id
// remapping. The side that set or cleared it last wins.
const takeNewerGroupOverride = local.query(
`UPDATE imm_anime SET group_override = ?, group_override_updated_at = ?
WHERE anime_id = ? AND (group_override_updated_at IS NULL
OR CAST(group_override_updated_at AS INTEGER) < CAST(? AS INTEGER))`,
);
for (const row of selectAll( for (const row of selectAll(
remote, remote,
@@ -195,6 +204,14 @@ export function mergeAnime(
row.media_kind, row.media_kind,
localId, localId,
); );
if (row.group_override_updated_at !== null) {
takeNewerGroupOverride.run(
row.group_override,
row.group_override_updated_at,
localId,
row.group_override_updated_at,
);
}
continue; continue;
} }
// Conflicting providers can share a title, but the stored title key is // Conflicting providers can share a title, but the stored title key is
+5
View File
@@ -20,6 +20,11 @@ export type { SyncMergeSummary } from './shared';
* are updated incrementally so history older than the session retention * are updated incrementally so history older than the session retention
* window is preserved on both sides. Idempotent: re-merging the same * window is preserved on both sides. Idempotent: re-merging the same
* snapshot is a no-op. * snapshot is a no-op.
*
* A library entry's franchise override (`group_override`) is last-writer-wins
* by `group_override_updated_at`. The AniList relation cache
* (`imm_anilist_media`, `imm_anilist_relations`) is not merged: each machine
* rebuilds it from AniList.
*/ */
export function mergeSnapshotIntoDb(localDbPath: string, snapshotPath: string): SyncMergeSummary { export function mergeSnapshotIntoDb(localDbPath: string, snapshotPath: string): SyncMergeSummary {
if (!fs.existsSync(localDbPath)) { if (!fs.existsSync(localDbPath)) {
@@ -18,12 +18,12 @@ export async function downloadSubtitleGenerationArtifact(input: {
const temporaryDirectory = await mkdtemp( const temporaryDirectory = await mkdtemp(
path.join(path.dirname(input.destination), '.download-'), path.join(path.dirname(input.destination), '.download-'),
); );
const temporaryPath = path.join(temporaryDirectory, 'artifact.bin'); const temporaryPath = path.join(temporaryDirectory, 'model.bin');
input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` }); input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` });
try { try {
const response = await fetch(input.url, { signal: input.signal }); const response = await fetch(input.url, { signal: input.signal });
if (!response.ok || !response.body) { if (!response.ok || !response.body) {
throw new Error(`${input.label} download failed: HTTP ${response.status}`); throw new Error(`Model download failed: HTTP ${response.status}`);
} }
const file = await open(temporaryPath, 'wx'); const file = await open(temporaryPath, 'wx');
const reader = response.body.getReader(); const reader = response.body.getReader();
@@ -36,8 +36,7 @@ export async function downloadSubtitleGenerationArtifact(input: {
const { done, value } = await reader.read(); const { done, value } = await reader.read();
if (done) break; if (done) break;
received += value.byteLength; received += value.byteLength;
if (received > input.size) if (received > input.size) throw new Error('Downloaded model exceeds expected size.');
throw new Error(`Downloaded ${input.label} exceeds expected size.`);
digest.update(value); digest.update(value);
await file.writeFile(value); await file.writeFile(value);
const percent = Math.min(99, Math.floor((received / input.size) * 100)); const percent = Math.min(99, Math.floor((received / input.size) * 100));
@@ -51,9 +50,7 @@ export async function downloadSubtitleGenerationArtifact(input: {
} }
} }
if (received !== input.size || digest.digest('hex') !== input.sha256) { if (received !== input.size || digest.digest('hex') !== input.sha256) {
throw new Error( throw new Error('Downloaded model failed integrity verification. Try downloading again.');
`Downloaded ${input.label} failed integrity verification. Try downloading again.`,
);
} }
await file.sync(); await file.sync();
} finally { } finally {
@@ -46,11 +46,7 @@ function executableNames(name: string, env: NodeJS.ProcessEnv): string[] {
return [name, ...extensions.map((extension) => `${name}${extension}`)]; return [name, ...extensions.map((extension) => `${name}${extension}`)];
} }
/** First executable on `env.PATH` matching any of `names` (PATHEXT-aware on Windows), or ''. */ async function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv): Promise<string> {
export async function findOnPath(
names: readonly string[],
env: NodeJS.ProcessEnv,
): Promise<string> {
const directories = (env.PATH ?? '') const directories = (env.PATH ?? '')
.split(path.delimiter) .split(path.delimiter)
.map((entry) => entry.trim()) .map((entry) => entry.trim())
-4
View File
@@ -155,7 +155,6 @@ import { createSyncAssembly } from './main/assemblies/sync';
import { createYoutubeAssembly } from './main/assemblies/youtube'; import { createYoutubeAssembly } from './main/assemblies/youtube';
import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals'; import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals';
import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup'; import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup';
import { appendManagedFfmpegToPath, getManagedFfmpegDir } from './core/services/managed-ffmpeg';
import { createOverlayAssembly } from './main/assemblies/overlay'; import { createOverlayAssembly } from './main/assemblies/overlay';
import { createYomitanAssembly } from './main/assemblies/yomitan'; import { createYomitanAssembly } from './main/assemblies/yomitan';
import { createStatsAssembly } from './main/assemblies/stats'; import { createStatsAssembly } from './main/assemblies/stats';
@@ -429,8 +428,6 @@ const {
appState, appState,
appLifecycleApp, appLifecycleApp,
} = bootServices; } = bootServices;
// Before any ffmpeg/ffprobe spawn: a system FFmpeg stays first, the setup-page download fills in.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(CONFIG_DIR));
// Backend changes take effect on restart; windows and parser must share one session. // Backend changes take effect on restart; windows and parser must share one session.
const activeDictionaryBackend = configService.getConfig().dictionaryBackend; const activeDictionaryBackend = configService.getConfig().dictionaryBackend;
const yomitan = createYomitanAssembly({ const yomitan = createYomitanAssembly({
@@ -691,7 +688,6 @@ const firstRunSetup = createFirstRunSetupAssembly({
ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(), ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(),
getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(), getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(),
createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(), createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(),
waitForLoginShellPath: () => loginShellPathReady,
getAppPath: (name) => app.getPath(name), getAppPath: (name) => app.getPath(name),
trashItem: (targetPath) => shell.trashItem(targetPath), trashItem: (targetPath) => shell.trashItem(targetPath),
writeShortcutLink: (shortcutPath, operation, details) => writeShortcutLink: (shortcutPath, operation, details) =>
@@ -30,7 +30,6 @@ function makeDeps(configDir: string): FirstRunSetupAssemblyDeps {
ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'), ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'),
getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'), getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'),
createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'), createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'),
waitForLoginShellPath: lazy('waitForLoginShellPath'),
getAppPath: lazy('getAppPath'), getAppPath: lazy('getAppPath'),
trashItem: lazy('trashItem'), trashItem: lazy('trashItem'),
writeShortcutLink: lazy('writeShortcutLink'), writeShortcutLink: lazy('writeShortcutLink'),
-32
View File
@@ -1,12 +1,6 @@
import os from 'node:os'; import os from 'node:os';
import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron'; import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron';
import type { ConfigService } from '../../config/service'; import type { ConfigService } from '../../config/service';
import {
appendManagedFfmpegToPath,
detectFfmpeg,
getManagedFfmpegDir,
installManagedFfmpeg,
} from '../../core/services/managed-ffmpeg';
import { getYomitanDictionaryInfo } from '../../core/services'; import { getYomitanDictionaryInfo } from '../../core/services';
import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime'; import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime';
import type { Logger } from '../../logger'; import type { Logger } from '../../logger';
@@ -68,8 +62,6 @@ export interface FirstRunSetupAssemblyDeps {
getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps; getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps;
/** Resolves the launcher options after the login-shell PATH is applied. */ /** Resolves the launcher options after the login-shell PATH is applied. */
createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>; createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>;
/** Resolves once the macOS login-shell PATH is merged, so FFmpeg detection sees it. */
waitForLoginShellPath: () => Promise<void>;
getAppPath: (name: 'appData' | 'desktop') => string; getAppPath: (name: 'appData' | 'desktop') => string;
trashItem: (targetPath: string) => Promise<void>; trashItem: (targetPath: string) => Promise<void>;
writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink']; writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink'];
@@ -91,23 +83,6 @@ export type FirstRunSetupAssembly = ReturnType<typeof createFirstRunSetupAssembl
export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) { export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
const { appState, configService, logger } = deps; const { appState, configService, logger } = deps;
let firstRunSetupMessage: string | null = null; let firstRunSetupMessage: string | null = null;
const managedFfmpegDir = getManagedFfmpegDir(deps.configDir);
// Shared by repeat clicks so a second press never starts a parallel download.
let ffmpegInstall: Promise<string> | null = null;
const installFfmpeg = (): Promise<string> =>
(ffmpegInstall ??= installManagedFfmpeg({ managedDir: managedFfmpegDir })
.then(() => {
appendManagedFfmpegToPath(process.env, managedFfmpegDir);
logger.info(`[ffmpeg] Downloaded FFmpeg to ${managedFfmpegDir}`);
return 'FFmpeg downloaded. SubMiner uses it whenever FFmpeg is not on PATH.';
})
.catch((error: unknown) => {
logger.error('[ffmpeg] FFmpeg download failed', error);
return `FFmpeg download failed: ${error instanceof Error ? error.message : String(error)}`;
})
.finally(() => {
ffmpegInstall = null;
}));
const resolveWindowsMpvShortcutRuntimePaths = () => const resolveWindowsMpvShortcutRuntimePaths = () =>
resolveWindowsMpvShortcutPaths({ resolveWindowsMpvShortcutPaths({
appDataDir: deps.getAppPath('appData'), appDataDir: deps.getAppPath('appData'),
@@ -257,9 +232,6 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath), mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath),
windowsMpvShortcuts: snapshot.windowsMpvShortcuts, windowsMpvShortcuts: snapshot.windowsMpvShortcuts,
commandLineLauncher: snapshot.commandLineLauncher, commandLineLauncher: snapshot.commandLineLauncher,
ffmpeg: await deps
.waitForLoginShellPath()
.then(() => detectFfmpeg({ managedDir: managedFfmpegDir })),
message: firstRunSetupMessage, message: firstRunSetupMessage,
}; };
}, },
@@ -332,10 +304,6 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
firstRunSetupMessage = snapshot.message; firstRunSetupMessage = snapshot.message;
return; return;
} }
if (submission.action === 'install-ffmpeg') {
firstRunSetupMessage = await installFfmpeg();
return;
}
if (submission.action === 'open-yomitan-settings') { if (submission.action === 'open-yomitan-settings') {
firstRunSetupMessage = deps.openDictionarySettings() firstRunSetupMessage = deps.openDictionarySettings()
? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.` ? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.`
+4
View File
@@ -1,6 +1,7 @@
import path from 'node:path'; import path from 'node:path';
import { ImmersionTrackerService } from '../../core/services'; import { ImmersionTrackerService } from '../../core/services';
import { createCoverArtFetcher } from '../../core/services/anilist/cover-art-fetcher'; import { createCoverArtFetcher } from '../../core/services/anilist/cover-art-fetcher';
import { createAnilistRelationFetcher } from '../../core/services/anilist/franchise-relation-fetcher';
import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter'; import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter';
import { resolveLegacyVocabularyPosFromTokens } from '../../core/services/immersion-tracker/legacy-vocabulary-pos'; import { resolveLegacyVocabularyPosFromTokens } from '../../core/services/immersion-tracker/legacy-vocabulary-pos';
import type { StatsWindowOptions } from '../../core/services/stats-window'; import type { StatsWindowOptions } from '../../core/services/stats-window';
@@ -172,6 +173,8 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
}, },
); );
const anilistRelationFetcher = createAnilistRelationFetcher(deps.anilistRateLimiter);
// One options object serves the overlay's IPC toggle and the session-action toggle. // One options object serves the overlay's IPC toggle and the session-action toggle.
const statsOverlayOptions: StatsWindowOptions = { const statsOverlayOptions: StatsWindowOptions = {
preloadPath: path.join(deps.mainDirname, 'preload-stats.js'), preloadPath: path.join(deps.mainDirname, 'preload-stats.js'),
@@ -235,6 +238,7 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
appState.immersionTracker = tracker as ImmersionTrackerService | null; appState.immersionTracker = tracker as ImmersionTrackerService | null;
appState.immersionTracker?.setCoverArtFetcher(coverArtFetcher); appState.immersionTracker?.setCoverArtFetcher(coverArtFetcher);
appState.immersionTracker?.setAnilistRelationFetcher(anilistRelationFetcher);
if (tracker) { if (tracker) {
// Start HTTP stats server // Start HTTP stats server
if (!appState.statsServer) { if (!appState.statsServer) {
@@ -7,14 +7,6 @@ import {
parseFirstRunSetupSubmissionUrl, parseFirstRunSetupSubmissionUrl,
} from './first-run-setup-window'; } from './first-run-setup-window';
import type { CommandLineLauncherSnapshot } from './command-line-launcher'; import type { CommandLineLauncherSnapshot } from './command-line-launcher';
import type { FfmpegSetupStatus } from '../../core/services/managed-ffmpeg';
const READY_FFMPEG: FfmpegSetupStatus = {
kind: 'ready',
source: 'system',
ffmpegPath: '/usr/bin/ffmpeg',
ffprobePath: '/usr/bin/ffprobe',
};
function createCommandLineLauncherSnapshot( function createCommandLineLauncherSnapshot(
overrides: Partial<CommandLineLauncherSnapshot> = {}, overrides: Partial<CommandLineLauncherSnapshot> = {},
@@ -60,7 +52,6 @@ test('buildFirstRunSetupHtml shows legacy mpv plugin removal action with confirm
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -99,7 +90,6 @@ test('buildFirstRunSetupHtml marks an invalid configured mpv path as invalid', (
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -127,7 +117,6 @@ test('buildFirstRunSetupHtml explains the config blocker when setup is missing c
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -157,7 +146,6 @@ test('buildFirstRunSetupHtml explains external yomitan mode and keeps finish ena
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -233,7 +221,6 @@ test('buildFirstRunSetupHtml reports a broken included runtime in the optional l
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
bun: { bun: {
status: 'failed', status: 'failed',
@@ -288,7 +275,6 @@ test('buildFirstRunSetupHtml labels a missing launcher without error-message wor
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
bun: { bun: {
status: 'ready', status: 'ready',
@@ -324,7 +310,6 @@ test('buildFirstRunSetupHtml disables launcher install when no target is install
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
launcher: { launcher: {
status: 'not_installable', status: 'not_installable',
@@ -418,7 +403,6 @@ test('opening first-run setup shows and focuses window after content loads', asy
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -485,7 +469,6 @@ test('opening first-run setup skips rendering if window is destroyed after snaps
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}; };
@@ -555,7 +538,6 @@ test('first-run setup action can skip rerender after launching another window',
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -638,7 +620,6 @@ test('closing incomplete first-run setup quits app outside background mode', asy
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -711,7 +692,6 @@ test('closing completed first-run setup quits app when completion policy allows
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -767,7 +747,6 @@ test('Hachidori setup names the active dictionary backend', () => {
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -796,55 +775,3 @@ test('setup parses link and unlink actions without losing the host address', ()
{ action: 'unlink-hachidori-host' }, { action: 'unlink-hachidori-host' },
); );
}); });
test('FFmpeg card offers a download only when one would be used', () => {
const render = (ffmpeg: FfmpegSetupStatus) =>
buildFirstRunSetupHtml({
configReady: true,
dictionaryCount: 1,
canFinish: true,
externalYomitanConfigured: false,
pluginStatus: 'installed',
pluginInstallPathSummary: null,
mpvExecutablePath: '',
mpvExecutablePathStatus: 'blank',
windowsMpvShortcuts: {
supported: false,
startMenuEnabled: false,
desktopEnabled: false,
startMenuInstalled: false,
desktopInstalled: false,
status: 'optional',
},
ffmpeg,
commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null,
});
const system = render(READY_FFMPEG);
assert.match(system, /Found on your system\. Nothing to do\./);
assert.match(system, /\/usr\/bin\/ffprobe/);
assert.doesNotMatch(system, /action=install-ffmpeg/);
const missing = render({ kind: 'missing', missing: ['ffprobe'], downloadable: true });
assert.match(missing, /Not found on PATH: ffprobe\./);
assert.match(missing, /action=install-ffmpeg/);
const unsupported = render({ kind: 'missing', missing: ['ffmpeg'], downloadable: false });
assert.match(unsupported, /No download is available for this platform/);
assert.doesNotMatch(unsupported, /action=install-ffmpeg/);
const broken = {
kind: 'broken',
path: '/x/ffmpeg',
message: 'exit 127',
downloadable: true,
} as const;
assert.doesNotMatch(render({ ...broken, managed: false }), /action=install-ffmpeg/);
assert.match(render({ ...broken, managed: true }), /Download FFmpeg again/);
assert.deepEqual(
parseFirstRunSetupSubmissionUrl('subminer://first-run-setup?action=install-ffmpeg'),
{ action: 'install-ffmpeg' },
);
});
@@ -1,4 +1,3 @@
import type { FfmpegSetupStatus } from '../../core/services/managed-ffmpeg';
import type { HachidoriHostStatus } from '../../shared/hachidori-sharing'; import type { HachidoriHostStatus } from '../../shared/hachidori-sharing';
import type { DictionaryBackend } from '../../types/config'; import type { DictionaryBackend } from '../../types/config';
import { getFirstRunSetupCompletionMessage } from './first-run-setup-service'; import { getFirstRunSetupCompletionMessage } from './first-run-setup-service';
@@ -35,7 +34,6 @@ export type FirstRunSetupSubmission =
| 'remove-legacy-plugin' | 'remove-legacy-plugin'
| 'install-bun' | 'install-bun'
| 'install-command-line-launcher' | 'install-command-line-launcher'
| 'install-ffmpeg'
| 'open-yomitan-settings' | 'open-yomitan-settings'
| 'open-config-settings' | 'open-config-settings'
| 'refresh' | 'refresh'
@@ -65,7 +63,6 @@ export interface FirstRunSetupHtmlModel {
status: 'installed' | 'optional' | 'skipped' | 'failed'; status: 'installed' | 'optional' | 'skipped' | 'failed';
}; };
commandLineLauncher: CommandLineLauncherSnapshot; commandLineLauncher: CommandLineLauncherSnapshot;
ffmpeg: FfmpegSetupStatus;
message: string | null; message: string | null;
} }
@@ -157,56 +154,6 @@ function renderCommandLineLauncherSection(
</section>`; </section>`;
} }
function renderFfmpegCard(ffmpeg: FfmpegSetupStatus): string {
const lines: string[] = [];
let badge: string;
let showDownload = false;
if (ffmpeg.kind === 'ready') {
lines.push(
ffmpeg.source === 'system'
? 'Found on your system. Nothing to do.'
: 'Using the copy SubMiner downloaded. Nothing to do.',
`FFmpeg: ${ffmpeg.ffmpegPath}`,
`FFprobe: ${ffmpeg.ffprobePath}`,
);
badge = renderStatusBadge(ffmpeg.source === 'system' ? 'Detected' : 'Downloaded', 'ready');
} else if (ffmpeg.kind === 'missing') {
lines.push(`Not found on PATH: ${ffmpeg.missing.join(', ')}.`);
lines.push(
ffmpeg.downloadable
? 'Download a copy for SubMiner (under 60 MB), or install FFmpeg yourself and refresh.'
: 'No download is available for this platform. Install FFmpeg, then refresh.',
);
badge = renderStatusBadge('Missing', 'warn');
showDownload = ffmpeg.downloadable;
} else {
lines.push(`${ffmpeg.path} failed to run: ${ffmpeg.message}`);
lines.push(
ffmpeg.managed
? 'Download it again to repair the copy SubMiner downloaded.'
: 'Repair or remove that FFmpeg install, then refresh.',
);
badge = renderStatusBadge('Not working', 'danger');
showDownload = ffmpeg.managed && ffmpeg.downloadable;
}
// The button relabels itself because the page only re-renders once the download finishes.
const downloadButton = showDownload
? `<div class="inline-actions"><button onclick="this.disabled = true; this.textContent = 'Downloading FFmpeg...'; window.location.href='subminer://first-run-setup?action=install-ffmpeg'">${ffmpeg.kind === 'broken' ? 'Download FFmpeg again' : 'Download FFmpeg'}</button></div>`
: '';
return `
<div class="card block">
<div class="card-head">
<div>
<strong>FFmpeg</strong>
<div class="meta">Used for card audio and screenshots, and subtitle generation.</div>
${lines.map((line) => `<div class="meta">${escapeHtml(line)}</div>`).join('')}
</div>
${badge}
</div>
${downloadButton}
</div>`;
}
export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string { export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? []; const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? [];
const finishButtonLabel = const finishButtonLabel =
@@ -588,7 +535,6 @@ export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)} ${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)}
</div> </div>
${hostCard} ${hostCard}
${renderFfmpegCard(model.ffmpeg)}
${mpvExecutablePathCard} ${mpvExecutablePathCard}
${windowsShortcutCard} ${windowsShortcutCard}
${renderCommandLineLauncherSection(model.commandLineLauncher)} ${renderCommandLineLauncherSection(model.commandLineLauncher)}
@@ -620,7 +566,6 @@ export function parseFirstRunSetupSubmissionUrl(rawUrl: string): FirstRunSetupSu
action !== 'configure-windows-mpv-shortcuts' && action !== 'configure-windows-mpv-shortcuts' &&
action !== 'install-bun' && action !== 'install-bun' &&
action !== 'install-command-line-launcher' && action !== 'install-command-line-launcher' &&
action !== 'install-ffmpeg' &&
action !== 'open-yomitan-settings' && action !== 'open-yomitan-settings' &&
action !== 'open-config-settings' && action !== 'open-config-settings' &&
action !== 'refresh' && action !== 'refresh' &&
+5 -1
View File
@@ -6,6 +6,7 @@ import { ConfigService } from './config/service';
import { createLogger, setLogLevel } from './logger'; import { createLogger, setLogLevel } from './logger';
import { ImmersionTrackerService } from './core/services/immersion-tracker-service'; import { ImmersionTrackerService } from './core/services/immersion-tracker-service';
import { createCoverArtFetcher } from './core/services/anilist/cover-art-fetcher'; import { createCoverArtFetcher } from './core/services/anilist/cover-art-fetcher';
import { createAnilistRelationFetcher } from './core/services/anilist/franchise-relation-fetcher';
import { createAnilistRateLimiter } from './core/services/anilist/rate-limiter'; import { createAnilistRateLimiter } from './core/services/anilist/rate-limiter';
import { createLiveActionMetadataResolver } from './core/services/tmdb/live-action-resolver'; import { createLiveActionMetadataResolver } from './core/services/tmdb/live-action-resolver';
import { createTmdbClient, createTmdbApiKeyResolver } from './core/services/tmdb/tmdb-client'; import { createTmdbClient, createTmdbApiKeyResolver } from './core/services/tmdb/tmdb-client';
@@ -212,11 +213,14 @@ async function main(): Promise<void> {
() => bundledTmdbApiKey, () => bundledTmdbApiKey,
), ),
}); });
// Cover art and franchise relations share one AniList request budget.
const anilistRateLimiter = createAnilistRateLimiter();
tracker.setCoverArtFetcher( tracker.setCoverArtFetcher(
createCoverArtFetcher(createAnilistRateLimiter(), createLogger('stats-daemon:cover-art'), { createCoverArtFetcher(anilistRateLimiter, createLogger('stats-daemon:cover-art'), {
liveAction: createLiveActionMetadataResolver(tmdbClient, createLogger('stats-daemon:tmdb')), liveAction: createLiveActionMetadataResolver(tmdbClient, createLogger('stats-daemon:tmdb')),
}), }),
); );
tracker.setAnilistRelationFetcher(createAnilistRelationFetcher(anilistRateLimiter));
statsServer = await startStatsServer({ statsServer = await startStatsServer({
port: config.stats.serverPort, port: config.stats.serverPort,
+18
View File
@@ -1,5 +1,6 @@
import type { import type {
AnimeDetailData, AnimeDetailData,
AnimeLibraryGroup,
AnimeLibraryItem, AnimeLibraryItem,
AnimeWord, AnimeWord,
DailyRollup, DailyRollup,
@@ -187,6 +188,16 @@ export interface StatsMoveVideoRequest {
animeId: number; animeId: number;
} }
/**
* Body of `PUT /api/stats/anime/:animeId/group`: list the entry with another
* entry's franchise (`join`), on its own (`standalone`), or where AniList's
* relations put it (`anilist`, which clears the override).
*/
export type StatsAnimeGroupOverrideRequest =
| { mode: 'join'; targetAnimeId: number }
| { mode: 'standalone' }
| { mode: 'anilist' };
export interface StatsAnimeMergeRecommendation { export interface StatsAnimeMergeRecommendation {
recommendationId: number; recommendationId: number;
animeIds: [number, number]; animeIds: [number, number];
@@ -251,6 +262,7 @@ export interface StatsJsonResponseMap {
mediaLibrary: MediaLibraryItem[]; mediaLibrary: MediaLibraryItem[];
mediaDetail: MediaDetailData; mediaDetail: MediaDetailData;
animeLibrary: AnimeLibraryItem[]; animeLibrary: AnimeLibraryItem[];
animeLibraryGroups: AnimeLibraryGroup[];
animeMergeRecommendations: StatsAnimeMergeRecommendationsResponse; animeMergeRecommendations: StatsAnimeMergeRecommendationsResponse;
animeDetail: AnimeDetailData; animeDetail: AnimeDetailData;
animeWords: AnimeWord[]; animeWords: AnimeWord[];
@@ -262,6 +274,7 @@ export interface StatsJsonResponseMap {
deleteAnime: StatsOkResponse; deleteAnime: StatsOkResponse;
mergeAnime: StatsMergeAnimeResponse; mergeAnime: StatsMergeAnimeResponse;
moveVideoToAnime: StatsMoveVideoResponse; moveVideoToAnime: StatsMoveVideoResponse;
setAnimeGroupOverride: StatsOkResponse;
dismissAnimeMergeRecommendation: StatsOkResponse; dismissAnimeMergeRecommendation: StatsOkResponse;
anilistSearch: StatsAnilistSearchResult[]; anilistSearch: StatsAnilistSearchResult[];
tmdbSearch: StatsTmdbSearchResult[]; tmdbSearch: StatsTmdbSearchResult[];
@@ -330,6 +343,7 @@ export interface StatsHttpClient {
getMediaLibrary: () => Promise<MediaLibraryItem[]>; getMediaLibrary: () => Promise<MediaLibraryItem[]>;
getMediaDetail: (videoId: number) => Promise<MediaDetailData>; getMediaDetail: (videoId: number) => Promise<MediaDetailData>;
getAnimeLibrary: () => Promise<AnimeLibraryItem[]>; getAnimeLibrary: () => Promise<AnimeLibraryItem[]>;
getAnimeLibraryGroups: () => Promise<AnimeLibraryGroup[]>;
getAnimeMergeRecommendations: () => Promise<StatsAnimeMergeRecommendationsResponse>; getAnimeMergeRecommendations: () => Promise<StatsAnimeMergeRecommendationsResponse>;
getAnimeDetail: (animeId: number) => Promise<AnimeDetailData>; getAnimeDetail: (animeId: number) => Promise<AnimeDetailData>;
getAnimeWords: (animeId: number, limit?: number) => Promise<AnimeWord[]>; getAnimeWords: (animeId: number, limit?: number) => Promise<AnimeWord[]>;
@@ -356,6 +370,10 @@ export interface StatsHttpClient {
deleteAnime: (animeId: number) => Promise<void>; deleteAnime: (animeId: number) => Promise<void>;
mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<StatsMergeAnimeResponse>; mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<StatsMergeAnimeResponse>;
moveVideoToAnime: (videoId: number, animeId: number) => Promise<StatsMoveVideoResponse>; moveVideoToAnime: (videoId: number, animeId: number) => Promise<StatsMoveVideoResponse>;
setAnimeGroupOverride: (
animeId: number,
request: StatsAnimeGroupOverrideRequest,
) => Promise<void>;
dismissAnimeMergeRecommendation: (recommendationId: number) => Promise<void>; dismissAnimeMergeRecommendation: (recommendationId: number) => Promise<void>;
getKnownWords: () => Promise<string[]>; getKnownWords: () => Promise<string[]>;
getKnownWordsSummary: () => Promise<StatsKnownWordsSummary>; getKnownWordsSummary: () => Promise<StatsKnownWordsSummary>;
+42
View File
@@ -306,6 +306,46 @@ export interface AnimeLibraryItem {
lastWatchedMs: number; lastWatchedMs: number;
} }
/** One library entry inside a franchise group, with its AniList format and start date when cached. */
export interface AnimeLibraryGroupPart extends AnimeLibraryItem {
/** AniList format (TV, MOVIE, OVA...); null without a cached AniList entry. */
format: string | null;
/** AniList start date as yyyymmdd (month/day 0 when unknown); null when unknown. */
startDate: number | null;
}
/**
* A library card: one franchise (seasons, movies and OVAs that AniList links
* together) or a single entry. Totals add up the parts; `lastWatchedMs` is the
* latest part's. Parts are in AniList release order.
*/
export interface AnimeLibraryGroup {
/** AniList id the franchise is named after, or minus the entry's animeId for a card of its own. */
groupKey: number;
title: string;
mediaKind: MediaKind;
/** Entry whose cover the card shows: the first part by release date. */
coverAnimeId: number;
totalSessions: number;
totalActiveMs: number;
totalCards: number;
totalTokensSeen: number;
episodeCount: number;
lastWatchedMs: number;
parts: AnimeLibraryGroupPart[];
}
/** How a library entry's franchise was chosen: by AniList, moved by the user, or kept on its own. */
export type AnimeGroupOverrideMode = 'anilist' | 'joined' | 'standalone';
/** Where one library entry sits in the grouped library. */
export interface AnimeGroupPlacement {
groupKey: number;
title: string;
partCount: number;
overrideMode: AnimeGroupOverrideMode;
}
export interface AnilistEntry { export interface AnilistEntry {
anilistId: number; anilistId: number;
titleRomaji: string | null; titleRomaji: string | null;
@@ -338,6 +378,8 @@ export interface AnimeDetailData {
}; };
episodes: AnimeEpisode[]; episodes: AnimeEpisode[];
anilistEntries: AnilistEntry[]; anilistEntries: AnilistEntry[];
/** Null when the entry has no watch history to list in the library. */
group: AnimeGroupPlacement | null;
} }
export interface AnimeEpisode { export interface AnimeEpisode {
+9 -3
View File
@@ -1,9 +1,9 @@
import { AnimeCoverImage } from './AnimeCoverImage'; import { AnimeCoverImage } from './AnimeCoverImage';
import { formatDuration, formatNumber } from '../../lib/formatters'; import { formatDuration, formatNumber } from '../../lib/formatters';
import type { AnimeLibraryItem } from '../../types/stats'; import type { AnimeCardData } from '../../lib/anime-groups';
interface AnimeCardProps { interface AnimeCardProps {
anime: AnimeLibraryItem; anime: AnimeCardData;
onClick: () => void; onClick: () => void;
/** While selecting, clicking the card toggles it instead of opening it. */ /** While selecting, clicking the card toggles it instead of opening it. */
selectable?: boolean; selectable?: boolean;
@@ -16,6 +16,7 @@ export function AnimeCard({
selectable = false, selectable = false,
selected = false, selected = false,
}: AnimeCardProps) { }: AnimeCardProps) {
const unit = anime.mediaKind === 'youtube' ? 'video' : 'episode';
return ( return (
<button <button
type="button" type="button"
@@ -44,11 +45,16 @@ export function AnimeCard({
{'✓'} {'✓'}
</span> </span>
)} )}
{anime.partCount ? (
<span className="absolute top-2 right-2 px-1.5 py-0.5 rounded text-[10px] font-medium bg-ctp-crust/80 text-ctp-text border border-ctp-surface2">
{anime.partCount} parts
</span>
) : null}
</div> </div>
<div className="p-3"> <div className="p-3">
<div className="text-sm font-medium text-ctp-text truncate">{anime.canonicalTitle}</div> <div className="text-sm font-medium text-ctp-text truncate">{anime.canonicalTitle}</div>
<div className="text-xs text-ctp-overlay2 mt-1"> <div className="text-xs text-ctp-overlay2 mt-1">
{anime.episodeCount} {anime.mediaKind === 'youtube' ? 'video' : 'episode'} {anime.episodeCount} {unit}
{anime.episodeCount !== 1 ? 's' : ''} {anime.episodeCount !== 1 ? 's' : ''}
</div> </div>
<div className="text-xs text-ctp-overlay2"> <div className="text-xs text-ctp-overlay2">
+70 -3
View File
@@ -9,13 +9,16 @@ import { AnimeWordList } from './AnimeWordList';
import { AnilistSelector } from './AnilistSelector'; import { AnilistSelector } from './AnilistSelector';
import { TmdbSelector } from './TmdbSelector'; import { TmdbSelector } from './TmdbSelector';
import { AnimeOverviewStats } from './AnimeOverviewStats'; import { AnimeOverviewStats } from './AnimeOverviewStats';
import { LibraryEntryPicker } from './LibraryEntryPicker';
import { CHART_THEME } from '../../lib/chart-theme'; import { CHART_THEME } from '../../lib/chart-theme';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts'; import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import type { DailyRollup } from '../../types/stats'; import type { DailyRollup, StatsAnimeGroupOverrideRequest } from '../../types/stats';
interface AnimeDetailViewProps { interface AnimeDetailViewProps {
animeId: number; animeId: number;
onBack: () => void; onBack: () => void;
/** Defaults to "Back to Library"; a part opened from a franchise card returns there. */
backLabel?: string;
onNavigateToWord?: (wordId: number) => void; onNavigateToWord?: (wordId: number) => void;
onOpenEpisodeDetail?: (videoId: number) => void; onOpenEpisodeDetail?: (videoId: number) => void;
/** Called after the whole library entry is deleted, so the caller can refresh. */ /** Called after the whole library entry is deleted, so the caller can refresh. */
@@ -28,6 +31,23 @@ interface AnimeDetailViewProps {
onProviderRelinked?: () => void; onProviderRelinked?: () => void;
/** Called after an episode is reassigned to another entry. */ /** Called after an episode is reassigned to another entry. */
onEpisodeMoved?: () => void; onEpisodeMoved?: () => void;
/** Called after the entry is moved to another franchise card or back. */
onGroupChanged?: () => void;
}
/** The server explains a refused move (409) in its JSON body; show that text. */
function describeGroupError(err: unknown): string {
const message = err instanceof Error ? err.message : '';
const refused = /^Stats API error: 409 (.*)$/s.exec(message);
if (refused) {
try {
const body = JSON.parse(refused[1]!) as { error?: unknown };
if (typeof body.error === 'string') return body.error;
} catch {
// Fall through to the raw message.
}
}
return message || 'Failed to move this title.';
} }
type Range = 14 | 30 | 90; type Range = 14 | 30 | 90;
@@ -149,11 +169,13 @@ function useAnimeKnownWords(animeId: number) {
export function AnimeDetailView({ export function AnimeDetailView({
animeId, animeId,
onBack, onBack,
backLabel = 'Back to Library',
onNavigateToWord, onNavigateToWord,
onOpenEpisodeDetail, onOpenEpisodeDetail,
onAnimeDeleted, onAnimeDeleted,
onProviderRelinked, onProviderRelinked,
onEpisodeMoved, onEpisodeMoved,
onGroupChanged,
}: AnimeDetailViewProps) { }: AnimeDetailViewProps) {
const { data, loading, error, reload } = useAnimeDetail(animeId); const { data, loading, error, reload } = useAnimeDetail(animeId);
const [showAnilistSelector, setShowAnilistSelector] = useState(false); const [showAnilistSelector, setShowAnilistSelector] = useState(false);
@@ -162,6 +184,9 @@ export function AnimeDetailView({
const [isDeletingAnime, setIsDeletingAnime] = useState(false); const [isDeletingAnime, setIsDeletingAnime] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null); const [deleteError, setDeleteError] = useState<string | null>(null);
const isDeletingAnimeRef = useRef(false); const isDeletingAnimeRef = useRef(false);
const [showGroupPicker, setShowGroupPicker] = useState(false);
const [groupBusyTargetId, setGroupBusyTargetId] = useState<number | null>(null);
const [groupError, setGroupError] = useState<string | null>(null);
const knownWordsSummary = useAnimeKnownWords(animeId); const knownWordsSummary = useAnimeKnownWords(animeId);
useEffect(() => { useEffect(() => {
@@ -172,7 +197,23 @@ export function AnimeDetailView({
if (error) return <div className="text-ctp-red p-4">Error: {error}</div>; if (error) return <div className="text-ctp-red p-4">Error: {error}</div>;
if (!data?.detail) return <div className="text-ctp-overlay2 p-4">Library entry not found</div>; if (!data?.detail) return <div className="text-ctp-overlay2 p-4">Library entry not found</div>;
const { detail, episodes, anilistEntries } = data; const { detail, episodes, anilistEntries, group } = data;
// `busyId` marks which picker row shows progress; the entry's own id for header actions.
const applyGroupOverride = async (request: StatsAnimeGroupOverrideRequest, busyId: number) => {
setGroupBusyTargetId(busyId);
setGroupError(null);
try {
await getStatsClient().setAnimeGroupOverride(animeId, request);
setShowGroupPicker(false);
reload();
onGroupChanged?.();
} catch (err) {
setGroupError(describeGroupError(err));
} finally {
setGroupBusyTargetId(null);
}
};
const handleDeleteAnime = async () => { const handleDeleteAnime = async () => {
if (isDeletingAnimeRef.current) return; if (isDeletingAnimeRef.current) return;
@@ -214,11 +255,18 @@ export function AnimeDetailView({
onClick={onBack} onClick={onBack}
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors" className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
> >
&larr; Back to Library &larr; {backLabel}
</button> </button>
<AnimeHeader <AnimeHeader
detail={detail} detail={detail}
anilistEntries={anilistEntries ?? []} anilistEntries={anilistEntries ?? []}
group={group}
groupBusy={groupBusyTargetId !== null}
onMoveToGroup={() => {
setGroupError(null);
setShowGroupPicker(true);
}}
onSetGroupMode={(mode) => void applyGroupOverride({ mode }, animeId)}
coverRetryToken={coverRetryToken} coverRetryToken={coverRetryToken}
onChangeAnilist={() => setShowAnilistSelector(true)} onChangeAnilist={() => setShowAnilistSelector(true)}
onChangeTmdb={() => setShowTmdbSelector(true)} onChangeTmdb={() => setShowTmdbSelector(true)}
@@ -226,6 +274,25 @@ export function AnimeDetailView({
isDeletingAnime={isDeletingAnime} isDeletingAnime={isDeletingAnime}
/> />
{deleteError ? <div className="text-sm text-ctp-red">{deleteError}</div> : null} {deleteError ? <div className="text-sm text-ctp-red">{deleteError}</div> : null}
{groupError && !showGroupPicker ? (
<div role="alert" className="text-sm text-ctp-red">
{groupError}
</div>
) : null}
{showGroupPicker && (
<LibraryEntryPicker
heading="Move to another anime"
mediaKind="anime"
excludeAnimeIds={[animeId]}
filter={(entry) => entry.anilistId !== null}
busyAnimeId={groupBusyTargetId}
error={groupError}
onSelect={(entry) =>
void applyGroupOverride({ mode: 'join', targetAnimeId: entry.animeId }, entry.animeId)
}
onClose={() => setShowGroupPicker(false)}
/>
)}
<AnimeOverviewStats detail={detail} knownWordsSummary={knownWordsSummary} /> <AnimeOverviewStats detail={detail} knownWordsSummary={knownWordsSummary} />
<EpisodeList <EpisodeList
episodes={episodes} episodes={episodes}
@@ -0,0 +1,87 @@
import { describeAnimePart } from '../../lib/anime-groups';
import { formatDuration, formatNumber, formatRelativeDate } from '../../lib/formatters';
import type { AnimeLibraryGroup } from '../../types/stats';
import { AnimeCoverImage } from './AnimeCoverImage';
interface AnimeGroupViewProps {
group: AnimeLibraryGroup;
onBack: () => void;
onOpenPart: (animeId: number) => void;
}
/** A franchise card opened: its library entries in release order, each opening its own page. */
export function AnimeGroupView({ group, onBack, onOpenPart }: AnimeGroupViewProps) {
const cover = group.parts.find((part) => part.animeId === group.coverAnimeId) ?? group.parts[0]!;
return (
<div className="space-y-4">
<button
type="button"
onClick={onBack}
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
>
&larr; Back to Library
</button>
<div className="flex gap-4">
<AnimeCoverImage
animeId={cover.animeId}
title={group.title}
coverRetryToken={cover.anilistId ?? 0}
className="w-32 h-44 rounded-lg shrink-0"
/>
<div className="flex-1 min-w-0">
<h2 className="text-lg font-bold text-ctp-text truncate">{group.title}</h2>
<div className="text-sm text-ctp-subtext0 mt-2">
{group.parts.length} parts · {group.episodeCount} episode
{group.episodeCount !== 1 ? 's' : ''}
</div>
<div className="text-xs text-ctp-overlay2 mt-1">
{formatDuration(group.totalActiveMs)} · {formatNumber(group.totalCards)} cards
{group.lastWatchedMs > 0
? ` · last watched ${formatRelativeDate(group.lastWatchedMs)}`
: ''}
</div>
<p className="text-xs text-ctp-overlay2 mt-3 leading-relaxed">
Grouped by AniList&apos;s season, movie and side-story links. Open a part to move it to
another anime or show it on its own.
</p>
</div>
</div>
<div className="bg-ctp-surface0 border border-ctp-surface1 rounded-lg p-4">
<h3 className="text-sm font-semibold text-ctp-text mb-3">Seasons and Movies</h3>
<ul className="space-y-1">
{group.parts.map((part) => {
const kind = describeAnimePart(part.format, part.startDate);
return (
<li key={part.animeId}>
<button
type="button"
onClick={() => onOpenPart(part.animeId)}
className="w-full flex items-center gap-3 p-2.5 rounded-lg hover:bg-ctp-surface1 transition-colors text-left"
>
<AnimeCoverImage
animeId={part.animeId}
title={part.canonicalTitle}
coverRetryToken={part.anilistId ?? part.tmdbId ?? 0}
className="w-10 h-14 rounded shrink-0"
/>
<div className="min-w-0 flex-1">
<div className="text-sm text-ctp-text truncate">{part.canonicalTitle}</div>
<div className="text-xs text-ctp-overlay2 mt-0.5">
{kind ? `${kind} · ` : ''}
{part.episodeCount} episode{part.episodeCount !== 1 ? 's' : ''}
</div>
</div>
<div className="text-xs text-ctp-overlay2 text-right shrink-0">
<div>{formatDuration(part.totalActiveMs)}</div>
<div>{formatNumber(part.totalCards)} cards</div>
</div>
</button>
</li>
);
})}
</ul>
</div>
</div>
);
}
@@ -0,0 +1,178 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { apiClient } from '../../lib/api-client';
import type {
AnimeDetailData,
AnimeLibraryGroup,
AnimeLibraryGroupPart,
StatsAnimeGroupOverrideRequest,
} from '../../types/stats';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
function part(
animeId: number,
title: string,
format: string,
startDate: number,
): AnimeLibraryGroupPart {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: title,
anilistId: animeId * 100,
tmdbId: null,
tmdbType: null,
totalSessions: 1,
totalActiveMs: 60_000,
totalCards: 2,
totalTokensSeen: 0,
episodeCount: format === 'MOVIE' ? 1 : 13,
episodesTotal: null,
lastWatchedMs: animeId,
format,
startDate,
};
}
const overlord: AnimeLibraryGroup = {
groupKey: 20832,
title: 'Overlord',
mediaKind: 'anime',
coverAnimeId: 2,
totalSessions: 2,
totalActiveMs: 120_000,
totalCards: 4,
totalTokensSeen: 0,
episodeCount: 14,
lastWatchedMs: 2,
parts: [part(2, 'The Undead King', 'MOVIE', 20170225), part(1, 'Overlord II', 'TV', 20180109)],
};
function detailData(): AnimeDetailData {
const {
format: _format,
startDate: _startDate,
episodesTotal: _total,
...item
} = part(1, 'Overlord II', 'TV', 20180109);
return {
detail: {
...item,
titleRomaji: null,
titleEnglish: null,
titleNative: null,
description: null,
totalLinesSeen: 0,
totalLookupCount: 0,
totalLookupHits: 0,
totalYomitanLookupCount: 0,
},
episodes: [],
anilistEntries: [],
group: { groupKey: 20832, title: 'Overlord', partCount: 2, overrideMode: 'anilist' },
};
}
function findButton(container: Element, label: string): HTMLElement {
const match = [...container.querySelectorAll('button')].find((button) =>
(button.textContent ?? '').includes(label),
);
assert.ok(match, `expected a "${label}" button`);
return match as unknown as HTMLElement;
}
test('a franchise card opens its parts in release order, and a part can stand alone', async () => {
const uninstallDom = installDom();
const original = { ...apiClient };
const overrides: Array<[number, StatsAnimeGroupOverrideRequest]> = [];
let libraryFetches = 0;
apiClient.getAnimeLibraryGroups = async () => {
libraryFetches += 1;
return [overlord];
};
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
apiClient.getAnimeDetail = async () => detailData();
apiClient.getAnimeWords = async () => [];
apiClient.getAnimeRollups = async () => [];
apiClient.getAnimeKnownWordsSummary = async () => ({ totalUniqueWords: 0, knownWordCount: 0 });
apiClient.setAnimeGroupOverride = async (animeId, request) => {
overrides.push([animeId, request]);
};
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
try {
await act(async () => root.render(<AnimeTab />));
// One card for the franchise, counted once, with the first-released part's cover.
assert.match(container.textContent ?? '', /1 title/);
assert.match(findButton(container, 'Overlord').textContent ?? '', /2 parts/);
assert.match(container.querySelector('img')?.getAttribute('src') ?? '', /anime\/2\/cover/);
await act(async () => findButton(container, 'Overlord').click());
const rows = [...container.querySelectorAll('li button')].map((row) => row.textContent ?? '');
assert.equal(rows.length, 2);
assert.match(rows[0]!, /The Undead King.*Movie · 2017/);
assert.match(rows[1]!, /Overlord II.*TV · 2018/);
await act(async () => findButton(container, 'Overlord II').click());
assert.match(container.textContent ?? '', /Listed under Overlord with 1 other part/);
await act(async () => findButton(container, 'Show On Its Own').click());
assert.deepEqual(overrides, [[1, { mode: 'standalone' }]]);
assert.equal(libraryFetches, 2);
await act(async () => findButton(container, 'Back to Overlord').click());
assert.match(container.textContent ?? '', /Seasons and Movies/);
} finally {
await act(async () => root.unmount());
Object.assign(apiClient, original);
uninstallDom();
}
});
test('a franchise left with one part closes and does not reopen on a later refresh', async () => {
const uninstallDom = installDom();
const original = { ...apiClient };
const [movie, season] = overlord.parts as [AnimeLibraryGroupPart, AnimeLibraryGroupPart];
const split: AnimeLibraryGroup[] = [
{ ...overlord, parts: [movie], coverAnimeId: movie.animeId },
{ ...overlord, groupKey: 1, title: season.canonicalTitle, parts: [season], coverAnimeId: 1 },
];
let library: AnimeLibraryGroup[] = [overlord];
apiClient.getAnimeLibraryGroups = async () => library;
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
apiClient.getAnimeDetail = async () => detailData();
apiClient.getAnimeWords = async () => [];
apiClient.getAnimeRollups = async () => [];
apiClient.getAnimeKnownWordsSummary = async () => ({ totalUniqueWords: 0, knownWordCount: 0 });
apiClient.setAnimeGroupOverride = async () => {
library = split;
};
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
try {
await act(async () => root.render(<AnimeTab />));
await act(async () => findButton(container, 'Overlord').click());
await act(async () => findButton(container, 'Overlord II').click());
await act(async () => findButton(container, 'Show On Its Own').click());
await act(async () => findButton(container, 'Back to Overlord').click());
assert.doesNotMatch(container.textContent ?? '', /Seasons and Movies/);
// The franchise gets its second part back; the library must stay where it is.
library = [overlord];
await act(async () => {
window.dispatchEvent(new window.Event('focus'));
});
assert.match(findButton(container, 'Overlord').textContent ?? '', /2 parts/);
assert.doesNotMatch(container.textContent ?? '', /Seasons and Movies/);
} finally {
await act(async () => root.unmount());
Object.assign(apiClient, original);
uninstallDom();
}
});
+57 -1
View File
@@ -1,9 +1,17 @@
import { AnimeCoverImage } from './AnimeCoverImage'; import { AnimeCoverImage } from './AnimeCoverImage';
import type { AnimeDetailData, AnilistEntry } from '../../types/stats'; import type { AnimeDetailData, AnimeGroupPlacement, AnilistEntry } from '../../types/stats';
const SECONDARY_BUTTON_CLASS =
'inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-ctp-surface1 text-ctp-overlay2 hover:bg-ctp-surface2 hover:text-ctp-subtext0 transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
interface AnimeHeaderProps { interface AnimeHeaderProps {
detail: AnimeDetailData['detail']; detail: AnimeDetailData['detail'];
anilistEntries: AnilistEntry[]; anilistEntries: AnilistEntry[];
/** The franchise card this entry is listed under; null hides the grouping actions. */
group?: AnimeGroupPlacement | null;
onMoveToGroup?: () => void;
onSetGroupMode?: (mode: 'standalone' | 'anilist') => void;
groupBusy?: boolean;
coverRetryToken?: number; coverRetryToken?: number;
onChangeAnilist?: () => void; onChangeAnilist?: () => void;
onChangeTmdb?: () => void; onChangeTmdb?: () => void;
@@ -33,6 +41,10 @@ function AnilistButton({ entry }: { entry: AnilistEntry }) {
export function AnimeHeader({ export function AnimeHeader({
detail, detail,
anilistEntries, anilistEntries,
group = null,
onMoveToGroup,
onSetGroupMode,
groupBusy = false,
coverRetryToken = 0, coverRetryToken = 0,
onChangeAnilist, onChangeAnilist,
onChangeTmdb, onChangeTmdb,
@@ -52,6 +64,9 @@ export function AnimeHeader({
? `https://www.themoviedb.org/${detail.tmdbType}/${detail.tmdbId}` ? `https://www.themoviedb.org/${detail.tmdbType}/${detail.tmdbId}`
: null; : null;
const coverCacheToken = (detail.anilistId ?? detail.tmdbId ?? 0) * 1_000_000 + coverRetryToken; const coverCacheToken = (detail.anilistId ?? detail.tmdbId ?? 0) * 1_000_000 + coverRetryToken;
// Only anime entries are grouped by AniList relations.
const placement = detail.mediaKind === 'anime' ? group : null;
const otherParts = placement ? placement.partCount - 1 : 0;
return ( return (
<div className="flex gap-4"> <div className="flex gap-4">
@@ -80,6 +95,11 @@ export function AnimeHeader({
</span> </span>
)} )}
</div> </div>
{placement && otherParts > 0 && (
<div className="text-xs text-ctp-overlay2 mt-1">
Listed under {placement.title} with {otherParts} other part{otherParts !== 1 ? 's' : ''}
</div>
)}
<div className="flex flex-wrap gap-1.5 mt-2"> <div className="flex flex-wrap gap-1.5 mt-2">
{tmdbUrl && ( {tmdbUrl && (
<a <a
@@ -138,6 +158,42 @@ export function AnimeHeader({
{tmdbUrl ? 'Change TMDB Title' : 'Link to TMDB'} {tmdbUrl ? 'Change TMDB Title' : 'Link to TMDB'}
</button> </button>
)} )}
{placement && onMoveToGroup && (
<button
type="button"
onClick={onMoveToGroup}
disabled={groupBusy}
title="List this entry with another anime's seasons and movies"
className={SECONDARY_BUTTON_CLASS}
>
{'Move to Another Anime\u2026'}
</button>
)}
{placement && onSetGroupMode && placement.overrideMode !== 'anilist' && (
<button
type="button"
onClick={() => onSetGroupMode('anilist')}
disabled={groupBusy}
title="Undo a manual move and group this entry by its AniList relations"
className={SECONDARY_BUTTON_CLASS}
>
Put Back Where AniList Has It
</button>
)}
{placement &&
onSetGroupMode &&
placement.overrideMode === 'anilist' &&
otherParts > 0 && (
<button
type="button"
onClick={() => onSetGroupMode('standalone')}
disabled={groupBusy}
title="List this entry as its own card instead of with its franchise"
className={SECONDARY_BUTTON_CLASS}
>
Show On Its Own
</button>
)}
{onDeleteAnime && ( {onDeleteAnime && (
<button <button
type="button" type="button"
@@ -7,6 +7,7 @@ import type { AnimeLibraryItem, StatsMergeAnimeResponse } from '../../types/stat
import { AnimeMergeDialog } from './AnimeMergeDialog'; import { AnimeMergeDialog } from './AnimeMergeDialog';
import { AnimeTab } from './AnimeTab'; import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom'; import { installDom } from '../../test-utils/dom';
import { singleGroupLibrary } from '../../test-utils/library';
function libraryItem(animeId: number, title: string, episodeCount: number): AnimeLibraryItem { function libraryItem(animeId: number, title: string, episodeCount: number): AnimeLibraryItem {
return { return {
@@ -52,7 +53,7 @@ function mergeButton(container: Element): HTMLButtonElement {
test('AnimeTab merges the selected duplicate entries into the chosen keeper', async () => { test('AnimeTab merges the selected duplicate entries into the chosen keeper', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
mergeAnime: apiClient.mergeAnime, mergeAnime: apiClient.mergeAnime,
}; };
@@ -61,10 +62,10 @@ test('AnimeTab merges the selected duplicate entries into the chosen keeper', as
let libraryFetches = 0; let libraryFetches = 0;
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null; let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
apiClient.getAnimeLibrary = (async () => { apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1; libraryFetches += 1;
return entries; return entries;
}) as typeof apiClient.getAnimeLibrary; });
apiClient.mergeAnime = (async (targetAnimeId: number, sourceAnimeIds: number[]) => { apiClient.mergeAnime = (async (targetAnimeId: number, sourceAnimeIds: number[]) => {
mergeCall = { targetAnimeId, sourceAnimeIds }; mergeCall = { targetAnimeId, sourceAnimeIds };
entries = [libraryItem(1, 'Show', 3)]; entries = [libraryItem(1, 'Show', 3)];
@@ -181,7 +182,7 @@ test('AnimeMergeDialog refuses to merge an AniList entry with a TMDB entry', asy
test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merged', async () => { test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merged', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation, dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
mergeAnime: apiClient.mergeAnime, mergeAnime: apiClient.mergeAnime,
@@ -191,7 +192,7 @@ test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merg
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] }]; let recommendations = [{ recommendationId: 41, animeIds: [1, 2] }];
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null; let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
apiClient.getAnimeLibrary = (async () => entries) as typeof apiClient.getAnimeLibrary; apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => entries);
apiClient.getAnimeMergeRecommendations = (async () => ({ apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations, recommendations,
})) as typeof apiClient.getAnimeMergeRecommendations; })) as typeof apiClient.getAnimeMergeRecommendations;
@@ -252,16 +253,16 @@ test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merg
test('AnimeTab dismisses a false-positive duplicate recommendation', async () => { test('AnimeTab dismisses a false-positive duplicate recommendation', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation, dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
}; };
let dismissedId: number | null = null; let dismissedId: number | null = null;
apiClient.getAnimeLibrary = (async () => [ apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2), libraryItem(1, 'Show', 2),
libraryItem(2, 'Different Show', 1), libraryItem(2, 'Different Show', 1),
]) as typeof apiClient.getAnimeLibrary; ]);
apiClient.getAnimeMergeRecommendations = (async () => ({ apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [{ recommendationId: 73, animeIds: [1, 2] }], recommendations: [{ recommendationId: 73, animeIds: [1, 2] }],
})) as typeof apiClient.getAnimeMergeRecommendations; })) as typeof apiClient.getAnimeMergeRecommendations;
@@ -291,16 +292,16 @@ test('AnimeTab dismisses a false-positive duplicate recommendation', async () =>
test('AnimeTab refreshes the library and recommendations when the window regains focus', async () => { test('AnimeTab refreshes the library and recommendations when the window regains focus', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
}; };
let entries = [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)]; let entries = [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
let libraryFetches = 0; let libraryFetches = 0;
let recommendationFetches = 0; let recommendationFetches = 0;
apiClient.getAnimeLibrary = (async () => { apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1; libraryFetches += 1;
return entries; return entries;
}) as typeof apiClient.getAnimeLibrary; });
apiClient.getAnimeMergeRecommendations = (async () => { apiClient.getAnimeMergeRecommendations = (async () => {
recommendationFetches += 1; recommendationFetches += 1;
return { recommendations: [] }; return { recommendations: [] };
@@ -330,14 +331,14 @@ test('AnimeTab refreshes the library and recommendations when the window regains
test('AnimeTab keeps a recommendation visible through a transient refresh failure', async () => { test('AnimeTab keeps a recommendation visible through a transient refresh failure', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
}; };
let failRecommendations = false; let failRecommendations = false;
apiClient.getAnimeLibrary = (async () => [ apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2), libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1), libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary; ]);
apiClient.getAnimeMergeRecommendations = (async () => { apiClient.getAnimeMergeRecommendations = (async () => {
if (failRecommendations) throw new Error('temporary failure'); if (failRecommendations) throw new Error('temporary failure');
return { recommendations: [{ recommendationId: 41, animeIds: [1, 2] }] }; return { recommendations: [{ recommendationId: 41, animeIds: [1, 2] }] };
@@ -364,14 +365,14 @@ test('AnimeTab keeps a recommendation visible through a transient refresh failur
test('AnimeTab retains a recommendation and reports a failed dismissal', async () => { test('AnimeTab retains a recommendation and reports a failed dismissal', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation, dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
}; };
apiClient.getAnimeLibrary = (async () => [ apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2), libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1), libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary; ]);
apiClient.getAnimeMergeRecommendations = (async () => ({ apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [{ recommendationId: 41, animeIds: [1, 2] }], recommendations: [{ recommendationId: 41, animeIds: [1, 2] }],
})) as typeof apiClient.getAnimeMergeRecommendations; })) as typeof apiClient.getAnimeMergeRecommendations;
@@ -399,14 +400,14 @@ test('AnimeTab retains a recommendation and reports a failed dismissal', async (
test('AnimeTab keeps an open recommendation review stable during background refresh', async () => { test('AnimeTab keeps an open recommendation review stable during background refresh', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
}; };
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] as [number, number] }]; let recommendations = [{ recommendationId: 41, animeIds: [1, 2] as [number, number] }];
apiClient.getAnimeLibrary = (async () => [ apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2), libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1), libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary; ]);
apiClient.getAnimeMergeRecommendations = (async () => ({ apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations, recommendations,
})) as typeof apiClient.getAnimeMergeRecommendations; })) as typeof apiClient.getAnimeMergeRecommendations;
@@ -434,14 +435,14 @@ test('AnimeTab keeps an open recommendation review stable during background refr
test('AnimeTab keeps the library visible through a transient background refresh failure', async () => { test('AnimeTab keeps the library visible through a transient background refresh failure', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
}; };
let failLibrary = false; let failLibrary = false;
apiClient.getAnimeLibrary = (async () => { apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
if (failLibrary) throw new Error('temporary failure'); if (failLibrary) throw new Error('temporary failure');
return [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)]; return [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
}) as typeof apiClient.getAnimeLibrary; });
apiClient.getAnimeMergeRecommendations = (async () => ({ apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [], recommendations: [],
})) as typeof apiClient.getAnimeMergeRecommendations; })) as typeof apiClient.getAnimeMergeRecommendations;
@@ -470,7 +471,7 @@ test('AnimeTab keeps the library visible through a transient background refresh
test('AnimeTab does not resurrect a dismissed recommendation from a stale in-flight refresh', async () => { test('AnimeTab does not resurrect a dismissed recommendation from a stale in-flight refresh', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation, dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
}; };
@@ -479,10 +480,10 @@ test('AnimeTab does not resurrect a dismissed recommendation from a stale in-fli
}; };
let holdNextFetch = false; let holdNextFetch = false;
let releaseHeldFetch: (() => void) | null = null; let releaseHeldFetch: (() => void) | null = null;
apiClient.getAnimeLibrary = (async () => [ apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2), libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1), libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary; ]);
apiClient.getAnimeMergeRecommendations = ((): Promise<typeof payload> => { apiClient.getAnimeMergeRecommendations = ((): Promise<typeof payload> => {
if (!holdNextFetch) return Promise.resolve(payload); if (!holdNextFetch) return Promise.resolve(payload);
holdNextFetch = false; holdNextFetch = false;
+12 -10
View File
@@ -6,6 +6,7 @@ import { apiClient } from '../../lib/api-client';
import type { AnimeDetailData, AnimeLibraryItem } from '../../types/stats'; import type { AnimeDetailData, AnimeLibraryItem } from '../../types/stats';
import { AnimeTab } from './AnimeTab'; import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom'; import { installDom } from '../../test-utils/dom';
import { singleGroupLibrary } from '../../test-utils/library';
function libraryItem(anilistId: number | null): AnimeLibraryItem { function libraryItem(anilistId: number | null): AnimeLibraryItem {
return { return {
@@ -51,6 +52,7 @@ function detailData(anilistId: number | null): AnimeDetailData {
}, },
episodes: [], episodes: [],
anilistEntries: [], anilistEntries: [],
group: null,
}; };
} }
@@ -65,7 +67,7 @@ function findButton(container: Element, label: string): HTMLElement {
test('AnimeTab refetches the library after the AniList entry is relinked', async () => { test('AnimeTab refetches the library after the AniList entry is relinked', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeDetail: apiClient.getAnimeDetail, getAnimeDetail: apiClient.getAnimeDetail,
getAnimeWords: apiClient.getAnimeWords, getAnimeWords: apiClient.getAnimeWords,
getAnimeRollups: apiClient.getAnimeRollups, getAnimeRollups: apiClient.getAnimeRollups,
@@ -79,10 +81,10 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
let anilistId: number | null = 14813; let anilistId: number | null = 14813;
let libraryFetches = 0; let libraryFetches = 0;
apiClient.getAnimeLibrary = (async () => { apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1; libraryFetches += 1;
return [libraryItem(anilistId)]; return [libraryItem(anilistId)];
}) as typeof apiClient.getAnimeLibrary; });
apiClient.getAnimeDetail = (async () => detailData(anilistId)) as typeof apiClient.getAnimeDetail; apiClient.getAnimeDetail = (async () => detailData(anilistId)) as typeof apiClient.getAnimeDetail;
apiClient.getAnimeWords = (async () => []) as typeof apiClient.getAnimeWords; apiClient.getAnimeWords = (async () => []) as typeof apiClient.getAnimeWords;
apiClient.getAnimeRollups = (async () => []) as typeof apiClient.getAnimeRollups; apiClient.getAnimeRollups = (async () => []) as typeof apiClient.getAnimeRollups;
@@ -150,8 +152,8 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
test('AnimeTab watch time follows the displayed kind filter', async () => { test('AnimeTab watch time follows the displayed kind filter', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = apiClient.getAnimeLibrary; const original = apiClient.getAnimeLibraryGroups;
apiClient.getAnimeLibrary = async () => [ apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
{ ...libraryItem(42), totalActiveMs: 3600000 }, { ...libraryItem(42), totalActiveMs: 3600000 },
{ {
...libraryItem(null), ...libraryItem(null),
@@ -162,7 +164,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
tmdbType: 'tv', tmdbType: 'tv',
totalActiveMs: 7200000, totalActiveMs: 7200000,
}, },
]; ]);
const container = document.createElement('div'); const container = document.createElement('div');
document.body.append(container); document.body.append(container);
const root = createRoot(container); const root = createRoot(container);
@@ -180,7 +182,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
await act(async () => { await act(async () => {
root.unmount(); root.unmount();
}); });
apiClient.getAnimeLibrary = original; apiClient.getAnimeLibraryGroups = original;
uninstallDom(); uninstallDom();
} }
}); });
@@ -188,10 +190,10 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
test('Library kind filter separates YouTube channels from anime and updates totals', async () => { test('Library kind filter separates YouTube channels from anime and updates totals', async () => {
const uninstallDom = installDom(); const uninstallDom = installDom();
const original = { const original = {
getAnimeLibrary: apiClient.getAnimeLibrary, getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations, getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
}; };
apiClient.getAnimeLibrary = async () => [ apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
{ ...libraryItem(null), totalActiveMs: 60_000 }, { ...libraryItem(null), totalActiveMs: 60_000 },
{ {
...libraryItem(null), ...libraryItem(null),
@@ -200,7 +202,7 @@ test('Library kind filter separates YouTube channels from anime and updates tota
canonicalTitle: 'Language Channel', canonicalTitle: 'Language Channel',
totalActiveMs: 120_000, totalActiveMs: 120_000,
}, },
]; ]);
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] }); apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
const container = document.createElement('div'); const container = document.createElement('div');
document.body.append(container); document.body.append(container);
+72 -9
View File
@@ -5,6 +5,7 @@ import {
} from '../../../../src/shared/media-kind'; } from '../../../../src/shared/media-kind';
import { useState, useMemo, useEffect } from 'react'; import { useState, useMemo, useEffect } from 'react';
import { useAnimeLibrary } from '../../hooks/useAnimeLibrary'; import { useAnimeLibrary } from '../../hooks/useAnimeLibrary';
import { groupCardData, groupMatchesSearch } from '../../lib/anime-groups';
import { formatDuration } from '../../lib/formatters'; import { formatDuration } from '../../lib/formatters';
import { import {
getLibraryCardSizeStorage, getLibraryCardSizeStorage,
@@ -14,6 +15,7 @@ import {
} from '../../lib/library-card-size'; } from '../../lib/library-card-size';
import { AnimeCard } from './AnimeCard'; import { AnimeCard } from './AnimeCard';
import { AnimeDetailView } from './AnimeDetailView'; import { AnimeDetailView } from './AnimeDetailView';
import { AnimeGroupView } from './AnimeGroupView';
import { AnimeMergeDialog } from './AnimeMergeDialog'; import { AnimeMergeDialog } from './AnimeMergeDialog';
import { DuplicateReviewStrip } from './DuplicateReviewStrip'; import { DuplicateReviewStrip } from './DuplicateReviewStrip';
@@ -39,7 +41,14 @@ const SORT_OPTIONS: { key: SortKey; label: string }[] = [
{ key: 'episodes', label: 'Episodes' }, { key: 'episodes', label: 'Episodes' },
]; ];
function sortAnime(list: ReturnType<typeof useAnimeLibrary>['anime'], key: SortKey) { interface SortableEntry {
lastWatchedMs: number;
totalActiveMs: number;
totalCards: number;
episodeCount: number;
}
function sortAnime<T extends SortableEntry>(list: T[], key: SortKey): T[] {
return [...list].sort((a, b) => { return [...list].sort((a, b) => {
switch (key) { switch (key) {
case 'lastWatched': case 'lastWatched':
@@ -68,6 +77,7 @@ export function AnimeTab({
onOpenEpisodeDetail, onOpenEpisodeDetail,
}: AnimeTabProps) { }: AnimeTabProps) {
const { const {
groups,
anime, anime,
loading, loading,
error, error,
@@ -87,6 +97,8 @@ export function AnimeTab({
), ),
); );
const [selectedAnimeId, setSelectedAnimeId] = useState<number | null>(null); const [selectedAnimeId, setSelectedAnimeId] = useState<number | null>(null);
// Franchise card that is open, and stays the back target while one of its parts is open.
const [selectedGroupKey, setSelectedGroupKey] = useState<number | null>(null);
const [selectionMode, setSelectionMode] = useState(false); const [selectionMode, setSelectionMode] = useState(false);
const [checkedAnimeIds, setCheckedAnimeIds] = useState<number[]>([]); const [checkedAnimeIds, setCheckedAnimeIds] = useState<number[]>([]);
const [showMergeDialog, setShowMergeDialog] = useState(false); const [showMergeDialog, setShowMergeDialog] = useState(false);
@@ -115,11 +127,14 @@ export function AnimeTab({
useEffect(() => { useEffect(() => {
if (initialAnimeId != null) { if (initialAnimeId != null) {
setSelectedGroupKey(null);
setSelectedAnimeId(initialAnimeId); setSelectedAnimeId(initialAnimeId);
onClearInitialAnime?.(); onClearInitialAnime?.();
} }
}, [initialAnimeId, onClearInitialAnime]); }, [initialAnimeId, onClearInitialAnime]);
// Merging works on individual entries, so selection mode lists every entry
// on its own; browsing lists one card per franchise.
const filtered = useMemo(() => { const filtered = useMemo(() => {
const entries = anime.filter((entry) => mediaKind === 'all' || entry.mediaKind === mediaKind); const entries = anime.filter((entry) => mediaKind === 'all' || entry.mediaKind === mediaKind);
const base = search.trim() const base = search.trim()
@@ -127,8 +142,32 @@ export function AnimeTab({
: entries; : entries;
return sortAnime(base, sortKey); return sortAnime(base, sortKey);
}, [anime, search, sortKey, mediaKind]); }, [anime, search, sortKey, mediaKind]);
const filteredGroups = useMemo(
() =>
sortAnime(
groups.filter(
(group) =>
(mediaKind === 'all' || group.mediaKind === mediaKind) &&
groupMatchesSearch(group, search),
),
sortKey,
),
[groups, search, sortKey, mediaKind],
);
const shownCount = selectionMode ? filtered.length : filteredGroups.length;
const totalMs = filtered.reduce((sum, a) => sum + a.totalActiveMs, 0); const totalMs = (selectionMode ? filtered : filteredGroups).reduce(
(sum, entry) => sum + entry.totalActiveMs,
0,
);
const selectedGroup = groups.find((group) => group.groupKey === selectedGroupKey) ?? null;
// A franchise that no longer has several parts closes, so a later refresh
// cannot reopen it on its own. Only loaded results count; while a part is
// open, the franchise stays its back target.
useEffect(() => {
if (loading || selectedGroupKey === null || selectedAnimeId !== null) return;
if (!selectedGroup || selectedGroup.parts.length < 2) setSelectedGroupKey(null);
}, [loading, selectedGroupKey, selectedAnimeId, selectedGroup]);
const checkedEntries = checkedAnimeIds const checkedEntries = checkedAnimeIds
.map((animeId) => anime.find((entry) => entry.animeId === animeId)) .map((animeId) => anime.find((entry) => entry.animeId === animeId))
.filter((entry): entry is (typeof anime)[number] => entry !== undefined); .filter((entry): entry is (typeof anime)[number] => entry !== undefined);
@@ -160,6 +199,7 @@ export function AnimeTab({
return ( return (
<AnimeDetailView <AnimeDetailView
animeId={selectedAnimeId} animeId={selectedAnimeId}
backLabel={selectedGroup ? `Back to ${selectedGroup.title}` : undefined}
onBack={() => setSelectedAnimeId(null)} onBack={() => setSelectedAnimeId(null)}
onNavigateToWord={onNavigateToWord} onNavigateToWord={onNavigateToWord}
onOpenEpisodeDetail={ onOpenEpisodeDetail={
@@ -170,6 +210,17 @@ export function AnimeTab({
onAnimeDeleted={reload} onAnimeDeleted={reload}
onProviderRelinked={reload} onProviderRelinked={reload}
onEpisodeMoved={reload} onEpisodeMoved={reload}
onGroupChanged={reload}
/>
);
}
if (selectedGroup && selectedGroup.parts.length > 1) {
return (
<AnimeGroupView
group={selectedGroup}
onBack={() => setSelectedGroupKey(null)}
onOpenPart={setSelectedAnimeId}
/> />
); );
} }
@@ -250,12 +301,12 @@ export function AnimeTab({
{selectionMode ? 'Cancel' : 'Select'} {selectionMode ? 'Cancel' : 'Select'}
</button> </button>
<div className="text-xs text-ctp-overlay2 shrink-0"> <div className="text-xs text-ctp-overlay2 shrink-0">
{filtered.length}{' '} {shownCount}{' '}
{mediaKind === 'youtube' {mediaKind === 'youtube'
? filtered.length === 1 ? shownCount === 1
? 'channel' ? 'channel'
: 'channels' : 'channels'
: filtered.length === 1 : shownCount === 1
? 'title' ? 'title'
: 'titles'}{' '} : 'titles'}{' '}
· {formatDuration(totalMs)} · {formatDuration(totalMs)}
@@ -298,18 +349,30 @@ export function AnimeTab({
</div> </div>
)} )}
{filtered.length === 0 ? ( {shownCount === 0 ? (
<div className="text-sm text-ctp-overlay2 p-4">No titles found</div> <div className="text-sm text-ctp-overlay2 p-4">No titles found</div>
) : ( ) : selectionMode ? (
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}> <div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
{filtered.map((item) => ( {filtered.map((item) => (
<AnimeCard <AnimeCard
key={item.animeId} key={item.animeId}
anime={item} anime={item}
selectable={selectionMode} selectable
selected={checkedAnimeIds.includes(item.animeId)} selected={checkedAnimeIds.includes(item.animeId)}
onClick={() => toggleChecked(item.animeId)}
/>
))}
</div>
) : (
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
{filteredGroups.map((group) => (
<AnimeCard
key={group.groupKey}
anime={groupCardData(group)}
onClick={() => onClick={() =>
selectionMode ? toggleChecked(item.animeId) : setSelectedAnimeId(item.animeId) group.parts.length > 1
? setSelectedGroupKey(group.groupKey)
: setSelectedAnimeId(group.parts[0]!.animeId)
} }
/> />
))} ))}
@@ -12,6 +12,8 @@ interface LibraryEntryPickerProps {
excludeAnimeIds?: number[]; excludeAnimeIds?: number[];
/** When set, only entries of this kind are offered. */ /** When set, only entries of this kind are offered. */
mediaKind?: MediaKind; mediaKind?: MediaKind;
/** Further narrows the entries offered. */
filter?: (entry: AnimeLibraryItem) => boolean;
initialQuery?: string; initialQuery?: string;
busyAnimeId?: number | null; busyAnimeId?: number | null;
error?: string | null; error?: string | null;
@@ -23,6 +25,7 @@ export function LibraryEntryPicker({
heading, heading,
excludeAnimeIds = [], excludeAnimeIds = [],
mediaKind, mediaKind,
filter,
initialQuery = '', initialQuery = '',
busyAnimeId = null, busyAnimeId = null,
error = null, error = null,
@@ -74,9 +77,10 @@ export function LibraryEntryPicker({
return (entries ?? []) return (entries ?? [])
.filter((entry) => !excluded.has(entry.animeId)) .filter((entry) => !excluded.has(entry.animeId))
.filter((entry) => mediaKind === undefined || shareTitleNamespace(entry.mediaKind, mediaKind)) .filter((entry) => mediaKind === undefined || shareTitleNamespace(entry.mediaKind, mediaKind))
.filter((entry) => filter === undefined || filter(entry))
.filter((entry) => !term || entry.canonicalTitle.toLowerCase().includes(term)) .filter((entry) => !term || entry.canonicalTitle.toLowerCase().includes(term))
.sort((a, b) => b.lastWatchedMs - a.lastWatchedMs); .sort((a, b) => b.lastWatchedMs - a.lastWatchedMs);
}, [entries, excluded, mediaKind, query]); }, [entries, excluded, mediaKind, filter, query]);
return ( return (
<div <div
+11 -5
View File
@@ -1,11 +1,16 @@
import { useCallback, useState, useEffect, useRef } from 'react'; import { useCallback, useMemo, useState, useEffect, useRef } from 'react';
import { getStatsClient } from './useStatsApi'; import { getStatsClient } from './useStatsApi';
import type { AnimeLibraryItem, StatsAnimeMergeRecommendation } from '../types/stats'; import type { AnimeLibraryGroup, StatsAnimeMergeRecommendation } from '../types/stats';
const BACKGROUND_REFRESH_MS = 30_000; const BACKGROUND_REFRESH_MS = 30_000;
/**
* The library as franchise cards (`groups`) plus every entry on its own
* (`anime`), which merging and duplicate review work on.
*/
export function useAnimeLibrary() { export function useAnimeLibrary() {
const [anime, setAnime] = useState<AnimeLibraryItem[]>([]); const [groups, setGroups] = useState<AnimeLibraryGroup[]>([]);
const anime = useMemo(() => groups.flatMap((group) => group.parts), [groups]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [recommendations, setRecommendations] = useState<StatsAnimeMergeRecommendation[]>([]); const [recommendations, setRecommendations] = useState<StatsAnimeMergeRecommendation[]>([]);
@@ -29,11 +34,11 @@ export function useAnimeLibrary() {
let cancelled = false; let cancelled = false;
const client = getStatsClient(); const client = getStatsClient();
client client
.getAnimeLibrary() .getAnimeLibraryGroups()
.then((data) => { .then((data) => {
if (!cancelled) { if (!cancelled) {
hasLoadedRef.current = true; hasLoadedRef.current = true;
setAnime(data); setGroups(data);
setError(null); setError(null);
} }
}) })
@@ -103,6 +108,7 @@ export function useAnimeLibrary() {
}, []); }, []);
return { return {
groups,
anime, anime,
loading, loading,
error, error,
+62
View File
@@ -0,0 +1,62 @@
import type { AnimeLibraryGroup, AnimeLibraryItem } from '../types/stats';
/** What a library card shows; a single entry or a whole franchise. */
export type AnimeCardData = Pick<
AnimeLibraryItem,
| 'animeId'
| 'canonicalTitle'
| 'anilistId'
| 'tmdbId'
| 'mediaKind'
| 'episodeCount'
| 'totalActiveMs'
| 'totalCards'
> & {
/** Set for franchise cards with more than one part. */
partCount?: number;
};
/** A one-part card is exactly that entry; a franchise card shows the first part's cover. */
export function groupCardData(group: AnimeLibraryGroup): AnimeCardData {
const cover = group.parts.find((part) => part.animeId === group.coverAnimeId) ?? group.parts[0]!;
if (group.parts.length === 1) return cover;
return {
animeId: cover.animeId,
canonicalTitle: group.title,
anilistId: cover.anilistId,
tmdbId: cover.tmdbId,
mediaKind: group.mediaKind,
episodeCount: group.episodeCount,
totalActiveMs: group.totalActiveMs,
totalCards: group.totalCards,
partCount: group.parts.length,
};
}
/** Matches the franchise name or any part's title, so "Undead King" finds Overlord. */
export function groupMatchesSearch(group: AnimeLibraryGroup, search: string): boolean {
const term = search.trim().toLowerCase();
if (!term) return true;
return (
group.title.toLowerCase().includes(term) ||
group.parts.some((part) => part.canonicalTitle.toLowerCase().includes(term))
);
}
const FORMAT_LABELS: Record<string, string> = {
TV: 'TV',
TV_SHORT: 'TV Short',
MOVIE: 'Movie',
SPECIAL: 'Special',
OVA: 'OVA',
ONA: 'ONA',
MUSIC: 'Music',
};
/** "Movie · 2017" from AniList's format and yyyymmdd start date; null when neither is known. */
export function describeAnimePart(format: string | null, startDate: number | null): string | null {
const label = format ? (FORMAT_LABELS[format] ?? format) : null;
const year = startDate ? String(Math.floor(startDate / 10_000)) : null;
const parts = [label, year].filter((value): value is string => value !== null);
return parts.length > 0 ? parts.join(' · ') : null;
}
+12
View File
@@ -3,6 +3,7 @@ import type {
StatsExcludedWord, StatsExcludedWord,
StatsCoverImagesData, StatsCoverImagesData,
StatsAnilistAssignment, StatsAnilistAssignment,
StatsAnimeGroupOverrideRequest,
StatsAnkiNotesInfoRequest, StatsAnkiNotesInfoRequest,
StatsCoverImagesRequest, StatsCoverImagesRequest,
StatsDeleteSessionsRequest, StatsDeleteSessionsRequest,
@@ -163,6 +164,7 @@ export const apiClient = {
getMediaLibrary: () => fetchJson('mediaLibrary', '/api/stats/media'), getMediaLibrary: () => fetchJson('mediaLibrary', '/api/stats/media'),
getMediaDetail: (videoId: number) => fetchJson('mediaDetail', `/api/stats/media/${videoId}`), getMediaDetail: (videoId: number) => fetchJson('mediaDetail', `/api/stats/media/${videoId}`),
getAnimeLibrary: () => fetchJson('animeLibrary', '/api/stats/anime'), getAnimeLibrary: () => fetchJson('animeLibrary', '/api/stats/anime'),
getAnimeLibraryGroups: () => fetchJson('animeLibraryGroups', '/api/stats/anime/groups'),
getAnimeMergeRecommendations: () => getAnimeMergeRecommendations: () =>
fetchJson('animeMergeRecommendations', '/api/stats/anime/merge-recommendations'), fetchJson('animeMergeRecommendations', '/api/stats/anime/merge-recommendations'),
getAnimeDetail: (animeId: number) => fetchJson('animeDetail', `/api/stats/anime/${animeId}`), getAnimeDetail: (animeId: number) => fetchJson('animeDetail', `/api/stats/anime/${animeId}`),
@@ -268,6 +270,16 @@ export const apiClient = {
}); });
return res.json() as Promise<StatsMoveVideoResponse>; return res.json() as Promise<StatsMoveVideoResponse>;
}, },
setAnimeGroupOverride: async (
animeId: number,
request: StatsAnimeGroupOverrideRequest,
): Promise<void> => {
await fetchResponse(`/api/stats/anime/${animeId}/group`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request satisfies StatsAnimeGroupOverrideRequest),
});
},
dismissAnimeMergeRecommendation: async (recommendationId: number): Promise<void> => { dismissAnimeMergeRecommendation: async (recommendationId: number): Promise<void> => {
await fetchResponse(`/api/stats/anime/merge-recommendations/${recommendationId}`, { await fetchResponse(`/api/stats/anime/merge-recommendations/${recommendationId}`, {
method: 'DELETE', method: 'DELETE',
+26
View File
@@ -0,0 +1,26 @@
import type { apiClient } from '../lib/api-client';
import type { AnimeLibraryGroup, AnimeLibraryItem } from '../types/stats';
/** Wraps each entry in a one-part card, as the server does for entries without AniList relations. */
export function asSingleGroups(items: AnimeLibraryItem[]): AnimeLibraryGroup[] {
return items.map((item) => ({
groupKey: -item.animeId,
title: item.canonicalTitle,
mediaKind: item.mediaKind,
coverAnimeId: item.animeId,
totalSessions: item.totalSessions,
totalActiveMs: item.totalActiveMs,
totalCards: item.totalCards,
totalTokensSeen: item.totalTokensSeen,
episodeCount: item.episodeCount,
lastWatchedMs: item.lastWatchedMs,
parts: [{ ...item, format: null, startDate: null }],
}));
}
/** A `getAnimeLibraryGroups` mock serving `load()`'s entries as one-part cards. */
export function singleGroupLibrary(
load: () => Promise<AnimeLibraryItem[]>,
): typeof apiClient.getAnimeLibraryGroups {
return async () => asSingleGroups(await load());
}