mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-23 04:46:08 -08:00
feat(stats): group library seasons, movies and OVAs into franchise cards (#336)
This commit is contained in:
1 parent
9d2057cc30
commit
71251b8d7b
41 files changed
+2335
-109
No files matched your search
@@ -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,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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
Reference in new issue
Block a user