mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-08-11 07:21:34 -07:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
d82a4fd8c6
|
|||
|
da80ece9f7
|
|||
|
73c553c6a1
|
|||
|
d6e6e29b5e
|
|||
|
5938095d92
|
|||
| 2fefc83e3f |
@@ -0,0 +1,6 @@
|
||||
type: added
|
||||
area: stats
|
||||
|
||||
- Library: duplicate cards for the same show can now be combined. Press "Select" above the library grid, tick the cards, and use "Merge Selected"; the dialog picks which entry to keep and moves every episode onto it. Sessions, mined cards, and watch time are preserved, and the emptied entries disappear from the grid.
|
||||
- Library: episodes can be reassigned to another library entry from the "→" button on an episode row, which is the fix when one file lands under a stray title (e.g. an episode name parsed as the series). Emptying an entry this way removes it and returns to the grid.
|
||||
- Library: once cover art resolves a title to an AniList entry, cards that resolve to the same AniList id are folded together automatically instead of being left as duplicates. Entries whose parsed seasons disagree are left alone.
|
||||
@@ -0,0 +1,4 @@
|
||||
type: fixed
|
||||
area: playback
|
||||
|
||||
- XWayland/X11 mode (`--backend=x11`, or the automatic fallback on non-Hyprland/Sway Wayland sessions) no longer forces mpv onto `--vo=gpu --gpu-api=opengl`. It now only pins the window context (`--gpu-context=x11vk,x11egl,x11`), so a `vo=gpu-next` config keeps its renderer, API, and user shaders. Forcing the legacy OpenGL renderer crashed mpv on the first fullscreen toggle for anyone using a gpu-next user shader that emits a 4-component LUMA hook (ArtCNN and friends), which asserts in mpv's old renderer (`copy_image: *offset + count < sizeof(dst)`) as soon as the shader's upscale-only condition turns on.
|
||||
@@ -57,6 +57,13 @@ Jellyfin stream URLs are normalized to stable item links before stats titles are
|
||||
|
||||
When YouTube channel metadata is available, the Library tab groups videos by creator/channel and treats each tracked video as an episode-like entry inside that channel section.
|
||||
|
||||
A library entry is identified by its parsed title plus any detected season, so the same show can end up on several cards when releases disagree about the title or omit the season tag. Two fixes are available:
|
||||
|
||||
- **Merge duplicates.** Hit **Select** above the grid, tick the cards that are the same show, and choose **Merge Selected**. Pick which entry to keep in the dialog; every episode moves onto it and the other cards are removed. Nothing is deleted, so sessions, mined cards and watch time all carry over.
|
||||
- **Move a single episode.** Hover an episode row in a title's episode list and use the **→** button to reassign it to another library entry. If that was the entry's last episode, the now-empty card is removed and you are returned to the grid.
|
||||
|
||||
Once cover art resolves a series to an AniList entry, cards that resolve to the same AniList id are folded together automatically. Entries with conflicting season numbers are left alone rather than merged.
|
||||
|
||||
Open a title and use **Delete Entry** in its header to remove a mistakenly tracked show outright. This deletes every episode of that title along with their sessions, subtitle lines, rollups and cover art, drops the words and kanji that were only seen there, and removes the card from the Library grid. Individual episodes and sessions can still be deleted on their own from the episode list and session rows. Entry deletion is refused while that title is the one currently playing.
|
||||
|
||||

|
||||
|
||||
@@ -406,7 +406,7 @@ On any Wayland session that is not Hyprland or Sway (KDE Plasma, GNOME, and othe
|
||||
SubMiner handles this automatically:
|
||||
|
||||
- It launches its own window under XWayland (it sets `--ozone-platform-hint=x11`).
|
||||
- Every mpv it launches (via the `subminer` launcher, Jellyfin, or YouTube) is pinned to XWayland too - Wayland environment hints are stripped and an X11 GPU context (`--gpu-context=x11egl,x11`) is applied.
|
||||
- Every mpv it launches (via the `subminer` launcher, Jellyfin, or YouTube) is pinned to XWayland too - Wayland environment hints are stripped and an X11 GPU context (`--gpu-context=x11vk,x11egl,x11`) is applied. Only the window context is overridden; your `vo`/`gpu-api` and user shaders are left alone.
|
||||
- While mpv is windowed, the overlay is a managed X11 window owned by the tracked mpv window (`WM_TRANSIENT_FOR`), so it stays above mpv while other foreground X11/Xwayland apps can still cover both windows.
|
||||
- While tracked mpv is fullscreen, SubMiner swaps the visible overlay to a focusable-false X11 override-redirect window. That path can stay above the active fullscreen mpv window without requiring a KDE/KWin-specific rule, and SubMiner hides/releases it when mpv is no longer the active X11/Xwayland window.
|
||||
- The visible overlay is shown inactive on Linux, so normal hover should not steal keyboard focus from mpv.
|
||||
@@ -420,7 +420,7 @@ Requirements: `xdotool`, `xprop`, and `xwininfo` must be installed. SubMiner use
|
||||
This almost always means mpv came up as a **native Wayland** window that the XWayland overlay cannot cover. It happens when mpv is launched **manually** (your own command), because SubMiner can only force XWayland on the mpv processes it launches itself. Fix it one of these ways:
|
||||
|
||||
- Launch playback through SubMiner (the `subminer` launcher or the tray), which forces XWayland for you, or
|
||||
- Force XWayland in your own mpv invocation, e.g. `mpv --gpu-context=x11egl …`, or launch with `WAYLAND_DISPLAY= mpv …`, or set `gpu-context=x11egl` in your `mpv.conf`.
|
||||
- Force XWayland in your own mpv invocation, e.g. `mpv --gpu-context=x11vk,x11egl,x11 …`, or launch with `WAYLAND_DISPLAY= mpv …`, or set `gpu-context=x11vk` (Vulkan) / `gpu-context=x11egl` (OpenGL) in your `mpv.conf`.
|
||||
|
||||
To confirm mpv is on XWayland, `xdotool search --class mpv` should return a window id (a native Wayland mpv returns nothing).
|
||||
|
||||
|
||||
@@ -222,7 +222,7 @@ test('buildMpvEnv preserves native Wayland env for supported Hyprland and Sway a
|
||||
});
|
||||
});
|
||||
|
||||
test('buildMpvBackendArgs forces an explicit X11 renderer stack when backend resolves to x11', () => {
|
||||
test('buildMpvBackendArgs pins the X11 window context when backend resolves to x11', () => {
|
||||
withPlatform('linux', () => {
|
||||
assert.deepEqual(
|
||||
buildMpvBackendArgs(makeArgs({ backend: 'x11' }), {
|
||||
@@ -230,12 +230,12 @@ test('buildMpvBackendArgs forces an explicit X11 renderer stack when backend res
|
||||
WAYLAND_DISPLAY: 'wayland-0',
|
||||
XDG_SESSION_TYPE: 'wayland',
|
||||
}),
|
||||
['--vo=gpu', '--gpu-api=opengl', '--gpu-context=x11egl,x11'],
|
||||
['--gpu-context=x11vk,x11egl,x11'],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('buildMpvBackendArgs forces the same X11 renderer stack for unsupported Wayland auto fallback', () => {
|
||||
test('buildMpvBackendArgs pins the same X11 window context for unsupported Wayland auto fallback', () => {
|
||||
withPlatform('linux', () => {
|
||||
assert.deepEqual(
|
||||
buildMpvBackendArgs(makeArgs({ backend: 'auto' }), {
|
||||
@@ -245,7 +245,7 @@ test('buildMpvBackendArgs forces the same X11 renderer stack for unsupported Way
|
||||
XDG_CURRENT_DESKTOP: 'KDE',
|
||||
XDG_SESSION_DESKTOP: 'plasma',
|
||||
}),
|
||||
['--vo=gpu', '--gpu-api=opengl', '--gpu-context=x11egl,x11'],
|
||||
['--gpu-context=x11vk,x11egl,x11'],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -292,9 +292,7 @@ test('buildConfiguredMpvDefaultArgs appends maximized launch mode to configured
|
||||
'--secondary-sub-visibility=no',
|
||||
'--alang=ja,jp,jpn,japanese,en,eng,english,enus,en-us',
|
||||
'--slang=ja,jp,jpn,japanese,en,eng,english,enus,en-us',
|
||||
'--vo=gpu',
|
||||
'--gpu-api=opengl',
|
||||
'--gpu-context=x11egl,x11',
|
||||
'--gpu-context=x11vk,x11egl,x11',
|
||||
'--window-maximized=yes',
|
||||
],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { DatabaseSync } from '../immersion-tracker/sqlite';
|
||||
|
||||
type ImmersionTrackerService = import('../immersion-tracker-service').ImmersionTrackerService;
|
||||
type ImmersionTrackerServiceCtor =
|
||||
typeof import('../immersion-tracker-service').ImmersionTrackerService;
|
||||
|
||||
let trackerCtor: ImmersionTrackerServiceCtor | null = null;
|
||||
|
||||
async function loadTrackerCtor(): Promise<ImmersionTrackerServiceCtor> {
|
||||
if (trackerCtor) return trackerCtor;
|
||||
const mod = await import('../immersion-tracker-service');
|
||||
trackerCtor = mod.ImmersionTrackerService;
|
||||
return trackerCtor;
|
||||
}
|
||||
|
||||
function makeDbPath(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-write-queue-test-'));
|
||||
return path.join(dir, 'immersion.sqlite');
|
||||
}
|
||||
|
||||
function cleanupDbPath(dbPath: string): void {
|
||||
const dir = path.dirname(dbPath);
|
||||
if (!fs.existsSync(dir)) return;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
interface TrackerInternals {
|
||||
db: DatabaseSync;
|
||||
queue: unknown[];
|
||||
recordWrite: (write: Record<string, unknown>) => void;
|
||||
mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<unknown>;
|
||||
moveVideoToAnime: (videoId: number, targetAnimeId: number) => Promise<unknown>;
|
||||
}
|
||||
|
||||
function seedTwoEntries(db: DatabaseSync): void {
|
||||
db.exec(`
|
||||
INSERT INTO imm_anime (anime_id, normalized_title_key, canonical_title, CREATED_DATE, LAST_UPDATE_DATE)
|
||||
VALUES (1, 'show', 'Show', 1000, 1000), (2, 'show season 1', 'Show Season 1', 1000, 1000);
|
||||
INSERT INTO imm_videos (video_id, video_key, canonical_title, anime_id, source_type, watched, duration_ms, CREATED_DATE, LAST_UPDATE_DATE)
|
||||
VALUES (1, 'local:/tmp/a.mkv', 'A', 1, 1, 0, 1440000, 1000, 1000),
|
||||
(2, 'local:/tmp/b.mkv', 'B', 2, 1, 0, 1440000, 1000, 1000);
|
||||
INSERT INTO imm_sessions (session_id, session_uuid, video_id, started_at_ms, ended_at_ms, status, active_watched_ms, CREATED_DATE, LAST_UPDATE_DATE)
|
||||
VALUES (1, 'drain-session', 2, '1000', '2000', 2, 1000, 1000, 2000);
|
||||
`);
|
||||
}
|
||||
|
||||
function queueSubtitleLines(tracker: TrackerInternals, count: number): void {
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
tracker.recordWrite({
|
||||
kind: 'subtitleLine',
|
||||
sessionId: 1,
|
||||
videoId: 2,
|
||||
lineIndex: index,
|
||||
segmentStartMs: index * 1000,
|
||||
segmentEndMs: index * 1000 + 900,
|
||||
text: `line ${index}`,
|
||||
wordOccurrences: [],
|
||||
kanjiOccurrences: [],
|
||||
firstSeen: 1000,
|
||||
lastSeen: 2000,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Queued last so it sits past the first batch. Lifetime `total_lines_seen`
|
||||
* reads this counter, not a COUNT over imm_subtitle_lines, so the rebuilt
|
||||
* summary only reflects the session once the queue is drained all the way.
|
||||
*/
|
||||
function queueTelemetry(tracker: TrackerInternals, linesSeen: number): void {
|
||||
tracker.recordWrite({
|
||||
kind: 'telemetry',
|
||||
sessionId: 1,
|
||||
sampleMs: 3000,
|
||||
lastMediaMs: 3000,
|
||||
totalWatchedMs: 4000,
|
||||
activeWatchedMs: 3500,
|
||||
linesSeen,
|
||||
tokensSeen: linesSeen * 5,
|
||||
cardsMined: 2,
|
||||
lookupCount: 0,
|
||||
lookupHits: 0,
|
||||
yomitanLookupCount: 0,
|
||||
pauseCount: 0,
|
||||
pauseMs: 0,
|
||||
seekForwardCount: 0,
|
||||
seekBackwardCount: 0,
|
||||
mediaBufferEvents: 0,
|
||||
});
|
||||
}
|
||||
|
||||
function lifetimeForAnime(
|
||||
db: DatabaseSync,
|
||||
animeId: number,
|
||||
): { linesSeen: number; activeMs: number; cards: number } | null {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT total_lines_seen AS linesSeen, total_active_ms AS activeMs, total_cards AS cards
|
||||
FROM imm_lifetime_anime WHERE anime_id = ?`,
|
||||
)
|
||||
.get(animeId) as { linesSeen: number; activeMs: number; cards: number } | undefined;
|
||||
return row
|
||||
? { linesSeen: Number(row.linesSeen), activeMs: Number(row.activeMs), cards: Number(row.cards) }
|
||||
: null;
|
||||
}
|
||||
|
||||
function countLinesForAnime(db: DatabaseSync, animeId: number): number {
|
||||
const row = db
|
||||
.prepare('SELECT COUNT(*) AS total FROM imm_subtitle_lines WHERE anime_id = ?')
|
||||
.get(animeId) as { total: number };
|
||||
return Number(row.total);
|
||||
}
|
||||
|
||||
/**
|
||||
* Both entry points rebuild the lifetime summaries, which recompute from the
|
||||
* database. A single flushNow() only writes one batch off the front of the
|
||||
* queue, so anything past `batchSize` would still be unwritten when the rebuild
|
||||
* reads.
|
||||
*/
|
||||
test('mergeAnime drains a queue larger than one batch before rebuilding summaries', async () => {
|
||||
const dbPath = makeDbPath();
|
||||
let tracker: ImmersionTrackerService | null = null;
|
||||
|
||||
try {
|
||||
const Ctor = await loadTrackerCtor();
|
||||
tracker = new Ctor({ dbPath, policy: { batchSize: 2 } });
|
||||
const internals = tracker as unknown as TrackerInternals;
|
||||
|
||||
seedTwoEntries(internals.db);
|
||||
queueSubtitleLines(internals, 8);
|
||||
queueTelemetry(internals, 8);
|
||||
assert.ok(internals.queue.length > 2, 'expected more queued writes than one batch');
|
||||
|
||||
await internals.mergeAnime(1, [2]);
|
||||
|
||||
assert.equal(internals.queue.length, 0);
|
||||
assert.equal(countLinesForAnime(internals.db, 1), 8);
|
||||
// The surviving entry's summary was rebuilt from the fully drained queue.
|
||||
const lifetime = lifetimeForAnime(internals.db, 1);
|
||||
assert.equal(lifetime?.linesSeen, 8);
|
||||
assert.equal(lifetime?.activeMs, 3500);
|
||||
assert.equal(lifetime?.cards, 2);
|
||||
} finally {
|
||||
tracker?.destroy();
|
||||
cleanupDbPath(dbPath);
|
||||
}
|
||||
});
|
||||
|
||||
test('moveVideoToAnime drains a queue larger than one batch before rebuilding summaries', async () => {
|
||||
const dbPath = makeDbPath();
|
||||
let tracker: ImmersionTrackerService | null = null;
|
||||
|
||||
try {
|
||||
const Ctor = await loadTrackerCtor();
|
||||
tracker = new Ctor({ dbPath, policy: { batchSize: 2 } });
|
||||
const internals = tracker as unknown as TrackerInternals;
|
||||
|
||||
seedTwoEntries(internals.db);
|
||||
queueSubtitleLines(internals, 8);
|
||||
queueTelemetry(internals, 8);
|
||||
|
||||
await internals.moveVideoToAnime(2, 1);
|
||||
|
||||
assert.equal(internals.queue.length, 0);
|
||||
assert.equal(countLinesForAnime(internals.db, 1), 8);
|
||||
const lifetime = lifetimeForAnime(internals.db, 1);
|
||||
assert.equal(lifetime?.linesSeen, 8);
|
||||
assert.equal(lifetime?.activeMs, 3500);
|
||||
assert.equal(lifetime?.cards, 2);
|
||||
} finally {
|
||||
tracker?.destroy();
|
||||
cleanupDbPath(dbPath);
|
||||
}
|
||||
});
|
||||
@@ -3024,6 +3024,148 @@ Aligned English subtitle
|
||||
assert.equal(deleteCalls, 0);
|
||||
});
|
||||
|
||||
it('POST /api/stats/anime/:animeId/merge folds the given entries into the target', async () => {
|
||||
let merged: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
|
||||
const app = createStatsApp(
|
||||
createMockTracker({
|
||||
mergeAnime: async (targetAnimeId: number, sourceAnimeIds: number[]) => {
|
||||
merged = { targetAnimeId, sourceAnimeIds };
|
||||
return {
|
||||
survivingAnimeId: targetAnimeId,
|
||||
mergedAnimeIds: sourceAnimeIds,
|
||||
movedVideos: 3,
|
||||
};
|
||||
},
|
||||
} as Partial<ImmersionTrackerService>),
|
||||
);
|
||||
|
||||
const res = await app.request('/api/stats/anime/7/merge', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
// The target repeated in the sources must not delete the entry we keep.
|
||||
body: '{"sourceAnimeIds":[8,9,8,7]}',
|
||||
});
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(merged, { targetAnimeId: 7, sourceAnimeIds: [8, 9] });
|
||||
assert.deepEqual(await res.json(), {
|
||||
ok: true,
|
||||
animeId: 7,
|
||||
mergedAnimeIds: [8, 9],
|
||||
movedVideos: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('POST /api/stats/anime/:animeId/merge rejects an empty or malformed source list', async () => {
|
||||
let mergeCalls = 0;
|
||||
const app = createStatsApp(
|
||||
createMockTracker({
|
||||
mergeAnime: async () => {
|
||||
mergeCalls += 1;
|
||||
return { survivingAnimeId: 7, mergedAnimeIds: [], movedVideos: 0 };
|
||||
},
|
||||
} as Partial<ImmersionTrackerService>),
|
||||
);
|
||||
|
||||
for (const body of [
|
||||
'{"sourceAnimeIds":[]}',
|
||||
'{"sourceAnimeIds":[7]}',
|
||||
'{"sourceAnimeIds":0}',
|
||||
]) {
|
||||
const res = await app.request('/api/stats/anime/7/merge', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body,
|
||||
});
|
||||
assert.equal(res.status, 400);
|
||||
}
|
||||
assert.equal(mergeCalls, 0);
|
||||
});
|
||||
|
||||
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(
|
||||
createMockTracker({
|
||||
moveVideoToAnime: async (videoId: number, animeId: number) => {
|
||||
moved = { videoId, animeId };
|
||||
return { targetAnimeId: animeId, previousAnimeId: 4, removedPreviousAnime: true };
|
||||
},
|
||||
} as Partial<ImmersionTrackerService>),
|
||||
);
|
||||
|
||||
const res = await app.request('/api/stats/media/12/anime', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{"animeId":7}',
|
||||
});
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(moved, { videoId: 12, animeId: 7 });
|
||||
assert.deepEqual(await res.json(), {
|
||||
ok: true,
|
||||
animeId: 7,
|
||||
previousAnimeId: 4,
|
||||
removedPreviousAnime: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('POST /api/stats/anime/:animeId/merge reports a merge that folded nothing as 404', async () => {
|
||||
const app = createStatsApp(
|
||||
createMockTracker({
|
||||
mergeAnime: async (targetAnimeId: number) => ({
|
||||
survivingAnimeId: targetAnimeId,
|
||||
mergedAnimeIds: [],
|
||||
movedVideos: 0,
|
||||
}),
|
||||
} as Partial<ImmersionTrackerService>),
|
||||
);
|
||||
|
||||
const res = await app.request('/api/stats/anime/7/merge', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{"sourceAnimeIds":[8]}',
|
||||
});
|
||||
|
||||
assert.equal(res.status, 404);
|
||||
});
|
||||
|
||||
it('PATCH /api/stats/media/:videoId/anime reports an unknown target as 404', async () => {
|
||||
const app = createStatsApp(
|
||||
createMockTracker({
|
||||
moveVideoToAnime: async () => {
|
||||
throw new Error('Unknown episode or target library entry');
|
||||
},
|
||||
} as Partial<ImmersionTrackerService>),
|
||||
);
|
||||
|
||||
const res = await app.request('/api/stats/media/12/anime', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{"animeId":99}',
|
||||
});
|
||||
|
||||
assert.equal(res.status, 404);
|
||||
});
|
||||
|
||||
it('PATCH /api/stats/media/:videoId/anime does not disguise storage failures as 404', async () => {
|
||||
const app = createStatsApp(
|
||||
createMockTracker({
|
||||
moveVideoToAnime: async () => {
|
||||
throw new Error('database is locked');
|
||||
},
|
||||
} as Partial<ImmersionTrackerService>),
|
||||
);
|
||||
|
||||
const res = await app.request('/api/stats/media/12/anime', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{"animeId":7}',
|
||||
});
|
||||
|
||||
assert.notEqual(res.status, 404);
|
||||
assert.equal(res.status >= 500, true);
|
||||
});
|
||||
|
||||
it('POST /api/stats/anki/browse returns 400 for missing noteId', async () => {
|
||||
const app = createStatsApp(createMockTracker());
|
||||
const res = await app.request('/api/stats/anki/browse', { method: 'POST' });
|
||||
|
||||
@@ -96,6 +96,12 @@ import {
|
||||
repairLegacySeasonlessAnimeRows,
|
||||
resolveAnimeAnilistConflict,
|
||||
} from './immersion-tracker/anime-season-repair';
|
||||
import {
|
||||
mergeAnimeRecords,
|
||||
moveVideoToAnime as moveVideoToAnimeQuery,
|
||||
type AnimeMergeSummary,
|
||||
type VideoMoveSummary,
|
||||
} from './immersion-tracker/anime-merge';
|
||||
import {
|
||||
buildVideoKey,
|
||||
deriveCanonicalTitle,
|
||||
@@ -596,8 +602,7 @@ export class ImmersionTrackerService {
|
||||
}
|
||||
|
||||
async rebuildLifetimeSummaries(): Promise<LifetimeRebuildSummary> {
|
||||
this.flushTelemetry(true);
|
||||
this.flushNow();
|
||||
this.drainWriteQueue('rebuilding lifetime summaries');
|
||||
return rebuildLifetimeSummaryTables(this.db);
|
||||
}
|
||||
|
||||
@@ -756,6 +761,57 @@ export class ImmersionTrackerService {
|
||||
deleteAnimeQuery(this.db, animeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold duplicate library entries into one. Sources that hold the currently
|
||||
* playing episode are fine: the videos move, nothing is deleted out from
|
||||
* under the active session.
|
||||
*/
|
||||
async mergeAnime(targetAnimeId: number, sourceAnimeIds: number[]): Promise<AnimeMergeSummary> {
|
||||
const pendingVideoId = this.sessionState?.videoId;
|
||||
if (pendingVideoId !== undefined) {
|
||||
await this.pendingAnimeMetadataUpdates.get(pendingVideoId);
|
||||
}
|
||||
// This rebuilds the lifetime summaries, which recompute from the database:
|
||||
// queued writes have to land first or the active session is dropped from
|
||||
// the merged totals.
|
||||
this.drainWriteQueue('merging library entries');
|
||||
return mergeAnimeRecords(this.db, targetAnimeId, sourceAnimeIds);
|
||||
}
|
||||
|
||||
async moveVideoToAnime(videoId: number, targetAnimeId: number): Promise<VideoMoveSummary> {
|
||||
await this.pendingAnimeMetadataUpdates.get(videoId);
|
||||
this.drainWriteQueue('moving an episode');
|
||||
return moveVideoToAnimeQuery(this.db, videoId, targetAnimeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist every queued write before a caller recomputes summaries from the
|
||||
* database.
|
||||
*
|
||||
* A single `flushNow()` is not enough: forced telemetry is appended to the
|
||||
* back of the queue while `flushNow()` writes at most `batchSize` entries off
|
||||
* the front, so a busy session leaves the newest sample unwritten. Stops as
|
||||
* soon as a pass makes no progress — a rolled-back batch is pushed back onto
|
||||
* the queue, and looping on that would spin forever.
|
||||
*
|
||||
* Returns false when the queue could not be emptied, in which case the
|
||||
* rebuild runs against a database still missing those writes.
|
||||
*/
|
||||
private drainWriteQueue(context: string): boolean {
|
||||
this.flushTelemetry(true);
|
||||
while (this.queue.length > 0) {
|
||||
const pending = this.queue.length;
|
||||
this.flushNow();
|
||||
if (this.queue.length >= pending) {
|
||||
this.logger.warn(
|
||||
`Immersion tracker queue did not drain before ${context}; summaries may lag by ${this.queue.length} writes`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async reassignAnimeAnilist(
|
||||
animeId: number,
|
||||
info: {
|
||||
@@ -768,7 +824,11 @@ export class ImmersionTrackerService {
|
||||
coverUrl?: string | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
const repair = resolveAnimeAnilistConflict(this.db, animeId, info.anilistId);
|
||||
// The user is acting on this entry, so it is the one that survives when
|
||||
// another row already claims the same AniList id.
|
||||
const repair = resolveAnimeAnilistConflict(this.db, animeId, info.anilistId, {
|
||||
survivor: 'target',
|
||||
});
|
||||
this.db
|
||||
.prepare(
|
||||
`
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { Database } from '../sqlite.js';
|
||||
import type { DatabaseSync } from '../sqlite.js';
|
||||
import { applyPragmas, ensureSchema } from '../storage.js';
|
||||
import { mergeAnimeRecords, moveVideoToAnime } from '../anime-merge.js';
|
||||
import { resolveAnimeAnilistConflict } from '../anime-season-repair.js';
|
||||
|
||||
const BASE_MS = 1_700_000_000_000;
|
||||
|
||||
function makeDbPath(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-anime-merge-test-'));
|
||||
return path.join(dir, 'immersion.sqlite');
|
||||
}
|
||||
|
||||
function cleanupDbPath(dbPath: string): void {
|
||||
const dir = path.dirname(dbPath);
|
||||
if (!fs.existsSync(dir)) return;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function withDb(work: (db: DatabaseSync) => void): void {
|
||||
const dbPath = makeDbPath();
|
||||
const db = new Database(dbPath);
|
||||
try {
|
||||
applyPragmas(db);
|
||||
ensureSchema(db);
|
||||
work(db);
|
||||
} finally {
|
||||
db.close();
|
||||
cleanupDbPath(dbPath);
|
||||
}
|
||||
}
|
||||
|
||||
interface AnimeSeed {
|
||||
animeId: number;
|
||||
key: string;
|
||||
title: string;
|
||||
anilistId?: number | null;
|
||||
titleRomaji?: string | null;
|
||||
}
|
||||
|
||||
function insertAnime(db: DatabaseSync, seed: AnimeSeed): void {
|
||||
db.prepare(
|
||||
`INSERT INTO imm_anime(anime_id, normalized_title_key, canonical_title, anilist_id, title_romaji, CREATED_DATE, LAST_UPDATE_DATE)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
seed.animeId,
|
||||
seed.key,
|
||||
seed.title,
|
||||
seed.anilistId ?? null,
|
||||
seed.titleRomaji ?? null,
|
||||
BASE_MS,
|
||||
BASE_MS,
|
||||
);
|
||||
}
|
||||
|
||||
interface EpisodeSeed {
|
||||
videoId: number;
|
||||
animeId: number;
|
||||
season?: number | null;
|
||||
episode?: number;
|
||||
activeMs?: number;
|
||||
cards?: number;
|
||||
}
|
||||
|
||||
/** One episode with one ended session, so lifetime rebuilds have something to sum. */
|
||||
function insertEpisode(db: DatabaseSync, seed: EpisodeSeed): void {
|
||||
const activeMs = seed.activeMs ?? 1000;
|
||||
const cards = seed.cards ?? 1;
|
||||
db.prepare(
|
||||
`INSERT INTO imm_videos(video_id, video_key, anime_id, canonical_title, source_type, parsed_title, parsed_season, parsed_episode, watched, duration_ms, CREATED_DATE, LAST_UPDATE_DATE)
|
||||
VALUES (?, ?, ?, ?, 1, 'Show', ?, ?, 1, 1440000, ?, ?)`,
|
||||
).run(
|
||||
seed.videoId,
|
||||
`local:/tmp/show-${seed.videoId}.mkv`,
|
||||
seed.animeId,
|
||||
`Show ${seed.videoId}`,
|
||||
seed.season ?? null,
|
||||
seed.episode ?? seed.videoId,
|
||||
BASE_MS,
|
||||
BASE_MS,
|
||||
);
|
||||
db.prepare(
|
||||
`INSERT INTO imm_sessions(session_id, session_uuid, video_id, started_at_ms, ended_at_ms, status, active_watched_ms, cards_mined, CREATED_DATE, LAST_UPDATE_DATE)
|
||||
VALUES (?, ?, ?, ?, ?, 2, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
seed.videoId,
|
||||
`session-${seed.videoId}`,
|
||||
seed.videoId,
|
||||
String(BASE_MS),
|
||||
String(BASE_MS + activeMs),
|
||||
activeMs,
|
||||
cards,
|
||||
BASE_MS,
|
||||
BASE_MS,
|
||||
);
|
||||
db.prepare(
|
||||
`INSERT INTO imm_subtitle_lines(session_id, video_id, anime_id, line_index, text, CREATED_DATE, LAST_UPDATE_DATE)
|
||||
VALUES (?, ?, ?, 1, ?, ?, ?)`,
|
||||
).run(seed.videoId, seed.videoId, seed.animeId, `line ${seed.videoId}`, BASE_MS, BASE_MS);
|
||||
}
|
||||
|
||||
function animeIds(db: DatabaseSync): number[] {
|
||||
return (
|
||||
db.prepare('SELECT anime_id AS id FROM imm_anime ORDER BY anime_id').all() as Array<{
|
||||
id: number;
|
||||
}>
|
||||
).map((row) => row.id);
|
||||
}
|
||||
|
||||
function videoAnimeId(db: DatabaseSync, videoId: number): number | null {
|
||||
return (
|
||||
db.prepare('SELECT anime_id AS id FROM imm_videos WHERE video_id = ?').get(videoId) as {
|
||||
id: number | null;
|
||||
}
|
||||
).id;
|
||||
}
|
||||
|
||||
function lineAnimeIds(db: DatabaseSync, animeId: number): number {
|
||||
return Number(
|
||||
(
|
||||
db
|
||||
.prepare('SELECT COUNT(*) AS total FROM imm_subtitle_lines WHERE anime_id = ?')
|
||||
.get(animeId) as { total: number }
|
||||
).total,
|
||||
);
|
||||
}
|
||||
|
||||
test('mergeAnimeRecords folds episodes, lines and lifetime totals into the target', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show' });
|
||||
insertAnime(db, { animeId: 2, key: 'show season 1', title: 'Show Season 1', anilistId: 555 });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1, activeMs: 1000, cards: 1 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 2, season: 1, activeMs: 2000, cards: 3 });
|
||||
|
||||
const summary = mergeAnimeRecords(db, 1, [2]);
|
||||
|
||||
assert.equal(summary.survivingAnimeId, 1);
|
||||
assert.deepEqual(summary.mergedAnimeIds, [2]);
|
||||
assert.equal(summary.movedVideos, 1);
|
||||
assert.deepEqual(animeIds(db), [1]);
|
||||
assert.equal(videoAnimeId(db, 2), 1);
|
||||
assert.equal(lineAnimeIds(db, 1), 2);
|
||||
|
||||
const lifetime = db
|
||||
.prepare(
|
||||
'SELECT total_active_ms AS activeMs, total_cards AS cards, episodes_started AS episodes FROM imm_lifetime_anime WHERE anime_id = 1',
|
||||
)
|
||||
.get() as { activeMs: number; cards: number; episodes: number };
|
||||
assert.equal(lifetime.activeMs, 3000);
|
||||
assert.equal(lifetime.cards, 4);
|
||||
assert.equal(lifetime.episodes, 2);
|
||||
});
|
||||
});
|
||||
|
||||
test('mergeAnimeRecords repoints subtitle lines recorded before the anime link landed', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show' });
|
||||
insertAnime(db, { animeId: 2, key: 'show season 1', title: 'Show Season 1' });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 2, season: 1 });
|
||||
// Lines are written with the video's anime_id at the time, which is NULL
|
||||
// until the async title parse assigns one.
|
||||
db.prepare(
|
||||
`INSERT INTO imm_subtitle_lines(session_id, video_id, anime_id, line_index, text, CREATED_DATE, LAST_UPDATE_DATE)
|
||||
VALUES (2, 2, NULL, 2, 'unlinked line', ?, ?)`,
|
||||
).run(BASE_MS, BASE_MS);
|
||||
|
||||
mergeAnimeRecords(db, 1, [2]);
|
||||
|
||||
assert.equal(lineAnimeIds(db, 1), 3);
|
||||
const orphaned = Number(
|
||||
(
|
||||
db
|
||||
.prepare('SELECT COUNT(*) AS total FROM imm_subtitle_lines WHERE anime_id IS NULL')
|
||||
.get() as { total: number }
|
||||
).total,
|
||||
);
|
||||
assert.equal(orphaned, 0);
|
||||
});
|
||||
});
|
||||
|
||||
test('mergeAnimeRecords inherits metadata the target is missing without clobbering its own', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show', titleRomaji: 'Shou' });
|
||||
insertAnime(db, {
|
||||
animeId: 2,
|
||||
key: 'show season 1',
|
||||
title: 'Show Season 1',
|
||||
anilistId: 555,
|
||||
titleRomaji: 'Show Romaji',
|
||||
});
|
||||
insertEpisode(db, { videoId: 1, animeId: 1 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 2, season: 1 });
|
||||
|
||||
mergeAnimeRecords(db, 1, [2]);
|
||||
|
||||
const row = db
|
||||
.prepare(
|
||||
'SELECT canonical_title AS title, anilist_id AS anilistId, title_romaji AS romaji FROM imm_anime WHERE anime_id = 1',
|
||||
)
|
||||
.get() as { title: string; anilistId: number | null; romaji: string | null };
|
||||
assert.equal(row.title, 'Show');
|
||||
// anilist_id is UNIQUE, so inheriting it proves the source row was gone first.
|
||||
assert.equal(row.anilistId, 555);
|
||||
assert.equal(row.romaji, 'Shou');
|
||||
});
|
||||
});
|
||||
|
||||
test('mergeAnimeRecords ignores unknown targets and self-merges', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show' });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1 });
|
||||
|
||||
assert.deepEqual(mergeAnimeRecords(db, 99, [1]).mergedAnimeIds, []);
|
||||
assert.deepEqual(mergeAnimeRecords(db, 1, [1]).mergedAnimeIds, []);
|
||||
assert.deepEqual(animeIds(db), [1]);
|
||||
assert.equal(videoAnimeId(db, 1), 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('moveVideoToAnime moves one episode and prunes the emptied entry', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show' });
|
||||
insertAnime(db, { animeId: 2, key: 'stray', title: 'Stray Episode Title', anilistId: 777 });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 2, activeMs: 5000, cards: 2 });
|
||||
|
||||
const summary = moveVideoToAnime(db, 2, 1);
|
||||
|
||||
assert.equal(summary.targetAnimeId, 1);
|
||||
assert.equal(summary.previousAnimeId, 2);
|
||||
assert.equal(summary.removedPreviousAnime, true);
|
||||
assert.deepEqual(animeIds(db), [1]);
|
||||
assert.equal(videoAnimeId(db, 2), 1);
|
||||
assert.equal(lineAnimeIds(db, 1), 2);
|
||||
const lifetime = db
|
||||
.prepare('SELECT total_active_ms AS activeMs FROM imm_lifetime_anime WHERE anime_id = 1')
|
||||
.get() as { activeMs: number };
|
||||
assert.equal(lifetime.activeMs, 6000);
|
||||
// The stray entry's AniList link is dropped, not inherited: a move makes no
|
||||
// claim that the two entries are the same show.
|
||||
const target = db
|
||||
.prepare('SELECT anilist_id AS anilistId FROM imm_anime WHERE anime_id = 1')
|
||||
.get() as { anilistId: number | null };
|
||||
assert.equal(target.anilistId, null);
|
||||
});
|
||||
});
|
||||
|
||||
test('moveVideoToAnime is a no-op when the episode is already in the target entry', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show' });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1 });
|
||||
|
||||
const summary = moveVideoToAnime(db, 1, 1);
|
||||
|
||||
assert.equal(summary.targetAnimeId, 1);
|
||||
assert.equal(summary.previousAnimeId, 1);
|
||||
assert.equal(summary.removedPreviousAnime, false);
|
||||
assert.deepEqual(animeIds(db), [1]);
|
||||
assert.equal(videoAnimeId(db, 1), 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('moveVideoToAnime keeps the source entry when other episodes remain', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show' });
|
||||
insertAnime(db, { animeId: 2, key: 'other', title: 'Other' });
|
||||
insertEpisode(db, { videoId: 1, animeId: 2 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 2 });
|
||||
|
||||
const summary = moveVideoToAnime(db, 2, 1);
|
||||
|
||||
assert.equal(summary.removedPreviousAnime, false);
|
||||
assert.deepEqual(animeIds(db), [1, 2]);
|
||||
assert.equal(videoAnimeId(db, 1), 2);
|
||||
assert.equal(videoAnimeId(db, 2), 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('moveVideoToAnime rejects unknown episodes and targets', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show' });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1 });
|
||||
|
||||
assert.throws(() => moveVideoToAnime(db, 99, 1));
|
||||
assert.throws(() => moveVideoToAnime(db, 1, 99));
|
||||
assert.equal(videoAnimeId(db, 1), 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('resolveAnimeAnilistConflict folds a seasonless duplicate into the entry that owns the id', () => {
|
||||
withDb((db) => {
|
||||
// Same show, split because one release tagged S01 and the other did not.
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show', anilistId: 163132 });
|
||||
insertAnime(db, { animeId: 2, key: 'show season 1', title: 'Show Season 1' });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 2, season: 1 });
|
||||
|
||||
const summary = resolveAnimeAnilistConflict(db, 2, 163132);
|
||||
|
||||
assert.equal(summary.survivingAnimeId, 1);
|
||||
assert.equal(summary.movedVideos, 1);
|
||||
assert.equal(summary.deletedAnimeRows, 1);
|
||||
assert.deepEqual(animeIds(db), [1]);
|
||||
assert.equal(videoAnimeId(db, 2), 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('resolveAnimeAnilistConflict keeps the target entry when the user drove the change', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show', anilistId: 163132 });
|
||||
insertAnime(db, { animeId: 2, key: 'show season 1', title: 'Show Season 1' });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 2, season: 1 });
|
||||
|
||||
const summary = resolveAnimeAnilistConflict(db, 2, 163132, { survivor: 'target' });
|
||||
|
||||
assert.equal(summary.survivingAnimeId, 2);
|
||||
assert.deepEqual(animeIds(db), [2]);
|
||||
assert.equal(videoAnimeId(db, 1), 2);
|
||||
const row = db.prepare('SELECT anilist_id AS id FROM imm_anime WHERE anime_id = 2').get() as {
|
||||
id: number | null;
|
||||
};
|
||||
assert.equal(row.id, 163132);
|
||||
});
|
||||
});
|
||||
|
||||
test('resolveAnimeAnilistConflict falls back to season redistribution for multi-season rows', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show', anilistId: 163132 });
|
||||
insertAnime(db, { animeId: 2, key: 'show season 1', title: 'Show Season 1' });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1, season: 1 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 1, season: 2 });
|
||||
insertEpisode(db, { videoId: 3, animeId: 2, season: 1 });
|
||||
|
||||
resolveAnimeAnilistConflict(db, 2, 163132);
|
||||
|
||||
// The mixed row is split by season instead of being poured onto one card.
|
||||
const titles = (
|
||||
db.prepare('SELECT canonical_title AS title FROM imm_anime ORDER BY title').all() as Array<{
|
||||
title: string;
|
||||
}>
|
||||
).map((row) => row.title);
|
||||
assert.deepEqual(titles, ['Show Season 1', 'Show Season 2']);
|
||||
assert.equal(videoAnimeId(db, 1), 2);
|
||||
assert.equal(videoAnimeId(db, 3), 2);
|
||||
assert.notEqual(videoAnimeId(db, 2), 2);
|
||||
});
|
||||
});
|
||||
|
||||
test('resolveAnimeAnilistConflict leaves an entry that already links elsewhere alone', () => {
|
||||
withDb((db) => {
|
||||
insertAnime(db, { animeId: 1, key: 'show', title: 'Show', anilistId: 163132 });
|
||||
insertAnime(db, { animeId: 2, key: 'show s2', title: 'Show Season 2', anilistId: 999 });
|
||||
insertEpisode(db, { videoId: 1, animeId: 1, season: 1 });
|
||||
insertEpisode(db, { videoId: 2, animeId: 2, season: 2 });
|
||||
|
||||
resolveAnimeAnilistConflict(db, 2, 163132);
|
||||
|
||||
assert.equal(videoAnimeId(db, 2), 2);
|
||||
assert.ok(animeIds(db).includes(2));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,268 @@
|
||||
import type { DatabaseSync } from './sqlite';
|
||||
import { rebuildLifetimeSummariesInTransaction } from './lifetime';
|
||||
import { toDbTimestamp } from './query-shared';
|
||||
import { nowMs } from './time';
|
||||
|
||||
/** Thrown when a move names an episode or destination entry that is not there. */
|
||||
export const UNKNOWN_MOVE_TARGET_MESSAGE = 'Unknown episode or target library entry';
|
||||
|
||||
export interface AnimeMergeSummary {
|
||||
/** Library entry that owns every moved episode once the merge finishes. */
|
||||
survivingAnimeId: number;
|
||||
/** Entries that were folded into the survivor and deleted. */
|
||||
mergedAnimeIds: number[];
|
||||
movedVideos: number;
|
||||
}
|
||||
|
||||
export interface VideoMoveSummary {
|
||||
targetAnimeId: number;
|
||||
/** Previous owner, or null when the episode had no library entry yet. */
|
||||
previousAnimeId: number | null;
|
||||
/** True when the previous owner was left empty and pruned. */
|
||||
removedPreviousAnime: boolean;
|
||||
}
|
||||
|
||||
interface AnimeMetadataRow {
|
||||
anilist_id: number | null;
|
||||
title_romaji: string | null;
|
||||
title_english: string | null;
|
||||
title_native: string | null;
|
||||
episodes_total: number | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
function emptyMergeSummary(survivingAnimeId: number): AnimeMergeSummary {
|
||||
return { survivingAnimeId, mergedAnimeIds: [], movedVideos: 0 };
|
||||
}
|
||||
|
||||
function runInTransaction<T>(db: DatabaseSync, work: () => T): T {
|
||||
db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
const result = work();
|
||||
db.exec('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function readAnimeMetadata(db: DatabaseSync, animeId: number): AnimeMetadataRow | null {
|
||||
return (db
|
||||
.prepare(
|
||||
`
|
||||
SELECT anilist_id, title_romaji, title_english, title_native, episodes_total, description
|
||||
FROM imm_anime
|
||||
WHERE anime_id = ?
|
||||
`,
|
||||
)
|
||||
.get(animeId) ?? null) as AnimeMetadataRow | null;
|
||||
}
|
||||
|
||||
function animeExists(db: DatabaseSync, animeId: number): boolean {
|
||||
return Boolean(db.prepare('SELECT 1 FROM imm_anime WHERE anime_id = ?').get(animeId));
|
||||
}
|
||||
|
||||
function hasAnimeReferences(db: DatabaseSync, animeId: number): boolean {
|
||||
const row = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT 1 AS found
|
||||
WHERE EXISTS (SELECT 1 FROM imm_videos WHERE anime_id = ?)
|
||||
OR EXISTS (SELECT 1 FROM imm_subtitle_lines WHERE anime_id = ?)
|
||||
`,
|
||||
)
|
||||
.get(animeId, animeId) as { found: number } | null;
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
/**
|
||||
* Distinct explicit seasons behind a library entry. Videos with no parsed
|
||||
* season are ignored, so an entry built from `Show - 03.mkv` style filenames
|
||||
* reports an empty set rather than a bogus season.
|
||||
*/
|
||||
export function getParsedSeasonsForAnime(db: DatabaseSync, animeId: number): Set<number> {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT DISTINCT parsed_season AS season
|
||||
FROM imm_videos
|
||||
WHERE anime_id = ?
|
||||
AND parsed_season IS NOT NULL
|
||||
AND parsed_season > 0
|
||||
`,
|
||||
)
|
||||
.all(animeId) as Array<{ season: number }>;
|
||||
return new Set(rows.map((row) => row.season));
|
||||
}
|
||||
|
||||
/**
|
||||
* Two entries are safe to fold together when neither spans more than one
|
||||
* explicit season and they do not disagree about which season that is. A
|
||||
* seasonless entry is compatible with anything single-season: those are the
|
||||
* `Show - 03.mkv` vs `Show.S01E03.mkv` splits that produce duplicate cards.
|
||||
*/
|
||||
export function animeSeasonsAreMergeCompatible(a: Set<number>, b: Set<number>): boolean {
|
||||
if (a.size > 1 || b.size > 1) return false;
|
||||
if (a.size === 0 || b.size === 0) return true;
|
||||
return [...a][0] === [...b][0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill in whatever the target is missing from a source row that is on its way
|
||||
* out. Must run after the source row is deleted: imm_anime.anilist_id is
|
||||
* UNIQUE, so the two rows cannot hold the same id at once.
|
||||
*/
|
||||
function absorbAnimeMetadata(
|
||||
db: DatabaseSync,
|
||||
targetAnimeId: number,
|
||||
source: AnimeMetadataRow | null,
|
||||
updatedAt: string,
|
||||
): void {
|
||||
if (!source) return;
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE imm_anime
|
||||
SET
|
||||
anilist_id = COALESCE(anilist_id, ?),
|
||||
title_romaji = COALESCE(title_romaji, ?),
|
||||
title_english = COALESCE(title_english, ?),
|
||||
title_native = COALESCE(title_native, ?),
|
||||
episodes_total = COALESCE(episodes_total, ?),
|
||||
description = COALESCE(description, ?),
|
||||
LAST_UPDATE_DATE = ?
|
||||
WHERE anime_id = ?
|
||||
`,
|
||||
).run(
|
||||
source.anilist_id,
|
||||
source.title_romaji,
|
||||
source.title_english,
|
||||
source.title_native,
|
||||
source.episodes_total,
|
||||
source.description,
|
||||
updatedAt,
|
||||
targetAnimeId,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold `sourceAnimeIds` into `targetAnimeId`: every episode and subtitle line
|
||||
* is repointed, metadata the target is missing is inherited from the sources,
|
||||
* and the emptied source rows are deleted.
|
||||
*
|
||||
* Assumes the caller already holds a write transaction and rebuilds the
|
||||
* lifetime summaries afterwards; use {@link mergeAnimeRecords} otherwise.
|
||||
*/
|
||||
export function mergeAnimeRecordsInTransaction(
|
||||
db: DatabaseSync,
|
||||
targetAnimeId: number,
|
||||
sourceAnimeIds: number[],
|
||||
): AnimeMergeSummary {
|
||||
const summary = emptyMergeSummary(targetAnimeId);
|
||||
if (!animeExists(db, targetAnimeId)) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
const updatedAt = toDbTimestamp(nowMs());
|
||||
const sourceVideosStmt = db.prepare(
|
||||
'SELECT video_id AS videoId FROM imm_videos WHERE anime_id = ?',
|
||||
);
|
||||
const moveVideosStmt = db.prepare(
|
||||
'UPDATE imm_videos SET anime_id = ?, LAST_UPDATE_DATE = ? WHERE anime_id = ?',
|
||||
);
|
||||
// Repointed per video rather than by anime_id: lines recorded before the
|
||||
// async title parse assigns the link are stored with a NULL anime_id, and
|
||||
// matching on the source id would strand them unattributed.
|
||||
const moveLinesStmt = db.prepare(
|
||||
'UPDATE imm_subtitle_lines SET anime_id = ?, LAST_UPDATE_DATE = ? WHERE video_id = ?',
|
||||
);
|
||||
const dropLifetimeStmt = db.prepare('DELETE FROM imm_lifetime_anime WHERE anime_id = ?');
|
||||
const dropAnimeStmt = db.prepare('DELETE FROM imm_anime WHERE anime_id = ?');
|
||||
|
||||
for (const sourceAnimeId of new Set(sourceAnimeIds)) {
|
||||
if (sourceAnimeId === targetAnimeId || !animeExists(db, sourceAnimeId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sourceMetadata = readAnimeMetadata(db, sourceAnimeId);
|
||||
const sourceVideoIds = (sourceVideosStmt.all(sourceAnimeId) as Array<{ videoId: number }>).map(
|
||||
(row) => row.videoId,
|
||||
);
|
||||
const moved = moveVideosStmt.run(targetAnimeId, updatedAt, sourceAnimeId) as {
|
||||
changes: number;
|
||||
};
|
||||
for (const videoId of sourceVideoIds) {
|
||||
moveLinesStmt.run(targetAnimeId, updatedAt, videoId);
|
||||
}
|
||||
dropLifetimeStmt.run(sourceAnimeId);
|
||||
dropAnimeStmt.run(sourceAnimeId);
|
||||
absorbAnimeMetadata(db, targetAnimeId, sourceMetadata, updatedAt);
|
||||
|
||||
summary.mergedAnimeIds.push(sourceAnimeId);
|
||||
summary.movedVideos += moved.changes;
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
export function mergeAnimeRecords(
|
||||
db: DatabaseSync,
|
||||
targetAnimeId: number,
|
||||
sourceAnimeIds: number[],
|
||||
): AnimeMergeSummary {
|
||||
return runInTransaction(db, () => {
|
||||
const summary = mergeAnimeRecordsInTransaction(db, targetAnimeId, sourceAnimeIds);
|
||||
if (summary.mergedAnimeIds.length > 0) {
|
||||
rebuildLifetimeSummariesInTransaction(db);
|
||||
}
|
||||
return summary;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a single episode to another library entry, pruning the previous owner
|
||||
* when it is left with nothing.
|
||||
*/
|
||||
export function moveVideoToAnime(
|
||||
db: DatabaseSync,
|
||||
videoId: number,
|
||||
targetAnimeId: number,
|
||||
): VideoMoveSummary {
|
||||
return runInTransaction(db, () => {
|
||||
const videoRow = db
|
||||
.prepare('SELECT anime_id AS animeId FROM imm_videos WHERE video_id = ?')
|
||||
.get(videoId) as { animeId: number | null } | null;
|
||||
if (!videoRow || !animeExists(db, targetAnimeId)) {
|
||||
throw new Error(UNKNOWN_MOVE_TARGET_MESSAGE);
|
||||
}
|
||||
|
||||
const previousAnimeId = videoRow.animeId;
|
||||
if (previousAnimeId === targetAnimeId) {
|
||||
return { targetAnimeId, previousAnimeId, removedPreviousAnime: false };
|
||||
}
|
||||
|
||||
const updatedAt = toDbTimestamp(nowMs());
|
||||
db.prepare('UPDATE imm_videos SET anime_id = ?, LAST_UPDATE_DATE = ? WHERE video_id = ?').run(
|
||||
targetAnimeId,
|
||||
updatedAt,
|
||||
videoId,
|
||||
);
|
||||
db.prepare(
|
||||
'UPDATE imm_subtitle_lines SET anime_id = ?, LAST_UPDATE_DATE = ? WHERE video_id = ?',
|
||||
).run(targetAnimeId, updatedAt, videoId);
|
||||
|
||||
let removedPreviousAnime = false;
|
||||
if (previousAnimeId !== null && !hasAnimeReferences(db, previousAnimeId)) {
|
||||
// The emptied entry's metadata is deliberately dropped rather than
|
||||
// absorbed. A move says "this episode belongs elsewhere", not "these are
|
||||
// the same show", and the entry being emptied is usually a mis-parse
|
||||
// whose AniList link would be wrong for the target.
|
||||
db.prepare('DELETE FROM imm_lifetime_anime WHERE anime_id = ?').run(previousAnimeId);
|
||||
db.prepare('DELETE FROM imm_anime WHERE anime_id = ?').run(previousAnimeId);
|
||||
removedPreviousAnime = true;
|
||||
}
|
||||
|
||||
rebuildLifetimeSummariesInTransaction(db);
|
||||
return { targetAnimeId, previousAnimeId, removedPreviousAnime };
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { DatabaseSync } from './sqlite';
|
||||
import {
|
||||
animeSeasonsAreMergeCompatible,
|
||||
getParsedSeasonsForAnime,
|
||||
mergeAnimeRecordsInTransaction,
|
||||
} from './anime-merge';
|
||||
import { getOrCreateAnimeRecord } from './storage';
|
||||
import { toDbTimestamp } from './query-shared';
|
||||
import { nowMs } from './time';
|
||||
@@ -8,6 +13,21 @@ export interface AnimeSeasonRepairSummary {
|
||||
repaired: number;
|
||||
movedVideos: number;
|
||||
deletedAnimeRows: number;
|
||||
/**
|
||||
* Entry that owns the videos afterwards when two rows were folded together,
|
||||
* so callers can keep pointing at a row that still exists.
|
||||
*/
|
||||
survivingAnimeId: number | null;
|
||||
}
|
||||
|
||||
export interface AnimeAnilistConflictOptions {
|
||||
/**
|
||||
* Which row keeps its identity when two entries claim the same AniList id.
|
||||
* `existing` (the default) keeps the row that already held the id, so
|
||||
* automatic cover-art resolution does not rename a card under the user;
|
||||
* `target` keeps the row the user is acting on.
|
||||
*/
|
||||
survivor?: 'target' | 'existing';
|
||||
}
|
||||
|
||||
interface AnimeRow {
|
||||
@@ -38,6 +58,7 @@ function emptySummary(scanned = 0): AnimeSeasonRepairSummary {
|
||||
repaired: 0,
|
||||
movedVideos: 0,
|
||||
deletedAnimeRows: 0,
|
||||
survivingAnimeId: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -49,6 +70,7 @@ function mergeSummary(
|
||||
target.repaired += source.repaired;
|
||||
target.movedVideos += source.movedVideos;
|
||||
target.deletedAnimeRows += source.deletedAnimeRows;
|
||||
target.survivingAnimeId = source.survivingAnimeId ?? target.survivingAnimeId;
|
||||
return target;
|
||||
}
|
||||
|
||||
@@ -301,10 +323,19 @@ export function repairLegacySeasonlessAnimeRows(db: DatabaseSync): AnimeSeasonRe
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Two library entries cannot both hold the same AniList id (imm_anime.anilist_id
|
||||
* is UNIQUE), and two entries resolving to the same id are the same show split
|
||||
* by a title or season-suffix mismatch. Fold them together when their parsed
|
||||
* seasons agree; fall back to the legacy season redistribution when the
|
||||
* conflicting row actually spans several seasons, since merging there would
|
||||
* pile unrelated seasons onto one card.
|
||||
*/
|
||||
export function resolveAnimeAnilistConflict(
|
||||
db: DatabaseSync,
|
||||
targetAnimeId: number,
|
||||
anilistId: number,
|
||||
options: AnimeAnilistConflictOptions = {},
|
||||
): AnimeSeasonRepairSummary {
|
||||
const conflict = db
|
||||
.prepare(
|
||||
@@ -321,10 +352,54 @@ export function resolveAnimeAnilistConflict(
|
||||
return emptySummary();
|
||||
}
|
||||
|
||||
return runInTransaction(db, () =>
|
||||
redistributeAnimeRowByParsedSeasonsInTransaction(db, conflict.animeId, {
|
||||
return runInTransaction(db, () => {
|
||||
if (canMergeAnilistConflict(db, targetAnimeId, conflict.animeId, anilistId, options)) {
|
||||
const survivingAnimeId = options.survivor === 'target' ? targetAnimeId : conflict.animeId;
|
||||
const absorbedAnimeId = survivingAnimeId === targetAnimeId ? conflict.animeId : targetAnimeId;
|
||||
const merge = mergeAnimeRecordsInTransaction(db, survivingAnimeId, [absorbedAnimeId]);
|
||||
const summary = emptySummary(1);
|
||||
summary.movedVideos = merge.movedVideos;
|
||||
summary.deletedAnimeRows = merge.mergedAnimeIds.length;
|
||||
if (merge.mergedAnimeIds.length > 0) {
|
||||
summary.repaired = 1;
|
||||
// Only reported once a row really absorbed the other, so callers never
|
||||
// follow this to an anime id that was never written.
|
||||
summary.survivingAnimeId = survivingAnimeId;
|
||||
}
|
||||
// Lifetime summaries are rebuilt by the caller off this summary, the same
|
||||
// as the redistribution path below.
|
||||
return summary;
|
||||
}
|
||||
|
||||
return redistributeAnimeRowByParsedSeasonsInTransaction(db, conflict.animeId, {
|
||||
transferAnilistToAnimeId: targetAnimeId,
|
||||
overwriteTargetAnilist: true,
|
||||
}),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function canMergeAnilistConflict(
|
||||
db: DatabaseSync,
|
||||
targetAnimeId: number,
|
||||
conflictAnimeId: number,
|
||||
anilistId: number,
|
||||
options: AnimeAnilistConflictOptions,
|
||||
): boolean {
|
||||
const targetRow = getAnimeRow(db, targetAnimeId);
|
||||
if (!targetRow) {
|
||||
// Nothing to merge with a row that no longer exists (a stale id from the
|
||||
// caller); fall through to the redistribution path.
|
||||
return false;
|
||||
}
|
||||
if (options.survivor !== 'target') {
|
||||
// The target is the row about to disappear here, so an existing link of its
|
||||
// own means this is a mis-resolution rather than a duplicate: leave it be.
|
||||
if (targetRow.anilist_id != null && targetRow.anilist_id !== anilistId) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return animeSeasonsAreMergeCompatible(
|
||||
getParsedSeasonsForAnime(db, targetAnimeId),
|
||||
getParsedSeasonsForAnime(db, conflictAnimeId),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Hono } from 'hono';
|
||||
import { statsJson } from '../../../types/stats-http-contract.js';
|
||||
import { UNKNOWN_MOVE_TARGET_MESSAGE } from '../immersion-tracker/anime-merge.js';
|
||||
import type { ImmersionTrackerService } from '../immersion-tracker-service.js';
|
||||
import {
|
||||
buildSentenceSearchOptions,
|
||||
@@ -7,6 +8,7 @@ import {
|
||||
parseBooleanQuery,
|
||||
parseExcludedWordsBody,
|
||||
parseIntQuery,
|
||||
parsePositiveIdList,
|
||||
} from './route-support.js';
|
||||
|
||||
export function registerStatsLibraryRoutes(
|
||||
@@ -197,4 +199,50 @@ export function registerStatsLibraryRoutes(
|
||||
await tracker.deleteAnime(animeId);
|
||||
return c.json(statsJson('deleteAnime', { ok: true }));
|
||||
});
|
||||
|
||||
app.post('/api/stats/anime/:animeId/merge', async (c) => {
|
||||
const animeId = parseIntQuery(c.req.param('animeId'), 0);
|
||||
if (animeId <= 0) return c.body(null, 400);
|
||||
const body = await c.req.json().catch(() => null);
|
||||
const sourceAnimeIds = parsePositiveIdList(body?.sourceAnimeIds).filter((id) => id !== animeId);
|
||||
if (sourceAnimeIds.length === 0) return c.body(null, 400);
|
||||
const summary = await tracker.mergeAnime(animeId, sourceAnimeIds);
|
||||
// Nothing folded means the target or every source was already gone, so the
|
||||
// caller should not be told the merge succeeded.
|
||||
if (summary.mergedAnimeIds.length === 0) return c.body(null, 404);
|
||||
return c.json(
|
||||
statsJson('mergeAnime', {
|
||||
ok: true,
|
||||
animeId: summary.survivingAnimeId,
|
||||
mergedAnimeIds: summary.mergedAnimeIds,
|
||||
movedVideos: summary.movedVideos,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
app.patch('/api/stats/media/:videoId/anime', async (c) => {
|
||||
const videoId = parseIntQuery(c.req.param('videoId'), 0);
|
||||
if (videoId <= 0) return c.body(null, 400);
|
||||
const body = await c.req.json().catch(() => null);
|
||||
const animeId = Number.isSafeInteger(body?.animeId) ? (body.animeId as number) : 0;
|
||||
if (animeId <= 0) return c.body(null, 400);
|
||||
try {
|
||||
const summary = await tracker.moveVideoToAnime(videoId, animeId);
|
||||
return c.json(
|
||||
statsJson('moveVideoToAnime', {
|
||||
ok: true,
|
||||
animeId: summary.targetAnimeId,
|
||||
previousAnimeId: summary.previousAnimeId,
|
||||
removedPreviousAnime: summary.removedPreviousAnime,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
// Only a missing episode or entry is a 404; storage failures must not be
|
||||
// reported to the caller as "not found".
|
||||
if (error instanceof Error && error.message === UNKNOWN_MOVE_TARGET_MESSAGE) {
|
||||
return c.body(null, 404);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -170,6 +170,18 @@ export async function enrichSessionsWithKnownWordMetrics<
|
||||
);
|
||||
}
|
||||
|
||||
/** Deduplicated positive integer ids from an untrusted JSON body field. */
|
||||
export function parsePositiveIdList(raw: unknown): number[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const ids = new Set<number>();
|
||||
for (const value of raw) {
|
||||
if (Number.isSafeInteger(value) && (value as number) > 0) {
|
||||
ids.add(value as number);
|
||||
}
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
export function parseBooleanQuery(raw: string | undefined, fallback: boolean): boolean {
|
||||
if (raw === undefined) return fallback;
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
|
||||
@@ -99,9 +99,10 @@ test('applyX11EnvOverrides strips Wayland hints and pins session type to x11', (
|
||||
assert.equal(result.XDG_SESSION_TYPE, 'x11');
|
||||
});
|
||||
|
||||
test('MPV_X11_BACKEND_ARGS pins the GPU stack to X11', () => {
|
||||
assert.deepEqual(
|
||||
[...MPV_X11_BACKEND_ARGS],
|
||||
['--vo=gpu', '--gpu-api=opengl', '--gpu-context=x11egl,x11'],
|
||||
test('MPV_X11_BACKEND_ARGS pins the window context to X11 without overriding the renderer', () => {
|
||||
assert.deepEqual([...MPV_X11_BACKEND_ARGS], ['--gpu-context=x11vk,x11egl,x11']);
|
||||
assert.equal(
|
||||
MPV_X11_BACKEND_ARGS.some((arg) => arg.startsWith('--vo=') || arg.startsWith('--gpu-api=')),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -12,12 +12,18 @@
|
||||
so the gate and the mpv backend args stay in one place.
|
||||
*/
|
||||
|
||||
/** mpv args that pin the GPU/windowing stack to X11/XWayland (libGL via EGL on X11). */
|
||||
export const MPV_X11_BACKEND_ARGS = [
|
||||
'--vo=gpu',
|
||||
'--gpu-api=opengl',
|
||||
'--gpu-context=x11egl,x11',
|
||||
] as const;
|
||||
/**
|
||||
* mpv args that pin the *windowing* stack to X11/XWayland, in Vulkan-then-OpenGL order.
|
||||
* mpv walks the list and skips contexts that do not match the configured `--gpu-api`,
|
||||
* so this works for both a Vulkan and an OpenGL config.
|
||||
*
|
||||
* Deliberately does NOT set `--vo`/`--gpu-api`: forcing `--vo=gpu --gpu-api=opengl` here
|
||||
* used to drop configs off `vo=gpu-next` onto the legacy renderer, where user shaders
|
||||
* written for gpu-next (e.g. ArtCNN, `//!COMPONENTS 4` LUMA hooks) abort mpv with
|
||||
* `copy_image: Assertion '*offset + count < sizeof(dst)' failed` as soon as their
|
||||
* upscale-only `//!WHEN` condition turns on, i.e. on the first fullscreen toggle.
|
||||
*/
|
||||
export const MPV_X11_BACKEND_ARGS = ['--gpu-context=x11vk,x11egl,x11'] as const;
|
||||
|
||||
export type LinuxDesktopEnv = {
|
||||
xdgCurrentDesktop: string;
|
||||
|
||||
@@ -100,6 +100,30 @@ export interface StatsAnkiNotesInfoRequest {
|
||||
noteIds: number[];
|
||||
}
|
||||
|
||||
export interface StatsMergeAnimeRequest {
|
||||
sourceAnimeIds: number[];
|
||||
}
|
||||
|
||||
export interface StatsMoveVideoRequest {
|
||||
animeId: number;
|
||||
}
|
||||
|
||||
export interface StatsMergeAnimeResponse {
|
||||
ok: true;
|
||||
/** Library entry that owns every merged episode afterwards. */
|
||||
animeId: number;
|
||||
mergedAnimeIds: number[];
|
||||
movedVideos: number;
|
||||
}
|
||||
|
||||
export interface StatsMoveVideoResponse {
|
||||
ok: true;
|
||||
animeId: number;
|
||||
previousAnimeId: number | null;
|
||||
/** True when the previous entry was emptied by the move and removed. */
|
||||
removedPreviousAnime: boolean;
|
||||
}
|
||||
|
||||
export interface StatsOkResponse {
|
||||
ok: true;
|
||||
}
|
||||
@@ -142,6 +166,8 @@ export interface StatsJsonResponseMap {
|
||||
deleteSession: StatsOkResponse;
|
||||
deleteVideo: StatsOkResponse;
|
||||
deleteAnime: StatsOkResponse;
|
||||
mergeAnime: StatsMergeAnimeResponse;
|
||||
moveVideoToAnime: StatsMoveVideoResponse;
|
||||
anilistSearch: StatsAnilistSearchResult[];
|
||||
knownWords: string[];
|
||||
knownWordsSummary: StatsKnownWordsSummary;
|
||||
@@ -221,6 +247,8 @@ export interface StatsHttpClient {
|
||||
deleteSessions: (sessionIds: number[]) => Promise<void>;
|
||||
deleteVideo: (videoId: number) => Promise<void>;
|
||||
deleteAnime: (animeId: number) => Promise<void>;
|
||||
mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<StatsMergeAnimeResponse>;
|
||||
moveVideoToAnime: (videoId: number, animeId: number) => Promise<StatsMoveVideoResponse>;
|
||||
getKnownWords: () => Promise<string[]>;
|
||||
getKnownWordsSummary: () => Promise<StatsKnownWordsSummary>;
|
||||
getAnimeKnownWordsSummary: (animeId: number) => Promise<StatsKnownWordsSummary>;
|
||||
|
||||
@@ -5,22 +5,45 @@ import type { AnimeLibraryItem } from '../../types/stats';
|
||||
interface AnimeCardProps {
|
||||
anime: AnimeLibraryItem;
|
||||
onClick: () => void;
|
||||
/** While selecting, clicking the card toggles it instead of opening it. */
|
||||
selectable?: boolean;
|
||||
selected?: boolean;
|
||||
}
|
||||
|
||||
export function AnimeCard({ anime, onClick }: AnimeCardProps) {
|
||||
export function AnimeCard({
|
||||
anime,
|
||||
onClick,
|
||||
selectable = false,
|
||||
selected = false,
|
||||
}: AnimeCardProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="group bg-ctp-surface0 border border-ctp-surface1 rounded-lg overflow-hidden hover:border-ctp-blue/50 hover:shadow-lg hover:shadow-ctp-blue/10 transition-all duration-200 hover:-translate-y-1 text-left w-full"
|
||||
aria-pressed={selectable ? selected : undefined}
|
||||
className={`group bg-ctp-surface0 border rounded-lg overflow-hidden hover:shadow-lg hover:shadow-ctp-blue/10 transition-all duration-200 hover:-translate-y-1 text-left w-full ${
|
||||
selected ? 'border-ctp-blue' : 'border-ctp-surface1 hover:border-ctp-blue/50'
|
||||
}`}
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="overflow-hidden relative">
|
||||
<AnimeCoverImage
|
||||
animeId={anime.animeId}
|
||||
title={anime.canonicalTitle}
|
||||
coverRetryToken={anime.anilistId ?? 0}
|
||||
className="w-full aspect-[3/4] rounded-t-lg transition-transform duration-200 group-hover:scale-105"
|
||||
/>
|
||||
{selectable && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`absolute top-2 left-2 w-5 h-5 rounded border flex items-center justify-center text-xs ${
|
||||
selected
|
||||
? 'bg-ctp-blue border-ctp-blue text-ctp-base'
|
||||
: 'bg-ctp-crust/70 border-ctp-surface2 text-transparent'
|
||||
}`}
|
||||
>
|
||||
{'✓'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<div className="text-sm font-medium text-ctp-text truncate">{anime.canonicalTitle}</div>
|
||||
|
||||
@@ -25,6 +25,8 @@ interface AnimeDetailViewProps {
|
||||
* keeps showing the previous title's art.
|
||||
*/
|
||||
onAnilistRelinked?: () => void;
|
||||
/** Called after an episode is reassigned to another entry. */
|
||||
onEpisodeMoved?: () => void;
|
||||
}
|
||||
|
||||
type Range = 14 | 30 | 90;
|
||||
@@ -150,6 +152,7 @@ export function AnimeDetailView({
|
||||
onOpenEpisodeDetail,
|
||||
onAnimeDeleted,
|
||||
onAnilistRelinked,
|
||||
onEpisodeMoved,
|
||||
}: AnimeDetailViewProps) {
|
||||
const { data, loading, error, reload } = useAnimeDetail(animeId);
|
||||
const [showAnilistSelector, setShowAnilistSelector] = useState(false);
|
||||
@@ -223,6 +226,13 @@ export function AnimeDetailView({
|
||||
<AnimeOverviewStats detail={detail} knownWordsSummary={knownWordsSummary} />
|
||||
<EpisodeList
|
||||
episodes={episodes}
|
||||
animeId={animeId}
|
||||
onEpisodeMoved={(removedPreviousAnime) => {
|
||||
onEpisodeMoved?.();
|
||||
// The last episode taking the entry with it leaves nothing to show.
|
||||
if (removedPreviousAnime) onBack();
|
||||
else reload();
|
||||
}}
|
||||
onOpenDetail={onOpenEpisodeDetail ? (videoId) => onOpenEpisodeDetail(videoId) : undefined}
|
||||
/>
|
||||
<AnimeWatchChart animeId={animeId} />
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useId, useState } from 'react';
|
||||
import { apiClient } from '../../lib/api-client';
|
||||
import { formatDuration, formatNumber } from '../../lib/formatters';
|
||||
import { AnimeCoverImage } from './AnimeCoverImage';
|
||||
import type { AnimeLibraryItem } from '../../types/stats';
|
||||
|
||||
interface AnimeMergeDialogProps {
|
||||
entries: AnimeLibraryItem[];
|
||||
onClose: () => void;
|
||||
onMerged: (survivingAnimeId: number) => void;
|
||||
}
|
||||
|
||||
/** Biggest entry first: the one most likely to carry the right title and art. */
|
||||
function pickDefaultKeeper(entries: AnimeLibraryItem[]): number {
|
||||
const best = [...entries].sort(
|
||||
(a, b) => b.episodeCount - a.episodeCount || b.totalActiveMs - a.totalActiveMs,
|
||||
)[0];
|
||||
return best?.animeId ?? 0;
|
||||
}
|
||||
|
||||
export function AnimeMergeDialog({ entries, onClose, onMerged }: AnimeMergeDialogProps) {
|
||||
const headingId = useId();
|
||||
const [keeperId, setKeeperId] = useState(() => pickDefaultKeeper(entries));
|
||||
const [merging, setMerging] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const totalEpisodes = entries.reduce((sum, entry) => sum + entry.episodeCount, 0);
|
||||
const totalCards = entries.reduce((sum, entry) => sum + entry.totalCards, 0);
|
||||
const totalActiveMs = entries.reduce((sum, entry) => sum + entry.totalActiveMs, 0);
|
||||
|
||||
const handleMerge = async () => {
|
||||
const sourceAnimeIds = entries
|
||||
.map((entry) => entry.animeId)
|
||||
.filter((animeId) => animeId !== keeperId);
|
||||
if (sourceAnimeIds.length === 0) return;
|
||||
setMerging(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await apiClient.mergeAnime(keeperId, sourceAnimeIds);
|
||||
onMerged(result.animeId);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to merge these entries.');
|
||||
setMerging(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Dismissing mid-request would leave the caller unaware of a merge that is
|
||||
// still going to land, so the backdrop and close button are inert until it
|
||||
// resolves.
|
||||
const handleDismiss = () => {
|
||||
if (!merging) onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-start justify-center pt-[10vh]"
|
||||
onClick={handleDismiss}
|
||||
>
|
||||
<div className="absolute inset-0 bg-ctp-crust/70 backdrop-blur-[2px]" />
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={headingId}
|
||||
className="relative bg-ctp-base border border-ctp-surface1 rounded-xl shadow-2xl w-full max-w-lg max-h-[70vh] flex flex-col animate-fade-in"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="p-4 border-b border-ctp-surface1">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 id={headingId} className="text-sm font-semibold text-ctp-text">
|
||||
Merge {entries.length} Library Entries
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDismiss}
|
||||
disabled={merging}
|
||||
aria-label="Close"
|
||||
className="text-ctp-overlay2 hover:text-ctp-text text-lg leading-none disabled:opacity-50"
|
||||
>
|
||||
{'✕'}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-ctp-overlay2 mt-2">
|
||||
Pick the entry to keep. Every episode moves onto it and the others are removed; no
|
||||
sessions or mined cards are deleted.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-2">
|
||||
{entries.map((entry) => (
|
||||
<button
|
||||
key={entry.animeId}
|
||||
type="button"
|
||||
disabled={merging}
|
||||
aria-pressed={keeperId === entry.animeId}
|
||||
onClick={() => setKeeperId(entry.animeId)}
|
||||
className={`w-full flex items-center gap-3 p-2.5 rounded-lg transition-colors text-left disabled:opacity-50 ${
|
||||
keeperId === entry.animeId ? 'bg-ctp-surface1' : 'hover:bg-ctp-surface0'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`w-4 h-4 rounded-full border shrink-0 ${
|
||||
keeperId === entry.animeId
|
||||
? 'border-ctp-blue bg-ctp-blue'
|
||||
: 'border-ctp-surface2 bg-transparent'
|
||||
}`}
|
||||
/>
|
||||
<AnimeCoverImage
|
||||
animeId={entry.animeId}
|
||||
title={entry.canonicalTitle}
|
||||
coverRetryToken={entry.anilistId ?? 0}
|
||||
className="w-10 h-14 rounded shrink-0"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm text-ctp-text truncate">{entry.canonicalTitle}</div>
|
||||
<div className="text-xs text-ctp-overlay2 mt-0.5">
|
||||
{entry.episodeCount} episode{entry.episodeCount !== 1 ? 's' : ''} ·{' '}
|
||||
{formatDuration(entry.totalActiveMs)} · {formatNumber(entry.totalCards)} cards
|
||||
</div>
|
||||
</div>
|
||||
{keeperId === entry.animeId ? (
|
||||
<span className="text-xs text-ctp-blue shrink-0">Keep</span>
|
||||
) : null}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="p-4 border-t border-ctp-surface1 space-y-2">
|
||||
{error ? (
|
||||
<div role="alert" className="text-xs text-ctp-red">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="text-xs text-ctp-overlay2">
|
||||
Result: {totalEpisodes} episode{totalEpisodes !== 1 ? 's' : ''} ·{' '}
|
||||
{formatDuration(totalActiveMs)} · {formatNumber(totalCards)} cards
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={merging}
|
||||
onClick={() => void handleMerge()}
|
||||
className="px-3 py-1.5 rounded-lg bg-ctp-blue/15 border border-ctp-blue/40 text-xs text-ctp-blue hover:bg-ctp-blue/25 transition-colors disabled:opacity-50"
|
||||
>
|
||||
{merging ? 'Merging…' : 'Merge Entries'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { Window } from 'happy-dom';
|
||||
import { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { apiClient } from '../../lib/api-client';
|
||||
import type { AnimeLibraryItem, StatsMergeAnimeResponse } from '../../types/stats';
|
||||
import { AnimeTab } from './AnimeTab';
|
||||
|
||||
interface TestWindow extends Window {
|
||||
IS_REACT_ACT_ENVIRONMENT?: boolean;
|
||||
}
|
||||
|
||||
function installDom(): () => void {
|
||||
const previousWindow = globalThis.window;
|
||||
const previousDocument = globalThis.document;
|
||||
const previousHTMLElement = globalThis.HTMLElement;
|
||||
const previousIsReactActEnvironment = (
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT;
|
||||
const window = new Window() as TestWindow;
|
||||
|
||||
Object.defineProperty(globalThis, 'window', { value: window, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: window.document, configurable: true });
|
||||
Object.defineProperty(globalThis, 'HTMLElement', {
|
||||
value: window.HTMLElement,
|
||||
configurable: true,
|
||||
});
|
||||
(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
return () => {
|
||||
Object.defineProperty(globalThis, 'window', { value: previousWindow, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: previousDocument, configurable: true });
|
||||
Object.defineProperty(globalThis, 'HTMLElement', {
|
||||
value: previousHTMLElement,
|
||||
configurable: true,
|
||||
});
|
||||
(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = previousIsReactActEnvironment;
|
||||
};
|
||||
}
|
||||
|
||||
function libraryItem(animeId: number, title: string, episodeCount: number): AnimeLibraryItem {
|
||||
return {
|
||||
animeId,
|
||||
canonicalTitle: title,
|
||||
anilistId: null,
|
||||
totalSessions: 1,
|
||||
totalActiveMs: 1000,
|
||||
totalCards: 1,
|
||||
totalTokensSeen: 0,
|
||||
episodeCount,
|
||||
episodesTotal: null,
|
||||
lastWatchedMs: animeId,
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Library cards only expose aria-pressed while selection mode is on. */
|
||||
function cardButtons(container: Element): HTMLButtonElement[] {
|
||||
return [...container.querySelectorAll('button[aria-pressed]')] as unknown as HTMLButtonElement[];
|
||||
}
|
||||
|
||||
function mergeButton(container: Element): HTMLButtonElement {
|
||||
const match = [...container.querySelectorAll('button')].find(
|
||||
(button) => (button.textContent ?? '').trim() === 'Merge Selected',
|
||||
);
|
||||
assert.ok(match, 'expected a "Merge Selected" button');
|
||||
return match as unknown as HTMLButtonElement;
|
||||
}
|
||||
|
||||
test('AnimeTab merges the selected duplicate entries into the chosen keeper', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
mergeAnime: apiClient.mergeAnime,
|
||||
};
|
||||
|
||||
// Two cards for one show, the split this feature exists to undo.
|
||||
let entries = [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
|
||||
let libraryFetches = 0;
|
||||
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
|
||||
|
||||
apiClient.getAnimeLibrary = (async () => {
|
||||
libraryFetches += 1;
|
||||
return entries;
|
||||
}) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.mergeAnime = (async (targetAnimeId: number, sourceAnimeIds: number[]) => {
|
||||
mergeCall = { targetAnimeId, sourceAnimeIds };
|
||||
entries = [libraryItem(1, 'Show', 3)];
|
||||
return {
|
||||
ok: true,
|
||||
animeId: targetAnimeId,
|
||||
mergedAnimeIds: sourceAnimeIds,
|
||||
movedVideos: 1,
|
||||
} satisfies StatsMergeAnimeResponse;
|
||||
}) as typeof apiClient.mergeAnime;
|
||||
|
||||
try {
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root.render(<AnimeTab />);
|
||||
});
|
||||
assert.equal(libraryFetches, 1);
|
||||
|
||||
await act(async () => {
|
||||
findButton(container, 'Select').click();
|
||||
});
|
||||
// Nothing to merge until at least two entries are picked.
|
||||
assert.equal(mergeButton(container).disabled, true);
|
||||
|
||||
// Sorted by last watched, so the season-tagged duplicate comes first.
|
||||
const cards = cardButtons(container);
|
||||
assert.equal(cards.length, 2);
|
||||
assert.match(cards[0]?.textContent ?? '', /Show Season 1/);
|
||||
|
||||
await act(async () => {
|
||||
cards[0]?.click();
|
||||
});
|
||||
assert.equal(mergeButton(container).disabled, true);
|
||||
|
||||
await act(async () => {
|
||||
cardButtons(container)[1]?.click();
|
||||
});
|
||||
assert.equal(mergeButton(container).disabled, false);
|
||||
|
||||
await act(async () => {
|
||||
mergeButton(container).click();
|
||||
});
|
||||
// The dialog defaults to the entry with the most episodes.
|
||||
assert.match(container.textContent ?? '', /Merge 2 Library Entries/);
|
||||
|
||||
await act(async () => {
|
||||
findButton(container, 'Merge Entries').click();
|
||||
});
|
||||
|
||||
assert.deepEqual(mergeCall, { targetAnimeId: 1, sourceAnimeIds: [2] });
|
||||
assert.equal(libraryFetches, 2);
|
||||
// Selection mode closes and the grid is back to a single card.
|
||||
assert.doesNotMatch(container.textContent ?? '', /Merge 2 Library Entries/);
|
||||
assert.doesNotMatch(container.textContent ?? '', /Show Season 1/);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
} finally {
|
||||
Object.assign(apiClient, original);
|
||||
uninstallDom();
|
||||
}
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from '../../lib/library-card-size';
|
||||
import { AnimeCard } from './AnimeCard';
|
||||
import { AnimeDetailView } from './AnimeDetailView';
|
||||
import { AnimeMergeDialog } from './AnimeMergeDialog';
|
||||
|
||||
type SortKey = 'lastWatched' | 'watchTime' | 'cards' | 'episodes';
|
||||
|
||||
@@ -62,6 +63,21 @@ export function AnimeTab({
|
||||
),
|
||||
);
|
||||
const [selectedAnimeId, setSelectedAnimeId] = useState<number | null>(null);
|
||||
const [selectionMode, setSelectionMode] = useState(false);
|
||||
const [checkedAnimeIds, setCheckedAnimeIds] = useState<number[]>([]);
|
||||
const [showMergeDialog, setShowMergeDialog] = useState(false);
|
||||
|
||||
function toggleChecked(animeId: number): void {
|
||||
setCheckedAnimeIds((ids) =>
|
||||
ids.includes(animeId) ? ids.filter((id) => id !== animeId) : [...ids, animeId],
|
||||
);
|
||||
}
|
||||
|
||||
function exitSelectionMode(): void {
|
||||
setSelectionMode(false);
|
||||
setCheckedAnimeIds([]);
|
||||
setShowMergeDialog(false);
|
||||
}
|
||||
|
||||
function handleCardSizeChange(size: LibraryCardSize): void {
|
||||
setCardSize(size);
|
||||
@@ -86,6 +102,9 @@ export function AnimeTab({
|
||||
}, [anime, search, sortKey]);
|
||||
|
||||
const totalMs = anime.reduce((sum, a) => sum + a.totalActiveMs, 0);
|
||||
const checkedEntries = checkedAnimeIds
|
||||
.map((animeId) => anime.find((entry) => entry.animeId === animeId))
|
||||
.filter((entry): entry is (typeof anime)[number] => entry !== undefined);
|
||||
|
||||
if (selectedAnimeId !== null) {
|
||||
return (
|
||||
@@ -100,6 +119,7 @@ export function AnimeTab({
|
||||
}
|
||||
onAnimeDeleted={reload}
|
||||
onAnilistRelinked={reload}
|
||||
onEpisodeMoved={reload}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -143,11 +163,41 @@ export function AnimeTab({
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (selectionMode ? exitSelectionMode() : setSelectionMode(true))}
|
||||
title="Select several entries to merge them into one"
|
||||
className={`px-2 py-2 rounded-lg border text-xs shrink-0 transition-colors ${
|
||||
selectionMode
|
||||
? 'bg-ctp-blue/15 border-ctp-blue/40 text-ctp-blue'
|
||||
: 'bg-ctp-surface0 border-ctp-surface1 text-ctp-overlay2 hover:text-ctp-subtext0'
|
||||
}`}
|
||||
>
|
||||
{selectionMode ? 'Cancel' : 'Select'}
|
||||
</button>
|
||||
<div className="text-xs text-ctp-overlay2 shrink-0">
|
||||
{filtered.length} titles · {formatDuration(totalMs)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectionMode && (
|
||||
<div className="flex items-center justify-between gap-3 bg-ctp-surface0 border border-ctp-surface1 rounded-lg px-3 py-2">
|
||||
<div className="text-xs text-ctp-overlay2">
|
||||
{checkedEntries.length === 0
|
||||
? 'Pick the duplicate entries to combine'
|
||||
: `${checkedEntries.length} selected`}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={checkedEntries.length < 2}
|
||||
onClick={() => setShowMergeDialog(true)}
|
||||
className="px-3 py-1.5 rounded-lg bg-ctp-blue/15 border border-ctp-blue/40 text-xs text-ctp-blue hover:bg-ctp-blue/25 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
Merge Selected
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
<div className="text-sm text-ctp-overlay2 p-4">No titles found</div>
|
||||
) : (
|
||||
@@ -156,11 +206,26 @@ export function AnimeTab({
|
||||
<AnimeCard
|
||||
key={item.animeId}
|
||||
anime={item}
|
||||
onClick={() => setSelectedAnimeId(item.animeId)}
|
||||
selectable={selectionMode}
|
||||
selected={checkedAnimeIds.includes(item.animeId)}
|
||||
onClick={() =>
|
||||
selectionMode ? toggleChecked(item.animeId) : setSelectedAnimeId(item.animeId)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showMergeDialog && checkedEntries.length >= 2 && (
|
||||
<AnimeMergeDialog
|
||||
entries={checkedEntries}
|
||||
onClose={() => setShowMergeDialog(false)}
|
||||
onMerged={() => {
|
||||
exitSelectionMode();
|
||||
reload();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,21 +4,39 @@ import { apiClient } from '../../lib/api-client';
|
||||
import { confirmEpisodeDelete } from '../../lib/delete-confirm';
|
||||
import { buildLookupRateDisplay } from '../../lib/yomitan-lookup';
|
||||
import { EpisodeDetail } from './EpisodeDetail';
|
||||
import { LibraryEntryPicker } from './LibraryEntryPicker';
|
||||
import type { AnimeEpisode } from '../../types/stats';
|
||||
|
||||
/**
|
||||
* Row actions that only appear on hover. Keyboard focus and pointers with no
|
||||
* hover (touch) reveal them too, otherwise those users cannot reach the button
|
||||
* at all.
|
||||
*/
|
||||
const HOVER_REVEALED =
|
||||
'opacity-0 group-hover:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100';
|
||||
|
||||
interface EpisodeListProps {
|
||||
episodes: AnimeEpisode[];
|
||||
/** Entry these episodes currently belong to; excluded from the move picker. */
|
||||
animeId?: number;
|
||||
onEpisodeDeleted?: () => void;
|
||||
/** Fires after an episode is reassigned, so the caller can refetch. */
|
||||
onEpisodeMoved?: (removedPreviousAnime: boolean) => void;
|
||||
onOpenDetail?: (videoId: number) => void;
|
||||
}
|
||||
|
||||
export function EpisodeList({
|
||||
episodes: initialEpisodes,
|
||||
animeId,
|
||||
onEpisodeDeleted,
|
||||
onEpisodeMoved,
|
||||
onOpenDetail,
|
||||
}: EpisodeListProps) {
|
||||
const [expandedVideoId, setExpandedVideoId] = useState<number | null>(null);
|
||||
const [episodes, setEpisodes] = useState(initialEpisodes);
|
||||
const [movingEpisode, setMovingEpisode] = useState<AnimeEpisode | null>(null);
|
||||
const [moveTargetId, setMoveTargetId] = useState<number | null>(null);
|
||||
const [moveError, setMoveError] = useState<string | null>(null);
|
||||
|
||||
if (episodes.length === 0) return null;
|
||||
|
||||
@@ -51,6 +69,22 @@ export function EpisodeList({
|
||||
onEpisodeDeleted?.();
|
||||
};
|
||||
|
||||
const handleMoveEpisode = async (videoId: number, targetAnimeId: number) => {
|
||||
setMoveTargetId(targetAnimeId);
|
||||
setMoveError(null);
|
||||
try {
|
||||
const result = await apiClient.moveVideoToAnime(videoId, targetAnimeId);
|
||||
setEpisodes((prev) => prev.filter((ep) => ep.videoId !== videoId));
|
||||
if (expandedVideoId === videoId) setExpandedVideoId(null);
|
||||
setMovingEpisode(null);
|
||||
onEpisodeMoved?.(result.removedPreviousAnime);
|
||||
} catch (err) {
|
||||
setMoveError(err instanceof Error ? err.message : 'Failed to move this episode.');
|
||||
} finally {
|
||||
setMoveTargetId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const watchedCount = episodes.filter((ep) => ep.watched).length;
|
||||
|
||||
return (
|
||||
@@ -164,14 +198,28 @@ export function EpisodeList({
|
||||
>
|
||||
{'\u2713'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setMoveError(null);
|
||||
setMovingEpisode(ep);
|
||||
}}
|
||||
className={`w-5 h-5 rounded border border-ctp-surface2 text-transparent hover:border-ctp-blue/50 hover:text-ctp-blue focus-visible:text-ctp-blue hover:bg-ctp-blue/10 transition-colors text-xs flex items-center justify-center ${HOVER_REVEALED}`}
|
||||
title="Move to another library entry"
|
||||
aria-label="Move to another library entry"
|
||||
>
|
||||
{'\u2192'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void handleDeleteEpisode(ep.videoId, ep.canonicalTitle);
|
||||
}}
|
||||
className="w-5 h-5 rounded border border-ctp-surface2 text-transparent hover:border-ctp-red/50 hover:text-ctp-red hover:bg-ctp-red/10 transition-colors opacity-0 group-hover:opacity-100 text-xs flex items-center justify-center"
|
||||
className={`w-5 h-5 rounded border border-ctp-surface2 text-transparent hover:border-ctp-red/50 hover:text-ctp-red focus-visible:text-ctp-red hover:bg-ctp-red/10 transition-colors text-xs flex items-center justify-center ${HOVER_REVEALED}`}
|
||||
title="Delete episode"
|
||||
aria-label="Delete episode"
|
||||
>
|
||||
{'\u2715'}
|
||||
</button>
|
||||
@@ -191,6 +239,19 @@ export function EpisodeList({
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{movingEpisode && (
|
||||
<LibraryEntryPicker
|
||||
heading={`Move "${movingEpisode.canonicalTitle}" To`}
|
||||
excludeAnimeIds={animeId != null ? [animeId] : []}
|
||||
busyAnimeId={moveTargetId}
|
||||
error={moveError}
|
||||
onSelect={(entry) => void handleMoveEpisode(movingEpisode.videoId, entry.animeId)}
|
||||
onClose={() => {
|
||||
setMovingEpisode(null);
|
||||
setMoveError(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { Window } from 'happy-dom';
|
||||
import { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { apiClient } from '../../lib/api-client';
|
||||
import type { AnimeEpisode, AnimeLibraryItem, StatsMoveVideoResponse } from '../../types/stats';
|
||||
import { EpisodeList } from './EpisodeList';
|
||||
|
||||
interface TestWindow extends Window {
|
||||
IS_REACT_ACT_ENVIRONMENT?: boolean;
|
||||
}
|
||||
|
||||
function installDom(): () => void {
|
||||
const previousWindow = globalThis.window;
|
||||
const previousDocument = globalThis.document;
|
||||
const previousHTMLElement = globalThis.HTMLElement;
|
||||
const previousIsReactActEnvironment = (
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT;
|
||||
const window = new Window() as TestWindow;
|
||||
|
||||
Object.defineProperty(globalThis, 'window', { value: window, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: window.document, configurable: true });
|
||||
Object.defineProperty(globalThis, 'HTMLElement', {
|
||||
value: window.HTMLElement,
|
||||
configurable: true,
|
||||
});
|
||||
(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
return () => {
|
||||
Object.defineProperty(globalThis, 'window', { value: previousWindow, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: previousDocument, configurable: true });
|
||||
Object.defineProperty(globalThis, 'HTMLElement', {
|
||||
value: previousHTMLElement,
|
||||
configurable: true,
|
||||
});
|
||||
(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = previousIsReactActEnvironment;
|
||||
};
|
||||
}
|
||||
|
||||
function episode(videoId: number, title: string): AnimeEpisode {
|
||||
return {
|
||||
videoId,
|
||||
episode: videoId,
|
||||
season: null,
|
||||
durationMs: 1_440_000,
|
||||
endedMediaMs: null,
|
||||
watched: 0,
|
||||
canonicalTitle: title,
|
||||
totalSessions: 1,
|
||||
totalActiveMs: 1000,
|
||||
totalCards: 0,
|
||||
totalTokensSeen: 0,
|
||||
totalYomitanLookupCount: 0,
|
||||
lastWatchedMs: 1,
|
||||
};
|
||||
}
|
||||
|
||||
function libraryItem(animeId: number, title: string): AnimeLibraryItem {
|
||||
return {
|
||||
animeId,
|
||||
canonicalTitle: title,
|
||||
anilistId: null,
|
||||
totalSessions: 1,
|
||||
totalActiveMs: 1000,
|
||||
totalCards: 0,
|
||||
totalTokensSeen: 0,
|
||||
episodeCount: 1,
|
||||
episodesTotal: null,
|
||||
lastWatchedMs: 1,
|
||||
};
|
||||
}
|
||||
|
||||
function findButtonByTitle(container: Element, title: string): HTMLElement {
|
||||
const match = [...container.querySelectorAll('button')].find(
|
||||
(button) => button.getAttribute('title') === title,
|
||||
);
|
||||
assert.ok(match, `expected a button titled "${title}"`);
|
||||
return match as unknown as HTMLElement;
|
||||
}
|
||||
|
||||
function findButtonByText(container: Element, text: string): HTMLElement {
|
||||
const match = [...container.querySelectorAll('button')].find((button) =>
|
||||
(button.textContent ?? '').includes(text),
|
||||
);
|
||||
assert.ok(match, `expected a "${text}" button`);
|
||||
return match as unknown as HTMLElement;
|
||||
}
|
||||
|
||||
test('EpisodeList moves an episode to the library entry picked in the dialog', async () => {
|
||||
const uninstallDom = installDom();
|
||||
const original = {
|
||||
getAnimeLibrary: apiClient.getAnimeLibrary,
|
||||
moveVideoToAnime: apiClient.moveVideoToAnime,
|
||||
};
|
||||
|
||||
let moveCall: { videoId: number; animeId: number } | null = null;
|
||||
let movedResult: boolean | null = null;
|
||||
|
||||
apiClient.getAnimeLibrary = (async () => [
|
||||
libraryItem(1, 'Current Entry'),
|
||||
libraryItem(2, 'Real Series'),
|
||||
]) as typeof apiClient.getAnimeLibrary;
|
||||
apiClient.moveVideoToAnime = (async (videoId: number, animeId: number) => {
|
||||
moveCall = { videoId, animeId };
|
||||
return {
|
||||
ok: true,
|
||||
animeId,
|
||||
previousAnimeId: 1,
|
||||
removedPreviousAnime: true,
|
||||
} satisfies StatsMoveVideoResponse;
|
||||
}) as typeof apiClient.moveVideoToAnime;
|
||||
|
||||
try {
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<EpisodeList
|
||||
episodes={[episode(5, 'Stray Episode')]}
|
||||
animeId={1}
|
||||
onEpisodeMoved={(removedPreviousAnime) => {
|
||||
movedResult = removedPreviousAnime;
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
findButtonByTitle(container, 'Move to another library entry').click();
|
||||
});
|
||||
assert.match(container.textContent ?? '', /Move "Stray Episode" To/);
|
||||
// The entry the episode already belongs to is not offered as a target.
|
||||
assert.doesNotMatch(container.textContent ?? '', /Current Entry/);
|
||||
|
||||
await act(async () => {
|
||||
findButtonByText(container, 'Real Series').click();
|
||||
});
|
||||
|
||||
assert.deepEqual(moveCall, { videoId: 5, animeId: 2 });
|
||||
assert.equal(movedResult, true);
|
||||
// The row leaves this entry's list and the picker closes.
|
||||
assert.doesNotMatch(container.textContent ?? '', /Stray Episode/);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
} finally {
|
||||
Object.assign(apiClient, original);
|
||||
uninstallDom();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { useEffect, useId, useMemo, useRef, useState } from 'react';
|
||||
import { apiClient } from '../../lib/api-client';
|
||||
import { formatDuration } from '../../lib/formatters';
|
||||
import { AnimeCoverImage } from './AnimeCoverImage';
|
||||
import type { AnimeLibraryItem } from '../../types/stats';
|
||||
|
||||
interface LibraryEntryPickerProps {
|
||||
heading: string;
|
||||
/** Entries that cannot be picked, typically the one being moved away from. */
|
||||
excludeAnimeIds?: number[];
|
||||
initialQuery?: string;
|
||||
busyAnimeId?: number | null;
|
||||
error?: string | null;
|
||||
onSelect: (entry: AnimeLibraryItem) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function LibraryEntryPicker({
|
||||
heading,
|
||||
excludeAnimeIds = [],
|
||||
initialQuery = '',
|
||||
busyAnimeId = null,
|
||||
error = null,
|
||||
onSelect,
|
||||
onClose,
|
||||
}: LibraryEntryPickerProps) {
|
||||
const [entries, setEntries] = useState<AnimeLibraryItem[] | null>(null);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const [query, setQuery] = useState(initialQuery);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const headingId = useId();
|
||||
const searchId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus();
|
||||
let cancelled = false;
|
||||
apiClient
|
||||
.getAnimeLibrary()
|
||||
.then((data) => {
|
||||
if (!cancelled) setEntries(data);
|
||||
})
|
||||
.catch(() => {
|
||||
// Distinct from an empty library: telling the user "no other titles"
|
||||
// when the request failed hides a retryable error.
|
||||
if (cancelled) return;
|
||||
setEntries([]);
|
||||
setLoadFailed(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const excluded = useMemo(() => new Set(excludeAnimeIds), [excludeAnimeIds]);
|
||||
const visible = useMemo(() => {
|
||||
const term = query.trim().toLowerCase();
|
||||
return (entries ?? [])
|
||||
.filter((entry) => !excluded.has(entry.animeId))
|
||||
.filter((entry) => !term || entry.canonicalTitle.toLowerCase().includes(term))
|
||||
.sort((a, b) => b.lastWatchedMs - a.lastWatchedMs);
|
||||
}, [entries, excluded, query]);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[10vh]" onClick={onClose}>
|
||||
<div className="absolute inset-0 bg-ctp-crust/70 backdrop-blur-[2px]" />
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={headingId}
|
||||
className="relative bg-ctp-base border border-ctp-surface1 rounded-xl shadow-2xl w-full max-w-lg max-h-[70vh] flex flex-col animate-fade-in"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="p-4 border-b border-ctp-surface1">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 id={headingId} className="text-sm font-semibold text-ctp-text">
|
||||
{heading}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
className="text-ctp-overlay2 hover:text-ctp-text text-lg leading-none"
|
||||
>
|
||||
{'✕'}
|
||||
</button>
|
||||
</div>
|
||||
<label htmlFor={searchId} className="sr-only">
|
||||
Search library
|
||||
</label>
|
||||
<input
|
||||
ref={inputRef}
|
||||
id={searchId}
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Search library..."
|
||||
className="w-full bg-ctp-surface0 border border-ctp-surface1 rounded-lg px-3 py-2 text-sm text-ctp-text placeholder:text-ctp-overlay2 focus:outline-none focus:border-ctp-blue"
|
||||
/>
|
||||
{error ? (
|
||||
<div role="alert" className="text-xs text-ctp-red mt-2">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-2">
|
||||
{entries === null && <div className="text-xs text-ctp-overlay2 p-3">Loading...</div>}
|
||||
{loadFailed && (
|
||||
<div role="alert" className="text-xs text-ctp-red p-3">
|
||||
Could not load the library. Close this dialog and try again.
|
||||
</div>
|
||||
)}
|
||||
{!loadFailed && entries !== null && visible.length === 0 && (
|
||||
<div className="text-xs text-ctp-overlay2 p-3">
|
||||
{query.trim() ? 'No matches' : 'No other titles'}
|
||||
</div>
|
||||
)}
|
||||
{visible.map((entry) => (
|
||||
<button
|
||||
key={entry.animeId}
|
||||
type="button"
|
||||
disabled={busyAnimeId !== null}
|
||||
onClick={() => onSelect(entry)}
|
||||
className="w-full flex items-center gap-3 p-2.5 rounded-lg hover:bg-ctp-surface0 transition-colors text-left disabled:opacity-50"
|
||||
>
|
||||
<AnimeCoverImage
|
||||
animeId={entry.animeId}
|
||||
title={entry.canonicalTitle}
|
||||
coverRetryToken={entry.anilistId ?? 0}
|
||||
className="w-10 h-14 rounded shrink-0"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm text-ctp-text truncate">{entry.canonicalTitle}</div>
|
||||
<div className="text-xs text-ctp-overlay2 mt-0.5">
|
||||
{entry.episodeCount} episode{entry.episodeCount !== 1 ? 's' : ''} ·{' '}
|
||||
{formatDuration(entry.totalActiveMs)}
|
||||
</div>
|
||||
</div>
|
||||
{busyAnimeId === entry.animeId ? (
|
||||
<span className="text-xs text-ctp-blue shrink-0">Moving...</span>
|
||||
) : (
|
||||
<span className="text-xs text-ctp-overlay2 shrink-0">Select</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,10 @@ import type {
|
||||
StatsExcludedWordsRequest,
|
||||
StatsHttpClient,
|
||||
StatsJsonResponseMap,
|
||||
StatsMergeAnimeRequest,
|
||||
StatsMergeAnimeResponse,
|
||||
StatsMoveVideoRequest,
|
||||
StatsMoveVideoResponse,
|
||||
StatsTrendGroupBy,
|
||||
StatsTrendRange,
|
||||
StatsVideoWatchedRequest,
|
||||
@@ -194,6 +198,25 @@ export const apiClient = {
|
||||
fetchResponse(`/api/stats/anime/${animeId}`, { method: 'DELETE' }),
|
||||
);
|
||||
},
|
||||
mergeAnime: async (
|
||||
targetAnimeId: number,
|
||||
sourceAnimeIds: number[],
|
||||
): Promise<StatsMergeAnimeResponse> => {
|
||||
const res = await fetchResponse(`/api/stats/anime/${targetAnimeId}/merge`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sourceAnimeIds } satisfies StatsMergeAnimeRequest),
|
||||
});
|
||||
return res.json() as Promise<StatsMergeAnimeResponse>;
|
||||
},
|
||||
moveVideoToAnime: async (videoId: number, animeId: number): Promise<StatsMoveVideoResponse> => {
|
||||
const res = await fetchResponse(`/api/stats/media/${videoId}/anime`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ animeId } satisfies StatsMoveVideoRequest),
|
||||
});
|
||||
return res.json() as Promise<StatsMoveVideoResponse>;
|
||||
},
|
||||
getKnownWords: () => fetchJson('knownWords', '/api/stats/known-words'),
|
||||
getKnownWordsSummary: () => fetchJson('knownWordsSummary', '/api/stats/known-words-summary'),
|
||||
getAnimeKnownWordsSummary: (animeId: number) =>
|
||||
|
||||
Reference in New Issue
Block a user