feat(stats): group library seasons, movies and OVAs into franchise cards (#336)

This commit is contained in:
sudacode authored and GitHub committed 2026-11-22 21:03:23 -08:00
1 parent 9d2057cc30
commit 71251b8d7b
41 files changed
+2335 -109

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
type: added
area: stats
- Library lists each anime once: seasons, movies, and OVAs that AniList links as sequels, prequels, side stories, summaries, or compilations share one card, named after the first TV series. Opening it lists the parts in release order with their own stats. Spin-offs and alternative versions keep their own cards.
- A title's page has **Move to Another Anime…**, **Show On Its Own**, and **Put Back Where AniList Has It** to correct the grouping. `subminer sync` keeps the most recent choice.
+6 -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.
Seasons get separate cards when a season number is detected. Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
Seasons, movies, and OVAs of one anime share a card. SubMiner follows AniList's sequel, prequel, parent, side-story, summary, and compilation links, including through entries you have not watched, so two films can meet at a TV series you never played. Spin-offs and alternative versions keep their own cards. A shared card is named after the anime's first TV series, shows the cover of the earliest part you have, and opens to a list of its parts in release order. Relations come from AniList in the background and refresh weekly, so a newly linked show can take a minute to join its card.
If a part lands on the wrong card, open it and choose **Move to Another Anime…** (the target must be linked to AniList) or **Show On Its Own**. **Put Back Where AniList Has It** undoes either. This only changes how the library is listed; duplicate entries for the same season still need a merge.
Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
The same show can end up on several cards when release names disagree. To fix that:
- Merge: click **Select**, tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
- Merge: click **Select** (the grid then lists every entry on its own), tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction.
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
+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
```
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.
+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`
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
Franchise grouping is a view over `imm_anime`, never a merge: `query-library-groups.ts` groups library rows by union-find over the AniList relation cache (`imm_anilist_media` + `imm_anilist_relations`, written by `anilist-relation-cache.ts`; pure graph and walk in `anilist/franchise-graph.ts`, where `FRANCHISE_RELATION_TYPES` is the joining set). `franchise-relation-refresher.ts` walks from owned AniList ids (bounded depth and fetches per run, 7-day staleness, shared AniList rate limiter) when the grouped library is read, after cover art links an id, and after manual AniList or group changes; a failed fetch leaves cached rows untouched. `imm_anime.group_override` (NULL = AniList, 0 = on its own, positive = join the franchise containing that AniList id) is the only user state; `/api/stats/anime/groups` and `PUT /api/stats/anime/:id/group` expose it.
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
`imm_anime.group_override` merges last-writer-wins on `group_override_updated_at` (clears carry a timestamp too); its values are AniList ids, so no id remapping. The AniList relation cache is not merged: each machine rebuilds it, and stale or partial remote cache rows would otherwise outlive the 7-day refresh.
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`. Every consumer maps a parsed title + season to an AniList entry through `anilist/season-resolver.ts` (sequel-chain walk; see its header for what counts as a season). Changing what it returns needs a `MEDIA_RESOLUTION_CACHE_VERSION` bump in `character-dictionary-runtime/cache.ts`, or old matches keep being served from `anilist-resolution-cache.json`.
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
+3 -1
View File
@@ -25,7 +25,9 @@ export const IMMERSION_DB_FIXTURE_DDL = `
tmdb_type TEXT,
metadata_json TEXT,
CREATED_DATE TEXT,
LAST_UPDATE_DATE TEXT
LAST_UPDATE_DATE TEXT,
group_override INTEGER,
group_override_updated_at TEXT
);
CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key);
CREATE TABLE imm_videos(
@@ -338,6 +338,7 @@ function createMockTracker(
hasAnime: async (animeId: number) => animeId === 1,
getAnimeEpisodes: async () => ANIME_EPISODES,
getAnimeAnilistEntries: async () => [],
getAnimeGroupPlacement: async () => null,
getAnimeWords: async () => ANIME_WORDS,
getAnimeDailyRollups: async () => DAILY_ROLLUPS,
getEpisodesPerDay: async () => EPISODES_PER_DAY,
@@ -712,7 +713,7 @@ const MALFORMED_IDS = [
/** Every route that takes a positive resource id; `:id` is replaced per request. */
const ID_ROUTES: Array<{
method: 'GET' | 'DELETE' | 'PATCH' | 'POST';
method: 'GET' | 'DELETE' | 'PATCH' | 'POST' | 'PUT';
path: string;
body?: unknown;
}> = [
@@ -739,6 +740,7 @@ const ID_ROUTES: Array<{
{ method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } },
{ method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } },
{ method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } },
{ method: 'PUT', path: '/api/stats/anime/:id/group', body: { mode: 'standalone' } },
{ method: 'POST', path: '/api/stats/anki/browse?noteId=:id' },
];
@@ -2429,6 +2431,50 @@ describe('stats server API routes', () => {
assert.equal(mergeCalls, 0);
});
it('PUT /api/stats/anime/:animeId/group validates the body and maps refusals', async () => {
const calls: unknown[] = [];
const app = createStatsApp(
createMockTracker({
setAnimeGroupOverride: async (animeId, target) => {
calls.push([animeId, target]);
if (target.mode === 'join' && target.targetAnimeId === 9) {
return { ok: false, reason: 'target-not-grouped' };
}
if (animeId === 404) return { ok: false, reason: 'not-found' };
return { ok: true };
},
}),
);
const put = (path: string, body: unknown) =>
app.request(path, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(body) });
for (const body of [
{},
{ mode: 'join' },
{ mode: 'join', targetAnimeId: 0 },
{ mode: 'join', targetAnimeId: '8' },
{ mode: 'join', targetAnimeId: 3 },
{ mode: 'reset' },
]) {
assert.equal((await put('/api/stats/anime/3/group', body)).status, 400, JSON.stringify(body));
}
assert.deepEqual(calls, []);
assert.equal(
(await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 8 })).status,
200,
);
assert.equal((await put('/api/stats/anime/3/group', { mode: 'anilist' })).status, 200);
assert.equal((await put('/api/stats/anime/404/group', { mode: 'standalone' })).status, 404);
const refused = await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 9 });
assert.equal(refused.status, 409);
assert.match((await refused.json()).error, /no AniList entry/);
assert.deepEqual(calls.slice(0, 2), [
[3, { mode: 'join', targetAnimeId: 8 }],
[3, { mode: 'anilist' }],
]);
});
it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => {
let moved: { videoId: number; animeId: number } | null = null;
const app = createStatsApp(
@@ -0,0 +1,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 { AnilistRateLimitedError, executeAnilistQuery } from './anilist-graphql';
import type { DatabaseSync } from '../immersion-tracker/sqlite';
import {
getAnimeCoverArt,
@@ -20,7 +21,6 @@ import { getVideoTmdbLink, linkAnimeToTmdbTitle } from '../immersion-tracker/liv
import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver';
import type { TmdbTitleDetails } from '../tmdb/tmdb-client';
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
export interface CoverArtFetcher {
@@ -76,47 +76,6 @@ export function stripFilenameTags(raw: string): string {
return title.trim().replace(/\s{2,}/g, ' ');
}
class AnilistRateLimitedError extends Error {
constructor() {
super('Anilist rate limit reached');
this.name = 'AnilistRateLimitedError';
}
}
async function executeAnilistQuery<T>(
rateLimiter: AnilistRateLimiter,
query: string,
variables: Record<string, unknown>,
): Promise<T> {
await rateLimiter.acquire();
const res = await fetch(ANILIST_GRAPHQL_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query, variables }),
});
rateLimiter.recordResponse(res.headers);
if (res.status === 429) {
throw new AnilistRateLimitedError();
}
if (!res.ok) {
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
}
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
if (firstError?.message) {
throw new Error(firstError.message);
}
if (!json.data) {
throw new Error('Anilist response missing data');
}
return json.data;
}
async function downloadImage(url: string): Promise<Buffer | null> {
try {
const res = await fetch(url);
@@ -0,0 +1,261 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildFranchiseGraph,
walkFranchiseRelations,
type AnilistMediaNode,
type FranchiseWalkOptions,
} from './franchise-graph';
function entry(
anilistId: number,
format: string | null,
startDate: number | null,
relations: Array<[string, number]> = [],
): AnilistMediaNode {
return {
anilistId,
format,
titleRomaji: `romaji ${anilistId}`,
titleEnglish: null,
titleNative: null,
startDate,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs: 0,
};
}
// Overlord: two recap films sit between seasons one and two; Isekai Quartet only shares characters.
const overlord = [
entry(20832, 'TV', 20150707, [
['SEQUEL', 98437],
['SUMMARY', 98873],
['CHARACTER', 104454],
]),
entry(98873, 'MOVIE', 20170225, [
['PARENT', 20832],
['SEQUEL', 98874],
]),
entry(98874, 'MOVIE', 20170311, [
['PREQUEL', 98873],
['SEQUEL', 98437],
]),
entry(98437, 'TV', 20180109, [
['PREQUEL', 20832],
['PREQUEL', 98874],
]),
entry(104454, 'TV_SHORT', 20190410, [['CHARACTER', 20832]]),
];
test('seasons, films and recaps share a root named after the first TV series', () => {
const graph = buildFranchiseGraph(overlord);
for (const id of [20832, 98873, 98874, 98437]) assert.equal(graph.rootOf(id), 20832);
assert.equal(graph.rootOf(104454), 104454);
assert.equal(graph.rootOf(1), undefined);
});
test('excluded relation types keep franchises apart even when the other end says PARENT', () => {
const graph = buildFranchiseGraph([
entry(1, 'TV', 20060101, [
['SPIN_OFF', 2],
['ALTERNATIVE', 3],
['ADAPTATION', 4],
['OTHER', 5],
]),
// A spin-off pointing back at its original as PARENT.
entry(2, 'TV', 20130101, [['PARENT', 1]]),
entry(3, 'TV', 20140101, [['ALTERNATIVE', 1]]),
]);
assert.deepEqual(
[1, 2, 3, 4, 5].map((id) => graph.rootOf(id)),
[1, 2, 3, undefined, undefined],
);
});
test('root falls back to episodic formats, then earliest entry, then lowest id', () => {
const ona = buildFranchiseGraph([
entry(10, 'MOVIE', 20000101, [['SEQUEL', 11]]),
entry(11, 'ONA', 20050101, [['PREQUEL', 10]]),
]);
assert.equal(ona.rootOf(10), 11);
const films = buildFranchiseGraph([
entry(20, 'MOVIE', 20100101, [['PREQUEL', 21]]),
entry(21, 'MOVIE', 20090101, [['SEQUEL', 20]]),
entry(22, 'OVA', null, [['PARENT', 20]]),
]);
assert.equal(films.rootOf(22), 21);
});
test('owned films join through an unowned, uncached TV entry they both point at', () => {
const graph = buildFranchiseGraph([
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
entry(1526, 'MOVIE', 20050716, [['PARENT', 527]]),
]);
assert.equal(graph.rootOf(528), graph.rootOf(1526));
});
test('relation cycles terminate and form one franchise', () => {
const graph = buildFranchiseGraph([
entry(1, 'TV', 20000101, [['SEQUEL', 2]]),
entry(2, 'TV', 20010101, [['SEQUEL', 3]]),
entry(3, 'TV', 20020101, [['SEQUEL', 1]]),
]);
assert.deepEqual(
[1, 2, 3].map((id) => graph.rootOf(id)),
[1, 1, 1],
);
});
function walkHarness(all: AnilistMediaNode[], overrides: Partial<FranchiseWalkOptions> = {}) {
const asked: number[][] = [];
const known = new Map<number, AnilistMediaNode>();
const options: FranchiseWalkOptions = {
seeds: [],
known,
isFresh: () => true,
fetchNodes: async (ids) => {
asked.push([...ids].sort((a, b) => a - b));
return all.filter((node) => ids.includes(node.anilistId));
},
onBatch: () => {},
now: () => 5,
maxDepth: 6,
maxFetch: 500,
...overrides,
};
return { asked, known, options };
}
test('walk follows franchise links through entries the user does not own', async () => {
const pokemon = [
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
entry(527, 'TV', 19970401, [
['SIDE_STORY', 528],
['SEQUEL', 1564],
]),
entry(1564, 'TV', 20021121, [
['PREQUEL', 527],
['SIDE_STORY', 1526],
['OTHER', 9],
]),
entry(1526, 'MOVIE', 20050716, [['PARENT', 1564]]),
entry(9, 'TV', 20000101),
];
const { asked, known, options } = walkHarness(pokemon, { seeds: [528, 1526, 404] });
await walkFranchiseRelations(options);
assert.deepEqual(asked, [
[404, 528, 1526],
[527, 1564],
]);
const graph = buildFranchiseGraph(known.values());
assert.equal(graph.rootOf(528), 527);
assert.equal(graph.rootOf(1526), 527);
// Missing ids are remembered so they are not asked about again; OTHER links are not followed.
assert.equal(known.get(404)?.format, null);
assert.equal(known.has(9), false);
});
test('walk does not follow the links of an entry that vetoes how it was reached', async () => {
const { asked, options } = walkHarness(
[
entry(2, 'TV', 20130101, [['PARENT', 1]]),
entry(1, 'TV', 20060101, [
['SPIN_OFF', 2],
['SEQUEL', 3],
]),
entry(3, 'TV', 20070101),
],
{ seeds: [2] },
);
await walkFranchiseRelations(options);
assert.deepEqual(asked, [[2], [1]]);
});
test('walk follows an entry reached through any link it accepts, whatever the seed order', async () => {
const nodes = [
entry(1, 'TV', 20100101, [['SEQUEL', 3]]),
entry(2, 'TV', 20110101, [['SEQUEL', 3]]),
// Rejects seed 1 but accepts seed 2, so its own links are still followed.
entry(3, 'TV', 20120101, [
['SPIN_OFF', 1],
['PREQUEL', 2],
['PARENT', 4],
]),
entry(4, 'TV', 20000101),
];
for (const seeds of [
[1, 2],
[2, 1],
]) {
const { asked, options } = walkHarness(nodes, { seeds });
await walkFranchiseRelations(options);
assert.deepEqual(asked, [[1, 2], [3], [4]]);
}
});
test('a cancelled walk starts no further request and drops the in-flight result', async () => {
const seeds = Array.from({ length: 51 }, (_, index) => index + 1);
let cancelled = false;
const batches: number[] = [];
const { asked, known, options } = walkHarness(
seeds.map((id) => entry(id, 'TV', 20200101)),
{
seeds,
isFresh: () => false,
onBatch: (nodes) => batches.push(nodes.length),
isCancelled: () => cancelled,
},
);
const fetchNodes = options.fetchNodes;
options.fetchNodes = async (ids) => {
cancelled = true;
return fetchNodes(ids);
};
const result = await walkFranchiseRelations(options);
assert.equal(asked.length, 1);
assert.deepEqual(batches, []);
assert.equal(known.size, 0);
assert.equal(result.truncated, true);
});
test('walk respects the depth and fetch bounds', async () => {
const chain = Array.from({ length: 10 }, (_, i) =>
entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []),
);
const deep = walkHarness(chain, { seeds: [1], maxDepth: 3 });
await walkFranchiseRelations(deep.options);
assert.deepEqual([...deep.known.keys()], [1, 2, 3, 4]);
const budget = walkHarness(chain, { seeds: [1], maxFetch: 2 });
const result = await walkFranchiseRelations(budget.options);
assert.deepEqual(result, { fetched: 2, truncated: true });
assert.deepEqual([...budget.known.keys()], [1, 2]);
});
test('walk follows fresh cached entries without asking and keeps old data on a failed fetch', async () => {
const cached = entry(1, 'TV', 20000101, [['SEQUEL', 2]]);
const stale = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
const { known, options } = walkHarness([], {
seeds: [1],
isFresh: (node) => node.fetchedAtMs >= 0,
fetchNodes: async () => {
throw new Error('AniList unavailable');
},
});
known.set(1, cached);
known.set(2, stale);
await assert.rejects(walkFranchiseRelations(options), /AniList unavailable/);
assert.deepEqual(known.get(2), stale);
});
test('an entry AniList stops returning keeps its cached links', async () => {
const previous = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
const { known, options } = walkHarness([], {
seeds: [2],
isFresh: (node) => node.fetchedAtMs >= 0,
});
known.set(2, previous);
await walkFranchiseRelations(options);
assert.deepEqual(known.get(2), { ...previous, fetchedAtMs: 5 });
});
@@ -0,0 +1,250 @@
/**
* Franchise grouping over AniList's relation graph. AniList keeps every
* season, movie and OVA as its own entry and says how entries relate; the
* stats library lists a franchise once by following those links, including
* through entries the user does not own (two movies meet at a TV series that
* is not in the library). Nothing here touches the database or the network.
*/
/**
* Relation types that make two entries parts of one franchise. SPIN_OFF,
* ALTERNATIVE, CHARACTER, OTHER, ADAPTATION and SOURCE are left out on purpose:
* following them collapses Gundam or Fate into a single card.
*/
export const FRANCHISE_RELATION_TYPES: ReadonlySet<string> = new Set([
'PREQUEL',
'SEQUEL',
'PARENT',
'SIDE_STORY',
'SUMMARY',
'COMPILATION',
'CONTAINS',
]);
export interface AnilistRelationEdge {
relationType: string;
targetId: number;
}
/** One cached AniList entry and its links to other anime entries. */
export interface AnilistMediaNode {
anilistId: number;
/** TV, MOVIE, OVA...; null when AniList did not return the entry. */
format: string | null;
titleRomaji: string | null;
titleEnglish: string | null;
titleNative: string | null;
/** First air date as yyyymmdd (month/day 0 when unknown); null when AniList has no year. */
startDate: number | null;
episodes: number | null;
relations: AnilistRelationEdge[];
fetchedAtMs: number;
}
export interface FranchiseGraph {
node(anilistId: number): AnilistMediaNode | undefined;
/** AniList id the franchise containing `anilistId` is named after; undefined when unknown. */
rootOf(anilistId: number): number | undefined;
}
export function anilistNodeTitle(node: AnilistMediaNode): string | null {
return node.titleEnglish ?? node.titleRomaji ?? node.titleNative;
}
/**
* True when `node` names `targetId` only through relations that do not join a
* franchise. AniList records most links from both ends; a spin-off can point
* back at its original as PARENT, so the original's SPIN_OFF edge has to veto
* the join or excluding SPIN_OFF would not keep the two apart.
*/
function vetoes(node: AnilistMediaNode, targetId: number): boolean {
const edges = node.relations.filter((edge) => edge.targetId === targetId);
return edges.length > 0 && !edges.some((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType));
}
function franchiseTargets(node: AnilistMediaNode): number[] {
return node.relations
.filter((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType))
.map((edge) => edge.targetId);
}
// TV first, then other episodic formats, then films/OVAs/specials, then entries with no data.
function formatRank(format: string | null): number {
if (format === 'TV') return 0;
if (format === 'TV_SHORT' || format === 'ONA') return 1;
return format === null ? 3 : 2;
}
export function buildFranchiseGraph(nodes: Iterable<AnilistMediaNode>): FranchiseGraph {
const byId = new Map<number, AnilistMediaNode>();
for (const node of nodes) byId.set(node.anilistId, node);
const parent = new Map<number, number>();
const find = (id: number): number => {
let top = parent.get(id) ?? id;
if (!parent.has(id)) parent.set(id, id);
while (parent.get(top) !== top) top = parent.get(top)!;
// Path compression keeps long sequel chains cheap.
let at = id;
while (at !== top) {
const next = parent.get(at)!;
parent.set(at, top);
at = next;
}
return top;
};
for (const node of byId.values()) {
find(node.anilistId);
for (const targetId of franchiseTargets(node)) {
const target = byId.get(targetId);
if (target && vetoes(target, node.anilistId)) continue;
const a = find(node.anilistId);
const b = find(targetId);
if (a !== b) parent.set(b, a);
}
}
const members = new Map<number, number[]>();
for (const id of parent.keys()) {
const top = find(id);
const list = members.get(top);
if (list) list.push(id);
else members.set(top, [id]);
}
// A franchise is named after its first TV series, else its first episodic
// entry, else its earliest entry; ties go to the lower id.
const compareRoots = (a: number, b: number): number => {
const left = byId.get(a);
const right = byId.get(b);
return (
formatRank(left?.format ?? null) - formatRank(right?.format ?? null) ||
(left?.startDate ?? Number.MAX_SAFE_INTEGER) -
(right?.startDate ?? Number.MAX_SAFE_INTEGER) ||
a - b
);
};
const roots = new Map<number, number>();
for (const ids of members.values()) {
const root = [...ids].sort(compareRoots)[0]!;
for (const id of ids) roots.set(id, root);
}
return {
node: (anilistId) => byId.get(anilistId),
rootOf: (anilistId) => roots.get(anilistId),
};
}
const FETCH_CHUNK_SIZE = 50;
export interface FranchiseWalkOptions {
/** AniList ids the walk starts from (the library's own entries). */
seeds: readonly number[];
/** Cached entries; updated in place with everything fetched. */
known: Map<number, AnilistMediaNode>;
isFresh: (node: AnilistMediaNode) => boolean;
/** Entries AniList returned for `ids` (at most 50). Throws on transport or API failure. */
fetchNodes: (ids: number[]) => Promise<AnilistMediaNode[]>;
/** Called once per fetched batch so progress survives a later failure. */
onBatch: (nodes: AnilistMediaNode[]) => void;
now: () => number;
/** Hops from a seed; entries at this depth are fetched but not followed. */
maxDepth: number;
/** Most entries fetched in one walk; the rest wait for the next walk. */
maxFetch: number;
/** When true, the walk starts no further request and drops an in-flight result. */
isCancelled?: () => boolean;
}
export interface FranchiseWalkResult {
fetched: number;
/** True when the fetch budget ran out before every stale entry was refreshed. */
truncated: boolean;
}
/**
* Breadth-first walk from the seeds along franchise relations, fetching
* entries that are missing or stale. Fresh cached entries are followed without
* a request. An entry AniList does not return keeps its previous data (or gets
* an empty placeholder) so it is not asked about again until it goes stale; a
* thrown fetch error stops the walk and leaves the cache as it was.
*/
export async function walkFranchiseRelations(
options: FranchiseWalkOptions,
): Promise<FranchiseWalkResult> {
const { known } = options;
const visited = new Set<number>();
// `from` lists every entry the walk reached this one through at this depth
// (empty for a seed), so the order seeds are given in cannot change the result.
let frontier: Array<{ id: number; from: number[] }> = [...new Set(options.seeds)].map((id) => ({
id,
from: [],
}));
let fetched = 0;
let truncated = false;
for (let depth = 0; frontier.length > 0; depth += 1) {
for (const step of frontier) visited.add(step.id);
const stale = frontier
.map((step) => step.id)
.filter((id) => {
const node = known.get(id);
return !node || !options.isFresh(node);
});
const allowed = stale.slice(0, Math.max(0, options.maxFetch - fetched));
if (allowed.length < stale.length) truncated = true;
for (let start = 0; start < allowed.length; start += FETCH_CHUNK_SIZE) {
if (options.isCancelled?.()) return { fetched, truncated: true };
const chunk = allowed.slice(start, start + FETCH_CHUNK_SIZE);
const fetchedNodes = await options.fetchNodes(chunk);
if (options.isCancelled?.()) return { fetched, truncated: true };
const found = new Map(fetchedNodes.map((node) => [node.anilistId, node] as const));
const fetchedAtMs = options.now();
const batch = chunk.map((id): AnilistMediaNode => {
const node = found.get(id);
if (node) return node;
const previous = known.get(id);
if (previous) return { ...previous, fetchedAtMs };
return {
anilistId: id,
format: null,
titleRomaji: null,
titleEnglish: null,
titleNative: null,
startDate: null,
episodes: null,
relations: [],
fetchedAtMs,
};
});
for (const node of batch) known.set(node.anilistId, node);
options.onBatch(batch);
fetched += chunk.length;
}
if (depth >= options.maxDepth) break;
const next = new Map<number, number[]>();
for (const step of frontier) {
const node = known.get(step.id);
if (!node) continue;
// Reached only through links the entry itself rejects (a spin-off's
// original): it is not part of the franchise, so its own links are not
// followed. One accepted incoming link is enough.
if (step.from.length > 0 && step.from.every((fromId) => vetoes(node, fromId))) continue;
for (const targetId of franchiseTargets(node)) {
if (visited.has(targetId)) continue;
const from = next.get(targetId);
if (from) from.push(node.anilistId);
else next.set(targetId, [node.anilistId]);
}
}
frontier = [...next].map(([id, from]) => ({ id, from }));
}
return { fetched, truncated };
}
@@ -0,0 +1,83 @@
import { executeAnilistQuery } from './anilist-graphql';
import type { AnilistMediaNode, AnilistRelationEdge } from './franchise-graph';
import type { AnilistRateLimiter } from './rate-limiter';
/** Loads AniList entries with their relations, for the library's franchise grouping. */
export interface AnilistRelationFetcher {
/** Entries AniList returned for `ids` (at most 50); ids it does not know are absent. */
fetchMedia(ids: number[]): Promise<AnilistMediaNode[]>;
}
const RELATIONS_QUERY = `
query ($ids: [Int], $perPage: Int) {
Page(page: 1, perPage: $perPage) {
media(id_in: $ids, type: ANIME) {
id
format
episodes
title { romaji english native }
startDate { year month day }
relations { edges { relationType(version: 2) node { id type } } }
}
}
}`;
interface RelationsMedia {
id: number;
format: string | null;
episodes: number | null;
title: { romaji: string | null; english: string | null; native: string | null } | null;
startDate: { year: number | null; month: number | null; day: number | null } | null;
relations: {
edges: Array<{
relationType: string | null;
node: { id: number; type: string | null } | null;
} | null> | null;
} | null;
}
interface RelationsResponse {
Page: { media: Array<RelationsMedia | null> | null } | null;
}
export function toAnilistMediaNode(media: RelationsMedia, fetchedAtMs: number): AnilistMediaNode {
const start = media.startDate;
const relations: AnilistRelationEdge[] = [];
for (const edge of media.relations?.edges ?? []) {
// Manga and novels are not part of a watch library.
if (!edge?.relationType || edge.node?.type !== 'ANIME') continue;
relations.push({ relationType: edge.relationType, targetId: edge.node.id });
}
return {
anilistId: media.id,
format: media.format,
titleRomaji: media.title?.romaji ?? null,
titleEnglish: media.title?.english ?? null,
titleNative: media.title?.native ?? null,
startDate: start?.year
? start.year * 10_000 + (start.month ?? 0) * 100 + (start.day ?? 0)
: null,
episodes: media.episodes,
relations,
fetchedAtMs,
};
}
export function createAnilistRelationFetcher(
rateLimiter: AnilistRateLimiter,
now: () => number = Date.now,
): AnilistRelationFetcher {
return {
async fetchMedia(ids) {
if (ids.length === 0) return [];
const data = await executeAnilistQuery<RelationsResponse>(rateLimiter, RELATIONS_QUERY, {
ids,
perPage: ids.length,
});
const fetchedAtMs = now();
return (data.Page?.media ?? [])
.filter((media): media is RelationsMedia => media !== null)
.map((media) => toAnilistMediaNode(media, fetchedAtMs));
},
};
}
@@ -4,6 +4,18 @@ import { createLogger } from '../../logger';
import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity';
import { MediaGenerator } from '../../media-generator';
import type { CoverArtFetcher } from './anilist/cover-art-fetcher';
import type { AnilistRelationFetcher } from './anilist/franchise-relation-fetcher';
import {
createFranchiseRelationRefresher,
type FranchiseRelationRefresher,
} from './immersion-tracker/franchise-relation-refresher';
import {
getAnimeGroupPlacement,
getAnimeLibraryGroups,
setAnimeGroupOverride,
type AnimeGroupOverrideResult,
type AnimeGroupOverrideTarget,
} from './immersion-tracker/query-library-groups';
import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata';
import {
pruneRawRetention,
@@ -61,6 +73,7 @@ import type {
StatsTrendGroupBy,
StatsTrendRange,
} from '../../types/stats-http-contract';
import type { AnimeGroupPlacement, AnimeLibraryGroup } from '../../types/stats-wire';
import {
getKanjiAnimeAppearances,
getKanjiDetail,
@@ -452,6 +465,7 @@ export class ImmersionTrackerService {
private readonly mediaGenerator = new MediaGenerator();
private readonly preparedStatements: TrackerPreparedStatements;
private coverArtFetcher: CoverArtFetcher | null = null;
private franchiseRelations: FranchiseRelationRefresher | null = null;
private readonly pendingCoverFetches = new Map<number, Promise<boolean>>();
private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>();
private readonly recordedSubtitleKeys = new Set<string>();
@@ -621,6 +635,7 @@ export class ImmersionTrackerService {
}
this.finalizeActiveSession();
this.isDestroyed = true;
this.franchiseRelations?.stop();
this.deleteMaintenanceScheduler.destroy();
this.destroyDeleteMaintenanceRunner();
this.destroyVocabularySummaryRunner();
@@ -833,6 +848,27 @@ export class ImmersionTrackerService {
return getAnimeLibrary(this.db);
}
/** The library as franchise cards; also schedules a background AniList relation refresh. */
async getAnimeLibraryGroups(): Promise<AnimeLibraryGroup[]> {
this.relinkYoutubeAnimeLibrary();
const groups = getAnimeLibraryGroups(this.db);
this.franchiseRelations?.requestRefresh();
return groups;
}
async getAnimeGroupPlacement(animeId: number): Promise<AnimeGroupPlacement | null> {
return getAnimeGroupPlacement(this.db, animeId);
}
async setAnimeGroupOverride(
animeId: number,
target: AnimeGroupOverrideTarget,
): Promise<AnimeGroupOverrideResult> {
const result = setAnimeGroupOverride(this.db, animeId, target);
if (result.ok) this.franchiseRelations?.requestRefresh({ force: true });
return result;
}
async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> {
return getAnimeMergeRecommendations(this.db);
}
@@ -1122,6 +1158,7 @@ export class ImmersionTrackerService {
this.db.exec('ROLLBACK');
throw error;
}
this.franchiseRelations?.requestRefresh({ force: true });
}
/**
@@ -1248,6 +1285,19 @@ export class ImmersionTrackerService {
this.coverArtFetcher = fetcher;
}
/** Enables franchise grouping refreshes; null disables them (tests, offline runs). */
setAnilistRelationFetcher(fetcher: AnilistRelationFetcher | null): void {
this.franchiseRelations?.stop();
this.franchiseRelations = fetcher
? createFranchiseRelationRefresher({
db: this.db,
fetcher,
logger: createLogger('immersion-tracker:franchise-relations'),
})
: null;
this.franchiseRelations?.requestRefresh();
}
async ensureAnimeCoverArt(animeId: number): Promise<boolean> {
const existing = await this.getAnimeCoverArt(animeId);
if (existing?.coverBlob) {
@@ -1300,6 +1350,8 @@ export class ImmersionTrackerService {
if (!fetched) {
return false;
}
// A fresh AniList link may join this entry to a franchise card.
this.franchiseRelations?.requestRefresh({ force: true });
const cover = await this.getCoverArt(videoId);
return cover?.coverBlob != null;
})();
@@ -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 type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types';
import { toDbTimestamp } from './query-shared';
import { ensureAnimeGroupingSchema } from './anilist-relation-cache';
export interface TrackerPreparedStatements {
telemetryInsertStmt: ReturnType<DatabaseSync['prepare']>;
@@ -998,6 +999,7 @@ export function ensureSchema(db: DatabaseSync): void {
ensureLifetimeSummaryTables(db);
ensureStatsExcludedWordsTable(db);
ensureAnimeMergeTables(db);
ensureAnimeGroupingSchema(db);
ensureSubtitleLineEventIndex(db);
return;
}
@@ -1064,6 +1066,8 @@ export function ensureSchema(db: DatabaseSync): void {
'INTEGER NOT NULL DEFAULT 0 CHECK(anime_assignment_locked IN (0, 1))',
);
ensureAnimeMergeTables(db);
// Schema 27: franchise grouping (AniList relation cache + per-entry override).
ensureAnimeGroupingSchema(db);
db.exec(`
CREATE TABLE IF NOT EXISTS imm_sessions(
session_id INTEGER PRIMARY KEY AUTOINCREMENT,
+2 -1
View File
@@ -1,7 +1,8 @@
import type { MediaKind, TmdbMediaType } from '../../../shared/media-kind';
// 26: live-action entries (TMDB link) and YouTube channels share the media_kind column.
export const SCHEMA_VERSION = 26;
// 27: AniList relation cache and imm_anime.group_override for franchise grouping.
export const SCHEMA_VERSION = 27;
export const DEFAULT_QUEUE_CAP = 1_000;
export const DEFAULT_BATCH_SIZE = 25;
export const DEFAULT_FLUSH_INTERVAL_MS = 500;
@@ -11,6 +11,7 @@ import {
enrichSessionsWithKnownWordMetrics,
isPositiveSafeInteger,
loadKnownWordsSet,
parseAnimeGroupOverrideBody,
parseBooleanQuery,
parseDuplicateLineCleanupBody,
parseExcludedWordsBody,
@@ -190,6 +191,11 @@ export function registerStatsLibraryRoutes(
return c.json(statsJson('animeLibrary', rows));
});
// Registered before `/api/stats/anime/:animeId` so `groups` is not read as an id.
app.get('/api/stats/anime/groups', async (c) => {
return c.json(statsJson('animeLibraryGroups', await tracker.getAnimeLibraryGroups()));
});
app.get('/api/stats/anime/merge-recommendations', async (c) => {
const recommendations = await tracker.getAnimeMergeRecommendations();
return c.json(statsJson('animeMergeRecommendations', { recommendations }));
@@ -208,11 +214,12 @@ export function registerStatsLibraryRoutes(
if (animeId === null) return c.body(null, 400);
const detail = await tracker.getAnimeDetail(animeId);
if (!detail) return c.body(null, 404);
const [episodes, anilistEntries] = await Promise.all([
const [episodes, anilistEntries, group] = await Promise.all([
tracker.getAnimeEpisodes(animeId),
tracker.getAnimeAnilistEntries(animeId),
tracker.getAnimeGroupPlacement(animeId),
]);
return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries }));
return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries, group }));
});
app.get('/api/stats/anime/:animeId/words', async (c) => {
@@ -267,6 +274,22 @@ export function registerStatsLibraryRoutes(
return c.json(statsJson('deleteAnime', { ok: true }));
});
app.put('/api/stats/anime/:animeId/group', async (c) => {
const animeId = parsePositiveId(c.req.param('animeId'));
if (animeId === null) return c.body(null, 400);
const request = parseAnimeGroupOverrideBody(await c.req.json().catch(() => null));
if (!request) return c.body(null, 400);
if (request.mode === 'join' && request.targetAnimeId === animeId) return c.body(null, 400);
const result = await tracker.setAnimeGroupOverride(animeId, request);
if (result.ok) return c.json(statsJson('setAnimeGroupOverride', { ok: true }));
if (result.reason === 'not-found') return c.body(null, 404);
const error =
result.reason === 'unsupported-kind'
? 'Only anime entries can be grouped.'
: 'That title has no AniList entry to group with. Link it to AniList or merge the entries instead.';
return c.json(statsJson('error', { error }), 409);
});
app.post('/api/stats/anime/:animeId/merge', async (c) => {
const animeId = parsePositiveId(c.req.param('animeId'));
if (animeId === null) return c.body(null, 400);
@@ -13,6 +13,7 @@ import {
import { createLogger } from '../../../logger.js';
import type { AnkiConnectConfig } from '../../../types.js';
import type {
StatsAnimeGroupOverrideRequest,
StatsDayRange,
StatsDictionaryWordQuery,
StatsDictionaryWordSort,
@@ -59,6 +60,15 @@ export function isPositiveSafeInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
}
/** Validates a `PUT /api/stats/anime/:animeId/group` body; null for anything malformed. */
export function parseAnimeGroupOverrideBody(body: unknown): StatsAnimeGroupOverrideRequest | null {
if (!body || typeof body !== 'object') return null;
const { mode, targetAnimeId } = body as Record<string, unknown>;
if (mode === 'standalone' || mode === 'anilist') return { mode };
if (mode === 'join' && isPositiveSafeInteger(targetAnimeId)) return { mode, targetAnimeId };
return null;
}
export function parsePositiveId(raw: string | undefined): number | null {
if (raw === undefined) return null;
const value = Number(raw);
@@ -58,3 +58,78 @@ for (const [localKind, remoteKind, sameEntry] of [
}
});
}
test('franchise override follows whichever side set or cleared it last', () => {
const adapt = (db: DatabaseSync) => ({
query: (sql: string) => db.prepare(sql),
exec: (sql: string) => {
db.exec(sql);
},
close: () => {
db.close();
},
});
const cases: Array<{
name: string;
local: [number | null, string | null];
remote: [number | null, string | null];
expected: number | null;
}> = [
{
name: 'newer remote join wins',
local: [null, null],
remote: [20832, '2000'],
expected: 20832,
},
{ name: 'newer remote clear wins', local: [0, '1000'], remote: [null, '2000'], expected: null },
{ name: 'older remote loses', local: [0, '3000'], remote: [20832, '2000'], expected: 0 },
{ name: 'untouched remote keeps local', local: [0, '1000'], remote: [null, null], expected: 0 },
];
for (const c of cases) {
const local = new Database(':memory:');
const remote = new Database(':memory:');
try {
for (const [db, [override, updatedAt]] of [
[local, c.local],
[remote, c.remote],
] as const) {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, group_override, group_override_updated_at)
VALUES ('overlord ii', 'Overlord II', 98437, ?, ?)`,
).run(override, updatedAt);
}
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
const row = local.prepare('SELECT group_override AS value FROM imm_anime').get() as {
value: number | null;
};
assert.equal(row.value, c.expected, c.name);
} finally {
local.close();
remote.close();
}
}
const local = new Database(':memory:');
const remote = new Database(':memory:');
try {
ensureSchema(local);
ensureSchema(remote);
remote
.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override, group_override_updated_at)
VALUES ('specials', 'Specials', 20832, '1000')`,
)
.run();
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
const row = local
.prepare(
'SELECT group_override AS value, group_override_updated_at AS updatedAt FROM imm_anime',
)
.get() as { value: number | null; updatedAt: string | null };
assert.deepEqual([row.value, row.updatedAt], [20832, '1000']);
} finally {
local.close();
remote.close();
}
});
@@ -15,6 +15,8 @@ const ANIME_COPY_COLUMNS = [
'tmdb_id',
'tmdb_type',
'metadata_json',
'group_override',
'group_override_updated_at',
'CREATED_DATE',
'LAST_UPDATE_DATE',
] as const;
@@ -146,6 +148,13 @@ export function mergeAnime(
END
WHERE anime_id = ?`,
);
// The franchise override holds AniList ids (or 0 / NULL), so it needs no id
// remapping. The side that set or cleared it last wins.
const takeNewerGroupOverride = local.query(
`UPDATE imm_anime SET group_override = ?, group_override_updated_at = ?
WHERE anime_id = ? AND (group_override_updated_at IS NULL
OR CAST(group_override_updated_at AS INTEGER) < CAST(? AS INTEGER))`,
);
for (const row of selectAll(
remote,
@@ -195,6 +204,14 @@ export function mergeAnime(
row.media_kind,
localId,
);
if (row.group_override_updated_at !== null) {
takeNewerGroupOverride.run(
row.group_override,
row.group_override_updated_at,
localId,
row.group_override_updated_at,
);
}
continue;
}
// Conflicting providers can share a title, but the stored title key is
+5
View File
@@ -20,6 +20,11 @@ export type { SyncMergeSummary } from './shared';
* are updated incrementally so history older than the session retention
* window is preserved on both sides. Idempotent: re-merging the same
* snapshot is a no-op.
*
* A library entry's franchise override (`group_override`) is last-writer-wins
* by `group_override_updated_at`. The AniList relation cache
* (`imm_anilist_media`, `imm_anilist_relations`) is not merged: each machine
* rebuilds it from AniList.
*/
export function mergeSnapshotIntoDb(localDbPath: string, snapshotPath: string): SyncMergeSummary {
if (!fs.existsSync(localDbPath)) {
+4
View File
@@ -1,6 +1,7 @@
import path from 'node:path';
import { ImmersionTrackerService } from '../../core/services';
import { createCoverArtFetcher } from '../../core/services/anilist/cover-art-fetcher';
import { createAnilistRelationFetcher } from '../../core/services/anilist/franchise-relation-fetcher';
import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter';
import { resolveLegacyVocabularyPosFromTokens } from '../../core/services/immersion-tracker/legacy-vocabulary-pos';
import type { StatsWindowOptions } from '../../core/services/stats-window';
@@ -172,6 +173,8 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
},
);
const anilistRelationFetcher = createAnilistRelationFetcher(deps.anilistRateLimiter);
// One options object serves the overlay's IPC toggle and the session-action toggle.
const statsOverlayOptions: StatsWindowOptions = {
preloadPath: path.join(deps.mainDirname, 'preload-stats.js'),
@@ -235,6 +238,7 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
appState.immersionTracker = tracker as ImmersionTrackerService | null;
appState.immersionTracker?.setCoverArtFetcher(coverArtFetcher);
appState.immersionTracker?.setAnilistRelationFetcher(anilistRelationFetcher);
if (tracker) {
// Start HTTP stats server
if (!appState.statsServer) {
+5 -1
View File
@@ -6,6 +6,7 @@ import { ConfigService } from './config/service';
import { createLogger, setLogLevel } from './logger';
import { ImmersionTrackerService } from './core/services/immersion-tracker-service';
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 { createLiveActionMetadataResolver } from './core/services/tmdb/live-action-resolver';
import { createTmdbClient, createTmdbApiKeyResolver } from './core/services/tmdb/tmdb-client';
@@ -212,11 +213,14 @@ async function main(): Promise<void> {
() => bundledTmdbApiKey,
),
});
// Cover art and franchise relations share one AniList request budget.
const anilistRateLimiter = createAnilistRateLimiter();
tracker.setCoverArtFetcher(
createCoverArtFetcher(createAnilistRateLimiter(), createLogger('stats-daemon:cover-art'), {
createCoverArtFetcher(anilistRateLimiter, createLogger('stats-daemon:cover-art'), {
liveAction: createLiveActionMetadataResolver(tmdbClient, createLogger('stats-daemon:tmdb')),
}),
);
tracker.setAnilistRelationFetcher(createAnilistRelationFetcher(anilistRateLimiter));
statsServer = await startStatsServer({
port: config.stats.serverPort,
+18
View File
@@ -1,5 +1,6 @@
import type {
AnimeDetailData,
AnimeLibraryGroup,
AnimeLibraryItem,
AnimeWord,
DailyRollup,
@@ -187,6 +188,16 @@ export interface StatsMoveVideoRequest {
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 {
recommendationId: number;
animeIds: [number, number];
@@ -251,6 +262,7 @@ export interface StatsJsonResponseMap {
mediaLibrary: MediaLibraryItem[];
mediaDetail: MediaDetailData;
animeLibrary: AnimeLibraryItem[];
animeLibraryGroups: AnimeLibraryGroup[];
animeMergeRecommendations: StatsAnimeMergeRecommendationsResponse;
animeDetail: AnimeDetailData;
animeWords: AnimeWord[];
@@ -262,6 +274,7 @@ export interface StatsJsonResponseMap {
deleteAnime: StatsOkResponse;
mergeAnime: StatsMergeAnimeResponse;
moveVideoToAnime: StatsMoveVideoResponse;
setAnimeGroupOverride: StatsOkResponse;
dismissAnimeMergeRecommendation: StatsOkResponse;
anilistSearch: StatsAnilistSearchResult[];
tmdbSearch: StatsTmdbSearchResult[];
@@ -330,6 +343,7 @@ export interface StatsHttpClient {
getMediaLibrary: () => Promise<MediaLibraryItem[]>;
getMediaDetail: (videoId: number) => Promise<MediaDetailData>;
getAnimeLibrary: () => Promise<AnimeLibraryItem[]>;
getAnimeLibraryGroups: () => Promise<AnimeLibraryGroup[]>;
getAnimeMergeRecommendations: () => Promise<StatsAnimeMergeRecommendationsResponse>;
getAnimeDetail: (animeId: number) => Promise<AnimeDetailData>;
getAnimeWords: (animeId: number, limit?: number) => Promise<AnimeWord[]>;
@@ -356,6 +370,10 @@ export interface StatsHttpClient {
deleteAnime: (animeId: number) => Promise<void>;
mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<StatsMergeAnimeResponse>;
moveVideoToAnime: (videoId: number, animeId: number) => Promise<StatsMoveVideoResponse>;
setAnimeGroupOverride: (
animeId: number,
request: StatsAnimeGroupOverrideRequest,
) => Promise<void>;
dismissAnimeMergeRecommendation: (recommendationId: number) => Promise<void>;
getKnownWords: () => Promise<string[]>;
getKnownWordsSummary: () => Promise<StatsKnownWordsSummary>;
+42
View File
@@ -306,6 +306,46 @@ export interface AnimeLibraryItem {
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 {
anilistId: number;
titleRomaji: string | null;
@@ -338,6 +378,8 @@ export interface AnimeDetailData {
};
episodes: AnimeEpisode[];
anilistEntries: AnilistEntry[];
/** Null when the entry has no watch history to list in the library. */
group: AnimeGroupPlacement | null;
}
export interface AnimeEpisode {
+9 -3
View File
@@ -1,9 +1,9 @@
import { AnimeCoverImage } from './AnimeCoverImage';
import { formatDuration, formatNumber } from '../../lib/formatters';
import type { AnimeLibraryItem } from '../../types/stats';
import type { AnimeCardData } from '../../lib/anime-groups';
interface AnimeCardProps {
anime: AnimeLibraryItem;
anime: AnimeCardData;
onClick: () => void;
/** While selecting, clicking the card toggles it instead of opening it. */
selectable?: boolean;
@@ -16,6 +16,7 @@ export function AnimeCard({
selectable = false,
selected = false,
}: AnimeCardProps) {
const unit = anime.mediaKind === 'youtube' ? 'video' : 'episode';
return (
<button
type="button"
@@ -44,11 +45,16 @@ export function AnimeCard({
{'✓'}
</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 className="p-3">
<div className="text-sm font-medium text-ctp-text truncate">{anime.canonicalTitle}</div>
<div className="text-xs text-ctp-overlay2 mt-1">
{anime.episodeCount} {anime.mediaKind === 'youtube' ? 'video' : 'episode'}
{anime.episodeCount} {unit}
{anime.episodeCount !== 1 ? 's' : ''}
</div>
<div className="text-xs text-ctp-overlay2">
+70 -3
View File
@@ -9,13 +9,16 @@ import { AnimeWordList } from './AnimeWordList';
import { AnilistSelector } from './AnilistSelector';
import { TmdbSelector } from './TmdbSelector';
import { AnimeOverviewStats } from './AnimeOverviewStats';
import { LibraryEntryPicker } from './LibraryEntryPicker';
import { CHART_THEME } from '../../lib/chart-theme';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import type { DailyRollup } from '../../types/stats';
import type { DailyRollup, StatsAnimeGroupOverrideRequest } from '../../types/stats';
interface AnimeDetailViewProps {
animeId: number;
onBack: () => void;
/** Defaults to "Back to Library"; a part opened from a franchise card returns there. */
backLabel?: string;
onNavigateToWord?: (wordId: number) => void;
onOpenEpisodeDetail?: (videoId: number) => void;
/** Called after the whole library entry is deleted, so the caller can refresh. */
@@ -28,6 +31,23 @@ interface AnimeDetailViewProps {
onProviderRelinked?: () => void;
/** Called after an episode is reassigned to another entry. */
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;
@@ -149,11 +169,13 @@ function useAnimeKnownWords(animeId: number) {
export function AnimeDetailView({
animeId,
onBack,
backLabel = 'Back to Library',
onNavigateToWord,
onOpenEpisodeDetail,
onAnimeDeleted,
onProviderRelinked,
onEpisodeMoved,
onGroupChanged,
}: AnimeDetailViewProps) {
const { data, loading, error, reload } = useAnimeDetail(animeId);
const [showAnilistSelector, setShowAnilistSelector] = useState(false);
@@ -162,6 +184,9 @@ export function AnimeDetailView({
const [isDeletingAnime, setIsDeletingAnime] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null);
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);
useEffect(() => {
@@ -172,7 +197,23 @@ export function AnimeDetailView({
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>;
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 () => {
if (isDeletingAnimeRef.current) return;
@@ -214,11 +255,18 @@ export function AnimeDetailView({
onClick={onBack}
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
>
&larr; Back to Library
&larr; {backLabel}
</button>
<AnimeHeader
detail={detail}
anilistEntries={anilistEntries ?? []}
group={group}
groupBusy={groupBusyTargetId !== null}
onMoveToGroup={() => {
setGroupError(null);
setShowGroupPicker(true);
}}
onSetGroupMode={(mode) => void applyGroupOverride({ mode }, animeId)}
coverRetryToken={coverRetryToken}
onChangeAnilist={() => setShowAnilistSelector(true)}
onChangeTmdb={() => setShowTmdbSelector(true)}
@@ -226,6 +274,25 @@ export function AnimeDetailView({
isDeletingAnime={isDeletingAnime}
/>
{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} />
<EpisodeList
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 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 {
detail: AnimeDetailData['detail'];
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;
onChangeAnilist?: () => void;
onChangeTmdb?: () => void;
@@ -33,6 +41,10 @@ function AnilistButton({ entry }: { entry: AnilistEntry }) {
export function AnimeHeader({
detail,
anilistEntries,
group = null,
onMoveToGroup,
onSetGroupMode,
groupBusy = false,
coverRetryToken = 0,
onChangeAnilist,
onChangeTmdb,
@@ -52,6 +64,9 @@ export function AnimeHeader({
? `https://www.themoviedb.org/${detail.tmdbType}/${detail.tmdbId}`
: null;
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 (
<div className="flex gap-4">
@@ -80,6 +95,11 @@ export function AnimeHeader({
</span>
)}
</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">
{tmdbUrl && (
<a
@@ -138,6 +158,42 @@ export function AnimeHeader({
{tmdbUrl ? 'Change TMDB Title' : 'Link to TMDB'}
</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 && (
<button
type="button"
@@ -7,6 +7,7 @@ import type { AnimeLibraryItem, StatsMergeAnimeResponse } from '../../types/stat
import { AnimeMergeDialog } from './AnimeMergeDialog';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
import { singleGroupLibrary } from '../../test-utils/library';
function libraryItem(animeId: number, title: string, episodeCount: number): AnimeLibraryItem {
return {
@@ -52,7 +53,7 @@ function mergeButton(container: Element): HTMLButtonElement {
test('AnimeTab merges the selected duplicate entries into the chosen keeper', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
mergeAnime: apiClient.mergeAnime,
};
@@ -61,10 +62,10 @@ test('AnimeTab merges the selected duplicate entries into the chosen keeper', as
let libraryFetches = 0;
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return entries;
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.mergeAnime = (async (targetAnimeId: number, sourceAnimeIds: number[]) => {
mergeCall = { targetAnimeId, sourceAnimeIds };
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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
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 mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
apiClient.getAnimeLibrary = (async () => entries) as typeof apiClient.getAnimeLibrary;
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => entries);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations,
})) 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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
let dismissedId: number | null = null;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Different Show', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [{ recommendationId: 73, animeIds: [1, 2] }],
})) 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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let entries = [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
let libraryFetches = 0;
let recommendationFetches = 0;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return entries;
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeMergeRecommendations = (async () => {
recommendationFetches += 1;
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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let failRecommendations = false;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => {
if (failRecommendations) throw new Error('temporary failure');
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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [{ recommendationId: 41, animeIds: [1, 2] }],
})) 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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] as [number, number] }];
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations,
})) 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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let failLibrary = false;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
if (failLibrary) throw new Error('temporary failure');
return [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [],
})) 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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
@@ -479,10 +480,10 @@ test('AnimeTab does not resurrect a dismissed recommendation from a stale in-fli
};
let holdNextFetch = false;
let releaseHeldFetch: (() => void) | null = null;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = ((): Promise<typeof payload> => {
if (!holdNextFetch) return Promise.resolve(payload);
holdNextFetch = false;
+12 -10
View File
@@ -6,6 +6,7 @@ import { apiClient } from '../../lib/api-client';
import type { AnimeDetailData, AnimeLibraryItem } from '../../types/stats';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
import { singleGroupLibrary } from '../../test-utils/library';
function libraryItem(anilistId: number | null): AnimeLibraryItem {
return {
@@ -51,6 +52,7 @@ function detailData(anilistId: number | null): AnimeDetailData {
},
episodes: [],
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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeDetail: apiClient.getAnimeDetail,
getAnimeWords: apiClient.getAnimeWords,
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 libraryFetches = 0;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return [libraryItem(anilistId)];
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeDetail = (async () => detailData(anilistId)) as typeof apiClient.getAnimeDetail;
apiClient.getAnimeWords = (async () => []) as typeof apiClient.getAnimeWords;
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 () => {
const uninstallDom = installDom();
const original = apiClient.getAnimeLibrary;
apiClient.getAnimeLibrary = async () => [
const original = apiClient.getAnimeLibraryGroups;
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
{ ...libraryItem(42), totalActiveMs: 3600000 },
{
...libraryItem(null),
@@ -162,7 +164,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
tmdbType: 'tv',
totalActiveMs: 7200000,
},
];
]);
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
@@ -180,7 +182,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
await act(async () => {
root.unmount();
});
apiClient.getAnimeLibrary = original;
apiClient.getAnimeLibraryGroups = original;
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 () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
apiClient.getAnimeLibrary = async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
{ ...libraryItem(null), totalActiveMs: 60_000 },
{
...libraryItem(null),
@@ -200,7 +202,7 @@ test('Library kind filter separates YouTube channels from anime and updates tota
canonicalTitle: 'Language Channel',
totalActiveMs: 120_000,
},
];
]);
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
const container = document.createElement('div');
document.body.append(container);
+72 -9
View File
@@ -5,6 +5,7 @@ import {
} from '../../../../src/shared/media-kind';
import { useState, useMemo, useEffect } from 'react';
import { useAnimeLibrary } from '../../hooks/useAnimeLibrary';
import { groupCardData, groupMatchesSearch } from '../../lib/anime-groups';
import { formatDuration } from '../../lib/formatters';
import {
getLibraryCardSizeStorage,
@@ -14,6 +15,7 @@ import {
} from '../../lib/library-card-size';
import { AnimeCard } from './AnimeCard';
import { AnimeDetailView } from './AnimeDetailView';
import { AnimeGroupView } from './AnimeGroupView';
import { AnimeMergeDialog } from './AnimeMergeDialog';
import { DuplicateReviewStrip } from './DuplicateReviewStrip';
@@ -39,7 +41,14 @@ const SORT_OPTIONS: { key: SortKey; label: string }[] = [
{ 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) => {
switch (key) {
case 'lastWatched':
@@ -68,6 +77,7 @@ export function AnimeTab({
onOpenEpisodeDetail,
}: AnimeTabProps) {
const {
groups,
anime,
loading,
error,
@@ -87,6 +97,8 @@ export function AnimeTab({
),
);
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 [checkedAnimeIds, setCheckedAnimeIds] = useState<number[]>([]);
const [showMergeDialog, setShowMergeDialog] = useState(false);
@@ -115,11 +127,14 @@ export function AnimeTab({
useEffect(() => {
if (initialAnimeId != null) {
setSelectedGroupKey(null);
setSelectedAnimeId(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 entries = anime.filter((entry) => mediaKind === 'all' || entry.mediaKind === mediaKind);
const base = search.trim()
@@ -127,8 +142,32 @@ export function AnimeTab({
: entries;
return sortAnime(base, sortKey);
}, [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
.map((animeId) => anime.find((entry) => entry.animeId === animeId))
.filter((entry): entry is (typeof anime)[number] => entry !== undefined);
@@ -160,6 +199,7 @@ export function AnimeTab({
return (
<AnimeDetailView
animeId={selectedAnimeId}
backLabel={selectedGroup ? `Back to ${selectedGroup.title}` : undefined}
onBack={() => setSelectedAnimeId(null)}
onNavigateToWord={onNavigateToWord}
onOpenEpisodeDetail={
@@ -170,6 +210,17 @@ export function AnimeTab({
onAnimeDeleted={reload}
onProviderRelinked={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'}
</button>
<div className="text-xs text-ctp-overlay2 shrink-0">
{filtered.length}{' '}
{shownCount}{' '}
{mediaKind === 'youtube'
? filtered.length === 1
? shownCount === 1
? 'channel'
: 'channels'
: filtered.length === 1
: shownCount === 1
? 'title'
: 'titles'}{' '}
· {formatDuration(totalMs)}
@@ -298,18 +349,30 @@ export function AnimeTab({
</div>
)}
{filtered.length === 0 ? (
{shownCount === 0 ? (
<div className="text-sm text-ctp-overlay2 p-4">No titles found</div>
) : (
) : selectionMode ? (
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
{filtered.map((item) => (
<AnimeCard
key={item.animeId}
anime={item}
selectable={selectionMode}
selectable
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={() =>
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[];
/** When set, only entries of this kind are offered. */
mediaKind?: MediaKind;
/** Further narrows the entries offered. */
filter?: (entry: AnimeLibraryItem) => boolean;
initialQuery?: string;
busyAnimeId?: number | null;
error?: string | null;
@@ -23,6 +25,7 @@ export function LibraryEntryPicker({
heading,
excludeAnimeIds = [],
mediaKind,
filter,
initialQuery = '',
busyAnimeId = null,
error = null,
@@ -74,9 +77,10 @@ export function LibraryEntryPicker({
return (entries ?? [])
.filter((entry) => !excluded.has(entry.animeId))
.filter((entry) => mediaKind === undefined || shareTitleNamespace(entry.mediaKind, mediaKind))
.filter((entry) => filter === undefined || filter(entry))
.filter((entry) => !term || entry.canonicalTitle.toLowerCase().includes(term))
.sort((a, b) => b.lastWatchedMs - a.lastWatchedMs);
}, [entries, excluded, mediaKind, query]);
}, [entries, excluded, mediaKind, filter, query]);
return (
<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 type { AnimeLibraryItem, StatsAnimeMergeRecommendation } from '../types/stats';
import type { AnimeLibraryGroup, StatsAnimeMergeRecommendation } from '../types/stats';
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() {
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 [error, setError] = useState<string | null>(null);
const [recommendations, setRecommendations] = useState<StatsAnimeMergeRecommendation[]>([]);
@@ -29,11 +34,11 @@ export function useAnimeLibrary() {
let cancelled = false;
const client = getStatsClient();
client
.getAnimeLibrary()
.getAnimeLibraryGroups()
.then((data) => {
if (!cancelled) {
hasLoadedRef.current = true;
setAnime(data);
setGroups(data);
setError(null);
}
})
@@ -103,6 +108,7 @@ export function useAnimeLibrary() {
}, []);
return {
groups,
anime,
loading,
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,
StatsCoverImagesData,
StatsAnilistAssignment,
StatsAnimeGroupOverrideRequest,
StatsAnkiNotesInfoRequest,
StatsCoverImagesRequest,
StatsDeleteSessionsRequest,
@@ -163,6 +164,7 @@ export const apiClient = {
getMediaLibrary: () => fetchJson('mediaLibrary', '/api/stats/media'),
getMediaDetail: (videoId: number) => fetchJson('mediaDetail', `/api/stats/media/${videoId}`),
getAnimeLibrary: () => fetchJson('animeLibrary', '/api/stats/anime'),
getAnimeLibraryGroups: () => fetchJson('animeLibraryGroups', '/api/stats/anime/groups'),
getAnimeMergeRecommendations: () =>
fetchJson('animeMergeRecommendations', '/api/stats/anime/merge-recommendations'),
getAnimeDetail: (animeId: number) => fetchJson('animeDetail', `/api/stats/anime/${animeId}`),
@@ -268,6 +270,16 @@ export const apiClient = {
});
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> => {
await fetchResponse(`/api/stats/anime/merge-recommendations/${recommendationId}`, {
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());
}