mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-16 04:46:07 -08:00
Compare commits
5
Commits
2a0e931325
...
af44735bb8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af44735bb8 | ||
|
|
804fb8933e
|
||
|
|
2924f04316 | ||
|
|
a9a4c4f083 | ||
|
|
90fc7cf940 |
No files matched your search
@@ -1,49 +0,0 @@
|
||||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
actions: read # Required for Claude to read CI results on PRs
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
|
||||
# This is an optional setting that allows Claude to read CI results on PRs
|
||||
additional_permissions: |
|
||||
actions: read
|
||||
|
||||
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
|
||||
# prompt: 'Update the pull request description to include a summary of changes.'
|
||||
|
||||
# Optional: Add claude_args to customize behavior and configuration
|
||||
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
|
||||
# or https://code.claude.com/docs/en/cli-reference for available options
|
||||
# claude_args: '--allowed-tools Bash(gh pr:*)'
|
||||
@@ -102,6 +102,10 @@ A stats dashboard tracks watch time, vocabulary growth, mining throughput, sessi
|
||||
<td><b>WebSocket</b></td>
|
||||
<td>Plain subtitle feed plus a dedicated annotated feed for texthooker pages and custom tools</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Plugins</b></td>
|
||||
<td>Load your own JavaScript at startup to react to playback, run timers, add key-bound actions, and show results in an overlay panel. The bundled example explains the current line with Codex. <a href="https://docs.subminer.moe/plugins">Plugin guide</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br>
|
||||
@@ -267,7 +271,7 @@ SubMiner builds on the work of these open-source projects:
|
||||
| [jellyfin-mpv-shim](https://github.com/jellyfin/jellyfin-mpv-shim) | Jellyfin integration |
|
||||
| [Jimaku.cc](https://jimaku.cc) | Japanese subtitle search and downloads |
|
||||
| [Renji's Texthooker Page](https://github.com/Renji-XD/texthooker-ui) | Base for the WebSocket texthooker integration |
|
||||
| [Yomitan](https://github.com/yomidevs/yomitan) | Default dictionary engine and morphological parser |
|
||||
| [Yomitan](https://github.com/yomidevs/yomitan) | Default dictionary engine and morphological parser |
|
||||
| [Hachidori](https://github.com/bee-san/hachidori) | Alternative dictionary backend, powered by HoshiDicts |
|
||||
| [yomitan-jlpt-vocab](https://github.com/stephenmk/yomitan-jlpt-vocab) | JLPT level tags for vocabulary |
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// Sends the current subtitle line, with a few lines of context, to `codex exec` and shows the
|
||||
// answer in the SubMiner plugin panel. Registers two actions: `explain` and `translate`.
|
||||
const { mkdtemp, readFile, rm } = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const DEFAULT_SETTINGS = {
|
||||
codexPath: 'codex',
|
||||
model: '',
|
||||
// Passed as -c model_reasoning_effort; low keeps answers to a few seconds. Empty uses your Codex config.
|
||||
reasoningEffort: 'low',
|
||||
before: 2,
|
||||
after: 1,
|
||||
timeoutMs: 120_000,
|
||||
pause: true,
|
||||
prompts: {},
|
||||
};
|
||||
|
||||
const ACTIONS = {
|
||||
explain: {
|
||||
title: 'Grammar',
|
||||
prompt:
|
||||
'You are a Japanese tutor. Explain the line marked >>> for an intermediate learner. ' +
|
||||
'Use the other lines only as context. Reply in English markdown: a natural translation, ' +
|
||||
'then a bullet list of the grammar points and notable vocabulary. Be concise.',
|
||||
},
|
||||
translate: {
|
||||
title: 'Translation',
|
||||
prompt:
|
||||
'Translate the line marked >>> into natural English. Use the other lines only as context. ' +
|
||||
'Reply with the translation, then one short note only if the line is ambiguous.',
|
||||
},
|
||||
};
|
||||
|
||||
function activate(ctx) {
|
||||
const settings = { ...DEFAULT_SETTINGS, ...ctx.settings };
|
||||
for (const [name, action] of Object.entries(ACTIONS)) {
|
||||
const prompt = settings.prompts?.[name] ?? action.prompt;
|
||||
ctx.actions.register(name, () => ask(ctx, settings, action.title, prompt));
|
||||
}
|
||||
}
|
||||
|
||||
function quote(text) {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((line) => `> ${line}`)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
// Subtitles wrap across lines; flatten each cue so the >>> marker covers all of it.
|
||||
function oneLine(text) {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
function tail(text, lineCount) {
|
||||
return text.trim().split('\n').slice(-lineCount).join('\n');
|
||||
}
|
||||
|
||||
async function ask(ctx, settings, title, instructions) {
|
||||
const { before, current, after } = ctx.subtitles.context({
|
||||
before: settings.before,
|
||||
after: settings.after,
|
||||
});
|
||||
if (!current) {
|
||||
ctx.notify('No subtitle line to send.', { variant: 'warning' });
|
||||
return;
|
||||
}
|
||||
if (settings.pause) ctx.mpv.command(['set', 'pause', 'yes']);
|
||||
|
||||
const header = quote(current.text);
|
||||
const panel = ctx.ui.panel({ title, markdown: `${header}\n\n_Asking Codex..._` });
|
||||
const prompt = [
|
||||
instructions,
|
||||
'',
|
||||
'Subtitles:',
|
||||
...before.map((line) => oneLine(line.text)),
|
||||
`>>> ${oneLine(current.text)}`,
|
||||
...after.map((line) => oneLine(line.text)),
|
||||
].join('\n');
|
||||
|
||||
// Codex runs in an empty read-only directory so any command it tries cannot touch real files.
|
||||
const workDir = await mkdtemp(path.join(os.tmpdir(), 'subminer-ai-explain-'));
|
||||
const answerPath = path.join(workDir, 'answer.md');
|
||||
const args = [
|
||||
'exec',
|
||||
'--ephemeral',
|
||||
'--skip-git-repo-check',
|
||||
'--sandbox',
|
||||
'read-only',
|
||||
'--color',
|
||||
'never',
|
||||
'-C',
|
||||
workDir,
|
||||
'-o',
|
||||
answerPath,
|
||||
];
|
||||
if (settings.model) args.push('-m', settings.model);
|
||||
if (settings.reasoningEffort) {
|
||||
args.push('-c', `model_reasoning_effort=${JSON.stringify(settings.reasoningEffort)}`);
|
||||
}
|
||||
args.push('-');
|
||||
|
||||
try {
|
||||
const result = await ctx.exec(settings.codexPath, args, {
|
||||
stdin: prompt,
|
||||
timeoutMs: settings.timeoutMs,
|
||||
signal: panel.signal,
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(tail(result.stderr, 6) || `codex exited with code ${result.exitCode}`);
|
||||
}
|
||||
const answer = (await readFile(answerPath, 'utf8')).trim();
|
||||
panel.update({ markdown: `${header}\n\n${answer || '_Codex returned an empty answer._'}` });
|
||||
} catch (error) {
|
||||
// Closing the panel aborts the request; there is nobody left to show the error to.
|
||||
if (panel.signal.aborted) return;
|
||||
const message =
|
||||
error?.code === 'ENOENT'
|
||||
? `Cannot find \`${settings.codexPath}\`. Set \`plugins.ai-explain.settings.codexPath\` to its full path.`
|
||||
: String(error?.message ?? error);
|
||||
ctx.log.warn(`Codex request failed: ${message}`);
|
||||
panel.update({
|
||||
markdown: `${header}\n\n**Codex request failed.**\n\n\`\`\`\n${message}\n\`\`\``,
|
||||
});
|
||||
} finally {
|
||||
await rm(workDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { activate };
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "AI Explain",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": 1,
|
||||
"main": "main.js"
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Runs AnkiConnect's `sync` (AnkiWeb) after you mine cards. A burst of mining becomes one sync:
|
||||
// it waits until no card has been mined for `delayMs`, and syncs right away when playback ends.
|
||||
// Also registers a `sync` action for a manual sync.
|
||||
|
||||
const DEFAULT_SETTINGS = {
|
||||
delayMs: 30_000,
|
||||
syncOnEnd: true,
|
||||
timeoutMs: 60_000,
|
||||
notify: true,
|
||||
};
|
||||
|
||||
const END_REASONS = new Set(['eof', 'stop', 'quit']);
|
||||
|
||||
function activate(ctx) {
|
||||
const settings = { ...DEFAULT_SETTINGS, ...ctx.settings };
|
||||
// Cards mined since the last sync started.
|
||||
let dirty = false;
|
||||
let syncing = false;
|
||||
let cancelTimer = null;
|
||||
|
||||
function schedule() {
|
||||
cancelTimer?.();
|
||||
cancelTimer = ctx.after(settings.delayMs, flush);
|
||||
}
|
||||
|
||||
async function flush() {
|
||||
cancelTimer?.();
|
||||
cancelTimer = null;
|
||||
// A sync already running picks up new cards when it finishes.
|
||||
if (!dirty || syncing) return;
|
||||
dirty = false;
|
||||
syncing = true;
|
||||
try {
|
||||
await ctx.anki.invoke('sync', {}, { timeoutMs: settings.timeoutMs });
|
||||
ctx.log.info('Synced Anki.');
|
||||
if (settings.notify) ctx.notify('Anki synced');
|
||||
} catch (error) {
|
||||
ctx.log.warn(`Anki sync failed: ${error.message}`);
|
||||
ctx.notify(`Anki sync failed: ${error.message}`, { variant: 'error' });
|
||||
} finally {
|
||||
syncing = false;
|
||||
if (dirty) schedule();
|
||||
}
|
||||
}
|
||||
|
||||
ctx.anki.on('card-mined', () => {
|
||||
dirty = true;
|
||||
schedule();
|
||||
});
|
||||
|
||||
ctx.mpv.on('end-file', ({ reason }) => {
|
||||
if (settings.syncOnEnd && END_REASONS.has(reason)) return flush();
|
||||
});
|
||||
|
||||
ctx.actions.register('sync', () => {
|
||||
dirty = true;
|
||||
return flush();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { activate };
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "Anki Sync",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": 1,
|
||||
"main": "main.js"
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Opens the Jimaku subtitle search when a file starts without a Japanese subtitle track.
|
||||
// It waits a few seconds after the file loads so external subtitles mpv or SubMiner add count.
|
||||
|
||||
const DEFAULT_SETTINGS = {
|
||||
// Built-in action to run, e.g. `openTsukihime` or `openSubtitleSelection`.
|
||||
action: 'openJimaku',
|
||||
// Track `lang` codes that count as Japanese. Track titles with "Japanese" or 日本語 count too.
|
||||
languages: ['ja', 'jp', 'jpn'],
|
||||
delayMs: 3_000,
|
||||
// Also check http(s) streams; Jimaku can only search by name, which streams rarely have.
|
||||
streams: false,
|
||||
};
|
||||
|
||||
const JAPANESE_TITLE = /japanese|日本語/i;
|
||||
|
||||
function activate(ctx) {
|
||||
const settings = { ...DEFAULT_SETTINGS, ...ctx.settings };
|
||||
const languages = new Set(settings.languages.map((lang) => lang.toLowerCase()));
|
||||
let cancelCheck = null;
|
||||
let playbackId = null;
|
||||
|
||||
function hasJapaneseSubtitle(trackList) {
|
||||
return trackList.some(
|
||||
(track) =>
|
||||
track?.type === 'sub' &&
|
||||
(languages.has(String(track.lang ?? '').toLowerCase()) ||
|
||||
JAPANESE_TITLE.test(String(track.title ?? ''))),
|
||||
);
|
||||
}
|
||||
|
||||
async function check(media) {
|
||||
cancelCheck = null;
|
||||
const trackList = await ctx.mpv.getProperty('track-list');
|
||||
if (ctx.media.current()?.playbackId !== media.playbackId || !Array.isArray(trackList)) return;
|
||||
if (hasJapaneseSubtitle(trackList)) return;
|
||||
ctx.log.info(`No Japanese subtitles for ${media.path}; running ${settings.action}.`);
|
||||
await ctx.actions.run(settings.action);
|
||||
}
|
||||
|
||||
ctx.media.on('change', (media) => {
|
||||
if (media?.playbackId === playbackId) return;
|
||||
playbackId = media?.playbackId ?? null;
|
||||
cancelCheck?.();
|
||||
cancelCheck = null;
|
||||
if (!media) return;
|
||||
if (!settings.streams && /^[a-z]+:\/\//i.test(media.path)) return;
|
||||
cancelCheck = ctx.after(settings.delayMs, () => check(media));
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { activate };
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "Auto Jimaku",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": 1,
|
||||
"main": "main.js"
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Tags each mined card with the show and episode it came from, e.g. `show::Frieren::S01E07`.
|
||||
// The show and episode are parsed from the file name, or from mpv's media title for streams.
|
||||
const path = require('node:path');
|
||||
|
||||
const DEFAULT_SETTINGS = {
|
||||
// Placeholders: {show}, {season}, {episode}, and {ep} (S01E07, or E07 without a season).
|
||||
// A tag stops before the first `::` level whose placeholder has no value.
|
||||
tags: ['show::{show}::{ep}'],
|
||||
notify: false,
|
||||
};
|
||||
|
||||
// Tried in order; the first match wins. Runs on names with brackets and dots already removed.
|
||||
const EPISODE_PATTERNS = [
|
||||
/^(?<show>.*?)\s*S(?<season>\d{1,2})\s?E(?<episode>\d{1,4})\b/i,
|
||||
/^(?<show>.*?)\s*(?:Season\s?(?<season>\d{1,2})\s*)?(?:Episode|Ep)\s?(?<episode>\d{1,4})\b/i,
|
||||
/^(?<show>.*?)\s+-\s+(?<episode>\d{1,4})(?:v\d)?\b/,
|
||||
/^(?<show>.*?)\s+(?<episode>\d{1,4})(?:v\d)?$/,
|
||||
/^(?<show>.*?)\s*第(?<episode>\d{1,4})話/,
|
||||
];
|
||||
|
||||
// `[Group] Show Name - 07 (1080p).mkv` -> { show: 'Show Name', season: null, episode: '07' }
|
||||
function parseMediaName(name) {
|
||||
const cleaned = name
|
||||
.replace(/\.[a-z0-9]{2,4}$/i, '')
|
||||
.replace(/\[[^\]]*\]|\([^)]*\)|【[^】]*】/g, ' ')
|
||||
.replace(/[._]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
for (const pattern of EPISODE_PATTERNS) {
|
||||
const groups = cleaned.match(pattern)?.groups;
|
||||
const show = groups?.show.replace(/[\s-]+$/, '');
|
||||
if (!show) continue;
|
||||
return { show, season: pad(groups.season), episode: pad(groups.episode) };
|
||||
}
|
||||
return { show: cleaned || null, season: null, episode: null };
|
||||
}
|
||||
|
||||
function pad(number) {
|
||||
return number ? String(Number(number)).padStart(2, '0') : null;
|
||||
}
|
||||
|
||||
// Anki tags can't hold spaces, and a `::` in a value would add a hierarchy level.
|
||||
function tagValue(value) {
|
||||
return value.replace(/::?/g, ' ').trim().replace(/\s+/g, '_').replace(/"/g, '');
|
||||
}
|
||||
|
||||
function renderTag(template, values) {
|
||||
const levels = [];
|
||||
for (const level of template.split('::')) {
|
||||
let missing = false;
|
||||
const rendered = level.replace(/\{(\w+)\}/g, (_, key) => {
|
||||
const value = values[key];
|
||||
if (!value) missing = true;
|
||||
return value ? tagValue(value) : '';
|
||||
});
|
||||
if (missing) break;
|
||||
levels.push(rendered);
|
||||
}
|
||||
return levels.join('::');
|
||||
}
|
||||
|
||||
function mediaName(mediaPath, title) {
|
||||
// A stream URL's last segment is usually an id, so streams use the title mpv shows.
|
||||
if (typeof mediaPath === 'string' && mediaPath && !/^[a-z]+:\/\//i.test(mediaPath)) {
|
||||
return path.basename(mediaPath);
|
||||
}
|
||||
return typeof title === 'string' && title ? title : null;
|
||||
}
|
||||
|
||||
function renderTags(templates, name) {
|
||||
const { show, season, episode } = parseMediaName(name);
|
||||
const ep = episode ? `${season ? `S${season}` : ''}E${episode}` : null;
|
||||
const values = { show, season, episode, ep };
|
||||
return [...new Set(templates.map((template) => renderTag(template, values)))].filter(Boolean);
|
||||
}
|
||||
|
||||
function activate(ctx) {
|
||||
const settings = { ...DEFAULT_SETTINGS, ...ctx.settings };
|
||||
ctx.anki.on('card-mined', async ({ notes }) => {
|
||||
// Notes from the same file share one addTags call.
|
||||
const notesByName = new Map();
|
||||
for (const { noteId, provenance } of notes) {
|
||||
const name = mediaName(provenance?.media?.path, provenance?.media?.title);
|
||||
if (!name) {
|
||||
ctx.log.debug(`Note ${noteId} has no known media source; not tagging it.`);
|
||||
continue;
|
||||
}
|
||||
if (!notesByName.has(name)) notesByName.set(name, new Set());
|
||||
notesByName.get(name).add(noteId);
|
||||
}
|
||||
|
||||
for (const [name, notes] of notesByName) {
|
||||
const tags = renderTags(settings.tags, name);
|
||||
if (tags.length === 0) {
|
||||
ctx.log.debug(`No tags for "${name}".`);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await ctx.anki.invoke('addTags', { notes: [...notes], tags: tags.join(' ') });
|
||||
ctx.log.info(`Tagged ${notes.size} note(s): ${tags.join(' ')}`);
|
||||
if (settings.notify) ctx.notify(`Tagged ${tags.join(' ')}`);
|
||||
} catch (error) {
|
||||
ctx.log.warn(`Tagging failed: ${error.message}`);
|
||||
ctx.notify(`Episode tagging failed: ${error.message}`, { variant: 'error' });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { activate };
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "Episode Tags",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": 1,
|
||||
"main": "main.js"
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
type: added
|
||||
area: plugins
|
||||
|
||||
- Added JavaScript plugins loaded at startup from `<config dir>/plugins/<id>/` and enabled under `plugins` in the config. Plugins can listen to mpv events, run timers, register actions bound with `__plugin-action:<id>/<action>` keybindings or run with `--plugin-action`, run built-in actions, react to mined Anki cards and call AnkiConnect, start mpv, run programs, keep state in a per-plugin data folder, and show results in an overlay panel or their own window.
|
||||
- Added an example `ai-explain` plugin that sends the current line and its neighbors to `codex exec` and shows a translation or grammar explanation.
|
||||
- Added an example `anki-sync` plugin that syncs Anki to AnkiWeb after you mine cards, once mining goes quiet or playback ends.
|
||||
- Added an example `episode-tags` plugin that tags mined cards with the show and episode, such as `show::Frieren::S01E07`.
|
||||
- Added an example `auto-jimaku` plugin that opens the Jimaku search when a file starts without a Japanese subtitle track.
|
||||
- Added a versioned plugin API with standalone authoring types, cached playback snapshots, lifecycle cancellation and cleanup, and awaitable mpv commands. Async activation is bounded and actions wait only for their own plugin. Shutdown skips pending loads, runs each deactivation once, and blocks calls from disposed plugins.
|
||||
- Mining events preserve original and kept note ids with the media and subtitle captured when mining starts, so delayed enrichment and merges into older notes keep the source episode. Stats-dashboard cards do not trigger plugin events. Plugin subtitle lookups and mining provenance account for subtitle delay and return timing on the subtitle file's timeline.
|
||||
@@ -218,6 +218,14 @@
|
||||
"overlayPosition": "top-right" // Position for in-overlay notification cards. Values: top-left | top | top-right
|
||||
}, // Overlay notification display behavior.
|
||||
|
||||
// ==========================================
|
||||
// Plugins
|
||||
// JavaScript plugins loaded from <config dir>/plugins/<id>/ at startup.
|
||||
// Plugins run inside SubMiner with full access to your system. Only enable code you trust.
|
||||
// Restart SubMiner after changing plugins.
|
||||
// ==========================================
|
||||
"plugins": {}, // Plugins to load at startup, keyed by directory name under <config dir>/plugins/. Each entry is { "enabled": true, "settings": { ... } }; settings are passed to the plugin as ctx.settings.
|
||||
|
||||
// ==========================================
|
||||
// Keyboard Shortcuts
|
||||
// Overlay keyboard shortcuts. Set a shortcut to null to disable.
|
||||
|
||||
@@ -221,6 +221,7 @@ const sidebar: DefaultTheme.SidebarItem[] = [
|
||||
{ text: 'AniList', link: '/anilist-integration' },
|
||||
{ text: 'AniSkip', link: '/aniskip-integration' },
|
||||
{ text: 'Character Dictionary', link: '/character-dictionary' },
|
||||
{ text: 'Plugins', link: '/plugins' },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -24,6 +24,7 @@ src/
|
||||
preload*.ts # preload bridges (overlay, settings, stats, sync, Jellyfin setup)
|
||||
main/ # main-process runtime modules and IPC/CLI wiring
|
||||
boot/ # pre-ready boot helpers
|
||||
assemblies/ # per-domain assemblies main.ts builds once (overlay, playback, first-run setup, YouTube, Jellyfin, AniList, settings, sync, dictionaries, overlay modals)
|
||||
runtime/composers/ # larger runtime clusters assembled for main.ts
|
||||
runtime/domains/ # domain barrels (startup, overlay, mpv, ipc, shortcuts, anilist, jellyfin, mining)
|
||||
core/services/ # focused services: mpv client, overlay, tokenizer, mining, integrations, stats
|
||||
@@ -138,7 +139,7 @@ Runtime code uses dependency injection:
|
||||
2. Build its runtime dependencies in a `src/main/` module. Pass simple dependencies inline; extract an adapter only when it adds behavior or gets reused.
|
||||
3. Call the service from lifecycle or command wiring.
|
||||
|
||||
`main.ts` gets domain handlers through `createMainRuntimeRegistry()` (`src/main/runtime/registry.ts`), which exposes the barrels in `src/main/runtime/domains/`. Larger clusters, such as app-ready startup, mpv, Jellyfin, AniList tracking, shortcuts, and IPC, are assembled by composers in `src/main/runtime/composers/`. Many handlers take a `*MainDeps` object built by a `createBuild*MainDepsHandler` builder, which keeps side effects out of the unit under test.
|
||||
`main.ts` gets domain handlers through `createMainRuntimeRegistry()` (`src/main/runtime/registry.ts`), which exposes the barrels in `src/main/runtime/domains/`. Larger clusters, such as app-ready startup, mpv, Jellyfin, AniList tracking, shortcuts, and IPC, are assembled by composers in `src/main/runtime/composers/`. A domain whose runtimes share state, such as the overlay windows, mpv playback and subtitle state, YouTube, Jellyfin, AniList, config settings, sync, or the character dictionary, is grouped into one assembly in `src/main/assemblies/` that owns that state and returns its runtimes. Handlers take their dependencies as a plain object passed straight to the handler factory, which keeps side effects out of the unit under test.
|
||||
|
||||
Composers declare their inputs with `ComposerInputs<T>` and results with `ComposerOutputs<T>` from `src/main/runtime/composers/contracts.ts`. A missing dependency then fails at compile time.
|
||||
|
||||
|
||||
@@ -106,6 +106,15 @@ Overlay notifications are also kept in a session-only history panel. Toggle it w
|
||||
|
||||
Mining and startup status notifications use `ankiConnect.behavior.notificationType` (see [AnkiConnect](#ankiconnect)).
|
||||
|
||||
### Plugins
|
||||
|
||||
`plugins` enables [plugins](/plugins) from the `plugins/` folder next to this config file. Each key is a plugin folder name. Changes apply after a restart.
|
||||
|
||||
| Key | Default | What it does |
|
||||
| ----------------------- | ------- | -------------------------------------- |
|
||||
| `plugins.<id>.enabled` | `false` | Load the plugin at startup |
|
||||
| `plugins.<id>.settings` | `{}` | Passed to the plugin as `ctx.settings` |
|
||||
|
||||
### Auto-start overlay
|
||||
|
||||
When mpv is started by SubMiner or the `subminer` launcher, the launcher passes these settings to the bundled mpv plugin. There is no separate plugin config file. `mpv.autoStartSubMiner` and `mpv.pauseUntilOverlayReady` (see [MPV launcher](#mpv-launcher)) control the background start and the initial pause.
|
||||
@@ -268,7 +277,7 @@ Adds a modal for choosing mpv's primary and secondary subtitle tracks. Open it w
|
||||
|
||||
- `key` uses `KeyboardEvent.code` names (`Space`, `KeyR`, `ArrowRight`) with optional `Ctrl+`, `Alt+`, `Shift+`, `Meta+`. Mouse buttons are `MBTN_LEFT`, `MBTN_MID`, `MBTN_RIGHT`, `MBTN_BACK`, `MBTN_FORWARD`. Scroll wheel keys are `WHEEL_UP`, `WHEEL_DOWN`, `WHEEL_LEFT`, `WHEEL_RIGHT`.
|
||||
- `command` is any mpv JSON IPC command array. Set it to `null` to disable a default.
|
||||
- Commands starting with `__` run inside SubMiner: `__playlist-browser-open`, `__youtube-picker-open`, `__replay-subtitle`, `__play-next-subtitle`, `__runtime-options-open`, and `__runtime-option-cycle:<id>[:next|prev]`.
|
||||
- Commands starting with `__` run inside SubMiner: `__playlist-browser-open`, `__youtube-picker-open`, `__replay-subtitle`, `__play-next-subtitle`, `__runtime-options-open`, `__runtime-option-cycle:<id>[:next|prev]`, and `__plugin-action:<plugin id>/<action>` (see [Plugins](/plugins)).
|
||||
- Unused single-key, mouse button, and scroll wheel bindings from your mpv config also work in the overlay. Your SubMiner bindings win on conflicts.
|
||||
|
||||
### Shortcuts configuration
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
# Plugins
|
||||
|
||||
Plugins are JavaScript files that SubMiner loads at startup. A plugin can react to playback, run code on a timer, add actions you bind to keys, run programs, and show results in an overlay panel, all without rebuilding SubMiner.
|
||||
|
||||
::: warning Only run plugins you trust
|
||||
Plugins run inside SubMiner with the same access to your files and system as SubMiner itself. There is no sandbox.
|
||||
:::
|
||||
|
||||
These are SubMiner app plugins. The Lua script that runs inside mpv is the separate [mpv plugin](/mpv-plugin).
|
||||
|
||||
## Install a plugin
|
||||
|
||||
1. Put the plugin in its own folder in `plugins/` next to your [config file](/configuration#configuration-file), for example `~/.config/SubMiner/plugins/ai-explain/`. The folder name is the plugin id.
|
||||
2. Enable it in `config.jsonc`. `settings` is passed to the plugin as-is:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"plugins": {
|
||||
"ai-explain": { "enabled": true, "settings": { "reasoningEffort": "medium" } },
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
3. Bind its actions to keys with the `__plugin-action:<plugin id>/<action>` command:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"keybindings": [
|
||||
{ "key": "Ctrl+KeyE", "command": ["__plugin-action:ai-explain/explain"] },
|
||||
{ "key": "Ctrl+KeyT", "command": ["__plugin-action:ai-explain/translate"] },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
To run an action from a script or a window-manager shortcut, use `subminer app --plugin-action ai-explain/explain`. It goes to the running SubMiner, or starts one if none is running.
|
||||
|
||||
4. Restart SubMiner. Plugin changes apply on the next start; keybinding changes apply immediately.
|
||||
|
||||
Load errors and plugin log output go to the app log with a `plugin:<id>` scope.
|
||||
|
||||
## Example: explain the current line with Codex
|
||||
|
||||
The repository ships [`assets/plugins/ai-explain`](https://github.com/ksyasuda/SubMiner/tree/main/assets/plugins/ai-explain). It sends the current line, plus the lines around it, to [`codex exec`](https://github.com/openai/codex) and shows the answer in a panel. It needs a logged-in Codex CLI.
|
||||
|
||||
| Action | What it does |
|
||||
| ----------- | --------------------------------------------------------------- |
|
||||
| `explain` | Translation plus a breakdown of the grammar and vocabulary |
|
||||
| `translate` | Natural English translation, with a note only when it's unclear |
|
||||
|
||||
| Setting | Default | What it does |
|
||||
| ----------------- | --------- | ----------------------------------------------------------------- |
|
||||
| `codexPath` | `"codex"` | Codex binary. Use a full path if SubMiner can't find it on `PATH` |
|
||||
| `model` | `""` | Model passed to `codex exec -m`; empty uses your Codex config |
|
||||
| `reasoningEffort` | `"low"` | Codex reasoning effort; empty uses your Codex config |
|
||||
| `before`, `after` | `2`, `1` | Lines of context sent before and after the current line |
|
||||
| `pause` | `true` | Pause playback when the panel opens |
|
||||
| `timeoutMs` | `120000` | Give up after this long |
|
||||
| `prompts` | `{}` | Replace an action's instructions, e.g. `{ "translate": "..." }` |
|
||||
|
||||
Press `Esc` to close the panel. Closing it, or starting another request, stops the running Codex process.
|
||||
|
||||
## Example: sync Anki after mining
|
||||
|
||||
[`assets/plugins/anki-sync`](https://github.com/ksyasuda/SubMiner/tree/main/assets/plugins/anki-sync) runs AnkiConnect's `sync` after you mine cards, so they reach AnkiWeb without opening Anki. It waits until you stop mining for a while, so a burst of cards becomes one sync. It also adds a `sync` action you can bind to a key.
|
||||
|
||||
| Setting | Default | What it does |
|
||||
| ----------- | ------- | ------------------------------------------------------- |
|
||||
| `delayMs` | `30000` | Sync after no card has been mined for this long |
|
||||
| `syncOnEnd` | `true` | Sync right away when playback ends or mpv quits |
|
||||
| `timeoutMs` | `60000` | Give up on a sync after this long |
|
||||
| `notify` | `true` | Show a notification after each sync. Failures always do |
|
||||
|
||||
Anki must be running and logged in to AnkiWeb. Cards mined from the stats dashboard don't trigger a sync.
|
||||
|
||||
## Example: tag cards with the episode
|
||||
|
||||
[`assets/plugins/episode-tags`](https://github.com/ksyasuda/SubMiner/tree/main/assets/plugins/episode-tags) tags each mined card with the show and episode it came from, such as `show::Sousou_no_Frieren::E07`. It reads them from the file name (`[Group] Show - 07 (1080p).mkv`, `Show.S01E07.mkv`, `Show 第7話.mkv`), or from the title mpv shows for streams. It uses the source captured when mining started, so delayed media and field grouping into an older note keep the correct episode. Notes with unknown provenance, including cards discovered by polling, are left alone. Spaces become `_`.
|
||||
|
||||
| Setting | Default | What it does |
|
||||
| -------- | ------------------------ | ----------------------------------------------- |
|
||||
| `tags` | `["show::{show}::{ep}"]` | Tags to add, one template each |
|
||||
| `notify` | `false` | Show a notification with the tags for each card |
|
||||
|
||||
Templates can use `{show}`, `{season}`, `{episode}`, and `{ep}` (`S01E07`, or `E07` when there is no season). When a placeholder has no value, the tag stops before that `::` level, so a movie gets `show::<title>`. The parsing is a guess from the name: a title ending in a number, like `Mob Psycho 100`, reads that number as the episode.
|
||||
|
||||
## Example: open Jimaku when a file has no Japanese subtitles
|
||||
|
||||
[`assets/plugins/auto-jimaku`](https://github.com/ksyasuda/SubMiner/tree/main/assets/plugins/auto-jimaku) opens the Jimaku search a few seconds after a file starts if none of its subtitle tracks is Japanese. A track counts as Japanese when its language code is in `languages`, or its title contains "Japanese" or 日本語.
|
||||
|
||||
| Setting | Default | What it does |
|
||||
| ----------- | --------------------- | --------------------------------------------------------------- |
|
||||
| `action` | `"openJimaku"` | Built-in action to run, e.g. `openTsukihime` |
|
||||
| `languages` | `["ja", "jp", "jpn"]` | Track language codes that count as Japanese |
|
||||
| `delayMs` | `3000` | Wait this long after the file starts, so external subs load |
|
||||
| `streams` | `false` | Also check `http(s)` streams, which Jimaku usually can't search |
|
||||
|
||||
## Write a plugin
|
||||
|
||||
A plugin folder needs a `plugin.json`:
|
||||
|
||||
```json
|
||||
{ "name": "My Plugin", "version": "1.0.0", "apiVersion": 1, "main": "main.js" }
|
||||
```
|
||||
|
||||
`apiVersion` declares the required SubMiner plugin API version. The current version is `1`; omitted values also mean v1 for existing plugins. An unsupported version is rejected before the plugin's entry module runs. `version` is the plugin's own version and does not control compatibility.
|
||||
|
||||
`main` points to a CommonJS module (`.js`) or an ES module (`.mjs`) that exports `activate(ctx)`. Activation may be asynchronous and has a 10-second timeout. A plugin's actions wait for its own activation, so a slow plugin does not hold up other plugins. If activation fails or times out, its registrations are removed and its signal aborts. Synchronous code still shares the app's main thread.
|
||||
|
||||
Activation may return a cleanup function, or the module can export `deactivate()`. On quit, SubMiner aborts `ctx.signal` first and waits up to 2 seconds in total for loading and deactivation. A plugin still reading its files is skipped. Everything a plugin registers through `ctx` is cleaned up automatically. A late activation cannot leave new listeners, timers, or actions behind, and its returned cleanup still runs once. Deactivation can call Anki, mpv, built-in actions, and notifications until disposal. After disposal, those calls throw or reject, including work that resumes after an activation or deactivation timeout.
|
||||
|
||||
```js
|
||||
function activate(ctx) {
|
||||
ctx.media.on('change', (media) => {
|
||||
if (media) ctx.log.info(`Now playing ${media.path}`);
|
||||
});
|
||||
ctx.every(60_000, () => ctx.log.info('Still watching'));
|
||||
ctx.actions.register('hello', () => {
|
||||
const line = ctx.subtitles.current();
|
||||
ctx.ui.panel({ title: 'Hello', markdown: line ? `> ${line.text}` : '_No subtitle_' });
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { activate };
|
||||
```
|
||||
|
||||
An error thrown by a plugin is logged and does not crash SubMiner. A plugin that blocks with a long synchronous loop still freezes the app, so keep slow work asynchronous.
|
||||
|
||||
### Types and cleanup
|
||||
|
||||
The public types live in [`src/plugin-api.ts`](https://github.com/ksyasuda/SubMiner/blob/main/src/plugin-api.ts). A build emits `dist/plugin-api.d.ts`; copy that file into your plugin as `subminer.d.ts`, or copy the source file with that name. It has no imports from SubMiner internals. Electron's types must be available to your editor because `ui.openWindow` returns a `BrowserWindow`.
|
||||
|
||||
JavaScript plugins can use the types through JSDoc:
|
||||
|
||||
```js
|
||||
/** @param {import('./subminer').PluginContext} ctx */
|
||||
function activate(ctx) {
|
||||
const { ipcMain } = require('electron');
|
||||
ipcMain.handle(`${ctx.id}:info`, () => ({ media: ctx.media.current() }));
|
||||
ctx.onDispose(() => ipcMain.removeHandler(`${ctx.id}:info`));
|
||||
}
|
||||
|
||||
module.exports = { activate };
|
||||
```
|
||||
|
||||
Use `ctx.signal` with `fetch` or other cancellable work. It aborts when unloading starts, before `deactivate` runs. `ctx.onDispose(fn)` registers synchronous cleanup for resources outside `ctx`, such as file watchers and Electron IPC handlers. The returned function runs the cleanup early, at most once. Registering cleanup after unloading starts runs it immediately. Timers and listeners registered after that point are removed immediately too. Use the returned activation cleanup or `deactivate` for asynchronous teardown, within the shared quit timeout.
|
||||
|
||||
### `ctx` reference
|
||||
|
||||
| Member | What it does |
|
||||
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id`, `dir`, `settings` | Plugin id, plugin folder path, and `plugins.<id>.settings` |
|
||||
| `apiVersion` | The host's plugin API version, currently `1` |
|
||||
| `signal`, `onDispose(fn)` | Lifetime cancellation and cleanup for resources created outside `ctx` |
|
||||
| `dataDir` | `plugin-data/<id>/` next to your config file, for caches and state. Exists before `activate` runs |
|
||||
| `log.debug/info/warn/error(message)` | Write to the app log |
|
||||
| `every(ms, fn)`, `after(ms, fn)` | Repeating and one-shot timers. Return a function that cancels them |
|
||||
| `mpv.on(event, fn)` | Listen to mpv events (below). Returns an unsubscribe function |
|
||||
| `mpv.command(args)` | Send an mpv command, e.g. `['set', 'pause', 'yes']` |
|
||||
| `mpv.request(args)` | Await an mpv command result; rejects on command error, disconnect, or timeout |
|
||||
| `mpv.getProperty(name)` | Read an mpv property (Promise) |
|
||||
| `mpv.connected` | Whether mpv is connected |
|
||||
| `mpv.ensureRunning()` | Connect to mpv, starting an idle mpv if none is running. Resolves `false` if that fails |
|
||||
| `media.current()` | Cached `{ playbackId, path, title }`, or `null` when there is no connected media |
|
||||
| `media.on('change', fn, options)` | Subscribe to playback snapshots; immediately delivers the current snapshot unless `emitCurrent: false` |
|
||||
| `anki.on(event, fn)` | Listen to Anki events (below). Returns an unsubscribe function |
|
||||
| `anki.invoke(action, params, options)` | Send an AnkiConnect action to `ankiConnect.url`, e.g. `('sync')`. Resolves its result (below) |
|
||||
| `subtitles.current()` | The displayed line as `{ text, startTime, endTime }`, or `null` |
|
||||
| `subtitles.context({ before, after })` | `{ current, before, after }`. Neighbors come from the loaded subtitle file, or recent lines for streams |
|
||||
| `actions.register(name, fn)` | Add an action, bindable as `__plugin-action:<id>/<name>` |
|
||||
| `actions.run(actionId, payload)` | Run a built-in action, the same ids keybindings use, e.g. `openJimaku` or `mineSentence` |
|
||||
| `notify(message, { variant })` | Overlay notification. `variant` is `info`, `warning`, or `error` |
|
||||
| `ui.panel({ title, markdown })` | Open the plugin panel. Returns `{ update(content), close(), closed, signal }` |
|
||||
| `ui.openWindow({ html, preload })` | Open a window from the plugin folder (below). Returns the Electron `BrowserWindow` |
|
||||
| `exec(command, args, options)` | Run a program without a shell (Windows `.cmd`/`.bat` shims go through `cmd.exe`). Resolves `{ exitCode, stdout, stderr }` |
|
||||
| `unstable` | SubMiner internals. These change between releases without notice |
|
||||
|
||||
A panel's `signal` aborts when the user closes it or another panel replaces it. Pass it to `exec` to stop work nobody will see. Closing or replacing a panel also cancels pending open requests, including while its window loads. Only one panel is open at a time. Panel markdown supports headings, lists, quotes, code, bold, and italics; HTML is shown as plain text.
|
||||
|
||||
`exec` options are `stdin`, `cwd`, `env`, `timeoutMs`, and `signal`. It resolves for any exit code and rejects when the program can't start, times out, or is aborted.
|
||||
|
||||
`ui.openWindow` takes `html` and an optional `preload`, both relative to the plugin folder, plus `title`, `width`, and `height`. Opening the same `html` again focuses the open window. The page runs with context isolation and no Node access. The preload is sandboxed too: it can `require('electron')` but nothing else, so bundle anything more into it. Expose what the page needs from the preload with `contextBridge`, and handle its messages with `ipcMain` from `require('electron')` in the plugin. Prefix channel names with the plugin id. Plugin windows close when SubMiner quits.
|
||||
|
||||
`media` snapshots are immutable. `playbackId` changes on a new load, including reopening the same path. A title may arrive later with the same id. Disconnecting or ending playback delivers `null`. Use the id to discard stale asynchronous results. Snapshots describe cached playback state; they do not promise that external subtitle discovery has finished.
|
||||
|
||||
`mpv.request` accepts string, number, and boolean arguments, e.g. `await ctx.mpv.request(['set_property', 'pause', true])`. It returns mpv's result data and rejects after 4 seconds. A timeout does not cancel the command in mpv, so a slow command may still complete. `mpv.command` remains available for commands whose result you do not need.
|
||||
|
||||
mpv events: `connection-change`, `subtitle-change`, `subtitle-timing`, `time-pos-change`, `duration-change`, `pause-change`, `fullscreen-change`, `media-path-change`, `media-title-change`, `subtitle-track-change`, `subtitle-track-list-change`, `secondary-subtitle-change`, `secondary-subtitle-track-change`, `secondary-subtitle-delay-change`, `secondary-subtitle-visibility`, `client-message`, `file-loaded`, and `end-file`. `file-loaded` has no payload. `end-file` gives `{ reason, playlistEntryId, error }`, where `reason` is `eof`, `stop`, `quit`, `error`, `redirect`, or `unknown`.
|
||||
|
||||
Anki events: `card-mined` gives `{ noteIds, notes }` once SubMiner has finished filling in a mined card (sentence, audio, image, and field grouping). For YouTube cards whose media waits on the download, it fires once that media is added or the download fails. With `ankiConnect.behavior.autoUpdateNewCards` off, it fires as soon as SubMiner sees the card. If field grouping merged the card into an older one, `noteIds` contains the older card's id.
|
||||
|
||||
Each `notes` entry has `{ originalNoteId, noteId, provenance }`. `originalNoteId` identifies the note before merges; `noteId` is the note that kept its content. `provenance` is `{ minedAt, media, subtitle }`, captured before asynchronous creation or the AnkiConnect proxy's upstream request. `minedAt` is Unix time in milliseconds. `media` uses the snapshot format above, and `subtitle` uses `{ text, startTime, endTime }`. Either may be `null`. Polling cannot establish the original source, so its provenance is `null` rather than the currently playing file.
|
||||
|
||||
`subtitles.current()` resolves parsed cues using the current subtitle delay and returns their times on the subtitle file's timeline.
|
||||
|
||||
Sentence-card provenance also uses the subtitle file's timeline. Multi-line mining converts the history range using the subtitle delay when mining starts; changing the delay between those lines can affect the reported range.
|
||||
|
||||
Several original notes can merge into one kept note. `notes` preserves each source, while `noteIds` contains unique kept ids. Existing listeners using only `noteIds` continue to work. Cards mined from the stats dashboard do not emit this event.
|
||||
|
||||
`anki.invoke` takes `{ timeoutMs }` (default 10 seconds), rejects on an Anki error, and never retries, so an action like `sync` or `addNote` runs at most once.
|
||||
@@ -218,6 +218,14 @@
|
||||
"overlayPosition": "top-right" // Position for in-overlay notification cards. Values: top-left | top | top-right
|
||||
}, // Overlay notification display behavior.
|
||||
|
||||
// ==========================================
|
||||
// Plugins
|
||||
// JavaScript plugins loaded from <config dir>/plugins/<id>/ at startup.
|
||||
// Plugins run inside SubMiner with full access to your system. Only enable code you trust.
|
||||
// Restart SubMiner after changing plugins.
|
||||
// ==========================================
|
||||
"plugins": {}, // Plugins to load at startup, keyed by directory name under <config dir>/plugins/. Each entry is { "enabled": true, "settings": { ... } }; settings are passed to the plugin as ctx.settings.
|
||||
|
||||
// ==========================================
|
||||
// Keyboard Shortcuts
|
||||
// Overlay keyboard shortcuts. Set a shortcut to null to disable.
|
||||
|
||||
@@ -138,6 +138,8 @@ The plugin's `v` replaces mpv's own subtitle visibility toggle. When the overlay
|
||||
}
|
||||
```
|
||||
|
||||
To run a [plugin](/plugins) action, use `["__plugin-action:<plugin id>/<action>"]` as the command.
|
||||
|
||||
Mouse button names are `MBTN_LEFT`, `MBTN_MID`, `MBTN_RIGHT`, `MBTN_BACK`, and `MBTN_FORWARD`. Scroll wheel names are `WHEEL_UP`, `WHEEL_DOWN`, `WHEEL_LEFT`, and `WHEEL_RIGHT`. See [keybindings](/configuration#keybindings) and [shortcuts configuration](/configuration#shortcuts-configuration) in the config reference.
|
||||
|
||||
## Automatic mpv bindings
|
||||
|
||||
@@ -104,6 +104,7 @@ subminer doctor # check dependencies, config, and the mpv soc
|
||||
subminer generate-subs video.mkv # make Japanese subtitles from the audio
|
||||
subminer logs -e # export a log ZIP for bug reports
|
||||
subminer app --setup # reopen first-run setup
|
||||
subminer app --plugin-action <id>/<name> # run a plugin action
|
||||
subminer -u # update SubMiner
|
||||
```
|
||||
|
||||
|
||||
@@ -206,7 +206,7 @@ The same pattern works for n8n or Zapier workflows, Discord notifiers, or append
|
||||
|
||||
## mpv script messages
|
||||
|
||||
SubMiner has no in-app plugin SDK. Besides the streams above, you can drive it from other mpv scripts and from the [launcher CLI](/launcher-script).
|
||||
SubMiner also supports [JavaScript app plugins](/plugins) for playback events, mining events, actions, and custom UI. Besides the streams above, you can drive it from other mpv scripts and from the [launcher CLI](/launcher-script).
|
||||
|
||||
The mpv plugin accepts these script messages:
|
||||
|
||||
|
||||
@@ -37,10 +37,12 @@ Update checks and startup launcher migration share a serialized update-state sto
|
||||
- `subtitle-generation-reference.ts` ranks mpv's loaded text subtitle tracks, excludes signs/songs and forced references, and extracts timing hints with FFmpeg. The overlay and launcher snapshot references only for matching media, including active subtitle delays. Hints guide long-passage cuts with or without VAD; they never limit audio coverage or replace Whisper timestamps.
|
||||
- `src/main/runtime/subtitle-selection.ts` reads and validates mpv subtitle tracks and applies primary/secondary selections. Its opt-in session shortcut opens the shared overlay modal window, with renderer focus and subtitle suppression handled by the modal registry.
|
||||
- `src/shared/session-key-sequences.ts` rejects sequence prefixes reserved by single-key actions. The session-binding compiler reserves configured and built-in overlay keys; `src/main/runtime/session-bindings-runtime.ts` adds active mpv bindings and publishes the effective list to both the plugin artifact and the renderer through `session-bindings:changed`. mpv no-op `ignore` bindings do not reserve prefixes.
|
||||
- `src/core/services/plugins/` owns user plugins: discovery from `<config dir>/plugins/<id>/plugin.json` for ids enabled in `plugins`, the per-plugin `ctx`, guarded callbacks, and `exec` (no shell, AppImage `LD_LIBRARY_PATH` dropped). `main.ts` supplies the host's deps, attaches each new mpv client so plugin listeners survive client replacement, starts plugins from the app-ready path after logging is configured, and unloads them first in the `will-quit` cleanup, before any teardown. Plugins run in the main process with no sandbox. `src/plugin-api.ts` is the standalone public v1 type contract; internal mpv event and session-action types derive from it. Manifests may declare `apiVersion`, which is checked before loading code. Async activation is bounded and actions wait only for their own plugin. The host owns cached media snapshots and playback ids, including repeated loads of the same path. `ctx.signal` aborts as unloading starts; `ctx.onDispose` manages outside resources and late registrations are disposed immediately. Awaitable `ctx.mpv.request` uses the existing request/response transport. Plugin actions are the `runPluginAction` session action (keybinding command `__plugin-action:<id>/<name>`, CLI `--plugin-action <id>/<name>`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `<config dir>/plugin-data/<id>/` as `ctx.dataDir`. `ctx.anki` carries the `card-mined` event with unique kept `noteIds` and per-original-note records. Sentence-card creation snapshots media and subtitle context before asynchronous work; the proxy snapshots before forwarding an upstream request. `AnkiIntegration` keeps provenance under original ids through merges and queued YouTube jobs; polling uses null provenance. The event is fed by `AnkiIntegration.setCardsReadyCallback`: polling, the AnkiConnect proxy, and sentence-card creation report a note once its enrichment finishes (or when they see it, if auto-update is off); `AnkiIntegration` holds a sentence card's report until field grouping finishes, and the pending YouTube media queue reports notes whose media it is still waiting on (directly or through the note field grouping merged them into), which is later than `recordCardsMined` (stats counts at add time). Stats-dashboard mining does not emit it. `ctx.anki.invoke` sends one action to the effective `ankiConnect.url` with no retries. `src/main/runtime/plugin-window-runtime.ts` owns plugin windows (`ctx.ui.openWindow`): one window per plugin + HTML path, raised above the overlay like the settings windows, destroyed on unload. `src/main/runtime/plugin-panel-runtime.ts` owns the single `plugin-panel` modal: a new panel aborts the previous handle's signal, updates broadcast to both overlay windows keyed by `panelId`, and the latest content is re-sent once the renderer acknowledges the open.
|
||||
- `src/renderer/` owns overlay rendering and input behavior.
|
||||
- `src/config/` owns config definitions, defaults, loading, and resolution.
|
||||
- `src/types/` owns shared cross-runtime contracts via domain entrypoints; `src/types.ts` stays a compatibility barrel.
|
||||
- `src/main/runtime/composers/` owns larger domain compositions.
|
||||
- `src/main/assemblies/` owns per-domain assemblies that `src/main.ts` builds once (see [Layering](./layering.md)).
|
||||
- `src/main.ts` call sites invoke configured runtime handlers and runtime-object methods directly;
|
||||
do not add local pass-through wrappers around them.
|
||||
|
||||
|
||||
@@ -19,21 +19,31 @@ Read when: you need to find the owner module for a behavior or test surface
|
||||
- Config system: `src/config/`; Anki resolution is composed by
|
||||
`src/config/resolve/anki-connect.ts` from focused resolvers in
|
||||
`src/config/resolve/anki-connect/`
|
||||
Config hot-reload and the settings window: `src/main/assemblies/settings.ts`
|
||||
- Overlay/window state: `src/core/services/overlay-*`, `src/main/overlay-*.ts`
|
||||
Overlay windows, visibility, and Linux fullscreen handling: `src/main/assemblies/overlay.ts`
|
||||
Overlay-hosted modal openers: `src/main/assemblies/overlay-modals.ts`
|
||||
- MPV runtime and protocol: `src/core/services/mpv*.ts`
|
||||
mpv event wiring, subtitle prefetch, and subtitle sidebar state: `src/main/assemblies/playback.ts`
|
||||
Windows executable lookup and detached process creation are shared in `src/main/runtime/mpv-process.ts`. The Windows launcher and Jellyfin handlers retain their own playback and connection workflows.
|
||||
- Subtitle/token pipeline: `src/core/services/subtitle-*.ts`, `src/core/services/tokenizer*`, `src/core/services/tokenizer/`, `src/subsync/`
|
||||
JLPT and frequency annotation lookups: `src/main/jlpt-runtime.ts`, `src/main/frequency-dictionary-runtime.ts`, assembled by `src/main/assemblies/dictionaries.ts`
|
||||
- First-run setup: `src/main/runtime/first-run-setup-*.ts`, assembled by `src/main/assemblies/first-run-setup.ts`
|
||||
- Anki workflow: `src/anki-integration/`, `src/core/services/anki-jimaku*.ts`
|
||||
- Media timing review: `src/main/runtime/media-timing-review.ts` owns the review and hidden `MediaTimingPreviewSession`. The session waits for mpv readiness and acknowledges playback commands; its `time-pos` observations reach the modal through `media-timing-review:preview-position`. The renderer places the cursor from those timestamps and uses an inactivity timeout instead of timing the clip itself.
|
||||
- Immersion tracking: `src/core/services/immersion-tracker/`
|
||||
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
|
||||
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
|
||||
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
|
||||
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`.
|
||||
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
|
||||
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
|
||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*`, `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`
|
||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`
|
||||
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
|
||||
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`
|
||||
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
|
||||
assembled by `src/main/assemblies/jellyfin.ts`
|
||||
- YouTube playback, subtitles, media cache, and in-app browser: `src/core/services/youtube/`,
|
||||
`src/main/runtime/youtube-*`, assembled by `src/main/assemblies/youtube.ts`
|
||||
- User plugins: `src/core/services/plugins/` (host, `ctx`, `exec`), `src/main/runtime/plugin-panel-runtime.ts` (panel modal), `src/main/runtime/plugin-window-runtime.ts` (plugin windows), `src/renderer/modals/plugin-panel*.ts`; examples in `assets/plugins/`
|
||||
- Window trackers: `src/window-trackers/`
|
||||
- Stats HTTP app: `src/core/services/stats-server.ts`, with route groups and shared route support
|
||||
in `src/core/services/stats-server/`
|
||||
|
||||
@@ -20,7 +20,14 @@ Renderer, launcher, plugin, and stats each keep their own local layering and sho
|
||||
|
||||
- Keep `src/main.ts` thin; wire, do not implement.
|
||||
- Pass deps straight to a handler factory (`createXHandler({...})`). Do not add
|
||||
`*-main-deps.ts` builders that only re-wrap deps; existing ones are being removed.
|
||||
deps builders (`createBuild*MainDepsHandler`, `*-main-deps.ts`) that re-wrap deps.
|
||||
Adaptation logic (defaults, appState getters/setters, shared state) belongs in the
|
||||
handler or in a named adapter that returns the deps directly.
|
||||
- Group a domain's runtimes in one assembly under `src/main/assemblies/` (for example
|
||||
`createYoutubeAssembly(deps)`). It owns the domain's state, takes an explicit deps
|
||||
object, and returns its runtimes; `main.ts` builds it once and calls through the result.
|
||||
Siblings built later in `main.ts` are passed as getters or callbacks, and construction must
|
||||
not call them.
|
||||
- Prefer injecting dependencies from `src/main/` instead of reaching outward from core services.
|
||||
- Keep side effects explicit and close to composition boundaries.
|
||||
- Put reusable business logic in focused services, not in top-level lifecycle files.
|
||||
|
||||
@@ -21,8 +21,8 @@ good test looks like here.
|
||||
|
||||
## Do Not Write
|
||||
|
||||
- Pass-through tests: a builder or handler that only forwards deps (`*-main-deps.ts`,
|
||||
`*-runtime-handlers.ts`) needs no test. TypeScript already checks the shape.
|
||||
- Pass-through tests: a handler or adapter that only forwards deps
|
||||
(`*-runtime-handlers.ts`) needs no test. TypeScript already checks the shape.
|
||||
- Source-text tests: reading `.ts`, `.css`, `.html`, `.lua`, `.swift`, or workflow YAML
|
||||
and asserting with regexes. If the invariant matters, extract the logic and run it
|
||||
(see `src/preload-ipc-listeners.ts`). Policy lints over workflow YAML are the
|
||||
@@ -47,3 +47,7 @@ good test looks like here.
|
||||
- `src/main/main-wiring.test.ts` and `src/renderer/renderer-init-order.test.ts` still
|
||||
regex `main.ts` / `renderer.ts` to guard startup ordering. Replace each test with a
|
||||
behavioral one as the logic moves out of `main.ts` closures.
|
||||
- `src/main/runtime/overlay-geometry-runtime.ts` and
|
||||
`src/main/runtime/visible-overlay-interaction-runtime.ts` value-import Electron, so they
|
||||
cannot load under `bun test` and stay outside `src/main/assemblies/overlay.ts`. Inject
|
||||
`screen`/`dialog` to make them testable and movable.
|
||||
@@ -123,7 +123,8 @@ whenever the behavior does not depend on a specific compositor.
|
||||
per-window screenshots), mpv over its JSON IPC socket, and app commands through the
|
||||
normal CLI handoff (`--mine-sentence`, `--toggle-subtitle-sidebar`, ...).
|
||||
- Scenarios live in `e2e/*.e2e.test.ts` and share one session per file through
|
||||
`startE2eSession()`. Pass `config` to override settings for a scenario file.
|
||||
`startE2eSession()`. Pass `config` to override settings for a scenario file, and `files`
|
||||
to write files such as plugins into the isolated config dir before launch.
|
||||
- On a failed startup the temp dir is kept and its path is in the error. Set
|
||||
`SUBMINER_E2E_KEEP=1` to keep it after any run (`app-stdio.log`, `app.log`, `mpv.log`,
|
||||
`mpv-stdio.log`).
|
||||
|
||||
+39
-21
@@ -28,6 +28,8 @@ type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
|
||||
export type E2eSessionOptions = {
|
||||
/** Deep-merged over the harness config, for scenarios that need other settings. */
|
||||
config?: JsonObject;
|
||||
/** Files written before launch, keyed by path relative to the config dir (e.g. plugins). */
|
||||
files?: Record<string, string>;
|
||||
};
|
||||
|
||||
export type AppTarget = {
|
||||
@@ -57,6 +59,8 @@ export type E2eSession = {
|
||||
mainProcess: () => Promise<CdpPage>;
|
||||
/** Runs a CLI command (e.g. `--mine-sentence`) against the running instance. */
|
||||
runAppCommand: (...args: string[]) => Promise<void>;
|
||||
/** After loading a file: waits for the app's autoplay resume, then leaves mpv paused. */
|
||||
settleAfterResume: () => Promise<void>;
|
||||
dispose: () => Promise<void>;
|
||||
};
|
||||
|
||||
@@ -155,6 +159,30 @@ async function openPage(cdpPort: number, urlPart: string): Promise<CdpPage> {
|
||||
return page;
|
||||
}
|
||||
|
||||
// mpv starts paused and the app resumes each newly loaded file once the overlay
|
||||
// and tokenizer are ready, so that resume marks the file as ready. Scenarios
|
||||
// expect a paused player, and the app retries its resume for a moment, so keep
|
||||
// pausing until the pause has held for longer than that retry window.
|
||||
async function settleAfterResume(mpv: MpvClient): Promise<void> {
|
||||
await waitUntil(async () => (await mpv.command('get_property', 'pause')) === false, {
|
||||
description: 'SubMiner to resume playback once the file is ready',
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
let pausedSince: number | null = null;
|
||||
await waitUntil(
|
||||
async () => {
|
||||
if ((await mpv.command('get_property', 'pause')) !== true) {
|
||||
pausedSince = null;
|
||||
await mpv.command('set_property', 'pause', true);
|
||||
return false;
|
||||
}
|
||||
pausedSince ??= Date.now();
|
||||
return Date.now() - pausedSince >= 1_500;
|
||||
},
|
||||
{ description: 'playback to stay paused after the resume', timeoutMs: 40_000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function startE2eSession(options: E2eSessionOptions = {}): Promise<E2eSession> {
|
||||
if (!fs.existsSync(path.join(repoRoot, 'dist', 'main-entry.js'))) {
|
||||
throw new Error('dist/ is missing. Run `bun run build` before the e2e harness.');
|
||||
@@ -193,6 +221,15 @@ export async function startE2eSession(options: E2eSessionOptions = {}): Promise<
|
||||
|
||||
const config = mergeConfig(buildConfig(mpvSocketPath, anki.url), options.config ?? {});
|
||||
fs.writeFileSync(path.join(userDataDir, 'config.jsonc'), JSON.stringify(config, null, 2));
|
||||
for (const [relativePath, content] of Object.entries(options.files ?? {})) {
|
||||
const filePath = path.resolve(userDataDir, relativePath);
|
||||
const inside = path.relative(userDataDir, filePath);
|
||||
if (!inside || inside.startsWith('..') || path.isAbsolute(inside)) {
|
||||
throw new Error(`E2E file path must stay inside the config dir: ${relativePath}`);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, content);
|
||||
}
|
||||
|
||||
const env: EnvDelta = {
|
||||
set: {
|
||||
@@ -287,27 +324,7 @@ export async function startE2eSession(options: E2eSessionOptions = {}): Promise<
|
||||
teardown.push(mpv.close);
|
||||
|
||||
const app = await launchApp(['--start']);
|
||||
// mpv starts paused and the app resumes it once the overlay and tokenizer
|
||||
// are ready, so that resume marks the end of startup.
|
||||
await waitUntil(async () => (await mpv.command('get_property', 'pause')) === false, {
|
||||
description: 'SubMiner to resume playback after overlay startup',
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
// Hand scenarios a paused player. The app retries its resume for a moment,
|
||||
// so keep pausing until the pause has held for longer than that retry window.
|
||||
let pausedSince: number | null = null;
|
||||
await waitUntil(
|
||||
async () => {
|
||||
if ((await mpv.command('get_property', 'pause')) !== true) {
|
||||
pausedSince = null;
|
||||
await mpv.command('set_property', 'pause', true);
|
||||
return false;
|
||||
}
|
||||
pausedSince ??= Date.now();
|
||||
return Date.now() - pausedSince >= 1_500;
|
||||
},
|
||||
{ description: 'playback to stay paused after startup', timeoutMs: 40_000 },
|
||||
);
|
||||
await settleAfterResume(mpv);
|
||||
const pages: CdpPage[] = [];
|
||||
teardown.push(() => pages.forEach((page) => page.close()));
|
||||
|
||||
@@ -331,6 +348,7 @@ export async function startE2eSession(options: E2eSessionOptions = {}): Promise<
|
||||
return page;
|
||||
},
|
||||
runAppCommand: (...args) => runAppCommand(target, args),
|
||||
settleAfterResume: () => settleAfterResume(mpv),
|
||||
dispose,
|
||||
};
|
||||
} catch (error) {
|
||||
|
||||
@@ -173,6 +173,12 @@ test(
|
||||
const delay = 2;
|
||||
await session.mpv.command('set_property', 'sub-delay', delay);
|
||||
try {
|
||||
// The previous test leaves this cue on screen, so blank the line first; otherwise the wait
|
||||
// below passes before the seek lands and mining can catch mpv's empty mid-seek sub-text.
|
||||
await session.mpv.command('seek', FIXTURE_CUES[0].start / 2, 'absolute+exact');
|
||||
await overlay.waitFor(`document.getElementById('subtitleRoot').textContent === ''`, {
|
||||
description: 'overlay to clear the line before the first delayed cue',
|
||||
});
|
||||
// Past the cue's own end, so the line is only on screen because of the delay.
|
||||
await session.mpv.command('seek', cue.end + delay / 2, 'absolute+exact');
|
||||
await overlay.waitFor(
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import test, { after } from 'node:test';
|
||||
import type { CdpPage } from './harness/cdp';
|
||||
import { FIXTURE_CUES } from './harness/fixtures';
|
||||
import { OVERLAY_PAGE, startE2eSession, type E2eSession } from './harness/session';
|
||||
import { waitUntil } from './harness/wait';
|
||||
|
||||
// Bun caps node:test hooks at 5s whatever their timeout option says, so the
|
||||
// session boots inside whichever test runs first and every test budgets for it.
|
||||
const TEST_TIMEOUT_MS = 120_000;
|
||||
|
||||
// Opens a panel describing the subtitle context and a child process result, and
|
||||
// logs when the panel's signal aborts so the test can see the close reach main.
|
||||
const PROBE_PLUGIN = `
|
||||
const { ipcMain } = require('electron');
|
||||
|
||||
exports.activate = (ctx) => {
|
||||
ipcMain.handle('e2e-probe:info', () => ({ dataDir: ctx.dataDir, greeting: ctx.settings.greeting }));
|
||||
ctx.onDispose(() => ipcMain.removeHandler('e2e-probe:info'));
|
||||
ctx.media.on('change', (media) => ctx.log.info('probe media ' + JSON.stringify(media)));
|
||||
ctx.anki.on('card-mined', ({ notes }) => ctx.log.info('probe mined ' + JSON.stringify(notes)));
|
||||
ctx.actions.register('subtitle', () => ctx.log.info('probe subtitle ' + JSON.stringify(ctx.subtitles.current())));
|
||||
ctx.actions.register('request', async () => {
|
||||
const title = await ctx.mpv.request(['get_property', 'media-title']);
|
||||
ctx.log.info('probe request ' + JSON.stringify(title));
|
||||
try { await ctx.mpv.request(['subminer-no-such-command']); }
|
||||
catch { ctx.log.info('probe request rejected'); }
|
||||
});
|
||||
ctx.actions.register('window', () => {
|
||||
ctx.ui.openWindow({ html: 'ui/index.html', preload: 'preload.js', title: 'E2E Probe Window' });
|
||||
});
|
||||
ctx.mpv.on('end-file', ({ reason }) => ctx.log.info('probe end-file ' + reason));
|
||||
ctx.actions.register('show', () => {
|
||||
const { before, current, after } = ctx.subtitles.context({ before: 1, after: 1 });
|
||||
const panel = ctx.ui.panel({ title: 'Probe', markdown: '_working_' });
|
||||
panel.signal.addEventListener('abort', () => ctx.log.info('probe panel aborted'));
|
||||
ctx
|
||||
.exec(process.execPath, ['-e', 'process.stdout.write("child-ok")'], {
|
||||
env: { ELECTRON_RUN_AS_NODE: '1' },
|
||||
signal: panel.signal,
|
||||
})
|
||||
.then((result) =>
|
||||
panel.update({
|
||||
markdown: [
|
||||
'## ' + ctx.settings.greeting,
|
||||
'',
|
||||
'- before: ' + before.map((line) => line.text).join('|'),
|
||||
'- current: **' + (current ? current.text : '') + '**',
|
||||
'- after: ' + after.map((line) => line.text).join('|'),
|
||||
'- exec: ' + result.stdout,
|
||||
].join('\\n'),
|
||||
}),
|
||||
)
|
||||
.catch((error) => panel.update({ markdown: 'exec failed: ' + error.message }));
|
||||
});
|
||||
};
|
||||
`;
|
||||
|
||||
const PROBE_PRELOAD = `
|
||||
const { contextBridge, ipcRenderer } = require('electron');
|
||||
contextBridge.exposeInMainWorld('probe', { info: () => ipcRenderer.invoke('e2e-probe:info') });
|
||||
`;
|
||||
|
||||
const PROBE_WINDOW_HTML = `<!doctype html>
|
||||
<html>
|
||||
<head><title>E2E Probe Window</title></head>
|
||||
<body>
|
||||
<pre id="out">loading</pre>
|
||||
<script>
|
||||
window.probe.info().then((info) => {
|
||||
document.getElementById('out').textContent = JSON.stringify(info);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
type Started = { session: E2eSession; overlay: CdpPage };
|
||||
let started: Promise<Started> | undefined;
|
||||
|
||||
function useSession(): Promise<Started> {
|
||||
started ??= (async () => {
|
||||
const session = await startE2eSession({
|
||||
config: { plugins: { 'e2e-probe': { enabled: true, settings: { greeting: 'hello' } } } },
|
||||
files: {
|
||||
'plugins/e2e-probe/plugin.json': JSON.stringify({ name: 'E2E Probe', main: 'main.cjs' }),
|
||||
'plugins/e2e-probe/main.cjs': PROBE_PLUGIN,
|
||||
'plugins/e2e-probe/preload.js': PROBE_PRELOAD,
|
||||
'plugins/e2e-probe/ui/index.html': PROBE_WINDOW_HTML,
|
||||
},
|
||||
});
|
||||
try {
|
||||
return { session, overlay: await session.openPage(OVERLAY_PAGE) };
|
||||
} catch (error) {
|
||||
await session.dispose();
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
return started;
|
||||
}
|
||||
|
||||
after(async () => {
|
||||
const running = await started?.catch(() => undefined);
|
||||
await running?.session.dispose();
|
||||
});
|
||||
|
||||
type PanelState = {
|
||||
title: string;
|
||||
heading: string;
|
||||
current: string;
|
||||
items: string[];
|
||||
};
|
||||
|
||||
test(
|
||||
'a plugin action opens the plugin panel with subtitle context and child process output',
|
||||
{ timeout: TEST_TIMEOUT_MS },
|
||||
async () => {
|
||||
const { session, overlay } = await useSession();
|
||||
const [previous, cue, next] = FIXTURE_CUES;
|
||||
await session.mpv.command('seek', cue.at, 'absolute+exact');
|
||||
await overlay.waitFor(
|
||||
`document.getElementById('subtitleRoot').textContent === ${JSON.stringify(cue.text)}`,
|
||||
{ description: `overlay to show "${cue.text}"` },
|
||||
);
|
||||
|
||||
await session.runAppCommand(
|
||||
'--session-action',
|
||||
JSON.stringify({
|
||||
actionId: 'runPluginAction',
|
||||
payload: { pluginActionId: 'e2e-probe/show' },
|
||||
}),
|
||||
);
|
||||
|
||||
const modal = await session.openPage('renderer/index.html?layer=modal');
|
||||
const panel = await modal
|
||||
.waitFor<PanelState | false>(
|
||||
`(() => {
|
||||
const root = document.getElementById('pluginPanelModal');
|
||||
const body = document.getElementById('pluginPanelBody');
|
||||
if (root.classList.contains('hidden') || !/exec[: ]/.test(body.textContent)) return false;
|
||||
return {
|
||||
title: document.getElementById('pluginPanelTitle').textContent,
|
||||
heading: body.querySelector('h4')?.textContent ?? '',
|
||||
current: body.querySelector('strong')?.textContent ?? '',
|
||||
items: Array.from(body.querySelectorAll('li'), (item) => item.textContent),
|
||||
};
|
||||
})()`,
|
||||
{ description: 'plugin panel to show the finished probe result' },
|
||||
)
|
||||
.catch(async (error: unknown) => {
|
||||
const body = await modal.evaluate<string>(
|
||||
`document.getElementById('pluginPanelBody').textContent`,
|
||||
);
|
||||
throw new Error(`Plugin panel body: ${JSON.stringify(body)}`, { cause: error });
|
||||
});
|
||||
|
||||
assert.deepEqual(panel, {
|
||||
title: 'Probe',
|
||||
heading: 'hello',
|
||||
current: cue.text,
|
||||
items: [
|
||||
`before: ${previous.text}`,
|
||||
`current: ${cue.text}`,
|
||||
`after: ${next.text}`,
|
||||
'exec: child-ok',
|
||||
],
|
||||
});
|
||||
|
||||
// Closing hides the modal window (Linux destroys it), often before Chromium
|
||||
// acknowledges the key event, so the send is not awaited. The plugin's log line
|
||||
// proves the close reached main and aborted the handle.
|
||||
void modal
|
||||
.send('Input.dispatchKeyEvent', {
|
||||
type: 'rawKeyDown',
|
||||
key: 'Escape',
|
||||
code: 'Escape',
|
||||
windowsVirtualKeyCode: 27,
|
||||
})
|
||||
.catch(() => {});
|
||||
await waitUntil(
|
||||
() =>
|
||||
fs.readFileSync(path.join(session.root, 'app.log'), 'utf8').includes('probe panel aborted'),
|
||||
{ description: 'closing the panel to abort the plugin handle in main' },
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a CLI plugin action opens a plugin window whose preload talks to the plugin',
|
||||
{ timeout: TEST_TIMEOUT_MS },
|
||||
async () => {
|
||||
const { session } = await useSession();
|
||||
|
||||
await session.runAppCommand('--plugin-action', 'e2e-probe/window');
|
||||
|
||||
const page = await session.openPage('plugins/e2e-probe/ui/index.html');
|
||||
const info = await page.waitFor<{ dataDir: string; greeting: string } | false>(
|
||||
`(() => {
|
||||
const text = document.getElementById('out')?.textContent;
|
||||
return text && text !== 'loading' ? JSON.parse(text) : false;
|
||||
})()`,
|
||||
{ description: 'plugin window to read plugin info over IPC' },
|
||||
);
|
||||
|
||||
assert.equal(info.greeting, 'hello');
|
||||
assert.equal(path.basename(info.dataDir), 'e2e-probe');
|
||||
assert.equal(path.basename(path.dirname(info.dataDir)), 'plugin-data');
|
||||
assert.equal(fs.statSync(info.dataDir).isDirectory(), true);
|
||||
},
|
||||
);
|
||||
|
||||
test('plugins receive mpv end-file events', { timeout: TEST_TIMEOUT_MS }, async () => {
|
||||
const { session } = await useSession();
|
||||
const mediaPath = await session.mpv.command('get_property', 'path');
|
||||
|
||||
// Replacing the playing file ends it with reason "stop".
|
||||
await session.mpv.command('loadfile', String(mediaPath), 'replace');
|
||||
|
||||
await waitUntil(
|
||||
() =>
|
||||
fs.readFileSync(path.join(session.root, 'app.log'), 'utf8').includes('probe end-file stop'),
|
||||
{ description: 'the plugin to log the end-file reason' },
|
||||
);
|
||||
// Later tests need the replacement loaded and paused: a sub-add during the reload lands on
|
||||
// the outgoing file, and the app's autoplay resume would keep cues moving under them.
|
||||
await session.settleAfterResume();
|
||||
});
|
||||
|
||||
test(
|
||||
'plugin subtitle lookup uses the subtitle clock for repeated retimed lines',
|
||||
{ timeout: TEST_TIMEOUT_MS },
|
||||
async () => {
|
||||
const { session, overlay } = await useSession();
|
||||
// Unlike any fixture cue, so the overlay showing it proves main received this line rather
|
||||
// than still displaying one from an earlier test.
|
||||
const text = '今日は猫が好きです。';
|
||||
const subtitlePath = path.join(session.root, 'repeated.srt');
|
||||
fs.writeFileSync(
|
||||
subtitlePath,
|
||||
`1\n00:00:01,000 --> 00:00:03,000\n${text}\n\n2\n00:00:06,000 --> 00:00:08,000\n${text}\n`,
|
||||
);
|
||||
const originalSid = await session.mpv.command('get_property', 'sid');
|
||||
// Runs the probe action and returns the cue it logged on its nth run.
|
||||
const reportSubtitle = async (run: number): Promise<unknown> => {
|
||||
await session.runAppCommand('--plugin-action', 'e2e-probe/subtitle');
|
||||
const line = await waitUntil(
|
||||
() =>
|
||||
fs
|
||||
.readFileSync(path.join(session.root, 'app.log'), 'utf8')
|
||||
.split('\n')
|
||||
.filter((entry) => entry.includes('probe subtitle '))[run - 1],
|
||||
{ description: `the plugin to report its current subtitle (run ${run})` },
|
||||
);
|
||||
assert.ok(line);
|
||||
return JSON.parse(line.slice(line.indexOf('probe subtitle ') + 'probe subtitle '.length));
|
||||
};
|
||||
const seekToCue = async (time: number, cueIndex: number): Promise<void> => {
|
||||
await session.mpv.command('seek', time, 'absolute+exact');
|
||||
// time-pos can activate the sidebar while mpv is still rendering the seek with
|
||||
// sub-text cleared. Wait for the seek, then for main to receive the live text.
|
||||
await waitUntil(
|
||||
async () => (await session.mpv.command('get_property', 'seeking')) === false,
|
||||
{
|
||||
description: `the seek to ${time}s to finish`,
|
||||
},
|
||||
);
|
||||
await overlay.waitFor(
|
||||
`(async () => {
|
||||
const text = await window.electronAPI.getCurrentSubtitleRaw();
|
||||
return text === ${JSON.stringify(text)} &&
|
||||
document.querySelectorAll('#subtitleSidebarList .subtitle-sidebar-item')[${cueIndex}]?.classList.contains('active') === true;
|
||||
})()`,
|
||||
{ description: `delayed cue ${cueIndex + 1} to be active with live subtitle text` },
|
||||
);
|
||||
};
|
||||
try {
|
||||
await session.mpv.command('seek', 0, 'absolute+exact');
|
||||
await session.mpv.command('sub-add', subtitlePath, 'select');
|
||||
await session.mpv.command('set_property', 'sub-delay', 5);
|
||||
await session.runAppCommand('--toggle-subtitle-sidebar');
|
||||
await overlay.waitFor(
|
||||
`document.querySelectorAll('#subtitleSidebarList .subtitle-sidebar-item').length === 2`,
|
||||
{ description: 'the repeated subtitle cues to be parsed' },
|
||||
);
|
||||
await seekToCue(7, 0);
|
||||
assert.deepEqual(await reportSubtitle(1), { text, startTime: 1, endTime: 3 });
|
||||
|
||||
// Same text again at 6-8 on the subtitle clock, so only the timings tell the cues apart.
|
||||
await seekToCue(12, 1);
|
||||
assert.deepEqual(await reportSubtitle(2), { text, startTime: 6, endTime: 8 });
|
||||
} finally {
|
||||
await session.mpv.command('set_property', 'sub-delay', 0);
|
||||
await session.mpv.command('set_property', 'sid', originalSid);
|
||||
await session.runAppCommand('--toggle-subtitle-sidebar');
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'plugin requests report command failures and mined notes carry the captured source',
|
||||
{ timeout: TEST_TIMEOUT_MS },
|
||||
async () => {
|
||||
const { session, overlay } = await useSession();
|
||||
const cue = FIXTURE_CUES[1];
|
||||
await session.mpv.command('seek', cue.at, 'absolute+exact');
|
||||
await overlay.waitFor(
|
||||
`document.getElementById('subtitleRoot').textContent === ${JSON.stringify(cue.text)}`,
|
||||
{ description: 'the mined subtitle to be visible' },
|
||||
);
|
||||
await session.runAppCommand('--plugin-action', 'e2e-probe/request');
|
||||
await waitUntil(
|
||||
() =>
|
||||
fs
|
||||
.readFileSync(path.join(session.root, 'app.log'), 'utf8')
|
||||
.includes('probe request rejected'),
|
||||
{ description: 'mpv to reject an invalid plugin request' },
|
||||
);
|
||||
await session.runAppCommand('--mine-sentence');
|
||||
const log = await waitUntil(
|
||||
() => {
|
||||
const text = fs.readFileSync(path.join(session.root, 'app.log'), 'utf8');
|
||||
return text.includes('probe mined ') ? text : null;
|
||||
},
|
||||
{ description: 'the mining event to reach the plugin' },
|
||||
);
|
||||
assert.ok(log);
|
||||
const line = log.split('\n').find((entry) => entry.includes('probe mined '));
|
||||
assert.ok(line);
|
||||
const notes: unknown = JSON.parse(
|
||||
line.slice(line.indexOf('probe mined ') + 'probe mined '.length),
|
||||
);
|
||||
assert.ok(Array.isArray(notes));
|
||||
assert.equal(notes.length, 1);
|
||||
const note: unknown = notes[0];
|
||||
assert.partialDeepStrictEqual(note, {
|
||||
provenance: {
|
||||
subtitle: { text: cue.text },
|
||||
media: { path: await session.mpv.command('get_property', 'path') },
|
||||
},
|
||||
});
|
||||
assert.ok(note && typeof note === 'object' && 'originalNoteId' in note && 'noteId' in note);
|
||||
assert.equal(note.originalNoteId, note.noteId);
|
||||
},
|
||||
);
|
||||
@@ -6,6 +6,7 @@ import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { AnkiIntegration } from './anki-integration';
|
||||
import type { PluginMinedNote, PluginMiningProvenance } from './plugin-api';
|
||||
import type { MediaInput } from './media-input';
|
||||
import { AnkiConnectConfig } from './types';
|
||||
|
||||
@@ -82,6 +83,8 @@ type IntegrationInternals = {
|
||||
fields: Record<string, { value: string }>;
|
||||
}) => void;
|
||||
rememberMergedNoteIds: (deletedNoteId: number, keptNoteId: number) => void;
|
||||
reportCardsReady: (noteIds: number[]) => void;
|
||||
rememberMiningProvenance: (noteIds: number[], provenance: PluginMiningProvenance | null) => void;
|
||||
};
|
||||
|
||||
/** Named stand-ins for AnkiIntegration's long positional constructor arguments. */
|
||||
@@ -273,6 +276,44 @@ test('AnkiIntegration resolves merged-away note ids to the kept note id', () =>
|
||||
assert.equal(integration.resolveCurrentNoteId(444), 444);
|
||||
});
|
||||
|
||||
test('AnkiIntegration reports ready cards under the note that kept them after a merge', () => {
|
||||
const integration = createIntegration({});
|
||||
const ready: number[][] = [];
|
||||
integration.setCardsReadyCallback((noteIds) => ready.push(noteIds));
|
||||
const internals = internalsOf(integration);
|
||||
internals.rememberMergedNoteIds(111, 222);
|
||||
|
||||
internals.reportCardsReady([111, 222, 444]);
|
||||
|
||||
assert.deepEqual(ready, [[222, 444]]);
|
||||
});
|
||||
|
||||
test('ready events preserve each mining source when multiple notes merge into an older note', () => {
|
||||
const integration = createIntegration({});
|
||||
const ready: PluginMinedNote[][] = [];
|
||||
integration.setCardsReadyCallback((_ids, notes) => ready.push(notes));
|
||||
const internals = internalsOf(integration);
|
||||
const provenance = {
|
||||
minedAt: 1234,
|
||||
media: { playbackId: 1, path: 'Show - 02.mkv', title: null },
|
||||
subtitle: { text: 'テスト', startTime: 1, endTime: 2 },
|
||||
};
|
||||
internals.rememberMiningProvenance([111, 222], provenance);
|
||||
provenance.media.path = 'Show - 03.mkv';
|
||||
internals.rememberMergedNoteIds(111, 7);
|
||||
internals.rememberMergedNoteIds(222, 7);
|
||||
internals.reportCardsReady([111, 222]);
|
||||
assert.deepEqual(
|
||||
ready[0]?.map((note) => [note.originalNoteId, note.noteId, note.provenance?.media?.path]),
|
||||
[
|
||||
[111, 7, 'Show - 02.mkv'],
|
||||
[222, 7, 'Show - 02.mkv'],
|
||||
],
|
||||
);
|
||||
internals.reportCardsReady([333]);
|
||||
assert.equal(ready[1]?.[0]?.provenance, null);
|
||||
});
|
||||
|
||||
// --- Sentence highlighting --------------------------------------------------
|
||||
|
||||
const MPV_SENTENCE = '先日 貴様らが潜入した キールダンジョンから―';
|
||||
@@ -404,6 +445,57 @@ test('AnkiIntegration triggers field grouping after a local duplicate sentence c
|
||||
assert.equal(groupingTriggered, 1);
|
||||
});
|
||||
|
||||
test('AnkiIntegration reports a new sentence card ready only after field grouping', async () => {
|
||||
const integration = createIntegration({
|
||||
isKiku: { enabled: true, fieldGrouping: 'manual' },
|
||||
});
|
||||
const events: string[] = [];
|
||||
integration.setCardsReadyCallback((noteIds) => events.push(`ready ${noteIds.join(',')}`));
|
||||
const internals = internalsOf(integration);
|
||||
internals.cardCreationService = {
|
||||
createSentenceCard: async () => {
|
||||
integration.trackDuplicateNoteIdsForNote(42, [7]);
|
||||
internals.reportCardsReady([42]);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
internals.fieldGroupingService = {
|
||||
triggerFieldGroupingForLastAddedCard: async () => {
|
||||
events.push('group');
|
||||
},
|
||||
};
|
||||
|
||||
assert.equal(await integration.createSentenceCard('duplicate sentence', 0, 1), true);
|
||||
assert.deepEqual(events, ['group', 'ready 42']);
|
||||
});
|
||||
|
||||
test('AnkiIntegration reports a card with queued YouTube media ready once the media lands', async () => {
|
||||
const events: string[] = [];
|
||||
const integration = createIntegration({
|
||||
fields: { audio: 'ExpressionAudio', image: 'Picture' },
|
||||
media: { imageFormat: 'jpg' },
|
||||
behavior: { notificationType: 'osd' },
|
||||
});
|
||||
installFakeAnki(integration, {
|
||||
noteFieldNames: ['ExpressionAudio', 'Picture'],
|
||||
mediaGenerator: {
|
||||
generateAudio: async () => Buffer.from('audio'),
|
||||
generateScreenshot: async () => Buffer.from('image'),
|
||||
},
|
||||
});
|
||||
integration.setCardsReadyCallback((noteIds) => events.push(`ready ${noteIds.join(',')}`));
|
||||
const internals = internalsOf(integration);
|
||||
internals.queuePendingYoutubeMediaUpdate(youtubeJob({ noteId: 101 }));
|
||||
// Note 7 was merged into 101, so it waits on 101's media too.
|
||||
internals.rememberMergedNoteIds(7, 101);
|
||||
|
||||
internals.reportCardsReady([101, 7, 5]);
|
||||
assert.deepEqual(events, ['ready 5']);
|
||||
|
||||
await integration.handleYoutubeMediaCacheReady('https://youtu.be/abc123', '/tmp/media.mkv');
|
||||
assert.deepEqual(events, ['ready 5', 'ready 101']);
|
||||
});
|
||||
|
||||
test('AnkiIntegration marks partial update notifications as failures in OSD mode', async () => {
|
||||
const osdMessages: string[] = [];
|
||||
const integration = createIntegration(
|
||||
|
||||
+128
-17
@@ -17,6 +17,7 @@
|
||||
*/
|
||||
|
||||
import { AnkiConnectClient } from './anki-connect';
|
||||
import type { PluginMinedNote, PluginMiningProvenance } from './plugin-api';
|
||||
import { SubtitleTimingTracker } from './subtitle-timing-tracker';
|
||||
import { MediaGenerator } from './media-generator';
|
||||
import path from 'path';
|
||||
@@ -241,6 +242,11 @@ export class AnkiIntegration {
|
||||
private runtime: AnkiIntegrationRuntime;
|
||||
private aiConfig: AiConfig;
|
||||
private recordCardsMinedCallback: ((count: number, noteIds?: number[]) => void) | null = null;
|
||||
private cardsReadyCallback: ((noteIds: number[], notes: PluginMinedNote[]) => void) | null = null;
|
||||
private miningProvenanceProvider: (() => PluginMiningProvenance | null) | null = null;
|
||||
private miningProvenance = new Map<number, PluginMiningProvenance | null>();
|
||||
// Ready reports collected while createSentenceCard still has field grouping to run.
|
||||
private heldReadyNoteIds: number[] | null = null;
|
||||
private knownWordCacheUpdatedCallback: (() => void) | null = null;
|
||||
private consumeSubtitleMiningContextCallback: (() => SubtitleMiningContext | null) | null = null;
|
||||
private generateSentenceFuriganaCallback:
|
||||
@@ -337,6 +343,74 @@ export class AnkiIntegration {
|
||||
}
|
||||
}
|
||||
|
||||
private reportCardsReady(noteIds: number[]): void {
|
||||
if (this.heldReadyNoteIds) {
|
||||
this.heldReadyNoteIds.push(...noteIds);
|
||||
return;
|
||||
}
|
||||
// Notes still waiting on queued YouTube media, directly or through the note they were
|
||||
// merged into, are reported by the queue once it settles.
|
||||
const queue = this.pendingYoutubeMediaQueue;
|
||||
this.emitCardsReady(
|
||||
noteIds.filter(
|
||||
(noteId) =>
|
||||
!queue.hasPendingNote(noteId) && !queue.hasPendingNote(this.resolveCurrentNoteId(noteId)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private emitCardsReady(noteIds: number[]): void {
|
||||
if (noteIds.length === 0) return;
|
||||
// Field grouping may have merged a note away; report the note that kept its content.
|
||||
const currentNoteIds = [...new Set(noteIds.map((noteId) => this.resolveCurrentNoteId(noteId)))];
|
||||
const notes: PluginMinedNote[] = [];
|
||||
for (const [originalNoteId, provenance] of this.miningProvenance) {
|
||||
const noteId = this.resolveCurrentNoteId(originalNoteId);
|
||||
if (
|
||||
!currentNoteIds.includes(noteId) ||
|
||||
this.pendingYoutubeMediaQueue.hasPendingNote(originalNoteId) ||
|
||||
this.pendingYoutubeMediaQueue.hasPendingNote(noteId)
|
||||
)
|
||||
continue;
|
||||
notes.push({ originalNoteId, noteId, provenance });
|
||||
this.miningProvenance.delete(originalNoteId);
|
||||
}
|
||||
for (const originalNoteId of noteIds) {
|
||||
const noteId = this.resolveCurrentNoteId(originalNoteId);
|
||||
if (
|
||||
!notes.some((note) => note.noteId === noteId) &&
|
||||
![...this.miningProvenance.keys()].some((id) => this.resolveCurrentNoteId(id) === noteId)
|
||||
) {
|
||||
notes.push({ originalNoteId, noteId, provenance: null });
|
||||
}
|
||||
}
|
||||
if (notes.length === 0) return;
|
||||
try {
|
||||
this.cardsReadyCallback?.([...new Set(notes.map((note) => note.noteId))], notes);
|
||||
} catch (error) {
|
||||
log.warn('cardsReady callback failed:', (error as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
private rememberMiningProvenance(
|
||||
noteIds: number[],
|
||||
provenance: PluginMiningProvenance | null,
|
||||
): void {
|
||||
for (const noteId of noteIds) {
|
||||
if (!this.miningProvenance.get(noteId)) {
|
||||
this.miningProvenance.set(
|
||||
noteId,
|
||||
provenance &&
|
||||
Object.freeze({
|
||||
...provenance,
|
||||
media: provenance.media && Object.freeze({ ...provenance.media }),
|
||||
subtitle: provenance.subtitle && Object.freeze({ ...provenance.subtitle }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getMediaResolverOptions(): MediaGenerationInputResolverOptions {
|
||||
const options: MediaGenerationInputResolverOptions = {
|
||||
logDebug: (message) => log.debug(message),
|
||||
@@ -415,6 +489,7 @@ export class AnkiIntegration {
|
||||
showStatusNotification: (message) => this.showStatusNotification(message),
|
||||
showNotification: (noteId, label, errorSuffix) =>
|
||||
this.showNotification(noteId, label, errorSuffix),
|
||||
onUpdateSettled: (noteId) => this.reportCardsReady([noteId]),
|
||||
logInfo: (...args) => log.info(args[0] as string, ...args.slice(1)),
|
||||
logWarn: (...args) => log.warn(args[0] as string, ...args.slice(1)),
|
||||
logError: (...args) => log.error(args[0] as string, ...args.slice(1)),
|
||||
@@ -445,6 +520,10 @@ export class AnkiIntegration {
|
||||
recordCardsAdded: (count, noteIds) => {
|
||||
this.recordCardsMinedSafely(count, noteIds, 'polling');
|
||||
},
|
||||
onCardsReady: (noteIds) => {
|
||||
this.rememberMiningProvenance(noteIds, null);
|
||||
this.reportCardsReady(noteIds);
|
||||
},
|
||||
isUpdateInProgress: () => this.updateInProgress,
|
||||
setUpdateInProgress: (value) => {
|
||||
this.updateInProgress = value;
|
||||
@@ -464,11 +543,14 @@ export class AnkiIntegration {
|
||||
const { AnkiConnectProxyServer } =
|
||||
require('./anki-integration/anki-connect-proxy') as typeof import('./anki-integration/anki-connect-proxy');
|
||||
return new AnkiConnectProxyServer({
|
||||
captureMiningProvenance: () => this.miningProvenanceProvider?.() ?? null,
|
||||
onNotesAdded: (noteIds, provenance) => this.rememberMiningProvenance(noteIds, provenance),
|
||||
shouldAutoUpdateNewCards: () => this.config.behavior?.autoUpdateNewCards !== false,
|
||||
processNewCard: (noteId: number) => this.processNewCard(noteId),
|
||||
recordCardsAdded: (count, noteIds) => {
|
||||
this.recordCardsMinedSafely(count, noteIds, 'proxy');
|
||||
},
|
||||
onCardsReady: (noteIds) => this.reportCardsReady(noteIds),
|
||||
trackAddedDuplicateNoteIds: (noteId, duplicateNoteIds) => {
|
||||
this.trackDuplicateNoteIdsForNote(noteId, duplicateNoteIds);
|
||||
},
|
||||
@@ -594,6 +676,9 @@ export class AnkiIntegration {
|
||||
recordCardsMinedCallback: (count, noteIds) => {
|
||||
this.recordCardsMinedSafely(count, noteIds, 'card creation');
|
||||
},
|
||||
captureMiningProvenance: () => this.miningProvenanceProvider?.() ?? null,
|
||||
onNoteCreated: (noteId, provenance) => this.rememberMiningProvenance([noteId], provenance),
|
||||
onCardsReady: (noteIds) => this.reportCardsReady(noteIds),
|
||||
reviewMediaTiming: (request) => this.reviewMediaTiming(request),
|
||||
});
|
||||
}
|
||||
@@ -1544,25 +1629,36 @@ export class AnkiIntegration {
|
||||
secondarySubText?: string,
|
||||
): Promise<boolean> {
|
||||
const trackedDuplicateNoteIdsBeforeCreate = new Set(this.trackedDuplicateNoteIds.keys());
|
||||
const created = await this.cardCreationService.createSentenceCard(
|
||||
sentence,
|
||||
startTime,
|
||||
endTime,
|
||||
secondarySubText,
|
||||
);
|
||||
if (
|
||||
created &&
|
||||
this.shouldTriggerFieldGroupingAfterLocalSentenceCardCreate(
|
||||
trackedDuplicateNoteIdsBeforeCreate,
|
||||
)
|
||||
) {
|
||||
try {
|
||||
await this.fieldGroupingService.triggerFieldGroupingForLastAddedCard();
|
||||
} catch (error) {
|
||||
log.warn('Failed to trigger field grouping after sentence card creation:', error);
|
||||
// Field grouping below can still rewrite the new card, so hold its ready report until then.
|
||||
const ownsHold = this.heldReadyNoteIds === null;
|
||||
if (ownsHold) this.heldReadyNoteIds = [];
|
||||
try {
|
||||
const created = await this.cardCreationService.createSentenceCard(
|
||||
sentence,
|
||||
startTime,
|
||||
endTime,
|
||||
secondarySubText,
|
||||
);
|
||||
if (
|
||||
created &&
|
||||
this.shouldTriggerFieldGroupingAfterLocalSentenceCardCreate(
|
||||
trackedDuplicateNoteIdsBeforeCreate,
|
||||
)
|
||||
) {
|
||||
try {
|
||||
await this.fieldGroupingService.triggerFieldGroupingForLastAddedCard();
|
||||
} catch (error) {
|
||||
log.warn('Failed to trigger field grouping after sentence card creation:', error);
|
||||
}
|
||||
}
|
||||
return created;
|
||||
} finally {
|
||||
if (ownsHold) {
|
||||
const held = this.heldReadyNoteIds ?? [];
|
||||
this.heldReadyNoteIds = null;
|
||||
this.reportCardsReady(held);
|
||||
}
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
trackDuplicateNoteIdsForNote(noteId: number, duplicateNoteIds: number[]): void {
|
||||
@@ -1781,6 +1877,21 @@ export class AnkiIntegration {
|
||||
this.recordCardsMinedCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called once SubMiner has finished writing a mined card (fields, media including queued YouTube
|
||||
* media, and field grouping), or as soon as polling or the proxy sees it when auto-update is off.
|
||||
* Ids merged away by field grouping are reported as the note that kept them.
|
||||
*/
|
||||
setCardsReadyCallback(
|
||||
callback: ((noteIds: number[], notes: PluginMinedNote[]) => void) | null,
|
||||
): void {
|
||||
this.cardsReadyCallback = callback;
|
||||
}
|
||||
|
||||
setMiningProvenanceProvider(provider: (() => PluginMiningProvenance | null) | null): void {
|
||||
this.miningProvenanceProvider = provider;
|
||||
}
|
||||
|
||||
setKnownWordCacheUpdatedCallback(callback: (() => void) | null): void {
|
||||
this.knownWordCacheUpdatedCallback = callback;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import http from 'node:http';
|
||||
import { once } from 'node:events';
|
||||
import test from 'node:test';
|
||||
import { AnkiConnectProxyServer } from './anki-connect-proxy';
|
||||
import type { PluginMiningProvenance } from '../plugin-api';
|
||||
|
||||
async function waitForCondition(
|
||||
condition: () => boolean,
|
||||
@@ -17,17 +18,23 @@ async function waitForCondition(
|
||||
throw new Error('Timed out waiting for condition');
|
||||
}
|
||||
|
||||
test('proxy enqueues addNote result for enrichment', async () => {
|
||||
test('proxy enqueues addNote result for enrichment and reports it ready afterwards', async () => {
|
||||
const processed: number[] = [];
|
||||
const recordedCards: number[] = [];
|
||||
const events: string[] = [];
|
||||
const proxy = new AnkiConnectProxyServer({
|
||||
shouldAutoUpdateNewCards: () => true,
|
||||
processNewCard: async (noteId) => {
|
||||
processed.push(noteId);
|
||||
events.push(`process ${noteId}`);
|
||||
throw new Error('enrichment failed');
|
||||
},
|
||||
recordCardsAdded: (count) => {
|
||||
recordedCards.push(count);
|
||||
},
|
||||
onCardsReady: (noteIds) => {
|
||||
events.push(`ready ${noteIds.join(',')}`);
|
||||
},
|
||||
logInfo: () => undefined,
|
||||
logWarn: () => undefined,
|
||||
logError: () => undefined,
|
||||
@@ -42,9 +49,44 @@ test('proxy enqueues addNote result for enrichment', async () => {
|
||||
Buffer.from(JSON.stringify({ result: 42, error: null }), 'utf8'),
|
||||
);
|
||||
|
||||
await waitForCondition(() => processed.length === 1);
|
||||
await waitForCondition(() => events.length === 2);
|
||||
assert.deepEqual(processed, [42]);
|
||||
assert.deepEqual(recordedCards, [1]);
|
||||
assert.deepEqual(events, ['process 42', 'ready 42']);
|
||||
});
|
||||
|
||||
test('proxy reports an added note ready right away when auto-update is off', () => {
|
||||
const processed: number[] = [];
|
||||
const recordedCards: number[] = [];
|
||||
const ready: number[][] = [];
|
||||
const proxy = new AnkiConnectProxyServer({
|
||||
shouldAutoUpdateNewCards: () => false,
|
||||
processNewCard: async (noteId) => {
|
||||
processed.push(noteId);
|
||||
},
|
||||
recordCardsAdded: (count) => {
|
||||
recordedCards.push(count);
|
||||
},
|
||||
onCardsReady: (noteIds) => {
|
||||
ready.push(noteIds);
|
||||
},
|
||||
logInfo: () => undefined,
|
||||
logWarn: () => undefined,
|
||||
logError: () => undefined,
|
||||
});
|
||||
|
||||
(
|
||||
proxy as unknown as {
|
||||
maybeEnqueueFromRequest: (request: Record<string, unknown>, responseBody: Buffer) => void;
|
||||
}
|
||||
).maybeEnqueueFromRequest(
|
||||
{ action: 'addNote' },
|
||||
Buffer.from(JSON.stringify({ result: 42, error: null }), 'utf8'),
|
||||
);
|
||||
|
||||
assert.deepEqual(ready, [[42]]);
|
||||
assert.deepEqual(processed, []);
|
||||
assert.deepEqual(recordedCards, []);
|
||||
});
|
||||
|
||||
test('proxy enqueues addNote bare numeric response for enrichment', async () => {
|
||||
@@ -360,8 +402,11 @@ test('proxy tracks duplicate note ids from addNote request metadata before enric
|
||||
assert.deepEqual(processed, [42]);
|
||||
});
|
||||
|
||||
test('proxy strips SubMiner duplicate metadata before forwarding upstream addNote request', async () => {
|
||||
test('proxy strips duplicate metadata and captures mining provenance before the upstream request', async () => {
|
||||
let upstreamBody = '';
|
||||
let mediaPath = 'Show - 02.mkv';
|
||||
let captureCount = 0;
|
||||
const sources: Array<PluginMiningProvenance | null> = [];
|
||||
const upstream = http.createServer(async (req, res) => {
|
||||
upstreamBody = await new Promise<string>((resolve) => {
|
||||
const chunks: Buffer[] = [];
|
||||
@@ -369,6 +414,7 @@ test('proxy strips SubMiner duplicate metadata before forwarding upstream addNot
|
||||
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||
});
|
||||
res.statusCode = 200;
|
||||
mediaPath = 'Show - 03.mkv';
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({ result: 42, error: null }));
|
||||
});
|
||||
@@ -380,6 +426,15 @@ test('proxy strips SubMiner duplicate metadata before forwarding upstream addNot
|
||||
|
||||
const tracked: Array<{ noteId: number; duplicateNoteIds: number[] }> = [];
|
||||
const proxy = new AnkiConnectProxyServer({
|
||||
captureMiningProvenance: () => {
|
||||
captureCount++;
|
||||
return {
|
||||
minedAt: 1234,
|
||||
media: { playbackId: 1, path: mediaPath, title: null },
|
||||
subtitle: null,
|
||||
};
|
||||
},
|
||||
onNotesAdded: (_ids, provenance) => sources.push(provenance),
|
||||
shouldAutoUpdateNewCards: () => true,
|
||||
processNewCard: async () => undefined,
|
||||
trackAddedDuplicateNoteIds: (noteId, duplicateNoteIds) => {
|
||||
@@ -434,6 +489,16 @@ test('proxy strips SubMiner duplicate metadata before forwarding upstream addNot
|
||||
await waitForCondition(() => tracked.length === 1);
|
||||
assert.equal(upstreamBody.includes('subminerDuplicateNoteIds'), false);
|
||||
assert.deepEqual(tracked, [{ noteId: 42, duplicateNoteIds: [7, 18] }]);
|
||||
assert.equal(sources[0]?.media?.path, 'Show - 02.mkv');
|
||||
assert.equal(captureCount, 1);
|
||||
const preflight = await fetch(`http://127.0.0.1:${proxyPort}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'canAddNotes', version: 6, params: { notes: [] } }),
|
||||
});
|
||||
assert.equal(preflight.status, 200);
|
||||
await preflight.json();
|
||||
assert.equal(captureCount, 1);
|
||||
} finally {
|
||||
proxy.stop();
|
||||
upstream.close();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import http, { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import type { PluginMiningProvenance } from '../plugin-api';
|
||||
|
||||
interface StartProxyOptions {
|
||||
host: string;
|
||||
@@ -13,9 +14,13 @@ interface AnkiConnectEnvelope {
|
||||
}
|
||||
|
||||
export interface AnkiConnectProxyServerDeps {
|
||||
captureMiningProvenance?: () => PluginMiningProvenance | null;
|
||||
onNotesAdded?: (noteIds: number[], provenance: PluginMiningProvenance | null) => void;
|
||||
shouldAutoUpdateNewCards: () => boolean;
|
||||
processNewCard: (noteId: number) => Promise<void>;
|
||||
recordCardsAdded?: (count: number, noteIds: number[]) => void;
|
||||
/** Called once SubMiner is done with an added note: after enrichment, or right away when it is off. */
|
||||
onCardsReady?: (noteIds: number[]) => void;
|
||||
trackAddedDuplicateNoteIds?: (noteId: number, duplicateNoteIds: number[]) => void;
|
||||
getDeck?: () => string | undefined;
|
||||
findNotes?: (
|
||||
@@ -186,6 +191,12 @@ export class AnkiConnectProxyServer {
|
||||
typeof req.headers['content-type'] === 'string'
|
||||
? req.headers['content-type']
|
||||
: 'application/json';
|
||||
const action = requestJson?.action;
|
||||
const provenance =
|
||||
typeof action === 'string' &&
|
||||
['addNote', 'addNotes', 'multi', 'updateNoteFields'].includes(action)
|
||||
? (this.deps.captureMiningProvenance?.() ?? null)
|
||||
: null;
|
||||
const upstreamResponse = await this.client.request<ArrayBuffer>({
|
||||
url: targetUrl,
|
||||
method: req.method,
|
||||
@@ -203,7 +214,7 @@ export class AnkiConnectProxyServer {
|
||||
res.end(responseBody);
|
||||
|
||||
if (req.method === 'POST') {
|
||||
this.maybeEnqueueFromRequest(requestJson, responseBody);
|
||||
this.maybeEnqueueFromRequest(requestJson, responseBody, provenance);
|
||||
}
|
||||
} catch (error) {
|
||||
this.deps.logWarn('[anki-proxy] Failed to forward request:', (error as Error).message);
|
||||
@@ -215,16 +226,19 @@ export class AnkiConnectProxyServer {
|
||||
private maybeEnqueueFromRequest(
|
||||
requestJson: Record<string, unknown> | null,
|
||||
responseBody: Buffer,
|
||||
provenance: PluginMiningProvenance | null = null,
|
||||
): void {
|
||||
if (!requestJson || !this.deps.shouldAutoUpdateNewCards()) {
|
||||
if (!requestJson) {
|
||||
return;
|
||||
}
|
||||
const autoUpdate = this.deps.shouldAutoUpdateNewCards();
|
||||
|
||||
const action =
|
||||
typeof requestJson.action === 'string'
|
||||
? requestJson.action
|
||||
: String(requestJson.action ?? '');
|
||||
if (action === 'updateNoteFields') {
|
||||
if (!autoUpdate) return;
|
||||
const params = requestJson.params;
|
||||
if (
|
||||
!params ||
|
||||
@@ -246,6 +260,7 @@ export class AnkiConnectProxyServer {
|
||||
response.result !== null
|
||||
)
|
||||
return;
|
||||
this.deps.onNotesAdded?.(this.collectSingleResultId(note.id), provenance);
|
||||
this.enqueueNotes(this.collectSingleResultId(note.id), false);
|
||||
return;
|
||||
}
|
||||
@@ -277,9 +292,16 @@ export class AnkiConnectProxyServer {
|
||||
params.subminerEnrich === false
|
||||
) {
|
||||
// Stats owns the saved sentence and media; the live mpv context is unrelated.
|
||||
if (noteIds.length > 0) this.deps.recordCardsAdded?.(noteIds.length, noteIds);
|
||||
if (autoUpdate && noteIds.length > 0) this.deps.recordCardsAdded?.(noteIds.length, noteIds);
|
||||
return;
|
||||
}
|
||||
if (!autoUpdate) {
|
||||
// Nothing to enrich, so the added notes are already in their final state.
|
||||
this.deps.onNotesAdded?.(noteIds, provenance);
|
||||
if (noteIds.length > 0) this.deps.onCardsReady?.(noteIds);
|
||||
return;
|
||||
}
|
||||
this.deps.onNotesAdded?.(noteIds, provenance);
|
||||
this.maybeTrackDuplicateNoteIds(requestJson, action, responseResult);
|
||||
if (noteIds.length === 0 && shouldFallbackToLatestAdded) {
|
||||
void this.enqueueMostRecentAddedNote();
|
||||
@@ -534,6 +556,7 @@ export class AnkiConnectProxyServer {
|
||||
this.pendingNoteIdSet.delete(noteId);
|
||||
|
||||
if (!this.deps.shouldAutoUpdateNewCards()) {
|
||||
this.deps.onCardsReady?.([noteId]);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -547,6 +570,7 @@ export class AnkiConnectProxyServer {
|
||||
);
|
||||
} finally {
|
||||
this.inFlightNoteIds.delete(noteId);
|
||||
this.deps.onCardsReady?.([noteId]);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -11,12 +11,37 @@ import {
|
||||
} from './card-creation-test-utils';
|
||||
import { toMpvEdlValue } from './mpv-edl-test-utils';
|
||||
import type { MediaInput } from '../media-generator';
|
||||
import type { PluginMiningProvenance } from '../plugin-api';
|
||||
|
||||
const YOUTUBE_URL = 'https://www.youtube.com/watch?v=abc123';
|
||||
|
||||
const mediaInputPath = (mediaInput: MediaInput): string =>
|
||||
typeof mediaInput === 'string' ? mediaInput : mediaInput.path;
|
||||
|
||||
test('sentence provenance is captured before asynchronous creation and uses the mined line', async () => {
|
||||
let currentPath = 'Show - 02.mkv';
|
||||
const captured: Array<PluginMiningProvenance | null> = [];
|
||||
const service = new CardCreationService(
|
||||
createCardCreationDeps({
|
||||
captureMiningProvenance: () => ({
|
||||
minedAt: 1234,
|
||||
media: { playbackId: 1, path: currentPath, title: null },
|
||||
subtitle: null,
|
||||
}),
|
||||
client: createFakeClient({
|
||||
addNote: async () => {
|
||||
currentPath = 'Show - 03.mkv';
|
||||
return 42;
|
||||
},
|
||||
}),
|
||||
onNoteCreated: (_noteId, provenance) => captured.push(provenance),
|
||||
}),
|
||||
);
|
||||
assert.equal(await service.createSentenceCard('テスト', 1, 2), true);
|
||||
assert.equal(captured[0]?.media?.path, 'Show - 02.mkv');
|
||||
assert.deepEqual(captured[0]?.subtitle, { text: 'テスト', startTime: 1, endTime: 2 });
|
||||
});
|
||||
|
||||
test('CardCreationService counts locally created sentence cards', async () => {
|
||||
const minedCards: Array<{ count: number; noteIds?: number[] }> = [];
|
||||
const service = new CardCreationService(
|
||||
@@ -31,6 +56,58 @@ test('CardCreationService counts locally created sentence cards', async () => {
|
||||
assert.deepEqual(minedCards, [{ count: 1, noteIds: [42] }]);
|
||||
});
|
||||
|
||||
for (const delay of [5, -5]) {
|
||||
test(`sentence provenance stays on the subtitle clock with delay ${delay}`, async () => {
|
||||
let captured: PluginMiningProvenance | null = null;
|
||||
const audioRanges: number[][] = [];
|
||||
const defaults = createCardCreationDeps();
|
||||
const service = new CardCreationService(
|
||||
createCardCreationDeps({
|
||||
getConfig: () => createAnkiConfig({ media: { generateAudio: true } }),
|
||||
getMpvClient: () => ({ ...defaults.getMpvClient()!, currentSubDelay: delay }),
|
||||
captureMiningProvenance: () => ({ minedAt: 1234, media: null, subtitle: null }),
|
||||
onNoteCreated: (_id, provenance) => {
|
||||
captured = provenance;
|
||||
},
|
||||
mediaGenerator: createFakeMediaGenerator({
|
||||
generateAudio: async (_path, start, end) => {
|
||||
audioRanges.push([start, end]);
|
||||
return Buffer.from('audio');
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
assert.equal(await service.createSentenceCard('first\nsecond', 10 + delay, 12 + delay), true);
|
||||
assert.partialDeepStrictEqual(captured, {
|
||||
subtitle: { text: 'first\nsecond', startTime: 10, endTime: 12 },
|
||||
});
|
||||
assert.deepEqual(audioRanges, [[10 + delay, 12 + delay]]);
|
||||
});
|
||||
}
|
||||
|
||||
test('CardCreationService reports a created card ready after its fields are written', async () => {
|
||||
const events: string[] = [];
|
||||
const service = new CardCreationService(
|
||||
createCardCreationDeps({
|
||||
client: createFakeClient({
|
||||
notesInfo: async () => [{ noteId: 42, fields: { Sentence: { value: 'existing' } } }],
|
||||
updateNoteFields: async () => {
|
||||
events.push('update');
|
||||
},
|
||||
}),
|
||||
setCardTypeFields: (updatedFields) => {
|
||||
updatedFields.CardType = 'sentence';
|
||||
},
|
||||
onCardsReady: (noteIds) => {
|
||||
events.push(`ready ${noteIds.join(',')}`);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(await service.createSentenceCard('テスト', 0, 1), true);
|
||||
assert.deepEqual(events, ['update', 'ready 42']);
|
||||
});
|
||||
|
||||
const THROWING_HOOKS: Array<{
|
||||
name: string;
|
||||
hook: Partial<CardCreationDeps>;
|
||||
|
||||
@@ -10,8 +10,9 @@ import {
|
||||
type MediaTimingReviewRequest,
|
||||
type WordCardKind,
|
||||
} from '../types/anki';
|
||||
import { shiftSubtitleRangeToVideoClock } from '../core/services/subtitle-clock';
|
||||
import { shiftSubtitleRangeToVideoClock, toSubtitleClock } from '../core/services/subtitle-clock';
|
||||
import { createLogger } from '../logger';
|
||||
import type { PluginMiningProvenance } from '../plugin-api';
|
||||
import type { MediaInput } from '../media-input';
|
||||
import { SubtitleTimingTracker } from '../subtitle-timing-tracker';
|
||||
import { AiConfig } from '../types/integrations';
|
||||
@@ -102,6 +103,8 @@ interface CardCreationMediaGenerator {
|
||||
}
|
||||
|
||||
interface CardCreationDeps {
|
||||
captureMiningProvenance?: () => PluginMiningProvenance | null;
|
||||
onNoteCreated?: (noteId: number, provenance: PluginMiningProvenance | null) => void;
|
||||
getConfig: () => AnkiConnectConfig;
|
||||
getAiConfig: () => AiConfig;
|
||||
getTimingTracker: () => SubtitleTimingTracker;
|
||||
@@ -153,6 +156,8 @@ interface CardCreationDeps {
|
||||
trackLastAddedDuplicateNoteIds?: (noteId: number, duplicateNoteIds: number[]) => void;
|
||||
findDuplicateNoteIds?: (expression: string, noteInfo: CardCreationNoteInfo) => Promise<number[]>;
|
||||
recordCardsMinedCallback?: (count: number, noteIds?: number[]) => void;
|
||||
/** Called once card creation is done writing a card; queued YouTube media may still be pending. */
|
||||
onCardsReady?: (noteIds: number[]) => void;
|
||||
reviewMediaTiming?: (
|
||||
request: Omit<MediaTimingReviewRequest, 'audioPadding' | 'maxMediaDuration'>,
|
||||
) => Promise<MediaTimingReviewDecision>;
|
||||
@@ -603,6 +608,15 @@ export class CardCreationService {
|
||||
}
|
||||
|
||||
const maxMediaDuration = this.deps.getConfig().media?.maxMediaDuration ?? 30;
|
||||
const captured = this.deps.captureMiningProvenance?.() ?? null;
|
||||
const provenance = captured && {
|
||||
...captured,
|
||||
subtitle: {
|
||||
text: sentence,
|
||||
startTime: toSubtitleClock(startTime, mpvClient.currentSubDelay ?? 0),
|
||||
endTime: toSubtitleClock(endTime, mpvClient.currentSubDelay ?? 0),
|
||||
},
|
||||
};
|
||||
const cappedEndTime = clampMediaEndTime(startTime, endTime, maxMediaDuration);
|
||||
if (cappedEndTime !== endTime) {
|
||||
log.warn(
|
||||
@@ -611,6 +625,7 @@ export class CardCreationService {
|
||||
endTime = cappedEndTime;
|
||||
}
|
||||
|
||||
let createdNoteId: number | null = null;
|
||||
try {
|
||||
return await this.deps.withUpdateProgress('Creating sentence card', async () => {
|
||||
const timingDecision = this.deps.reviewMediaTiming
|
||||
@@ -723,6 +738,8 @@ export class CardCreationService {
|
||||
fields,
|
||||
this.getConfiguredAnkiTags(),
|
||||
);
|
||||
createdNoteId = noteId;
|
||||
this.deps.onNoteCreated?.(noteId, provenance);
|
||||
log.info('Created sentence card:', noteId);
|
||||
} catch (error) {
|
||||
log.error('Failed to create sentence card:', (error as Error).message);
|
||||
@@ -887,6 +904,8 @@ export class CardCreationService {
|
||||
log.error('Error creating sentence card:', (error as Error).message);
|
||||
this.deps.showUpdateResult(`Sentence card failed: ${(error as Error).message}`, false);
|
||||
return false;
|
||||
} finally {
|
||||
if (createdNoteId !== null) this.deps.onCardsReady?.([createdNoteId]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@ export interface PendingYoutubeMediaQueueDeps {
|
||||
) => string;
|
||||
showStatusNotification: (message: string) => void;
|
||||
showNotification: (noteId: number, label: string | number, errorSuffix?: string) => Promise<void>;
|
||||
/** Called once a queued note's media was applied or dropped, so the card is in its final state. */
|
||||
onUpdateSettled?: (noteId: number) => void;
|
||||
logInfo: (message: string, ...args: unknown[]) => void;
|
||||
logWarn: (message: string, ...args: unknown[]) => void;
|
||||
logError: (message: string, ...args: unknown[]) => void;
|
||||
@@ -79,9 +81,18 @@ function shouldGenerateImage(config: AnkiConnectConfig): boolean {
|
||||
|
||||
export class PendingYoutubeMediaQueue {
|
||||
private updates: PendingYoutubeMediaUpdate[] = [];
|
||||
// Jobs taken off the queue whose media is still being applied or dropped.
|
||||
private settlingNoteIds = new Set<number>();
|
||||
|
||||
constructor(private readonly deps: PendingYoutubeMediaQueueDeps) {}
|
||||
|
||||
/** True while the note still waits on queued media. */
|
||||
hasPendingNote(noteId: number): boolean {
|
||||
return (
|
||||
this.settlingNoteIds.has(noteId) || this.updates.some((update) => update.noteId === noteId)
|
||||
);
|
||||
}
|
||||
|
||||
enqueue(job: PendingYoutubeMediaUpdate): void {
|
||||
if (!job.generateAudio && !job.generateImage) {
|
||||
return;
|
||||
@@ -195,6 +206,8 @@ export class PendingYoutubeMediaQueue {
|
||||
'Failed to apply queued YouTube media update:',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
} finally {
|
||||
this.settle(job);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,16 +247,24 @@ export class PendingYoutubeMediaQueue {
|
||||
'Failed to show queued YouTube media failure notification:',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
} finally {
|
||||
this.settle(job);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private settle(job: PendingYoutubeMediaUpdate): void {
|
||||
this.settlingNoteIds.delete(job.noteId);
|
||||
this.deps.onUpdateSettled?.(job.noteId);
|
||||
}
|
||||
|
||||
private takeMatchingUpdates(sourceUrl: string): PendingYoutubeMediaUpdate[] {
|
||||
const matched: PendingYoutubeMediaUpdate[] = [];
|
||||
const remaining: PendingYoutubeMediaUpdate[] = [];
|
||||
for (const job of this.updates) {
|
||||
if (youtubeMediaUrlsMatch(job.sourceUrl, sourceUrl)) {
|
||||
matched.push(job);
|
||||
this.settlingNoteIds.add(job.noteId);
|
||||
} else {
|
||||
remaining.push(job);
|
||||
}
|
||||
|
||||
@@ -3,9 +3,10 @@ import test from 'node:test';
|
||||
|
||||
import { PollingRunner } from './polling';
|
||||
|
||||
test('polling runner records newly added cards after initialization', async () => {
|
||||
test('polling runner records new cards and reports each ready after enrichment', async () => {
|
||||
const originalDateNow = Date.now;
|
||||
const recordedCards: number[] = [];
|
||||
const events: string[] = [];
|
||||
let tracked = new Set<number>();
|
||||
const responses = [
|
||||
[10, 11],
|
||||
@@ -16,12 +17,17 @@ test('polling runner records newly added cards after initialization', async () =
|
||||
const runner = new PollingRunner({
|
||||
getDeck: () => 'Mining',
|
||||
getPollingRate: () => 250,
|
||||
findNotes: async () => responses.shift() ?? [],
|
||||
findNotes: async (query) => (query.includes('tag:') ? [] : (responses.shift() ?? [])),
|
||||
shouldAutoUpdateNewCards: () => true,
|
||||
processNewCard: async () => undefined,
|
||||
processNewCard: async (noteId) => {
|
||||
events.push(`process ${noteId}`);
|
||||
},
|
||||
recordCardsAdded: (count) => {
|
||||
recordedCards.push(count);
|
||||
},
|
||||
onCardsReady: (noteIds) => {
|
||||
events.push(`ready ${noteIds.join(',')}`);
|
||||
},
|
||||
isUpdateInProgress: () => false,
|
||||
setUpdateInProgress: () => undefined,
|
||||
getTrackedNoteIds: () => tracked,
|
||||
@@ -38,7 +44,132 @@ test('polling runner records newly added cards after initialization', async () =
|
||||
await runner.pollOnce();
|
||||
|
||||
assert.deepEqual(recordedCards, [2]);
|
||||
assert.deepEqual(events, ['process 12', 'ready 12', 'process 13', 'ready 13']);
|
||||
} finally {
|
||||
Date.now = originalDateNow;
|
||||
}
|
||||
});
|
||||
|
||||
test('polling runner keeps going after one note fails to enrich', async () => {
|
||||
const originalDateNow = Date.now;
|
||||
const events: string[] = [];
|
||||
const warnings: unknown[][] = [];
|
||||
let tracked = new Set<number>();
|
||||
const responses = [[10], [10, 12, 13]];
|
||||
try {
|
||||
Date.now = () => 120_000;
|
||||
const runner = new PollingRunner({
|
||||
getDeck: () => undefined,
|
||||
getPollingRate: () => 250,
|
||||
findNotes: async (query) => (query.includes('tag:') ? [] : (responses.shift() ?? [])),
|
||||
shouldAutoUpdateNewCards: () => true,
|
||||
processNewCard: async (noteId) => {
|
||||
events.push(`process ${noteId}`);
|
||||
if (noteId === 12) throw new Error('overlay callback failed');
|
||||
},
|
||||
onCardsReady: (noteIds) => {
|
||||
events.push(`ready ${noteIds.join(',')}`);
|
||||
},
|
||||
isUpdateInProgress: () => false,
|
||||
setUpdateInProgress: () => undefined,
|
||||
getTrackedNoteIds: () => tracked,
|
||||
setTrackedNoteIds: (noteIds) => {
|
||||
tracked = noteIds;
|
||||
},
|
||||
showStatusNotification: () => undefined,
|
||||
logDebug: () => undefined,
|
||||
logInfo: () => undefined,
|
||||
logWarn: (...args) => {
|
||||
warnings.push(args);
|
||||
},
|
||||
});
|
||||
|
||||
await runner.pollOnce();
|
||||
await runner.pollOnce();
|
||||
|
||||
assert.deepEqual(events, ['process 12', 'ready 12', 'process 13', 'ready 13']);
|
||||
assert.deepEqual(warnings, [['Failed to auto-enrich note 12:', 'overlay callback failed']]);
|
||||
} finally {
|
||||
Date.now = originalDateNow;
|
||||
}
|
||||
});
|
||||
|
||||
function createStatsHarness(autoUpdate: boolean, sourceLookupFails = false) {
|
||||
let currentIds: number[] = [];
|
||||
let tracked = new Set<number>();
|
||||
const recorded: Array<{ count: number; noteIds: number[] }> = [];
|
||||
const processed: number[] = [];
|
||||
const ready: number[][] = [];
|
||||
const warnings: unknown[][] = [];
|
||||
const queries: string[] = [];
|
||||
const runner = new PollingRunner({
|
||||
getDeck: () => 'Mining',
|
||||
getPollingRate: () => 250,
|
||||
findNotes: async (query) => {
|
||||
queries.push(query);
|
||||
if (!query.includes('tag:')) return currentIds;
|
||||
if (sourceLookupFails) throw new Error('source lookup failed');
|
||||
return [2];
|
||||
},
|
||||
shouldAutoUpdateNewCards: () => autoUpdate,
|
||||
processNewCard: async (noteId) => {
|
||||
processed.push(noteId);
|
||||
},
|
||||
recordCardsAdded: (count, noteIds) => {
|
||||
recorded.push({ count, noteIds });
|
||||
},
|
||||
onCardsReady: (noteIds) => {
|
||||
ready.push(noteIds);
|
||||
},
|
||||
isUpdateInProgress: () => false,
|
||||
setUpdateInProgress: () => {},
|
||||
getTrackedNoteIds: () => tracked,
|
||||
setTrackedNoteIds: (noteIds) => {
|
||||
tracked = noteIds;
|
||||
},
|
||||
showStatusNotification: () => assert.fail('source lookup failures must not back off polling'),
|
||||
logDebug: () => {},
|
||||
logInfo: () => {},
|
||||
logWarn: (...args) => {
|
||||
warnings.push(args);
|
||||
},
|
||||
});
|
||||
return {
|
||||
recorded,
|
||||
processed,
|
||||
ready,
|
||||
warnings,
|
||||
queries,
|
||||
poll: async (noteIds: number[]) => {
|
||||
currentIds = noteIds;
|
||||
await runner.pollOnce();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
for (const autoUpdate of [true, false]) {
|
||||
test(`stats cards count without triggering plugins when auto-update is ${autoUpdate}`, async () => {
|
||||
const h = createStatsHarness(autoUpdate);
|
||||
await h.poll([]);
|
||||
await h.poll([1, 2]);
|
||||
assert.deepEqual(h.recorded, [{ count: 2, noteIds: [1, 2] }]);
|
||||
assert.deepEqual(h.processed, autoUpdate ? [1, 2] : []);
|
||||
assert.deepEqual(h.ready, [[1]]);
|
||||
assert.ok(h.queries.includes('nid:1,2 tag:"SubMiner::Stats"'));
|
||||
assert.deepEqual(h.warnings, []);
|
||||
});
|
||||
}
|
||||
|
||||
test('a failed source lookup skips plugin events without stopping counting or enrichment', async () => {
|
||||
const h = createStatsHarness(true, true);
|
||||
await h.poll([]);
|
||||
await h.poll([1, 2]);
|
||||
await h.poll([1, 2, 3]);
|
||||
assert.deepEqual(h.processed, [1, 2, 3]);
|
||||
assert.deepEqual(h.recorded, [
|
||||
{ count: 2, noteIds: [1, 2] },
|
||||
{ count: 1, noteIds: [3] },
|
||||
]);
|
||||
assert.deepEqual(h.ready, []);
|
||||
assert.equal(h.warnings.length, 2);
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { STATS_MINING_TAG } from '../shared/anki-source';
|
||||
|
||||
export interface PollingRunnerDeps {
|
||||
getDeck: () => string | undefined;
|
||||
getPollingRate: () => number;
|
||||
@@ -10,6 +12,8 @@ export interface PollingRunnerDeps {
|
||||
shouldAutoUpdateNewCards: () => boolean;
|
||||
processNewCard: (noteId: number) => Promise<void>;
|
||||
recordCardsAdded?: (count: number, noteIds: number[]) => void;
|
||||
/** Called once SubMiner is done with a new note: after enrichment, or at detection when it is off. */
|
||||
onCardsReady?: (noteIds: number[]) => void;
|
||||
isUpdateInProgress: () => boolean;
|
||||
setUpdateInProgress: (value: boolean) => void;
|
||||
getTrackedNoteIds: () => Set<number>;
|
||||
@@ -83,11 +87,39 @@ export class PollingRunner {
|
||||
this.deps.setTrackedNoteIds(previousNoteIds);
|
||||
this.deps.recordCardsAdded?.(newNoteIds.length, newNoteIds);
|
||||
|
||||
// Stats cards still count and update known words, but do not trigger plugins.
|
||||
const pluginNoteIds = new Set<number>();
|
||||
if (this.deps.onCardsReady) {
|
||||
try {
|
||||
const statsNoteIds = new Set(
|
||||
await this.deps.findNotes(`nid:${newNoteIds.join(',')} tag:"${STATS_MINING_TAG}"`, {
|
||||
maxRetries: 0,
|
||||
}),
|
||||
);
|
||||
for (const noteId of newNoteIds) {
|
||||
if (!statsNoteIds.has(noteId)) pluginNoteIds.add(noteId);
|
||||
}
|
||||
} catch (error) {
|
||||
this.deps.logWarn(
|
||||
'Skipping plugin events because note sources could not be checked:',
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.deps.shouldAutoUpdateNewCards()) {
|
||||
for (const noteId of newNoteIds) {
|
||||
await this.deps.processNewCard(noteId);
|
||||
try {
|
||||
await this.deps.processNewCard(noteId);
|
||||
} catch (error) {
|
||||
// One failed note must not leave the rest of the batch unprocessed.
|
||||
this.deps.logWarn(`Failed to auto-enrich note ${noteId}:`, (error as Error).message);
|
||||
} finally {
|
||||
if (pluginNoteIds.has(noteId)) this.deps.onCardsReady?.([noteId]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (pluginNoteIds.size > 0) this.deps.onCardsReady?.([...pluginNoteIds]);
|
||||
this.deps.logInfo(
|
||||
'New card detected (auto-update disabled). Press Ctrl+V to update from clipboard.',
|
||||
);
|
||||
|
||||
@@ -340,6 +340,14 @@ test('hasExplicitCommand and shouldStartApp preserve command intent', () => {
|
||||
assert.equal(shouldStartApp(sessionAction), true);
|
||||
assert.equal(commandNeedsOverlayRuntime(sessionAction), true);
|
||||
|
||||
const pluginAction = parseArgs(['--plugin-action', 'anime/open']);
|
||||
assert.equal(pluginAction.pluginAction, 'anime/open');
|
||||
assert.equal(parseArgs(['--plugin-action=anime/open']).pluginAction, 'anime/open');
|
||||
assert.equal(hasExplicitCommand(pluginAction), true);
|
||||
assert.equal(shouldStartApp(pluginAction), true);
|
||||
// The plugin decides what it needs; a window-only action must not force the overlay up.
|
||||
assert.equal(commandNeedsOverlayRuntime(pluginAction), false);
|
||||
|
||||
const toggleStatsOverlayRuntime = parseArgs(['--toggle-stats-overlay']);
|
||||
assert.equal(commandNeedsOverlayRuntime(toggleStatsOverlayRuntime), true);
|
||||
|
||||
|
||||
@@ -48,6 +48,8 @@ export interface CliArgs {
|
||||
cycleRuntimeOptionId?: string;
|
||||
cycleRuntimeOptionDirection?: 1 | -1;
|
||||
sessionAction?: SessionActionDispatchRequest;
|
||||
/** `<plugin id>/<action name>` to run, like a `__plugin-action:` keybinding. */
|
||||
pluginAction?: string;
|
||||
copySubtitleCount?: number;
|
||||
mineSentenceCount?: number;
|
||||
anilistStatus: boolean;
|
||||
@@ -338,6 +340,12 @@ export function parseArgs(argv: string[]): CliArgs {
|
||||
} else if (arg === '--session-action') {
|
||||
const parsed = parseSessionAction(readValue(argv[i + 1]));
|
||||
if (parsed) args.sessionAction = parsed;
|
||||
} else if (arg.startsWith('--plugin-action=')) {
|
||||
const value = arg.slice('--plugin-action='.length).trim();
|
||||
if (value) args.pluginAction = value;
|
||||
} else if (arg === '--plugin-action') {
|
||||
const value = readValue(argv[i + 1])?.trim();
|
||||
if (value) args.pluginAction = value;
|
||||
} else if (arg.startsWith('--copy-subtitle-count=')) {
|
||||
const value = Number(arg.split('=', 2)[1]);
|
||||
if (Number.isInteger(value) && value > 0) args.copySubtitleCount = value;
|
||||
@@ -601,6 +609,7 @@ export function hasExplicitCommand(args: CliArgs): boolean {
|
||||
args.playbackFeedback !== undefined ||
|
||||
args.cycleRuntimeOptionId !== undefined ||
|
||||
args.sessionAction !== undefined ||
|
||||
args.pluginAction !== undefined ||
|
||||
args.copySubtitleCount !== undefined ||
|
||||
args.mineSentenceCount !== undefined ||
|
||||
args.anilistStatus ||
|
||||
@@ -682,6 +691,7 @@ export function isStandaloneTexthookerCommand(args: CliArgs): boolean {
|
||||
args.playbackFeedback === undefined &&
|
||||
args.cycleRuntimeOptionId === undefined &&
|
||||
args.sessionAction === undefined &&
|
||||
args.pluginAction === undefined &&
|
||||
args.copySubtitleCount === undefined &&
|
||||
args.mineSentenceCount === undefined &&
|
||||
!args.anilistStatus &&
|
||||
@@ -752,6 +762,7 @@ export function shouldStartApp(args: CliArgs): boolean {
|
||||
args.playbackFeedback !== undefined ||
|
||||
args.cycleRuntimeOptionId !== undefined ||
|
||||
args.sessionAction !== undefined ||
|
||||
args.pluginAction !== undefined ||
|
||||
args.copySubtitleCount !== undefined ||
|
||||
args.mineSentenceCount !== undefined ||
|
||||
args.dictionary ||
|
||||
@@ -819,6 +830,7 @@ export function shouldRunDictionarySettingsOnlyStartup(args: CliArgs): boolean {
|
||||
args.playbackFeedback === undefined &&
|
||||
args.cycleRuntimeOptionId === undefined &&
|
||||
args.sessionAction === undefined &&
|
||||
args.pluginAction === undefined &&
|
||||
args.copySubtitleCount === undefined &&
|
||||
args.mineSentenceCount === undefined &&
|
||||
!args.anilistStatus &&
|
||||
|
||||
@@ -46,6 +46,7 @@ ${B}Mining${R}
|
||||
--open-session-help Open session help modal
|
||||
--open-controller-select Open controller select modal
|
||||
--open-controller-debug Open controller debug modal
|
||||
--plugin-action ${D}<id>/<name>${R} Run a plugin action
|
||||
|
||||
${B}AniList${R}
|
||||
--anilist-setup Open AniList authentication flow
|
||||
|
||||
@@ -37,6 +37,7 @@ const {
|
||||
startupWarmups,
|
||||
updates,
|
||||
notifications,
|
||||
plugins,
|
||||
auto_start_overlay,
|
||||
} = CORE_DEFAULT_CONFIG;
|
||||
const {
|
||||
@@ -74,6 +75,7 @@ export const DEFAULT_CONFIG: ResolvedConfig = {
|
||||
startupWarmups,
|
||||
updates,
|
||||
notifications,
|
||||
plugins,
|
||||
subtitleStyle,
|
||||
subtitleSidebar,
|
||||
auto_start_overlay,
|
||||
|
||||
@@ -17,6 +17,7 @@ export const CORE_DEFAULT_CONFIG: Pick<
|
||||
| 'startupWarmups'
|
||||
| 'updates'
|
||||
| 'notifications'
|
||||
| 'plugins'
|
||||
| 'auto_start_overlay'
|
||||
> = {
|
||||
dictionaryBackend: 'yomitan',
|
||||
@@ -145,5 +146,6 @@ export const CORE_DEFAULT_CONFIG: Pick<
|
||||
notifications: {
|
||||
overlayPosition: 'top-right',
|
||||
},
|
||||
plugins: {},
|
||||
auto_start_overlay: true,
|
||||
};
|
||||
@@ -546,6 +546,13 @@ export function buildCoreConfigOptionRegistry(
|
||||
defaultValue: defaultConfig.notifications.overlayPosition,
|
||||
description: 'Position for in-overlay notification cards.',
|
||||
},
|
||||
{
|
||||
path: 'plugins',
|
||||
kind: 'object',
|
||||
defaultValue: defaultConfig.plugins,
|
||||
description:
|
||||
'Plugins to load at startup, keyed by directory name under <config dir>/plugins/. Each entry is { "enabled": true, "settings": { ... } }; settings are passed to the plugin as ctx.settings.',
|
||||
},
|
||||
{
|
||||
path: 'shortcuts.multiCopyTimeoutMs',
|
||||
kind: 'number',
|
||||
|
||||
@@ -57,6 +57,7 @@ export const SPECIAL_COMMANDS = {
|
||||
ANIMETOSHO_OPEN: '__animetosho-open',
|
||||
TSUKIHIME_OPEN: '__tsukihime-open',
|
||||
RUNTIME_OPTION_CYCLE_PREFIX: '__runtime-option-cycle:',
|
||||
PLUGIN_ACTION_PREFIX: '__plugin-action:',
|
||||
REPLAY_SUBTITLE: '__replay-subtitle',
|
||||
PLAY_NEXT_SUBTITLE: '__play-next-subtitle',
|
||||
YOUTUBE_PICKER_OPEN: '__youtube-picker-open',
|
||||
|
||||
@@ -92,6 +92,15 @@ const CORE_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
|
||||
notes: ['Hot-reload: position changes apply to the next overlay notification.'],
|
||||
key: 'notifications',
|
||||
},
|
||||
{
|
||||
title: 'Plugins',
|
||||
description: [
|
||||
'JavaScript plugins loaded from <config dir>/plugins/<id>/ at startup.',
|
||||
'Plugins run inside SubMiner with full access to your system. Only enable code you trust.',
|
||||
],
|
||||
notes: ['Restart SubMiner after changing plugins.'],
|
||||
key: 'plugins',
|
||||
},
|
||||
{
|
||||
title: 'Keyboard Shortcuts',
|
||||
description: ['Overlay keyboard shortcuts. Set a shortcut to null to disable.'],
|
||||
|
||||
@@ -4,6 +4,7 @@ import { createResolveContext } from './resolve/context';
|
||||
import { applyCoreDomainConfig } from './resolve/core-domains';
|
||||
import { applyImmersionTrackingConfig } from './resolve/immersion-tracking';
|
||||
import { applyIntegrationConfig } from './resolve/integrations';
|
||||
import { applyPluginsConfig } from './resolve/plugins';
|
||||
import { applyStatsConfig } from './resolve/stats';
|
||||
import { applySubtitleDomainConfig } from './resolve/subtitle-domains';
|
||||
import { applyTopLevelConfig } from './resolve/top-level';
|
||||
@@ -15,6 +16,7 @@ const APPLY_RESOLVE_STEPS = [
|
||||
applyIntegrationConfig,
|
||||
applyImmersionTrackingConfig,
|
||||
applyStatsConfig,
|
||||
applyPluginsConfig,
|
||||
applyAnkiConnectResolution,
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { resolveConfig } from '../resolve';
|
||||
|
||||
test('resolveConfig keeps plugin entries and their settings', () => {
|
||||
const { resolved, warnings } = resolveConfig({
|
||||
plugins: {
|
||||
'ai-explain': { enabled: true, settings: { codexPath: 'codex', before: 2 } },
|
||||
dormant: {},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(resolved.plugins, {
|
||||
'ai-explain': { enabled: true, settings: { codexPath: 'codex', before: 2 } },
|
||||
dormant: { enabled: false, settings: {} },
|
||||
});
|
||||
assert.deepEqual(warnings, []);
|
||||
});
|
||||
|
||||
test('resolveConfig warns about malformed plugin entries and keeps them disabled', () => {
|
||||
const { resolved, warnings } = resolveConfig({
|
||||
plugins: {
|
||||
flag: { enabled: 'yes' as never, settings: [] as never },
|
||||
scalar: true as never,
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(resolved.plugins, { flag: { enabled: false, settings: {} } });
|
||||
assert.deepEqual(
|
||||
warnings.map((warning) => warning.path),
|
||||
['plugins.flag.enabled', 'plugins.flag.settings', 'plugins.scalar'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { ResolveContext } from './context';
|
||||
import { isObject } from './shared';
|
||||
|
||||
/** Keeps well-formed `plugins.<id>` entries; ids are validated again when the plugin loads. */
|
||||
export function applyPluginsConfig(context: ResolveContext): void {
|
||||
const { src, resolved, warn } = context;
|
||||
if (src.plugins === undefined) return;
|
||||
if (!isObject(src.plugins)) {
|
||||
warn('plugins', src.plugins, resolved.plugins, 'Expected object keyed by plugin id.');
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [id, entry] of Object.entries(src.plugins)) {
|
||||
const path = `plugins.${id}`;
|
||||
if (!isObject(entry)) {
|
||||
warn(path, entry, undefined, 'Expected { "enabled": boolean, "settings"?: object }.');
|
||||
continue;
|
||||
}
|
||||
if (entry.enabled !== undefined && typeof entry.enabled !== 'boolean') {
|
||||
warn(`${path}.enabled`, entry.enabled, false, 'Expected boolean.');
|
||||
}
|
||||
if (entry.settings !== undefined && !isObject(entry.settings)) {
|
||||
warn(`${path}.settings`, entry.settings, {}, 'Expected object.');
|
||||
}
|
||||
resolved.plugins[id] = {
|
||||
enabled: entry.enabled === true,
|
||||
settings: isObject(entry.settings) ? { ...entry.settings } : {},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,7 @@ const JSON_OBJECT_FIELDS = new Set([
|
||||
'keybindings',
|
||||
'controller.bindings',
|
||||
'controller.profiles',
|
||||
'plugins',
|
||||
'ankiConnect.knownWords.decks',
|
||||
'subtitleStyle.css',
|
||||
'subtitleStyle.secondary.css',
|
||||
@@ -441,6 +442,9 @@ function categoryAndSection(path: string): { category: ConfigSettingsCategory; s
|
||||
if (path.startsWith('notifications.')) {
|
||||
return { category: 'behavior', section: 'Notifications' };
|
||||
}
|
||||
if (path === 'plugins') {
|
||||
return { category: 'advanced', section: 'Plugins' };
|
||||
}
|
||||
if (path === 'mpv.aniskipButtonKey') {
|
||||
return { category: 'input', section: 'Overlay Shortcuts' };
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ function makeDeps(overrides: Partial<AppReadyRuntimeDeps> = {}) {
|
||||
loadSubtitlePosition: () => calls.push('loadSubtitlePosition'),
|
||||
resolveKeybindings: () => calls.push('resolveKeybindings'),
|
||||
createMpvClient: () => calls.push('createMpvClient'),
|
||||
startPlugins: () => calls.push('startPlugins'),
|
||||
reloadConfig: () => calls.push('reloadConfig'),
|
||||
getResolvedConfig: () => ({
|
||||
websocket: { enabled: 'auto' },
|
||||
@@ -162,6 +163,7 @@ test('runAppReadyRuntime skips heavy startup when shouldSkipHeavyStartup returns
|
||||
assert.equal(calls.includes('loadSubtitlePosition'), false);
|
||||
assert.equal(calls.includes('resolveKeybindings'), false);
|
||||
assert.equal(calls.includes('createMpvClient'), false);
|
||||
assert.equal(calls.includes('startPlugins'), false);
|
||||
assert.equal(calls.includes('initRuntimeOptionsManager'), false);
|
||||
assert.equal(calls.includes('createImmersionTracker'), false);
|
||||
assert.equal(calls.includes('startJellyfinRemoteSession'), false);
|
||||
@@ -326,6 +328,9 @@ test('runAppReadyRuntime starts background warmups after overlay startup', async
|
||||
|
||||
assert.ok(calls.indexOf('loadSubtitlePosition') < calls.indexOf('startBackgroundWarmups'));
|
||||
assert.ok(calls.indexOf('createMpvClient') < calls.indexOf('startBackgroundWarmups'));
|
||||
assert.ok(calls.includes('setLogLevel:info:config'));
|
||||
assert.ok(calls.indexOf('setLogLevel:info:config') < calls.indexOf('startPlugins'));
|
||||
assert.ok(calls.indexOf('startPlugins') < calls.indexOf('startBackgroundWarmups'));
|
||||
assert.ok(calls.indexOf('initializeOverlayRuntime') < calls.indexOf('startBackgroundWarmups'));
|
||||
assert.ok(calls.indexOf('startBackgroundWarmups') < calls.indexOf('handleInitialArgs'));
|
||||
});
|
||||
|
||||
@@ -737,6 +737,23 @@ test('handleCliCommand dispatches generic session action payloads', async () =>
|
||||
});
|
||||
});
|
||||
|
||||
test('handleCliCommand runs plugin actions through the session action dispatcher', async () => {
|
||||
let request: unknown = null;
|
||||
const { deps } = createDeps({
|
||||
dispatchSessionAction: async (nextRequest) => {
|
||||
request = nextRequest;
|
||||
},
|
||||
});
|
||||
|
||||
handleCliCommand(makeArgs({ pluginAction: 'anime/open' }), 'initial', deps);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
assert.deepEqual(request, {
|
||||
actionId: 'runPluginAction',
|
||||
payload: { pluginActionId: 'anime/open' },
|
||||
});
|
||||
});
|
||||
|
||||
test('handleCliCommand dispatches mark-watched session action', async () => {
|
||||
let request: unknown = null;
|
||||
const { deps } = createDeps({
|
||||
|
||||
@@ -422,6 +422,12 @@ export function handleCliCommand(
|
||||
`sessionAction:${args.sessionAction.actionId}`,
|
||||
'Session action failed',
|
||||
);
|
||||
} else if (args.pluginAction) {
|
||||
dispatchCliSessionAction(
|
||||
{ actionId: 'runPluginAction', payload: { pluginActionId: args.pluginAction } },
|
||||
`pluginAction:${args.pluginAction}`,
|
||||
'Plugin action failed',
|
||||
);
|
||||
} else if (args.toggle || args.toggleVisibleOverlay) {
|
||||
deps.toggleVisibleOverlay();
|
||||
} else if (args.togglePrimarySubtitleBar) {
|
||||
|
||||
@@ -576,8 +576,8 @@ test('registerIpcHandlers ignores malformed fire-and-forget payloads', () => {
|
||||
const openedModals: unknown[] = [];
|
||||
registerIpcHandlers(
|
||||
{
|
||||
onOverlayModalClosed: (modal) => {
|
||||
closedModals.push(modal);
|
||||
onOverlayModalClosed: (modal, _senderWindow, instanceId) => {
|
||||
closedModals.push(instanceId === undefined ? modal : [modal, instanceId]);
|
||||
},
|
||||
onOverlayModalOpened: (modal) => {
|
||||
openedModals.push(modal);
|
||||
@@ -638,7 +638,9 @@ test('registerIpcHandlers ignores malformed fire-and-forget payloads', () => {
|
||||
handlers.on.get(IPC_CHANNELS.command.overlayModalClosed)!({}, 'not-a-modal');
|
||||
handlers.on.get(IPC_CHANNELS.command.overlayModalClosed)!({}, 'subsync');
|
||||
handlers.on.get(IPC_CHANNELS.command.overlayModalClosed)!({}, 'kiku');
|
||||
assert.deepEqual(closedModals, ['subsync', 'kiku']);
|
||||
handlers.on.get(IPC_CHANNELS.command.overlayModalClosed)!({}, 'plugin-panel', 4);
|
||||
handlers.on.get(IPC_CHANNELS.command.overlayModalClosed)!({}, 'plugin-panel', 'bad');
|
||||
assert.deepEqual(closedModals, ['subsync', 'kiku', ['plugin-panel', 4], 'plugin-panel']);
|
||||
|
||||
handlers.on.get(IPC_CHANNELS.command.overlayModalOpened)!({}, 'bad');
|
||||
handlers.on.get(IPC_CHANNELS.command.overlayModalOpened)!({}, 'subsync');
|
||||
|
||||
@@ -50,6 +50,7 @@ export interface IpcServiceDeps {
|
||||
onOverlayModalClosed: (
|
||||
modal: OverlayHostedModal,
|
||||
senderWindow: ElectronBrowserWindow | null,
|
||||
instanceId?: number,
|
||||
) => void;
|
||||
onOverlayModalOpened?: (
|
||||
modal: OverlayHostedModal,
|
||||
@@ -317,6 +318,7 @@ export interface IpcDepsRuntimeOptions {
|
||||
onOverlayModalClosed: (
|
||||
modal: OverlayHostedModal,
|
||||
senderWindow: ElectronBrowserWindow | null,
|
||||
instanceId?: number,
|
||||
) => void;
|
||||
onOverlayModalOpened?: (
|
||||
modal: OverlayHostedModal,
|
||||
@@ -527,13 +529,20 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
|
||||
},
|
||||
);
|
||||
|
||||
ipc.on(IPC_CHANNELS.command.overlayModalClosed, (event: unknown, modal: unknown) => {
|
||||
const parsedModal = parseOverlayHostedModal(modal);
|
||||
if (!parsedModal) return;
|
||||
const senderWindow =
|
||||
electron.BrowserWindow?.fromWebContents((event as IpcMainEvent).sender) ?? null;
|
||||
deps.onOverlayModalClosed(parsedModal, senderWindow);
|
||||
});
|
||||
ipc.on(
|
||||
IPC_CHANNELS.command.overlayModalClosed,
|
||||
(event: unknown, modal: unknown, instanceId: unknown) => {
|
||||
const parsedModal = parseOverlayHostedModal(modal);
|
||||
if (!parsedModal) return;
|
||||
const senderWindow =
|
||||
electron.BrowserWindow?.fromWebContents((event as IpcMainEvent).sender) ?? null;
|
||||
deps.onOverlayModalClosed(
|
||||
parsedModal,
|
||||
senderWindow,
|
||||
Number.isInteger(instanceId) ? (instanceId as number) : undefined,
|
||||
);
|
||||
},
|
||||
);
|
||||
ipc.on(IPC_CHANNELS.command.overlayModalOpened, (event: unknown, modal: unknown) => {
|
||||
const parsedModal = parseOverlayHostedModal(modal);
|
||||
if (!parsedModal) return;
|
||||
|
||||
@@ -486,3 +486,19 @@ test('dispatchMpvProtocolMessage emits client-message string args', async () =>
|
||||
|
||||
assert.deepEqual(received, [{ args: ['subminer-skip-intro', 'extra'] }]);
|
||||
});
|
||||
|
||||
test('dispatchMpvProtocolMessage emits end-file with reason, entry id, and error', async () => {
|
||||
const received: unknown[] = [];
|
||||
const { deps } = createDeps({ emitEndFile: (payload) => received.push(payload) });
|
||||
|
||||
await dispatchMpvProtocolMessage(
|
||||
{ event: 'end-file', reason: 'error', playlist_entry_id: 3, file_error: 'loading failed' },
|
||||
deps,
|
||||
);
|
||||
await dispatchMpvProtocolMessage({ event: 'end-file', reason: 'something-new' }, deps);
|
||||
|
||||
assert.deepEqual(received, [
|
||||
{ reason: 'error', playlistEntryId: 3, error: 'loading failed' },
|
||||
{ reason: 'unknown', playlistEntryId: null, error: null },
|
||||
]);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MpvSubtitleRenderMetrics } from '../../types';
|
||||
import { sanitizeMediaTitle } from '../../shared/media-identity';
|
||||
import { widenHalfwidthKana } from '../utils/halfwidth-kana';
|
||||
import type { PluginMpvEventMap } from '../../plugin-api';
|
||||
import { toVideoClock } from './subtitle-clock';
|
||||
|
||||
export type MpvMessage = {
|
||||
@@ -10,8 +11,26 @@ export type MpvMessage = {
|
||||
args?: unknown;
|
||||
request_id?: number;
|
||||
error?: string;
|
||||
reason?: unknown;
|
||||
playlist_entry_id?: unknown;
|
||||
file_error?: unknown;
|
||||
};
|
||||
|
||||
const MPV_END_FILE_REASONS = ['eof', 'stop', 'quit', 'error', 'redirect'] as const;
|
||||
export type MpvEndFileReason = PluginMpvEventMap['end-file']['reason'];
|
||||
|
||||
/** mpv's `end-file` event: why the current file stopped, and mpv's error text when it failed. */
|
||||
export type MpvEndFileEvent = PluginMpvEventMap['end-file'];
|
||||
|
||||
function parseEndFileEvent(msg: MpvMessage): MpvEndFileEvent {
|
||||
const reason = MPV_END_FILE_REASONS.find((known) => known === msg.reason) ?? 'unknown';
|
||||
return {
|
||||
reason,
|
||||
playlistEntryId: typeof msg.playlist_entry_id === 'number' ? msg.playlist_entry_id : null,
|
||||
error: typeof msg.file_error === 'string' && msg.file_error ? msg.file_error : null,
|
||||
};
|
||||
}
|
||||
|
||||
export const MPV_REQUEST_ID_SUBTEXT = 101;
|
||||
export const MPV_REQUEST_ID_PATH = 102;
|
||||
export const MPV_REQUEST_ID_SECONDARY_SUBTEXT = 103;
|
||||
@@ -103,6 +122,8 @@ export interface MpvProtocolHandleMessageDeps {
|
||||
shouldQuitOnMpvShutdown: () => boolean;
|
||||
requestAppQuit: () => void;
|
||||
emitClientMessage?: (payload: { args: string[] }) => void;
|
||||
emitEndFile?: (payload: MpvEndFileEvent) => void;
|
||||
emitFileLoaded?: () => void;
|
||||
}
|
||||
|
||||
type SubtitleTrackCandidate = {
|
||||
@@ -433,6 +454,10 @@ export async function dispatchMpvProtocolMessage(
|
||||
if (args.length > 0) {
|
||||
deps.emitClientMessage?.({ args });
|
||||
}
|
||||
} else if (msg.event === 'file-loaded') {
|
||||
deps.emitFileLoaded?.();
|
||||
} else if (msg.event === 'end-file') {
|
||||
deps.emitEndFile?.(parseEndFileEvent(msg));
|
||||
} else if (msg.event === 'shutdown') {
|
||||
deps.restorePreviousSecondarySubVisibility();
|
||||
if (deps.shouldQuitOnMpvShutdown()) {
|
||||
|
||||
+14
-17
@@ -1,3 +1,4 @@
|
||||
import type { PluginMpvEventMap } from '../../plugin-api';
|
||||
import { EventEmitter } from 'events';
|
||||
import { Config, MpvClient, MpvSubtitleRenderMetrics } from '../../types';
|
||||
import {
|
||||
@@ -120,24 +121,8 @@ export interface MpvIpcClientProtocolDeps {
|
||||
|
||||
export interface MpvIpcClientDeps extends MpvIpcClientProtocolDeps {}
|
||||
|
||||
export interface MpvIpcClientEventMap {
|
||||
'connection-change': { connected: boolean };
|
||||
'subtitle-change': { text: string; isOverlayVisible: boolean };
|
||||
'subtitle-timing': { text: string; start: number; end: number };
|
||||
'time-pos-change': { time: number };
|
||||
'duration-change': { duration: number };
|
||||
'pause-change': { paused: boolean };
|
||||
'fullscreen-change': { fullscreen: boolean };
|
||||
'secondary-subtitle-change': { text: string };
|
||||
'subtitle-track-change': { sid: number | null };
|
||||
'secondary-subtitle-track-change': { sid: number | null };
|
||||
'secondary-subtitle-delay-change': { delay: number };
|
||||
'subtitle-track-list-change': { trackList: unknown[] | null };
|
||||
'media-path-change': { path: string };
|
||||
'media-title-change': { title: string | null };
|
||||
export interface MpvIpcClientEventMap extends PluginMpvEventMap {
|
||||
'subtitle-metrics-change': { patch: Partial<MpvSubtitleRenderMetrics> };
|
||||
'secondary-subtitle-visibility': { visible: boolean };
|
||||
'client-message': { args: string[] };
|
||||
}
|
||||
|
||||
type MpvIpcClientEventName = keyof MpvIpcClientEventMap;
|
||||
@@ -525,6 +510,10 @@ export class MpvIpcClient implements MpvClient {
|
||||
emitClientMessage: (payload) => {
|
||||
this.emit('client-message', payload);
|
||||
},
|
||||
emitEndFile: (payload) => {
|
||||
this.emit('end-file', payload);
|
||||
},
|
||||
emitFileLoaded: () => this.emit('file-loaded', undefined),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -604,6 +593,14 @@ export class MpvIpcClient implements MpvClient {
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async requestCommand(command: (string | number | boolean)[]): Promise<unknown> {
|
||||
const response = await this.request(command);
|
||||
if (response.error && response.error !== 'success') {
|
||||
throw new Error(`MPV command failed: ${response.error}`);
|
||||
}
|
||||
return response.data;
|
||||
}
|
||||
|
||||
private failPendingRequests(): void {
|
||||
for (const [requestId, resolve] of this.pendingRequests.entries()) {
|
||||
resolve({ request_id: requestId, error: 'disconnected' });
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
|
||||
import { execPluginCommand, resolvePluginSpawnTarget } from './exec';
|
||||
|
||||
// The test runtime (bun or node) doubles as a portable child process.
|
||||
const runtime = process.execPath;
|
||||
|
||||
test('pipes stdin to the child and collects stdout', async () => {
|
||||
const result = await execPluginCommand(
|
||||
runtime,
|
||||
['-e', 'process.stdin.on("data", (d) => process.stdout.write(String(d).toUpperCase()))'],
|
||||
{ stdin: '字幕 line' },
|
||||
);
|
||||
|
||||
assert.equal(result.exitCode, 0);
|
||||
assert.equal(result.stdout, '字幕 LINE');
|
||||
});
|
||||
|
||||
test('resolves with a non-zero exit code and stderr', async () => {
|
||||
const result = await execPluginCommand(runtime, [
|
||||
'-e',
|
||||
'process.stderr.write("bad things"); process.exit(3)',
|
||||
]);
|
||||
|
||||
assert.equal(result.exitCode, 3);
|
||||
assert.equal(result.stderr, 'bad things');
|
||||
});
|
||||
|
||||
test('drops the AppImage library path from the child environment', async () => {
|
||||
const previous = process.env.LD_LIBRARY_PATH;
|
||||
process.env.LD_LIBRARY_PATH = '/tmp/.mount_SubMinXXXXXX/usr/lib';
|
||||
try {
|
||||
const result = await execPluginCommand(
|
||||
runtime,
|
||||
['-e', 'process.stdout.write(String(process.env.LD_LIBRARY_PATH) + "|" + process.env.EXTRA)'],
|
||||
{ env: { EXTRA: 'kept' } },
|
||||
);
|
||||
assert.equal(result.stdout, 'undefined|kept');
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.LD_LIBRARY_PATH;
|
||||
else process.env.LD_LIBRARY_PATH = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test('aborting kills the child and rejects with AbortError', async () => {
|
||||
const controller = new AbortController();
|
||||
const pending = execPluginCommand(runtime, ['-e', 'setTimeout(() => {}, 60_000)'], {
|
||||
signal: controller.signal,
|
||||
});
|
||||
setTimeout(() => controller.abort(), 50);
|
||||
|
||||
await assert.rejects(pending, { name: 'AbortError' });
|
||||
});
|
||||
|
||||
test('force-kills a child that ignores SIGTERM after the grace period', async (t) => {
|
||||
if (process.platform === 'win32') return t.skip('POSIX signals only');
|
||||
const pidFile = path.join(await mkdtemp(path.join(os.tmpdir(), 'plugin-exec-')), 'pid');
|
||||
const controller = new AbortController();
|
||||
const pending = execPluginCommand(
|
||||
runtime,
|
||||
[
|
||||
'-e',
|
||||
`process.on("SIGTERM", () => {}); require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(() => {}, 1000);`,
|
||||
],
|
||||
{ signal: controller.signal },
|
||||
100,
|
||||
);
|
||||
|
||||
let pid = 0;
|
||||
for (let i = 0; i < 100 && !pid; i += 1) {
|
||||
pid = Number(await readFile(pidFile, 'utf8').catch(() => '0'));
|
||||
if (!pid) await sleep(20);
|
||||
}
|
||||
assert.ok(pid > 0, 'child never reported its pid');
|
||||
try {
|
||||
controller.abort();
|
||||
await assert.rejects(pending, { name: 'AbortError' });
|
||||
let alive = true;
|
||||
for (let i = 0; i < 100 && alive; i += 1) {
|
||||
await sleep(20);
|
||||
alive = isRunning(pid);
|
||||
}
|
||||
assert.equal(alive, false, 'child survived SIGTERM');
|
||||
} finally {
|
||||
if (isRunning(pid)) process.kill(pid, 'SIGKILL');
|
||||
await rm(path.dirname(pidFile), { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function isRunning(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
test('rejects when the binary does not exist', async () => {
|
||||
await assert.rejects(
|
||||
execPluginCommand('subminer-definitely-missing-binary', []),
|
||||
(error: NodeJS.ErrnoException) => error.code === 'ENOENT',
|
||||
);
|
||||
});
|
||||
|
||||
test('Windows batch shims run through cmd.exe; other commands spawn directly', async () => {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), 'plugin-exec-shim-'));
|
||||
try {
|
||||
await writeFile(path.join(dir, 'codex.cmd'), '');
|
||||
await writeFile(path.join(dir, 'native.exe'), '');
|
||||
const env = { PATH: dir, PATHEXT: '.exe;.cmd', ComSpec: 'cmd.exe' };
|
||||
|
||||
const shim = resolvePluginSpawnTarget('codex', ['exec', '-'], env, 'win32');
|
||||
assert.equal(shim.viaShell, true);
|
||||
assert.equal(shim.file, 'cmd.exe');
|
||||
assert.deepEqual(shim.args.slice(0, 4), ['/d', '/s', '/v:off', '/c']);
|
||||
assert.ok(shim.args[4]!.includes(path.join(dir, 'codex.cmd')));
|
||||
|
||||
assert.deepEqual(resolvePluginSpawnTarget('native', ['-v'], env, 'win32'), {
|
||||
file: path.join(dir, 'native.exe'),
|
||||
args: ['-v'],
|
||||
viaShell: false,
|
||||
});
|
||||
assert.deepEqual(resolvePluginSpawnTarget('codex', ['-'], env, 'linux'), {
|
||||
file: 'codex',
|
||||
args: ['-'],
|
||||
viaShell: false,
|
||||
});
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { type ChildProcess, spawn } from 'node:child_process';
|
||||
|
||||
import { buildSystemBinaryEnv } from '../../utils/system-binary-env';
|
||||
import {
|
||||
buildWindowsShimInvocation,
|
||||
isWindowsCommandShim,
|
||||
resolveWindowsCommand,
|
||||
} from '../../utils/windows-command-shim';
|
||||
import type { PluginExecOptions, PluginExecResult } from './types';
|
||||
|
||||
const MAX_CAPTURED_OUTPUT_CHARS = 4 * 1024 * 1024;
|
||||
const DEFAULT_KILL_GRACE_MS = 3_000;
|
||||
|
||||
function appendCapped(current: string, chunk: string): string {
|
||||
if (current.length >= MAX_CAPTURED_OUTPUT_CHARS) return current;
|
||||
return (current + chunk).slice(0, MAX_CAPTURED_OUTPUT_CHARS);
|
||||
}
|
||||
|
||||
interface SpawnTarget {
|
||||
file: string;
|
||||
args: string[];
|
||||
viaShell: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows batch shims (npm installs `codex` as `codex.cmd`) only run through cmd.exe. Native
|
||||
* binaries, and every command on Linux and macOS, are spawned directly.
|
||||
*/
|
||||
export function resolvePluginSpawnTarget(
|
||||
command: string,
|
||||
args: string[],
|
||||
env: NodeJS.ProcessEnv,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): SpawnTarget {
|
||||
if (platform !== 'win32') return { file: command, args, viaShell: false };
|
||||
const resolved = resolveWindowsCommand(command, env);
|
||||
if (!isWindowsCommandShim(resolved)) return { file: resolved, args, viaShell: false };
|
||||
return { ...buildWindowsShimInvocation(resolved, args, env), viaShell: true };
|
||||
}
|
||||
|
||||
// Killing cmd.exe alone would leave the shim's own child running, so end the whole tree.
|
||||
function killWindowsProcessTree(child: ChildProcess): void {
|
||||
if (child.pid === undefined) return;
|
||||
spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
}).on('error', () => child.kill());
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `command` (no shell, except cmd.exe for Windows batch shims) and collects its output. Resolves with the exit code on any exit,
|
||||
* including non-zero; rejects when the binary cannot start, the timeout passes, or `signal` aborts.
|
||||
* A timed-out or aborted child gets SIGTERM, then SIGKILL after `killGraceMs` (a shim's
|
||||
* process tree is ended with taskkill instead).
|
||||
*/
|
||||
export function execPluginCommand(
|
||||
command: string,
|
||||
args: string[],
|
||||
options: PluginExecOptions = {},
|
||||
killGraceMs = DEFAULT_KILL_GRACE_MS,
|
||||
): Promise<PluginExecResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (options.signal?.aborted) {
|
||||
reject(new DOMException('Command aborted.', 'AbortError'));
|
||||
return;
|
||||
}
|
||||
|
||||
const env = { ...buildSystemBinaryEnv(), ...options.env };
|
||||
const target = resolvePluginSpawnTarget(command, args, env);
|
||||
const child = spawn(target.file, target.args, {
|
||||
cwd: options.cwd,
|
||||
env,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
windowsHide: true,
|
||||
windowsVerbatimArguments: target.viaShell,
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let settled = false;
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const settle = (finish: () => void): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timeout) clearTimeout(timeout);
|
||||
options.signal?.removeEventListener('abort', onAbort);
|
||||
finish();
|
||||
};
|
||||
|
||||
// Rejects right away, then escalates to SIGKILL if the child ignores SIGTERM.
|
||||
const killWith = (error: Error): void => {
|
||||
settle(() => reject(error));
|
||||
if (target.viaShell) {
|
||||
killWindowsProcessTree(child);
|
||||
return;
|
||||
}
|
||||
child.kill('SIGTERM');
|
||||
const forceKill = setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
|
||||
}, killGraceMs);
|
||||
forceKill.unref();
|
||||
child.once('exit', () => clearTimeout(forceKill));
|
||||
};
|
||||
|
||||
function onAbort(): void {
|
||||
killWith(new DOMException('Command aborted.', 'AbortError'));
|
||||
}
|
||||
|
||||
options.signal?.addEventListener('abort', onAbort, { once: true });
|
||||
if (options.timeoutMs !== undefined && options.timeoutMs > 0) {
|
||||
timeout = setTimeout(
|
||||
() => killWith(new Error(`${command} timed out after ${options.timeoutMs} ms.`)),
|
||||
options.timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
child.stdout.setEncoding('utf8');
|
||||
child.stderr.setEncoding('utf8');
|
||||
child.stdout.on('data', (chunk: string) => {
|
||||
stdout = appendCapped(stdout, chunk);
|
||||
});
|
||||
child.stderr.on('data', (chunk: string) => {
|
||||
stderr = appendCapped(stderr, chunk);
|
||||
});
|
||||
// A child that exits without reading stdin raises EPIPE here; the exit code tells the story.
|
||||
child.stdin.on('error', () => {});
|
||||
|
||||
child.on('error', (error) => settle(() => reject(error)));
|
||||
child.on('close', (exitCode) => settle(() => resolve({ exitCode, stdout, stderr })));
|
||||
|
||||
child.stdin.end(options.stdin ?? '');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import { PLUGIN_API_VERSION, type PluginManifest } from './types';
|
||||
|
||||
const PLUGIN_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/i;
|
||||
|
||||
/** Plugin ids double as directory names and action prefixes, and action names follow the same rule. */
|
||||
export function isValidPluginName(id: string): boolean {
|
||||
return PLUGIN_NAME_PATTERN.test(id);
|
||||
}
|
||||
|
||||
/** Validates parsed `plugin.json` content. Returns an error message instead of throwing. */
|
||||
export function parsePluginManifest(
|
||||
raw: unknown,
|
||||
fallbackName: string,
|
||||
): { manifest: PluginManifest } | { error: string } {
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
||||
return { error: 'plugin.json must contain a JSON object.' };
|
||||
}
|
||||
const value = raw as Record<string, unknown>;
|
||||
if (typeof value.main !== 'string' || value.main.trim().length === 0) {
|
||||
return { error: 'plugin.json needs a "main" entry file.' };
|
||||
}
|
||||
if (value.name !== undefined && typeof value.name !== 'string') {
|
||||
return { error: 'plugin.json "name" must be a string.' };
|
||||
}
|
||||
if (value.version !== undefined && typeof value.version !== 'string') {
|
||||
return { error: 'plugin.json "version" must be a string.' };
|
||||
}
|
||||
const apiVersion = value.apiVersion === undefined ? 1 : value.apiVersion;
|
||||
if (typeof apiVersion !== 'number' || !Number.isInteger(apiVersion) || apiVersion < 1) {
|
||||
return { error: 'plugin.json "apiVersion" must be a positive integer.' };
|
||||
}
|
||||
if (apiVersion !== PLUGIN_API_VERSION) {
|
||||
return {
|
||||
error: `Plugin requires API ${apiVersion}; this SubMiner supports API ${PLUGIN_API_VERSION}.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
manifest: {
|
||||
name: typeof value.name === 'string' && value.name.trim() ? value.name.trim() : fallbackName,
|
||||
version: typeof value.version === 'string' ? value.version : null,
|
||||
apiVersion,
|
||||
main: value.main.trim(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Resolves a plugin file (entry, window HTML, preload), rejecting paths that leave the plugin directory. */
|
||||
export function resolvePluginFilePath(pluginDir: string, file: string): string | null {
|
||||
const resolved = path.resolve(pluginDir, file);
|
||||
const relative = path.relative(pluginDir, resolved);
|
||||
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
|
||||
return null;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { PluginMediaSnapshot } from './types';
|
||||
|
||||
/** Keeps plugin snapshots coherent without asynchronous property reads crossing file changes. */
|
||||
export function createPluginMediaState(onChange: (media: PluginMediaSnapshot | null) => void) {
|
||||
let nextId = 0;
|
||||
let current: PluginMediaSnapshot | null = null;
|
||||
let waitingForLoad = false;
|
||||
|
||||
function publish(media: PluginMediaSnapshot | null): void {
|
||||
current = media && Object.freeze(media);
|
||||
onChange(current);
|
||||
}
|
||||
|
||||
function start(path: string, title: string | null = null): void {
|
||||
publish({ playbackId: ++nextId, path, title });
|
||||
}
|
||||
|
||||
return {
|
||||
current: () => current,
|
||||
reset(path = '', title: string | null = null): void {
|
||||
waitingForLoad = false;
|
||||
if (path) start(path, title);
|
||||
else if (current) publish(null);
|
||||
},
|
||||
pathChanged(path: string): void {
|
||||
if (!path) {
|
||||
this.reset();
|
||||
} else if (path !== current?.path) {
|
||||
waitingForLoad = true;
|
||||
start(path);
|
||||
}
|
||||
},
|
||||
titleChanged(title: string | null): void {
|
||||
if (current && title !== current.title) publish({ ...current, title });
|
||||
},
|
||||
fileLoaded(path: string, title: string | null): void {
|
||||
if (!path) return;
|
||||
if (waitingForLoad && current?.path === path) {
|
||||
this.titleChanged(title);
|
||||
} else {
|
||||
start(path, title);
|
||||
}
|
||||
waitingForLoad = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,791 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
import type { BrowserWindow } from 'electron';
|
||||
|
||||
import type { SessionActionDispatchRequest } from '../../../types/runtime';
|
||||
import { createPluginHost, type PluginHostDeps } from './plugin-host';
|
||||
import type {
|
||||
PluginConfigEntry,
|
||||
PluginContext,
|
||||
PluginLogger,
|
||||
PluginMpvEventName,
|
||||
PluginMpvEventMap,
|
||||
PluginWindowRequest,
|
||||
} from './types';
|
||||
|
||||
function writePlugin(root: string, id: string, files: Record<string, string>): void {
|
||||
const dir = path.join(root, id);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
writeFileSync(path.join(dir, name), content);
|
||||
}
|
||||
}
|
||||
|
||||
type FakeWindow = ReturnType<typeof createFakeWindow>;
|
||||
|
||||
/** The slice of BrowserWindow the host touches: destroy, isDestroyed, and the `closed` event. */
|
||||
function createFakeWindow() {
|
||||
const events = new EventEmitter();
|
||||
const fake = {
|
||||
destroyed: false,
|
||||
isDestroyed: () => fake.destroyed,
|
||||
destroy: () => {
|
||||
fake.destroyed = true;
|
||||
events.emit('closed');
|
||||
},
|
||||
once: (event: string, listener: () => void) => events.once(event, listener),
|
||||
asWindow: () => fake as unknown as BrowserWindow,
|
||||
};
|
||||
return fake;
|
||||
}
|
||||
|
||||
function createHarness(
|
||||
config: Record<string, PluginConfigEntry>,
|
||||
overrides: Partial<PluginHostDeps<{ marker: string }>> = {},
|
||||
) {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'subminer-plugins-'));
|
||||
const errors: string[] = [];
|
||||
const notifications: string[] = [];
|
||||
const sessionActions: SessionActionDispatchRequest[] = [];
|
||||
const windowRequests: PluginWindowRequest[] = [];
|
||||
const windows = new Map<string, FakeWindow>();
|
||||
const logger: PluginLogger = {
|
||||
debug: () => {},
|
||||
info: () => {},
|
||||
warn: () => {},
|
||||
error: (message) => errors.push(message),
|
||||
};
|
||||
const deps: PluginHostDeps<{ marker: string }> = {
|
||||
pluginsDir: path.join(root, 'plugins'),
|
||||
pluginDataDir: path.join(root, 'data'),
|
||||
getPluginConfig: () => config,
|
||||
createLogger: () => logger,
|
||||
isMpvConnected: () => true,
|
||||
sendMpvCommand: () => {},
|
||||
requestMpvProperty: async () => null,
|
||||
requestMpvCommand: async () => null,
|
||||
ensureMpvRunning: async () => true,
|
||||
invokeAnkiConnect: async () => null,
|
||||
dispatchSessionAction: async (request) => {
|
||||
sessionActions.push(request);
|
||||
},
|
||||
getCurrentSubtitle: () => null,
|
||||
getSubtitleContext: () => ({ current: null, before: [], after: [] }),
|
||||
notify: (message) => notifications.push(message),
|
||||
openPanel: () => {
|
||||
throw new Error('not used');
|
||||
},
|
||||
openWindow: (request) => {
|
||||
windowRequests.push(request);
|
||||
const existing = windows.get(request.key);
|
||||
if (existing && !existing.destroyed) return { window: existing.asWindow(), created: false };
|
||||
const window = createFakeWindow();
|
||||
windows.set(request.key, window);
|
||||
return { window: window.asWindow(), created: true };
|
||||
},
|
||||
unstable: { marker: 'internals' },
|
||||
...overrides,
|
||||
};
|
||||
return {
|
||||
root: deps.pluginsDir,
|
||||
dataRoot: deps.pluginDataDir,
|
||||
errors,
|
||||
notifications,
|
||||
sessionActions,
|
||||
windowRequests,
|
||||
windows,
|
||||
host: createPluginHost(deps),
|
||||
cleanup: () => rmSync(root, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
|
||||
const enabled = (settings: Record<string, unknown> = {}): PluginConfigEntry => ({
|
||||
enabled: true,
|
||||
settings,
|
||||
});
|
||||
|
||||
function deferred() {
|
||||
let resolve = () => {};
|
||||
const promise = new Promise<void>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve: () => resolve() };
|
||||
}
|
||||
|
||||
function createFakeMpvClient() {
|
||||
const bus = new EventEmitter();
|
||||
return {
|
||||
on: <E extends PluginMpvEventName>(
|
||||
event: E,
|
||||
listener: (payload: PluginMpvEventMap[E]) => void,
|
||||
) => bus.on(event, listener),
|
||||
off: <E extends PluginMpvEventName>(
|
||||
event: E,
|
||||
listener: (payload: PluginMpvEventMap[E]) => void,
|
||||
) => bus.off(event, listener),
|
||||
emit: <E extends PluginMpvEventName>(event: E, payload: PluginMpvEventMap[E]) =>
|
||||
bus.emit(event, payload),
|
||||
};
|
||||
}
|
||||
|
||||
test('loads enabled plugins and runs their registered actions', async () => {
|
||||
const h = createHarness({
|
||||
greeter: enabled({ greeting: 'hi' }),
|
||||
off: { enabled: false, settings: {} },
|
||||
});
|
||||
try {
|
||||
writePlugin(h.root, 'greeter', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.actions.register('say', () => ctx.notify(ctx.settings.greeting + ' ' + ctx.unstable.marker));
|
||||
};`,
|
||||
});
|
||||
writePlugin(h.root, 'off', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `throw new Error('disabled plugins must not load');`,
|
||||
});
|
||||
|
||||
await h.host.loadAll();
|
||||
|
||||
assert.equal(await h.host.runAction('greeter/say'), true);
|
||||
assert.deepEqual(h.notifications, ['hi internals']);
|
||||
assert.equal(await h.host.runAction('greeter/missing'), false);
|
||||
assert.deepEqual(h.errors, []);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('loads ES module plugins', async () => {
|
||||
const h = createHarness({ esm: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'esm', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.mjs' }),
|
||||
'main.mjs': `export function activate(ctx) { ctx.actions.register('go', () => ctx.notify('esm')); }`,
|
||||
});
|
||||
|
||||
await h.host.loadAll();
|
||||
|
||||
assert.equal(await h.host.runAction('esm/go'), true);
|
||||
assert.deepEqual(h.notifications, ['esm']);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a failed activation rolls back its registrations without affecting other plugins', async () => {
|
||||
const h = createHarness({ broken: enabled(), healthy: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'broken', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.actions.register('half', () => {});
|
||||
throw new Error('boom');
|
||||
};`,
|
||||
});
|
||||
writePlugin(h.root, 'healthy', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => { ctx.actions.register('ok', () => {}); };`,
|
||||
});
|
||||
|
||||
await h.host.loadAll();
|
||||
|
||||
assert.equal(await h.host.runAction('broken/half'), false);
|
||||
assert.equal(await h.host.runAction('healthy/ok'), true);
|
||||
assert.deepEqual(h.errors, ['Activation failed: boom']);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects entry files outside the plugin directory', async () => {
|
||||
const h = createHarness({ escape: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'escape', {
|
||||
'plugin.json': JSON.stringify({ main: '../elsewhere.cjs' }),
|
||||
});
|
||||
|
||||
await h.host.loadAll();
|
||||
|
||||
assert.equal(h.errors.length, 1);
|
||||
assert.match(h.errors[0]!, /must stay inside/);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('mpv listener errors are contained and unload detaches listeners and calls deactivate', async () => {
|
||||
const h = createHarness({ watcher: enabled() });
|
||||
const client = createFakeMpvClient();
|
||||
try {
|
||||
writePlugin(h.root, 'watcher', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.mpv.on('pause-change', ({ paused }) => {
|
||||
ctx.notify('paused=' + paused);
|
||||
throw new Error('listener bug');
|
||||
});
|
||||
return () => ctx.notify('deactivated');
|
||||
};`,
|
||||
});
|
||||
h.host.attachMpvClient(client);
|
||||
await h.host.loadAll();
|
||||
|
||||
client.emit('pause-change', { paused: true });
|
||||
assert.deepEqual(h.notifications, ['paused=true']);
|
||||
assert.deepEqual(h.errors, ['mpv pause-change listener failed: listener bug']);
|
||||
|
||||
await h.host.unloadAll();
|
||||
client.emit('pause-change', { paused: false });
|
||||
assert.deepEqual(h.notifications, ['paused=true', 'deactivated']);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('unload gives up on a deactivate that never settles and still disposes the plugin', async () => {
|
||||
const h = createHarness({ stuck: enabled() }, { deactivateTimeoutMs: 20 });
|
||||
const client = createFakeMpvClient();
|
||||
try {
|
||||
writePlugin(h.root, 'stuck', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.mpv.on('pause-change', () => ctx.notify('still listening'));
|
||||
return () => new Promise(() => {});
|
||||
};`,
|
||||
});
|
||||
h.host.attachMpvClient(client);
|
||||
await h.host.loadAll();
|
||||
|
||||
await h.host.unloadAll();
|
||||
client.emit('pause-change', { paused: true });
|
||||
|
||||
assert.deepEqual(h.notifications, []);
|
||||
// Deactivate gets what is left of the shared unload budget, so the reported ms can be below 20.
|
||||
assert.equal(h.errors.length, 1);
|
||||
assert.match(h.errors[0]!, /^deactivate failed: timed out after \d+ ms$/);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('events follow a replacement mpv client', async () => {
|
||||
const h = createHarness({ watcher: enabled() });
|
||||
const first = createFakeMpvClient();
|
||||
const second = createFakeMpvClient();
|
||||
try {
|
||||
writePlugin(h.root, 'watcher', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.mpv.on('media-path-change', ({ path }) => ctx.notify(path));
|
||||
};`,
|
||||
});
|
||||
h.host.attachMpvClient(first);
|
||||
await h.host.loadAll();
|
||||
h.host.attachMpvClient(second);
|
||||
|
||||
first.emit('media-path-change', { path: 'stale.mkv' });
|
||||
second.emit('media-path-change', { path: 'current.mkv' });
|
||||
|
||||
assert.deepEqual(h.notifications, ['current.mkv']);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('unload skips modules whose manifest is still being read and prevents later loads', async () => {
|
||||
const h = createHarness({ late: enabled() });
|
||||
const client = createFakeMpvClient();
|
||||
try {
|
||||
writePlugin(h.root, 'late', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `throw new Error('module must not execute after unload starts');`,
|
||||
});
|
||||
h.host.attachMpvClient(client);
|
||||
|
||||
// The plugin is still reading its manifest when unload starts.
|
||||
const loading = h.host.loadAll();
|
||||
await h.host.unloadAll();
|
||||
await loading;
|
||||
await h.host.loadAll();
|
||||
client.emit('pause-change', { paused: true });
|
||||
|
||||
assert.deepEqual(h.notifications, []);
|
||||
assert.deepEqual(h.errors, []);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a plugin that finishes activating after unload gave up unloads itself', async () => {
|
||||
const started = deferred();
|
||||
const resume = deferred();
|
||||
const cleaned = deferred();
|
||||
let deactivated = 0;
|
||||
const h = createHarness(
|
||||
{ slow: enabled() },
|
||||
{
|
||||
deactivateTimeoutMs: 20,
|
||||
loadModule: () => ({
|
||||
activate: async (ctx) => {
|
||||
started.resolve();
|
||||
await resume.promise;
|
||||
ctx.mpv.on('pause-change', () => ctx.notify('still listening'));
|
||||
return async () => {
|
||||
deactivated++;
|
||||
await Promise.resolve();
|
||||
cleaned.resolve();
|
||||
};
|
||||
},
|
||||
}),
|
||||
},
|
||||
);
|
||||
const client = createFakeMpvClient();
|
||||
try {
|
||||
writePlugin(h.root, 'slow', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
});
|
||||
h.host.attachMpvClient(client);
|
||||
|
||||
const loading = h.host.loadAll();
|
||||
await started.promise;
|
||||
await h.host.unloadAll();
|
||||
resume.resolve();
|
||||
await loading;
|
||||
await cleaned.promise;
|
||||
await h.host.unloadAll();
|
||||
client.emit('pause-change', { paused: true });
|
||||
|
||||
assert.equal(deactivated, 1);
|
||||
assert.deepEqual(h.notifications, []);
|
||||
assert.deepEqual(h.errors, []);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('unload awaits asynchronous cleanup once when activation finishes during unload', async () => {
|
||||
const started = deferred();
|
||||
const resume = deferred();
|
||||
const deactivating = deferred();
|
||||
const finish = deferred();
|
||||
let deactivated = 0;
|
||||
const h = createHarness(
|
||||
{ slow: enabled() },
|
||||
{
|
||||
loadModule: () => ({
|
||||
activate: async (ctx) => {
|
||||
started.resolve();
|
||||
await resume.promise;
|
||||
return async () => {
|
||||
deactivated++;
|
||||
deactivating.resolve();
|
||||
await finish.promise;
|
||||
await ctx.anki.invoke('sync');
|
||||
ctx.notify('cleaned');
|
||||
};
|
||||
},
|
||||
}),
|
||||
},
|
||||
);
|
||||
try {
|
||||
writePlugin(h.root, 'slow', { 'plugin.json': '{"main":"main.cjs"}' });
|
||||
const loading = h.host.loadAll();
|
||||
await started.promise;
|
||||
let unloaded = false;
|
||||
const unloading = Promise.all([h.host.unloadAll(), h.host.unloadAll()]).then(() => {
|
||||
unloaded = true;
|
||||
});
|
||||
resume.resolve();
|
||||
await deactivating.promise;
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(unloaded, false);
|
||||
assert.equal(deactivated, 1);
|
||||
finish.resolve();
|
||||
await unloading;
|
||||
await loading;
|
||||
assert.deepEqual(h.notifications, ['cleaned']);
|
||||
assert.deepEqual(h.errors, []);
|
||||
} finally {
|
||||
finish.resolve();
|
||||
resume.resolve();
|
||||
await h.host.unloadAll();
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a timed-out plugin cannot call app APIs after disposal', async () => {
|
||||
let context: PluginContext | undefined;
|
||||
const calls: string[] = [];
|
||||
const h = createHarness(
|
||||
{ stuck: enabled() },
|
||||
{
|
||||
activateTimeoutMs: 10,
|
||||
loadModule: () => ({
|
||||
activate: (ctx) => {
|
||||
context = ctx;
|
||||
return new Promise(() => {});
|
||||
},
|
||||
}),
|
||||
sendMpvCommand: () => {
|
||||
calls.push('command');
|
||||
},
|
||||
requestMpvCommand: async () => {
|
||||
calls.push('request');
|
||||
},
|
||||
requestMpvProperty: async () => {
|
||||
calls.push('property');
|
||||
},
|
||||
ensureMpvRunning: async () => {
|
||||
calls.push('start');
|
||||
return true;
|
||||
},
|
||||
invokeAnkiConnect: async () => {
|
||||
calls.push('anki');
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
writePlugin(h.root, 'stuck', { 'plugin.json': '{"main":"main.cjs"}' });
|
||||
await h.host.loadAll();
|
||||
assert.ok(context);
|
||||
const ctx = context;
|
||||
assert.equal(ctx.signal.aborted, true);
|
||||
assert.throws(() => ctx.mpv.command(['stop']), /disposed/);
|
||||
assert.throws(() => ctx.notify('late'), /disposed/);
|
||||
await assert.rejects(ctx.mpv.request(['stop']), /disposed/);
|
||||
await assert.rejects(ctx.mpv.getProperty('path'), /disposed/);
|
||||
await assert.rejects(ctx.mpv.ensureRunning(), /disposed/);
|
||||
await assert.rejects(ctx.anki.invoke('sync'), /disposed/);
|
||||
await assert.rejects(ctx.actions.run('openJimaku'), /disposed/);
|
||||
assert.deepEqual(calls, []);
|
||||
assert.deepEqual(h.notifications, []);
|
||||
assert.deepEqual(h.sessionActions, []);
|
||||
} finally {
|
||||
await h.host.unloadAll();
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('runAction waits for a load that is still in progress', async () => {
|
||||
const h = createHarness({ slow: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'slow', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = async (ctx) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
ctx.actions.register('go', () => ctx.notify('went'));
|
||||
};`,
|
||||
});
|
||||
|
||||
void h.host.loadAll();
|
||||
|
||||
assert.equal(await h.host.runAction('slow/go'), true);
|
||||
assert.deepEqual(h.notifications, ['went']);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a stuck activation cannot block another plugin and times out its own registrations', async () => {
|
||||
const h = createHarness({ stuck: enabled(), healthy: enabled() }, { activateTimeoutMs: 30 });
|
||||
try {
|
||||
writePlugin(h.root, 'stuck', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.actions.register('go', () => ctx.notify('stuck ran'));
|
||||
return new Promise(() => {});
|
||||
};`,
|
||||
});
|
||||
writePlugin(h.root, 'healthy', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => ctx.actions.register('go', () => ctx.notify('healthy ran'));`,
|
||||
});
|
||||
const loading = h.host.loadAll();
|
||||
assert.equal(await h.host.runAction('healthy/go'), true);
|
||||
assert.deepEqual(h.notifications, ['healthy ran']);
|
||||
assert.deepEqual(h.errors, []);
|
||||
await loading;
|
||||
assert.equal(await h.host.runAction('stuck/go'), false);
|
||||
assert.match(h.errors[0]!, /timed out/);
|
||||
} finally {
|
||||
await h.host.unloadAll();
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('lifetime aborts before deactivate and disposes early and late registrations once', async () => {
|
||||
const events: string[] = [];
|
||||
const h = createHarness(
|
||||
{ lifetime: enabled() },
|
||||
{
|
||||
loadModule: () => ({
|
||||
activate: (ctx) => {
|
||||
const dispose = ctx.onDispose(() => events.push('early'));
|
||||
dispose();
|
||||
dispose();
|
||||
ctx.onDispose(() => events.push('cleanup'));
|
||||
ctx.signal.addEventListener('abort', () => events.push('aborted'));
|
||||
return () => {
|
||||
events.push('deactivate aborted=' + ctx.signal.aborted);
|
||||
ctx.onDispose(() => events.push('late cleanup'));
|
||||
ctx.after(0, () => events.push('leaked timer'));
|
||||
ctx.actions.register('late', () => events.push('leaked action'));
|
||||
};
|
||||
},
|
||||
}),
|
||||
},
|
||||
);
|
||||
try {
|
||||
writePlugin(h.root, 'lifetime', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
});
|
||||
await h.host.loadAll();
|
||||
await h.host.unloadAll();
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
assert.equal(await h.host.runAction('lifetime/late'), false);
|
||||
assert.deepEqual(events, [
|
||||
'early',
|
||||
'aborted',
|
||||
'deactivate aborted=true',
|
||||
'late cleanup',
|
||||
'cleanup',
|
||||
]);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('media subscriptions replay the initial state and follow repeated loads and disconnects', async () => {
|
||||
const h = createHarness({ media: enabled() });
|
||||
const client = createFakeMpvClient();
|
||||
try {
|
||||
writePlugin(h.root, 'media', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.media.on('change', (media) => ctx.notify(JSON.stringify(media)));
|
||||
};`,
|
||||
});
|
||||
h.host.attachMpvClient(client);
|
||||
client.emit('media-path-change', { path: 'episode.mkv' });
|
||||
client.emit('media-title-change', { title: 'Episode 1' });
|
||||
await h.host.loadAll();
|
||||
const first = h.host.getMediaSnapshot();
|
||||
assert.ok(first);
|
||||
assert.deepEqual(h.notifications, [JSON.stringify(first)]);
|
||||
client.emit('file-loaded', undefined);
|
||||
client.emit('file-loaded', undefined);
|
||||
assert.notEqual(h.host.getMediaSnapshot()?.playbackId, first.playbackId);
|
||||
assert.equal(first.title, 'Episode 1');
|
||||
client.emit('media-path-change', { path: 'next.mkv' });
|
||||
assert.equal(h.host.getMediaSnapshot()?.title, null);
|
||||
client.emit('connection-change', { connected: false });
|
||||
assert.equal(h.host.getMediaSnapshot(), null);
|
||||
await h.host.unloadAll();
|
||||
const count = h.notifications.length;
|
||||
client.emit('media-path-change', { path: 'later.mkv' });
|
||||
assert.equal(h.notifications.length, count);
|
||||
} finally {
|
||||
await h.host.unloadAll();
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('incompatible API versions are rejected before the entry module executes', async () => {
|
||||
const h = createHarness({ future: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'future', {
|
||||
'plugin.json': JSON.stringify({ apiVersion: 999, main: 'main.cjs' }),
|
||||
'main.cjs': `throw new Error('should never execute');`,
|
||||
});
|
||||
await h.host.loadAll();
|
||||
assert.match(h.errors[0]!, /requires API 999/);
|
||||
assert.equal(h.errors.length, 1);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a malformed manifest version cannot prevent compatible plugins from loading', async () => {
|
||||
const h = createHarness({ bad: enabled(), good: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'bad', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs', apiVersion: { toString: null } }),
|
||||
'main.cjs': `throw new Error('should never execute');`,
|
||||
});
|
||||
writePlugin(h.root, 'good', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs', apiVersion: 1 }),
|
||||
'main.cjs': `exports.activate = (ctx) => { ctx.actions.register('go', () => ctx.notify('good')); };`,
|
||||
});
|
||||
await h.host.loadAll();
|
||||
assert.equal(await h.host.runAction('good/go'), true);
|
||||
assert.deepEqual(h.notifications, ['good']);
|
||||
assert.deepEqual(h.errors, ['plugin.json "apiVersion" must be a positive integer.']);
|
||||
} finally {
|
||||
await h.host.unloadAll();
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('episode-tags uses mining provenance for a kept note older than this playback', async () => {
|
||||
const calls: unknown[] = [];
|
||||
const h = createHarness(
|
||||
{ tags: enabled() },
|
||||
{
|
||||
invokeAnkiConnect: async (action, params) => {
|
||||
calls.push({ action, params });
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
writePlugin(h.root, 'tags', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs', apiVersion: 1 }),
|
||||
'main.cjs': `module.exports = require(${JSON.stringify(path.resolve(__dirname, '../../../../assets/plugins/episode-tags/main.js'))});`,
|
||||
});
|
||||
await h.host.loadAll();
|
||||
h.host.emitAnkiEvent('card-mined', {
|
||||
noteIds: [7],
|
||||
notes: [
|
||||
{
|
||||
originalNoteId: 1234,
|
||||
noteId: 7,
|
||||
provenance: {
|
||||
minedAt: 1234,
|
||||
media: { playbackId: 1, path: 'Show - 02.mkv', title: null },
|
||||
subtitle: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.deepEqual(calls, [
|
||||
{ action: 'addTags', params: { notes: [7], tags: 'show::Show::E02' } },
|
||||
]);
|
||||
} finally {
|
||||
await h.host.unloadAll();
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('each plugin gets its own data folder, created before activate', async () => {
|
||||
const h = createHarness({ keeper: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'keeper', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `const fs = require('node:fs');
|
||||
exports.activate = (ctx) => {
|
||||
fs.writeFileSync(require('node:path').join(ctx.dataDir, 'state.json'), '{}');
|
||||
ctx.notify(ctx.dataDir);
|
||||
};`,
|
||||
});
|
||||
|
||||
await h.host.loadAll();
|
||||
|
||||
const expected = path.join(h.dataRoot, 'keeper');
|
||||
assert.deepEqual(h.notifications, [expected]);
|
||||
assert.equal(existsSync(path.join(expected, 'state.json')), true);
|
||||
assert.deepEqual(h.errors, []);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('anki card-mined reaches listeners until unload, and invoke forwards to AnkiConnect', async () => {
|
||||
const invoked: unknown[][] = [];
|
||||
const h = createHarness(
|
||||
{ syncer: enabled() },
|
||||
{
|
||||
invokeAnkiConnect: async (...args) => {
|
||||
invoked.push(args);
|
||||
return 'synced';
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
writePlugin(h.root, 'syncer', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.anki.on('card-mined', async ({ noteIds }) => {
|
||||
ctx.notify(noteIds.join(',') + ' ' + (await ctx.anki.invoke('sync', undefined, { timeoutMs: 5 })));
|
||||
});
|
||||
};`,
|
||||
});
|
||||
await h.host.loadAll();
|
||||
|
||||
h.host.emitAnkiEvent('card-mined', { noteIds: [1, 2], notes: [] });
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.deepEqual(h.notifications, ['1,2 synced']);
|
||||
assert.deepEqual(invoked, [['sync', {}, { timeoutMs: 5 }]]);
|
||||
|
||||
await h.host.unloadAll();
|
||||
h.host.emitAnkiEvent('card-mined', { noteIds: [3], notes: [] });
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(h.notifications.length, 1);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('actions.run forwards built-in session actions', async () => {
|
||||
const h = createHarness({ caller: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'caller', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = async (ctx) => {
|
||||
await ctx.actions.run('openJimaku');
|
||||
await ctx.actions.run('cycleRuntimeOption', { runtimeOptionId: 'x', direction: -1 });
|
||||
};`,
|
||||
});
|
||||
|
||||
await h.host.loadAll();
|
||||
|
||||
assert.deepEqual(h.sessionActions, [
|
||||
{ actionId: 'openJimaku' },
|
||||
{ actionId: 'cycleRuntimeOption', payload: { runtimeOptionId: 'x', direction: -1 } },
|
||||
]);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('openWindow resolves plugin files, reuses open windows, and closes them on unload', async () => {
|
||||
const h = createHarness({ viewer: enabled() });
|
||||
try {
|
||||
writePlugin(h.root, 'viewer', {
|
||||
'plugin.json': JSON.stringify({ main: 'main.cjs' }),
|
||||
'main.cjs': `exports.activate = (ctx) => {
|
||||
ctx.actions.register('open', () => ctx.ui.openWindow({ html: 'ui/index.html', preload: 'preload.js', width: 400 }));
|
||||
ctx.actions.register('escape', () => ctx.ui.openWindow({ html: '../other/index.html' }));
|
||||
};`,
|
||||
});
|
||||
await h.host.loadAll();
|
||||
|
||||
await h.host.runAction('viewer/open');
|
||||
await h.host.runAction('viewer/open');
|
||||
const dir = path.join(h.root, 'viewer');
|
||||
assert.deepEqual(h.windowRequests[0], {
|
||||
key: `viewer:${path.join(dir, 'ui', 'index.html')}`,
|
||||
htmlPath: path.join(dir, 'ui', 'index.html'),
|
||||
preloadPath: path.join(dir, 'preload.js'),
|
||||
title: 'viewer',
|
||||
width: 400,
|
||||
height: 720,
|
||||
});
|
||||
assert.equal(h.windows.size, 1);
|
||||
|
||||
await h.host.runAction('viewer/escape');
|
||||
assert.equal(h.windowRequests.length, 2);
|
||||
assert.match(h.errors[0] ?? '', /must stay inside/);
|
||||
|
||||
const [window] = [...h.windows.values()];
|
||||
await h.host.unloadAll();
|
||||
assert.equal(window?.destroyed, true);
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,568 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { promises as fs } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import type { BrowserWindow } from 'electron';
|
||||
|
||||
import type { SessionActionDispatchRequest } from '../../../types/runtime';
|
||||
import { execPluginCommand } from './exec';
|
||||
import { isValidPluginName, parsePluginManifest, resolvePluginFilePath } from './manifest';
|
||||
import { createPluginMediaState } from './media-state';
|
||||
import {
|
||||
PLUGIN_API_VERSION,
|
||||
PLUGIN_MPV_EVENT_NAMES,
|
||||
type PluginAnkiEventMap,
|
||||
type PluginAnkiEventName,
|
||||
type PluginAnkiInvokeOptions,
|
||||
type PluginConfigEntry,
|
||||
type PluginContext,
|
||||
type PluginLogger,
|
||||
type PluginModule,
|
||||
type PluginMpvEventName,
|
||||
type PluginMpvEventMap,
|
||||
type PluginNotifyVariant,
|
||||
type PluginPanelContent,
|
||||
type PluginPanelHandle,
|
||||
type PluginSubtitleContext,
|
||||
type PluginSubtitleLine,
|
||||
type PluginWindowRequest,
|
||||
} from './types';
|
||||
|
||||
const MIN_TIMER_INTERVAL_MS = 100;
|
||||
const DEFAULT_WINDOW_WIDTH = 960;
|
||||
const DEFAULT_WINDOW_HEIGHT = 720;
|
||||
/**
|
||||
* Quit waits for unloadAll, so a load or deactivate that never settles must not hold the app open.
|
||||
* The forced-exit fallback in main adds its own budget on top of this.
|
||||
*/
|
||||
export const PLUGIN_DEACTIVATE_TIMEOUT_MS = 2_000;
|
||||
export const PLUGIN_ACTIVATE_TIMEOUT_MS = 10_000;
|
||||
|
||||
interface MpvClientEvents {
|
||||
currentVideoPath?: string;
|
||||
currentMediaTitle?: string | null;
|
||||
on: <E extends PluginMpvEventName>(
|
||||
event: E,
|
||||
listener: (payload: PluginMpvEventMap[E]) => void,
|
||||
) => void;
|
||||
off: <E extends PluginMpvEventName>(
|
||||
event: E,
|
||||
listener: (payload: PluginMpvEventMap[E]) => void,
|
||||
) => void;
|
||||
}
|
||||
|
||||
export interface PluginHostDeps<TUnstable> {
|
||||
pluginsDir: string;
|
||||
/** Root of the per-plugin data folders; each plugin gets `<pluginDataDir>/<id>`. */
|
||||
pluginDataDir: string;
|
||||
getPluginConfig: () => Record<string, PluginConfigEntry>;
|
||||
createLogger: (scope: string) => PluginLogger;
|
||||
isMpvConnected: () => boolean;
|
||||
sendMpvCommand: (command: (string | number)[]) => void;
|
||||
requestMpvProperty: (name: string) => Promise<unknown>;
|
||||
requestMpvCommand: (command: (string | number | boolean)[]) => Promise<unknown>;
|
||||
ensureMpvRunning: () => Promise<boolean>;
|
||||
invokeAnkiConnect: (
|
||||
action: string,
|
||||
params: Record<string, unknown>,
|
||||
options: PluginAnkiInvokeOptions,
|
||||
) => Promise<unknown>;
|
||||
dispatchSessionAction: (request: SessionActionDispatchRequest) => Promise<void>;
|
||||
getCurrentSubtitle: () => PluginSubtitleLine | null;
|
||||
getSubtitleContext: (options: { before?: number; after?: number }) => PluginSubtitleContext;
|
||||
notify: (message: string, variant: PluginNotifyVariant) => void;
|
||||
openPanel: (content: PluginPanelContent) => PluginPanelHandle;
|
||||
/** Focuses the window already open under `request.key`, or creates it (`created: true`). */
|
||||
openWindow: (request: PluginWindowRequest) => { window: BrowserWindow; created: boolean };
|
||||
unstable: TUnstable;
|
||||
/** Test seam; defaults to Node's `require`, which also loads synchronous ES modules. */
|
||||
loadModule?: (entryPath: string) => PluginModule;
|
||||
exec?: typeof execPluginCommand;
|
||||
/** How long unload waits, in total, for loading and deactivate before disposing anyway. */
|
||||
deactivateTimeoutMs?: number;
|
||||
/** Async activation is bounded; synchronous plugin code still shares the main thread. */
|
||||
activateTimeoutMs?: number;
|
||||
}
|
||||
|
||||
interface LoadedPlugin {
|
||||
id: string;
|
||||
disposers: Set<() => void>;
|
||||
deactivate: (() => unknown) | null;
|
||||
deactivation: Promise<void> | null;
|
||||
disposed: boolean;
|
||||
/** Aborted on unload so in-flight `exec` children die with the plugin. */
|
||||
lifetime: AbortController;
|
||||
}
|
||||
|
||||
/** Resolves when `promise` settles, or rejects once `timeoutMs` passes first. */
|
||||
async function settleWithin<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
promise,
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
typeof (value as { then?: unknown }).then === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
function pickExport<K extends 'activate' | 'deactivate'>(
|
||||
mod: PluginModule,
|
||||
key: K,
|
||||
): NonNullable<PluginModule[K]> | null {
|
||||
const direct = mod[key];
|
||||
if (typeof direct === 'function') return direct as NonNullable<PluginModule[K]>;
|
||||
const fromDefault = mod.default?.[key];
|
||||
return typeof fromDefault === 'function' ? (fromDefault as NonNullable<PluginModule[K]>) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads enabled plugins from `<pluginsDir>/<id>/plugin.json` and gives each one a scoped context.
|
||||
* Every plugin callback runs behind a guard, so a throwing plugin logs instead of breaking the app.
|
||||
* Plugins run in the main process: a synchronous busy loop still blocks it.
|
||||
*/
|
||||
export function createPluginHost<TUnstable>(deps: PluginHostDeps<TUnstable>) {
|
||||
const mpvEvents = new EventEmitter();
|
||||
mpvEvents.setMaxListeners(0);
|
||||
const ankiEvents = new EventEmitter();
|
||||
ankiEvents.setMaxListeners(0);
|
||||
const mediaEvents = new EventEmitter();
|
||||
mediaEvents.setMaxListeners(0);
|
||||
const media = createPluginMediaState((snapshot) => mediaEvents.emit('change', snapshot));
|
||||
const plugins = new Map<string, LoadedPlugin>();
|
||||
const actions = new Map<string, { pluginId: string; handler: () => unknown }>();
|
||||
const loadModule = deps.loadModule ?? ((entryPath: string) => require(entryPath) as PluginModule);
|
||||
const exec = deps.exec ?? execPluginCommand;
|
||||
let detachClient: (() => void) | null = null;
|
||||
let loadPromise: Promise<void> | null = null;
|
||||
const pluginLoads = new Map<string, Promise<void>>();
|
||||
let unloading = false;
|
||||
|
||||
function runGuarded(log: PluginLogger, label: string, callback: () => unknown): void {
|
||||
try {
|
||||
const result = callback();
|
||||
if (isPromiseLike(result)) {
|
||||
Promise.resolve(result).catch((error) =>
|
||||
log.error(`${label} failed: ${errorMessage(error)}`),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
log.error(`${label} failed: ${errorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function createContext(
|
||||
plugin: LoadedPlugin,
|
||||
dir: string,
|
||||
dataDir: string,
|
||||
entry: PluginConfigEntry,
|
||||
log: PluginLogger,
|
||||
): PluginContext<TUnstable> {
|
||||
const assertActive = (): void => {
|
||||
if (plugin.disposed) throw new Error(`Plugin "${plugin.id}" has been disposed.`);
|
||||
};
|
||||
const track = (dispose: () => void): (() => void) => {
|
||||
let disposed = false;
|
||||
const disposer = (): void => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
plugin.disposers.delete(disposer);
|
||||
dispose();
|
||||
};
|
||||
if (plugin.lifetime.signal.aborted) disposer();
|
||||
else plugin.disposers.add(disposer);
|
||||
return disposer;
|
||||
};
|
||||
|
||||
return {
|
||||
apiVersion: PLUGIN_API_VERSION,
|
||||
id: plugin.id,
|
||||
signal: plugin.lifetime.signal,
|
||||
onDispose: (dispose) => track(() => runGuarded(log, 'Cleanup', dispose)),
|
||||
dir,
|
||||
settings: Object.freeze({ ...entry.settings }),
|
||||
dataDir,
|
||||
log,
|
||||
every: (intervalMs, callback) => {
|
||||
const handle = setInterval(
|
||||
() => runGuarded(log, 'Timer', callback),
|
||||
Math.max(MIN_TIMER_INTERVAL_MS, intervalMs),
|
||||
);
|
||||
return track(() => clearInterval(handle));
|
||||
},
|
||||
after: (delayMs, callback) => {
|
||||
const handle = setTimeout(
|
||||
() => {
|
||||
dispose();
|
||||
runGuarded(log, 'Timer', callback);
|
||||
},
|
||||
Math.max(0, delayMs),
|
||||
);
|
||||
const dispose = track(() => clearTimeout(handle));
|
||||
return dispose;
|
||||
},
|
||||
mpv: {
|
||||
get connected() {
|
||||
return deps.isMpvConnected();
|
||||
},
|
||||
on: (event, listener) => {
|
||||
const wrapped = (payload: unknown): void =>
|
||||
runGuarded(log, `mpv ${event} listener`, () =>
|
||||
listener(payload as Parameters<typeof listener>[0]),
|
||||
);
|
||||
mpvEvents.on(event, wrapped);
|
||||
return track(() => mpvEvents.off(event, wrapped));
|
||||
},
|
||||
command: (command) => {
|
||||
assertActive();
|
||||
deps.sendMpvCommand(command);
|
||||
},
|
||||
request: async (command) => {
|
||||
assertActive();
|
||||
return deps.requestMpvCommand(command);
|
||||
},
|
||||
getProperty: async (name) => {
|
||||
assertActive();
|
||||
return deps.requestMpvProperty(name);
|
||||
},
|
||||
ensureRunning: async () => {
|
||||
assertActive();
|
||||
return deps.ensureMpvRunning();
|
||||
},
|
||||
},
|
||||
media: {
|
||||
current: () => media.current(),
|
||||
on: (event, listener, options) => {
|
||||
if (event !== 'change') throw new Error(`Unknown media event "${event}".`);
|
||||
const wrapped = (snapshot: ReturnType<typeof media.current>): void =>
|
||||
runGuarded(log, 'media change listener', () => listener(snapshot));
|
||||
mediaEvents.on('change', wrapped);
|
||||
const dispose = track(() => mediaEvents.off('change', wrapped));
|
||||
if (!plugin.lifetime.signal.aborted && options?.emitCurrent !== false) {
|
||||
wrapped(media.current());
|
||||
}
|
||||
return dispose;
|
||||
},
|
||||
},
|
||||
anki: {
|
||||
on: (event, listener) => {
|
||||
const wrapped = (payload: unknown): void =>
|
||||
runGuarded(log, `anki ${event} listener`, () =>
|
||||
listener(payload as Parameters<typeof listener>[0]),
|
||||
);
|
||||
ankiEvents.on(event, wrapped);
|
||||
return track(() => ankiEvents.off(event, wrapped));
|
||||
},
|
||||
invoke: async (action, params = {}, options = {}) => {
|
||||
assertActive();
|
||||
return deps.invokeAnkiConnect(action, params, options);
|
||||
},
|
||||
},
|
||||
subtitles: {
|
||||
current: () => deps.getCurrentSubtitle(),
|
||||
context: (options = {}) => deps.getSubtitleContext(options),
|
||||
},
|
||||
actions: {
|
||||
register: (name, handler) => {
|
||||
if (!isValidPluginName(name)) {
|
||||
throw new Error(`Invalid action name "${name}"; use letters, digits, ".", "_" or "-".`);
|
||||
}
|
||||
const actionId = `${plugin.id}/${name}`;
|
||||
if (actions.has(actionId)) {
|
||||
throw new Error(`Action "${actionId}" is already registered.`);
|
||||
}
|
||||
actions.set(actionId, { pluginId: plugin.id, handler });
|
||||
return track(() => actions.delete(actionId));
|
||||
},
|
||||
run: async (actionId, payload) => {
|
||||
assertActive();
|
||||
return deps.dispatchSessionAction(
|
||||
payload === undefined ? { actionId } : { actionId, payload },
|
||||
);
|
||||
},
|
||||
},
|
||||
notify: (message, options) => {
|
||||
assertActive();
|
||||
deps.notify(message, options?.variant ?? 'info');
|
||||
},
|
||||
ui: {
|
||||
panel: (content) => {
|
||||
plugin.lifetime.signal.throwIfAborted();
|
||||
const handle = deps.openPanel({
|
||||
title: content.title ?? plugin.id,
|
||||
markdown: content.markdown,
|
||||
});
|
||||
const dispose = track(() => handle.close());
|
||||
handle.signal.addEventListener('abort', dispose, { once: true });
|
||||
return handle;
|
||||
},
|
||||
openWindow: (options) => {
|
||||
plugin.lifetime.signal.throwIfAborted();
|
||||
const resolveFile = (label: string, file: string): string => {
|
||||
const resolved = resolvePluginFilePath(dir, file);
|
||||
if (!resolved) throw new Error(`Window ${label} "${file}" must stay inside ${dir}.`);
|
||||
return resolved;
|
||||
};
|
||||
const htmlPath = resolveFile('html', options.html);
|
||||
const { window, created } = deps.openWindow({
|
||||
key: `${plugin.id}:${htmlPath}`,
|
||||
htmlPath,
|
||||
preloadPath:
|
||||
options.preload === undefined ? null : resolveFile('preload', options.preload),
|
||||
title: options.title ?? plugin.id,
|
||||
width: options.width ?? DEFAULT_WINDOW_WIDTH,
|
||||
height: options.height ?? DEFAULT_WINDOW_HEIGHT,
|
||||
});
|
||||
if (created) {
|
||||
let closed = false;
|
||||
const dispose = track(() => {
|
||||
if (!closed && !window.isDestroyed()) window.destroy();
|
||||
});
|
||||
window.once('closed', () => {
|
||||
closed = true;
|
||||
dispose();
|
||||
});
|
||||
}
|
||||
return window;
|
||||
},
|
||||
},
|
||||
exec: (command, args, options = {}) =>
|
||||
exec(command, args, {
|
||||
...options,
|
||||
signal: options.signal
|
||||
? AbortSignal.any([options.signal, plugin.lifetime.signal])
|
||||
: plugin.lifetime.signal,
|
||||
}),
|
||||
unstable: deps.unstable,
|
||||
};
|
||||
}
|
||||
|
||||
function disposePlugin(plugin: LoadedPlugin): void {
|
||||
if (plugin.disposed) return;
|
||||
plugin.disposed = true;
|
||||
plugin.lifetime.abort();
|
||||
for (const dispose of [...plugin.disposers]) {
|
||||
try {
|
||||
dispose();
|
||||
} catch {
|
||||
// A failing disposer must not keep the rest registered.
|
||||
}
|
||||
}
|
||||
plugins.delete(plugin.id);
|
||||
}
|
||||
|
||||
/** Shares one bounded deactivate call between unload and an activation that finishes late. */
|
||||
function finishPlugin(
|
||||
plugin: LoadedPlugin,
|
||||
timeoutMs = deps.deactivateTimeoutMs ?? PLUGIN_DEACTIVATE_TIMEOUT_MS,
|
||||
): Promise<void> {
|
||||
if (plugin.deactivation) return plugin.deactivation;
|
||||
if (!plugin.deactivate) {
|
||||
disposePlugin(plugin);
|
||||
return Promise.resolve();
|
||||
}
|
||||
plugin.deactivation = (async () => {
|
||||
try {
|
||||
await settleWithin(
|
||||
Promise.resolve().then(() => plugin.deactivate?.()),
|
||||
timeoutMs,
|
||||
);
|
||||
} catch (error) {
|
||||
deps.createLogger(`plugin:${plugin.id}`).error(`deactivate failed: ${errorMessage(error)}`);
|
||||
} finally {
|
||||
disposePlugin(plugin);
|
||||
}
|
||||
})();
|
||||
return plugin.deactivation;
|
||||
}
|
||||
|
||||
async function loadPlugin(id: string, entry: PluginConfigEntry): Promise<void> {
|
||||
const log = deps.createLogger(`plugin:${id}`);
|
||||
if (!isValidPluginName(id)) {
|
||||
log.error(`Invalid plugin id "${id}"; use letters, digits, ".", "_" or "-".`);
|
||||
return;
|
||||
}
|
||||
|
||||
const dir = path.join(deps.pluginsDir, id);
|
||||
let rawManifest: unknown;
|
||||
try {
|
||||
rawManifest = JSON.parse(await fs.readFile(path.join(dir, 'plugin.json'), 'utf8'));
|
||||
} catch (error) {
|
||||
log.error(`Cannot read ${path.join(dir, 'plugin.json')}: ${errorMessage(error)}`);
|
||||
return;
|
||||
}
|
||||
const parsed = parsePluginManifest(rawManifest, id);
|
||||
if ('error' in parsed) {
|
||||
log.error(parsed.error);
|
||||
return;
|
||||
}
|
||||
const entryPath = resolvePluginFilePath(dir, parsed.manifest.main);
|
||||
if (!entryPath) {
|
||||
log.error(`Entry "${parsed.manifest.main}" must stay inside ${dir}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const dataDir = path.join(deps.pluginDataDir, id);
|
||||
try {
|
||||
await fs.mkdir(dataDir, { recursive: true });
|
||||
} catch (error) {
|
||||
log.error(`Cannot create data folder ${dataDir}: ${errorMessage(error)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (unloading) return;
|
||||
const plugin: LoadedPlugin = {
|
||||
id,
|
||||
disposers: new Set(),
|
||||
deactivate: null,
|
||||
deactivation: null,
|
||||
disposed: false,
|
||||
lifetime: new AbortController(),
|
||||
};
|
||||
plugins.set(id, plugin);
|
||||
try {
|
||||
const mod = loadModule(entryPath);
|
||||
const activate = pickExport(mod, 'activate');
|
||||
if (!activate) {
|
||||
throw new Error(`${parsed.manifest.main} does not export an activate(ctx) function.`);
|
||||
}
|
||||
const activation = Promise.resolve(
|
||||
activate(createContext(plugin, dir, dataDir, entry, log)),
|
||||
).then((returned) => {
|
||||
plugin.deactivate =
|
||||
typeof returned === 'function'
|
||||
? (returned as () => unknown)
|
||||
: pickExport(mod, 'deactivate');
|
||||
// Unload owns cleanup while it is waiting for activation. A timed-out plugin owns it later.
|
||||
if (plugin.disposed) void finishPlugin(plugin);
|
||||
});
|
||||
await settleWithin(activation, deps.activateTimeoutMs ?? PLUGIN_ACTIVATE_TIMEOUT_MS);
|
||||
if (plugin.lifetime.signal.aborted) return;
|
||||
const version = parsed.manifest.version ? ` v${parsed.manifest.version}` : '';
|
||||
log.info(`Loaded ${parsed.manifest.name}${version}.`);
|
||||
} catch (error) {
|
||||
log.error(`Activation failed: ${errorMessage(error)}`);
|
||||
disposePlugin(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getMediaSnapshot: () => media.current(),
|
||||
/** Forwards the client's events to plugin listeners, replacing any previously attached client. */
|
||||
attachMpvClient(client: MpvClientEvents): void {
|
||||
detachClient?.();
|
||||
const disposers: Array<() => void> = [];
|
||||
const listen = <E extends PluginMpvEventName>(
|
||||
event: E,
|
||||
listener: (payload: PluginMpvEventMap[E]) => void,
|
||||
): void => {
|
||||
client.on(event, listener);
|
||||
disposers.push(() => client.off(event, listener));
|
||||
};
|
||||
listen('media-path-change', ({ path }) => media.pathChanged(path));
|
||||
listen('media-title-change', ({ title }) => media.titleChanged(title));
|
||||
listen('file-loaded', () =>
|
||||
media.fileLoaded(
|
||||
client.currentVideoPath ?? media.current()?.path ?? '',
|
||||
client.currentMediaTitle === undefined
|
||||
? (media.current()?.title ?? null)
|
||||
: client.currentMediaTitle,
|
||||
),
|
||||
);
|
||||
listen('end-file', () => media.reset());
|
||||
listen('connection-change', ({ connected }) => {
|
||||
if (!connected) media.reset();
|
||||
});
|
||||
for (const event of PLUGIN_MPV_EVENT_NAMES) {
|
||||
listen(event, (payload) => {
|
||||
mpvEvents.emit(event, payload);
|
||||
});
|
||||
}
|
||||
detachClient = () => {
|
||||
for (const dispose of disposers) dispose();
|
||||
};
|
||||
media.reset(client.currentVideoPath, client.currentMediaTitle);
|
||||
},
|
||||
|
||||
/** Delivers an Anki event to every plugin listening for it. */
|
||||
emitAnkiEvent<E extends PluginAnkiEventName>(event: E, payload: PluginAnkiEventMap[E]): void {
|
||||
ankiEvents.emit(event, payload);
|
||||
},
|
||||
|
||||
/** Loads every enabled plugin once; later calls return the first load. */
|
||||
loadAll(): Promise<void> {
|
||||
if (unloading) return Promise.resolve();
|
||||
loadPromise ??= Promise.all(
|
||||
Object.entries(deps.getPluginConfig())
|
||||
.filter(([, entry]) => entry.enabled)
|
||||
.map(([id, entry]) => {
|
||||
const loading = loadPlugin(id, entry);
|
||||
pluginLoads.set(id, loading);
|
||||
return loading;
|
||||
}),
|
||||
).then(() => undefined);
|
||||
return loadPromise;
|
||||
},
|
||||
|
||||
async unloadAll(): Promise<void> {
|
||||
unloading = true;
|
||||
for (const plugin of plugins.values()) plugin.lifetime.abort();
|
||||
// One budget covers the load wait and every deactivate, so quit is bounded by it.
|
||||
const timeoutMs = deps.deactivateTimeoutMs ?? PLUGIN_DEACTIVATE_TIMEOUT_MS;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
// Plugins still reading their files are not in `plugins` yet; let the load finish first.
|
||||
if (loadPromise) {
|
||||
try {
|
||||
await settleWithin(loadPromise, timeoutMs);
|
||||
} catch (error) {
|
||||
deps
|
||||
.createLogger('plugins')
|
||||
.warn(`Unloading before load finished: ${errorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
loadPromise = null;
|
||||
await Promise.all(
|
||||
[...plugins.values()].map((plugin) =>
|
||||
finishPlugin(plugin, Math.max(0, deadline - Date.now())),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Runs a registered `<plugin id>/<name>` action, waiting for an in-progress load first so a
|
||||
* command sent at startup is not lost. Resolves false when no plugin registered the action.
|
||||
*/
|
||||
async runAction(actionId: string): Promise<boolean> {
|
||||
const separator = actionId.indexOf('/');
|
||||
if (separator < 1) return false;
|
||||
const pluginId = actionId.slice(0, separator);
|
||||
await pluginLoads.get(pluginId);
|
||||
if (unloading) return false;
|
||||
const action = actions.get(actionId);
|
||||
if (!action) return false;
|
||||
runGuarded(
|
||||
deps.createLogger(`plugin:${action.pluginId}`),
|
||||
`Action ${actionId}`,
|
||||
action.handler,
|
||||
);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type PluginHost = ReturnType<typeof createPluginHost>;
|
||||
@@ -0,0 +1,63 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { buildPluginSubtitleContext } from './subtitle-context';
|
||||
|
||||
const cues = [
|
||||
{ text: '一', startTime: 1, endTime: 2 },
|
||||
{ text: 'はい', startTime: 3, endTime: 4 },
|
||||
{ text: '二', startTime: 5, endTime: 6 },
|
||||
{ text: '三', startTime: 7, endTime: 8 },
|
||||
{ text: 'はい', startTime: 9, endTime: 10 },
|
||||
{ text: '四', startTime: 11, endTime: 12 },
|
||||
];
|
||||
|
||||
test('returns neighbors of the matching cue, preferring the one nearest the live timing', () => {
|
||||
// Live timing is shifted by a +1.5 s sub-delay, so it sits outside both はい cues.
|
||||
const context = buildPluginSubtitleContext({
|
||||
cues,
|
||||
current: { text: 'はい', startTime: 10.5, endTime: 11.5 },
|
||||
recentLines: [],
|
||||
before: 2,
|
||||
after: 1,
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
context.before.map((line) => line.text),
|
||||
['二', '三'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
context.after.map((line) => line.text),
|
||||
['四'],
|
||||
);
|
||||
});
|
||||
|
||||
test('falls back to recently displayed lines when the line is not in the cue list', () => {
|
||||
const context = buildPluginSubtitleContext({
|
||||
cues: [],
|
||||
current: { text: '今', startTime: 20, endTime: 21 },
|
||||
recentLines: [
|
||||
{ text: '前の前', startTime: 16, endTime: 17 },
|
||||
{ text: '前', startTime: 18, endTime: 19 },
|
||||
{ text: '今', startTime: 20, endTime: 21 },
|
||||
],
|
||||
before: 2,
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
context.before.map((line) => line.text),
|
||||
['前の前', '前'],
|
||||
);
|
||||
assert.deepEqual(context.after, []);
|
||||
});
|
||||
|
||||
test('returns an empty context when no subtitle is displayed', () => {
|
||||
assert.deepEqual(
|
||||
buildPluginSubtitleContext({
|
||||
cues,
|
||||
current: { text: ' ', startTime: null, endTime: null },
|
||||
recentLines: [],
|
||||
}),
|
||||
{ current: null, before: [], after: [] },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { PluginSubtitleContext, PluginSubtitleLine } from './types';
|
||||
|
||||
interface CueLike {
|
||||
text: string;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
}
|
||||
|
||||
const MAX_CONTEXT_LINES = 20;
|
||||
|
||||
function normalizeText(text: string): string {
|
||||
return text.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
function clampCount(value: number | undefined, fallback: number): number {
|
||||
if (value === undefined || !Number.isFinite(value)) return fallback;
|
||||
return Math.min(MAX_CONTEXT_LINES, Math.max(0, Math.floor(value)));
|
||||
}
|
||||
|
||||
function toLine(cue: CueLike): PluginSubtitleLine {
|
||||
return { text: cue.text.trim(), startTime: cue.startTime, endTime: cue.endTime };
|
||||
}
|
||||
|
||||
/**
|
||||
* Locates the displayed line in the parsed cue list. Text decides, timing breaks ties: mpv's live
|
||||
* timing can be shifted by sub-delay, so the same text nearest the reported start wins.
|
||||
*/
|
||||
function findCurrentCueIndex(cues: readonly CueLike[], current: PluginSubtitleLine): number {
|
||||
const target = normalizeText(current.text);
|
||||
const anchor = current.startTime;
|
||||
let best = -1;
|
||||
let bestDistance = Number.POSITIVE_INFINITY;
|
||||
cues.forEach((cue, index) => {
|
||||
if (normalizeText(cue.text) !== target) return;
|
||||
const distance = anchor === null ? 0 : Math.abs(cue.startTime - anchor);
|
||||
if (distance < bestDistance) {
|
||||
best = index;
|
||||
bestDistance = distance;
|
||||
}
|
||||
});
|
||||
if (best >= 0 || anchor === null) return best;
|
||||
return cues.findIndex((cue) => anchor >= cue.startTime && anchor < cue.endTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the current line plus neighbors. Uses the parsed subtitle file when one is loaded and
|
||||
* falls back to recently displayed lines (no `after` context) for streams without a cue list.
|
||||
*/
|
||||
export function buildPluginSubtitleContext(input: {
|
||||
cues: readonly CueLike[];
|
||||
current: PluginSubtitleLine | null;
|
||||
recentLines: readonly PluginSubtitleLine[];
|
||||
before?: number;
|
||||
after?: number;
|
||||
}): PluginSubtitleContext {
|
||||
const beforeCount = clampCount(input.before, 2);
|
||||
const afterCount = clampCount(input.after, 1);
|
||||
const current = input.current && normalizeText(input.current.text) ? input.current : null;
|
||||
if (!current) return { current: null, before: [], after: [] };
|
||||
|
||||
const cues = input.cues
|
||||
.filter((cue) => normalizeText(cue.text).length > 0)
|
||||
.slice()
|
||||
.sort((a, b) => a.startTime - b.startTime || a.endTime - b.endTime);
|
||||
const index = findCurrentCueIndex(cues, current);
|
||||
if (index >= 0) {
|
||||
return {
|
||||
current,
|
||||
before: cues.slice(Math.max(0, index - beforeCount), index).map(toLine),
|
||||
after: cues.slice(index + 1, index + 1 + afterCount).map(toLine),
|
||||
};
|
||||
}
|
||||
|
||||
const target = normalizeText(current.text);
|
||||
const recent = input.recentLines.filter((line) => normalizeText(line.text).length > 0);
|
||||
// The tracker usually already holds the current line as its newest entry.
|
||||
const history =
|
||||
recent.length > 0 && normalizeText(recent[recent.length - 1]!.text) === target
|
||||
? recent.slice(0, -1)
|
||||
: recent;
|
||||
return {
|
||||
current,
|
||||
before: beforeCount > 0 ? history.slice(-beforeCount) : [],
|
||||
after: [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { PluginMpvEventName } from '../../../plugin-api';
|
||||
export type * from '../../../plugin-api';
|
||||
|
||||
export const PLUGIN_API_VERSION = 1;
|
||||
|
||||
/** `plugin.json` at the root of a plugin directory. */
|
||||
export interface PluginManifest {
|
||||
/** Display name; defaults to the directory name. */
|
||||
name: string;
|
||||
version: string | null;
|
||||
/** Omitted by older plugins, which use API v1. */
|
||||
apiVersion: number;
|
||||
/** Entry module, relative to the plugin directory. */
|
||||
main: string;
|
||||
}
|
||||
|
||||
/** One `plugins.<id>` entry from config. */
|
||||
export interface PluginConfigEntry {
|
||||
enabled: boolean;
|
||||
settings: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const pluginMpvEvents = {
|
||||
'connection-change': true,
|
||||
'subtitle-change': true,
|
||||
'subtitle-timing': true,
|
||||
'time-pos-change': true,
|
||||
'duration-change': true,
|
||||
'pause-change': true,
|
||||
'fullscreen-change': true,
|
||||
'secondary-subtitle-change': true,
|
||||
'subtitle-track-change': true,
|
||||
'secondary-subtitle-track-change': true,
|
||||
'secondary-subtitle-delay-change': true,
|
||||
'subtitle-track-list-change': true,
|
||||
'media-path-change': true,
|
||||
'media-title-change': true,
|
||||
'secondary-subtitle-visibility': true,
|
||||
'client-message': true,
|
||||
'file-loaded': true,
|
||||
'end-file': true,
|
||||
} satisfies Record<PluginMpvEventName, true>;
|
||||
|
||||
export const PLUGIN_MPV_EVENT_NAMES = Object.keys(pluginMpvEvents) as PluginMpvEventName[];
|
||||
|
||||
/** What the host needs to show a plugin window; paths are absolute and already validated. */
|
||||
export interface PluginWindowRequest {
|
||||
/** Same key, same window: reopening focuses the existing one. */
|
||||
key: string;
|
||||
htmlPath: string;
|
||||
preloadPath: string | null;
|
||||
title: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
@@ -55,6 +55,10 @@ function createDeps(overrides: Partial<SessionActionExecutorDeps> = {}) {
|
||||
playNextSubtitle: () => calls.push('play-next'),
|
||||
cycleRuntimeOption: () => ({ ok: true }),
|
||||
playNextPlaylistItem: () => calls.push('playlist-next'),
|
||||
runPluginAction: async (pluginActionId) => {
|
||||
calls.push(`plugin:${pluginActionId}`);
|
||||
return pluginActionId === 'ai-explain/explain';
|
||||
},
|
||||
showMpvOsd: (text) => calls.push(`osd:${text}`),
|
||||
...overrides,
|
||||
};
|
||||
@@ -81,3 +85,22 @@ test('dispatchSessionAction does not advance playlist when mark watched no-ops',
|
||||
|
||||
assert.deepEqual(calls, ['mark-watched']);
|
||||
});
|
||||
|
||||
test('dispatchSessionAction runs plugin actions and reports unregistered ones', async () => {
|
||||
const { calls, deps } = createDeps();
|
||||
|
||||
await dispatchSessionAction(
|
||||
{ actionId: 'runPluginAction', payload: { pluginActionId: 'ai-explain/explain' } },
|
||||
deps,
|
||||
);
|
||||
await dispatchSessionAction(
|
||||
{ actionId: 'runPluginAction', payload: { pluginActionId: 'ai-explain/missing' } },
|
||||
deps,
|
||||
);
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
'plugin:ai-explain/explain',
|
||||
'plugin:ai-explain/missing',
|
||||
'osd:Plugin action not available: ai-explain/missing',
|
||||
]);
|
||||
});
|
||||
@@ -32,6 +32,8 @@ export interface SessionActionExecutorDeps {
|
||||
playNextSubtitle: () => void;
|
||||
cycleRuntimeOption: (id: RuntimeOptionId, direction: 1 | -1) => RuntimeOptionApplyResult;
|
||||
playNextPlaylistItem: () => void;
|
||||
/** Returns false when no loaded plugin registered the action. */
|
||||
runPluginAction: (pluginActionId: string) => Promise<boolean>;
|
||||
showMpvOsd: (text: string) => void;
|
||||
}
|
||||
|
||||
@@ -151,6 +153,13 @@ export async function dispatchSessionAction(
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'runPluginAction': {
|
||||
const pluginActionId = request.payload?.pluginActionId;
|
||||
if (!pluginActionId || !(await deps.runPluginAction(pluginActionId))) {
|
||||
deps.showMpvOsd(`Plugin action not available: ${pluginActionId ?? 'unknown'}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
default:
|
||||
return assertUnreachableSessionAction(request.actionId);
|
||||
}
|
||||
|
||||
@@ -323,6 +323,31 @@ test('compileSessionBindings maps the legacy Animetosho command to the TsukiHime
|
||||
);
|
||||
});
|
||||
|
||||
test('compileSessionBindings maps plugin action commands to a validated session action', () => {
|
||||
const result = compileSessionBindings({
|
||||
shortcuts: createShortcuts(),
|
||||
keybindings: [
|
||||
createKeybinding('Ctrl+E', [`${SPECIAL_COMMANDS.PLUGIN_ACTION_PREFIX}ai-explain/explain`]),
|
||||
createKeybinding('Ctrl+R', [`${SPECIAL_COMMANDS.PLUGIN_ACTION_PREFIX}no-action-name`]),
|
||||
],
|
||||
platform: 'linux',
|
||||
});
|
||||
|
||||
const binding = result.bindings[0];
|
||||
assert.equal(result.bindings.length, 1);
|
||||
assert.ok(binding?.actionType === 'session-action');
|
||||
assert.equal(binding.actionId, 'runPluginAction');
|
||||
assert.deepEqual(binding.payload, { pluginActionId: 'ai-explain/explain' });
|
||||
assert.deepEqual(
|
||||
parseSessionActionDispatchRequest({ actionId: binding.actionId, payload: binding.payload }),
|
||||
{ actionId: 'runPluginAction', payload: { pluginActionId: 'ai-explain/explain' } },
|
||||
);
|
||||
assert.deepEqual(
|
||||
result.warnings.map((warning) => `${warning.kind}:${warning.path}`),
|
||||
['unsupported:keybindings[1].command'],
|
||||
);
|
||||
});
|
||||
|
||||
test('compileSessionBindings leaves retired subtitle-delay shift tokens as mpv commands', () => {
|
||||
const result = compileSessionBindings({
|
||||
shortcuts: createShortcuts(),
|
||||
|
||||
@@ -342,6 +342,16 @@ function resolveCommandBinding(
|
||||
if (command.length !== 1) return null;
|
||||
return { actionType: 'session-action', actionId: 'playNextSubtitle' };
|
||||
}
|
||||
if (first.startsWith(SPECIAL_COMMANDS.PLUGIN_ACTION_PREFIX)) {
|
||||
const pluginActionId = first.slice(SPECIAL_COMMANDS.PLUGIN_ACTION_PREFIX.length);
|
||||
const [pluginId, actionName, ...rest] = pluginActionId.split('/');
|
||||
if (command.length !== 1 || !pluginId || !actionName || rest.length > 0) return null;
|
||||
return {
|
||||
actionType: 'session-action',
|
||||
actionId: 'runPluginAction',
|
||||
payload: { pluginActionId },
|
||||
};
|
||||
}
|
||||
if (first.startsWith(SPECIAL_COMMANDS.RUNTIME_OPTION_CYCLE_PREFIX)) {
|
||||
if (command.length !== 1) {
|
||||
return null;
|
||||
|
||||
@@ -117,6 +117,8 @@ export interface AppReadyRuntimeDeps {
|
||||
loadSubtitlePosition: () => void;
|
||||
resolveKeybindings: () => void;
|
||||
createMpvClient: () => void;
|
||||
/** Loads enabled plugins; full startup only. */
|
||||
startPlugins?: () => void;
|
||||
reloadConfig: () => void;
|
||||
getResolvedConfig: () => AppReadyConfigLike;
|
||||
getConfigWarnings: () => ConfigValidationWarning[];
|
||||
@@ -310,6 +312,7 @@ export async function runAppReadyRuntime(deps: AppReadyRuntimeDeps): Promise<voi
|
||||
deps.createMpvClient();
|
||||
deps.initRuntimeOptionsManager();
|
||||
deps.setSecondarySubMode(config.secondarySub?.defaultMode ?? deps.defaultSecondarySubMode);
|
||||
deps.startPlugins?.();
|
||||
|
||||
const wsConfig = config.websocket || {};
|
||||
const wsEnabled = wsConfig.enabled ?? 'auto';
|
||||
|
||||
@@ -1,22 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
buildNotifySendEnv,
|
||||
createNotifySendReplacer,
|
||||
resolveDefaultNotificationIconPath,
|
||||
} from './notification';
|
||||
|
||||
test('notify-send child environment drops the AppImage library-path override', () => {
|
||||
const env = buildNotifySendEnv({
|
||||
LD_LIBRARY_PATH: '/tmp/.mount_SubMinXXXXXX/usr/lib',
|
||||
DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus',
|
||||
HOME: '/home/user',
|
||||
});
|
||||
|
||||
assert.equal(env.LD_LIBRARY_PATH, undefined);
|
||||
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, 'unix:path=/run/user/1000/bus');
|
||||
assert.equal(env.HOME, '/home/user');
|
||||
});
|
||||
import { createNotifySendReplacer, resolveDefaultNotificationIconPath } from './notification';
|
||||
|
||||
test('default notification icon resolves packaged SubMiner asset when no per-notification icon is provided', () => {
|
||||
const path = resolveDefaultNotificationIconPath({
|
||||
|
||||
@@ -3,6 +3,7 @@ import electron from 'electron';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { createLogger } from '../../logger';
|
||||
import { buildSystemBinaryEnv } from './system-binary-env';
|
||||
|
||||
const { Notification, nativeImage } = electron;
|
||||
const logger = createLogger('core:notification');
|
||||
@@ -203,19 +204,8 @@ export function createNotifySendReplacer(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Electron AppImages export `LD_LIBRARY_PATH=<mount>/usr/lib`, whose bundled libnotify predates the
|
||||
* symbols the system notify-send links against, so an inherited environment kills the child with a
|
||||
* symbol lookup error before it can send anything. A system binary resolves its own libraries fine,
|
||||
* so the override is dropped entirely rather than filtered.
|
||||
*/
|
||||
export function buildNotifySendEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
|
||||
const { LD_LIBRARY_PATH: _dropped, ...rest } = env;
|
||||
return rest;
|
||||
}
|
||||
|
||||
const showLinuxReplaceableNotification = createNotifySendReplacer((args, callback) =>
|
||||
execFile('notify-send', args, { timeout: 5_000, env: buildNotifySendEnv() }, (error, stdout) =>
|
||||
execFile('notify-send', args, { timeout: 5_000, env: buildSystemBinaryEnv() }, (error, stdout) =>
|
||||
callback(error, stdout ?? ''),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { buildSystemBinaryEnv } from './system-binary-env';
|
||||
|
||||
test('system binary environment drops the AppImage library-path override', () => {
|
||||
const env = buildSystemBinaryEnv({
|
||||
LD_LIBRARY_PATH: '/tmp/.mount_SubMinXXXXXX/usr/lib',
|
||||
DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus',
|
||||
HOME: '/home/user',
|
||||
});
|
||||
|
||||
assert.equal(env.LD_LIBRARY_PATH, undefined);
|
||||
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, 'unix:path=/run/user/1000/bus');
|
||||
assert.equal(env.HOME, '/home/user');
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Electron AppImages export `LD_LIBRARY_PATH=<mount>/usr/lib`, whose bundled libraries (libnotify and
|
||||
* friends) predate the symbols system binaries link against, so an inherited environment can kill a
|
||||
* spawned child with a symbol lookup error. A system binary resolves its own libraries fine, so the
|
||||
* override is dropped entirely rather than filtered.
|
||||
*/
|
||||
export function buildSystemBinaryEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
|
||||
const { LD_LIBRARY_PATH: _dropped, ...rest } = env;
|
||||
return rest;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
buildWindowsShimInvocation,
|
||||
isWindowsCommandShim,
|
||||
resolveWindowsCommand,
|
||||
} from './windows-command-shim';
|
||||
|
||||
test('resolves a bare name through PATH and PATHEXT in order', () => {
|
||||
const npmDir = path.join('/fake', 'npm');
|
||||
const binDir = path.join('/fake', 'bin');
|
||||
const existing = new Set([path.join(npmDir, 'codex.CMD'), path.join(binDir, 'codex.EXE')]);
|
||||
const env = { PATH: [npmDir, binDir].join(path.delimiter), PATHEXT: '.EXE;.CMD' };
|
||||
|
||||
assert.equal(
|
||||
resolveWindowsCommand('codex', env, (candidate) => existing.has(candidate)),
|
||||
path.join(npmDir, 'codex.CMD'),
|
||||
);
|
||||
assert.equal(
|
||||
resolveWindowsCommand('codex.exe', env, () => true),
|
||||
'codex.exe',
|
||||
'commands with an extension are left alone',
|
||||
);
|
||||
assert.equal(
|
||||
resolveWindowsCommand('missing', env, () => false),
|
||||
'missing',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolves an extensionless path in its own directory', () => {
|
||||
const shim = path.join('/fake', 'npm', 'codex');
|
||||
assert.equal(
|
||||
resolveWindowsCommand(shim, { PATHEXT: '.CMD' }, (candidate) => candidate === `${shim}.CMD`),
|
||||
`${shim}.CMD`,
|
||||
);
|
||||
});
|
||||
|
||||
test('recognizes batch shims only', () => {
|
||||
assert.equal(isWindowsCommandShim('C:\\npm\\codex.cmd'), true);
|
||||
assert.equal(isWindowsCommandShim('run.BAT'), true);
|
||||
assert.equal(isWindowsCommandShim('codex.exe'), false);
|
||||
});
|
||||
|
||||
test('quotes the shim call for cmd.exe', () => {
|
||||
const invocation = buildWindowsShimInvocation(
|
||||
'C:\\npm\\codex.cmd',
|
||||
['-C', 'C:\\Temp dir\\a&b', '-c', 'effort="low"'],
|
||||
{ ComSpec: 'C:\\Windows\\system32\\cmd.exe' },
|
||||
);
|
||||
|
||||
assert.deepEqual(invocation, {
|
||||
file: 'C:\\Windows\\system32\\cmd.exe',
|
||||
args: [
|
||||
'/d',
|
||||
'/s',
|
||||
'/v:off',
|
||||
'/c',
|
||||
'"^"C:\\npm\\codex.cmd^" ^"-C^" ^"C:\\Temp^ dir\\a^&b^" ^"-c^" ^"effort=\\^"low\\^"^""',
|
||||
],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/** True for batch shims (`.cmd`/`.bat`), which Windows only runs through cmd.exe. */
|
||||
export function isWindowsCommandShim(command: string): boolean {
|
||||
return /\.(cmd|bat)$/i.test(command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an extensionless Windows command the way cmd.exe does: each `PATHEXT` extension in
|
||||
* the command's own directory, or in each `PATH` entry for a bare name. Returns `command`
|
||||
* unchanged when it already has an extension or nothing matches.
|
||||
*/
|
||||
export function resolveWindowsCommand(
|
||||
command: string,
|
||||
env: NodeJS.ProcessEnv,
|
||||
existsSync: (candidate: string) => boolean = fs.existsSync,
|
||||
): string {
|
||||
if (path.extname(command)) return command;
|
||||
const directory = path.dirname(command);
|
||||
const directories =
|
||||
directory === '.' ? (env.PATH ?? env.Path ?? '').split(path.delimiter).filter(Boolean) : [''];
|
||||
const extensions = (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
|
||||
for (const entry of directories) {
|
||||
for (const extension of extensions) {
|
||||
const candidate = entry ? path.join(entry, command + extension) : command + extension;
|
||||
if (existsSync(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
/*!
|
||||
* Windows command escaping adapted from cross-spawn 7.0.6.
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
const WINDOWS_SHELL_META_CHARACTERS = /([()\][%!^"`<>&|;, *?])/g;
|
||||
|
||||
// Quote for both cmd.exe and the Windows argv parser. The outer caret escapes
|
||||
// are consumed by cmd, leaving the quoted argument unchanged for the command.
|
||||
function escapeWindowsShellArgument(value: string): string {
|
||||
const quotesEscaped = value
|
||||
.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
|
||||
.replace(/(?=(\\+?)?)\1$/, '$1$1');
|
||||
return `"${quotesEscaped}"`.replace(WINDOWS_SHELL_META_CHARACTERS, '^$1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the cmd.exe invocation that runs a batch shim with `args`. Spawn the result with
|
||||
* `windowsVerbatimArguments: true` so Node does not re-quote the prepared command line.
|
||||
*/
|
||||
export function buildWindowsShimInvocation(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
env: NodeJS.ProcessEnv,
|
||||
): { file: string; args: string[] } {
|
||||
const commandLine = [command, ...args].map(escapeWindowsShellArgument).join(' ');
|
||||
return {
|
||||
file: env.ComSpec ?? env.COMSPEC ?? process.env.ComSpec ?? 'cmd.exe',
|
||||
args: ['/d', '/s', '/v:off', '/c', `"${commandLine}"`],
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@ export type LogLevelSource = 'cli' | 'config';
|
||||
|
||||
type LogMethod = (message: string, ...meta: unknown[]) => void;
|
||||
|
||||
type Logger = {
|
||||
export type Logger = {
|
||||
debug: LogMethod;
|
||||
info: LogMethod;
|
||||
warn: LogMethod;
|
||||
|
||||
+615
-3404
File diff suppressed because it is too large.
Load diff
@@ -24,6 +24,7 @@ export interface AppReadyRuntimeDepsFactoryInput {
|
||||
loadSubtitlePosition: AppReadyRuntimeDeps['loadSubtitlePosition'];
|
||||
resolveKeybindings: AppReadyRuntimeDeps['resolveKeybindings'];
|
||||
createMpvClient: AppReadyRuntimeDeps['createMpvClient'];
|
||||
startPlugins?: AppReadyRuntimeDeps['startPlugins'];
|
||||
reloadConfig: AppReadyRuntimeDeps['reloadConfig'];
|
||||
getResolvedConfig: AppReadyRuntimeDeps['getResolvedConfig'];
|
||||
getConfigWarnings: AppReadyRuntimeDeps['getConfigWarnings'];
|
||||
@@ -94,6 +95,7 @@ export function createAppReadyRuntimeDeps(
|
||||
loadSubtitlePosition: params.loadSubtitlePosition,
|
||||
resolveKeybindings: params.resolveKeybindings,
|
||||
createMpvClient: params.createMpvClient,
|
||||
startPlugins: params.startPlugins,
|
||||
reloadConfig: params.reloadConfig,
|
||||
getResolvedConfig: params.getResolvedConfig,
|
||||
getConfigWarnings: params.getConfigWarnings,
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter';
|
||||
import { createAnilistAssembly, type AnilistAssemblyDeps } from './anilist';
|
||||
|
||||
// Every callback throws, so a test fails if the assembly calls a dep it should only call later.
|
||||
function makeDeps(): AnilistAssemblyDeps {
|
||||
const lazy = (name: string) => (): never => {
|
||||
throw new Error(`${name} called unexpectedly`);
|
||||
};
|
||||
return {
|
||||
appState: {
|
||||
mpvClient: null,
|
||||
currentMediaPath: null,
|
||||
currentMediaTitle: null,
|
||||
anilistClientSecretState: {
|
||||
status: 'not_checked',
|
||||
source: 'none',
|
||||
message: null,
|
||||
resolvedAt: null,
|
||||
errorAt: null,
|
||||
},
|
||||
anilistRetryQueueState: {
|
||||
pending: 0,
|
||||
ready: 0,
|
||||
deadLetter: 0,
|
||||
lastAttemptAt: null,
|
||||
lastError: null,
|
||||
},
|
||||
anilistSetupPageOpened: false,
|
||||
anilistSetupWindow: null,
|
||||
},
|
||||
configService: { getConfig: lazy('getConfig') },
|
||||
logger: { info: lazy('info'), warn: lazy('warn'), debug: lazy('debug'), error: lazy('error') },
|
||||
anilistTokenStore: {
|
||||
saveToken: lazy('saveToken'),
|
||||
loadToken: lazy('loadToken'),
|
||||
clearToken: lazy('clearToken'),
|
||||
},
|
||||
anilistUpdateQueue: {
|
||||
enqueue: lazy('enqueue'),
|
||||
nextReady: lazy('nextReady'),
|
||||
markSuccess: lazy('markSuccess'),
|
||||
markFailure: lazy('markFailure'),
|
||||
getSnapshot: lazy('getSnapshot'),
|
||||
},
|
||||
anilistRateLimiter: createAnilistRateLimiter(),
|
||||
getOverlayNotifications: lazy('getOverlayNotifications'),
|
||||
showDesktopNotification: lazy('showDesktopNotification'),
|
||||
resolveMediaPathForJimaku: lazy('resolveMediaPathForJimaku'),
|
||||
resolvePinnedMediaId: lazy('resolvePinnedMediaId'),
|
||||
createBrowserWindow: lazy('createBrowserWindow'),
|
||||
shell: { openExternal: lazy('openExternal') },
|
||||
app: { setAsDefaultProtocolClient: lazy('setAsDefaultProtocolClient') },
|
||||
};
|
||||
}
|
||||
|
||||
// main.ts builds the assembly before most siblings exist, so construction must stay lazy.
|
||||
test('createAnilistAssembly does not call its deps while constructing', () => {
|
||||
const anilist = createAnilistAssembly(makeDeps());
|
||||
assert.equal(anilist.getMediaDurationSec(), null);
|
||||
});
|
||||
@@ -0,0 +1,527 @@
|
||||
import path from 'node:path';
|
||||
import type { App, BrowserWindow, BrowserWindowConstructorOptions, Shell } from 'electron';
|
||||
import type { ConfigService } from '../../config/service';
|
||||
import type { createAnilistTokenStore } from '../../core/services/anilist/anilist-token-store';
|
||||
import type { createAnilistUpdateQueue } from '../../core/services/anilist/anilist-update-queue';
|
||||
import {
|
||||
guessAnilistMediaInfo,
|
||||
updateAnilistPostWatchProgress,
|
||||
} from '../../core/services/anilist/anilist-updater';
|
||||
import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter';
|
||||
import type { Logger } from '../../logger';
|
||||
import { DEFAULT_MIN_WATCH_RATIO } from '../../shared/watch-threshold';
|
||||
import type { ResolvedConfig } from '../../types';
|
||||
import {
|
||||
isAllowedAnilistExternalUrl,
|
||||
isAllowedAnilistSetupNavigationUrl,
|
||||
} from '../anilist-url-guard';
|
||||
import { composeAnilistSetupHandlers, composeAnilistTrackingHandlers } from '../runtime/composers';
|
||||
import {
|
||||
buildAnilistSetupUrl,
|
||||
consumeAnilistSetupCallbackUrl,
|
||||
createAnilistStateRuntime,
|
||||
createMaybeFocusExistingAnilistSetupWindowHandler,
|
||||
createOpenAnilistSetupWindowHandler,
|
||||
isAnilistTrackingEnabled,
|
||||
loadAnilistManualTokenEntry,
|
||||
openAnilistSetupInBrowser,
|
||||
rememberAnilistAttemptedUpdateKey,
|
||||
} from '../runtime/domains/anilist';
|
||||
import type { createOverlayNotificationsRuntime } from '../runtime/overlay-notifications-runtime';
|
||||
import { createCreateAnilistSetupWindowHandler } from '../runtime/setup-window-factory';
|
||||
import {
|
||||
type AnilistMediaGuessRuntimeState,
|
||||
type AppState,
|
||||
createInitialAnilistMediaGuessRuntimeState,
|
||||
createInitialAnilistUpdateInFlightState,
|
||||
transitionAnilistClientSecretState,
|
||||
transitionAnilistMediaGuessRuntimeState,
|
||||
transitionAnilistRetryQueueLastAttemptAt,
|
||||
transitionAnilistRetryQueueLastError,
|
||||
transitionAnilistRetryQueueState,
|
||||
transitionAnilistUpdateInFlightState,
|
||||
} from '../state';
|
||||
|
||||
const ANILIST_SETUP_CLIENT_ID_URL = 'https://anilist.co/api/v2/oauth/authorize';
|
||||
const ANILIST_SETUP_RESPONSE_TYPE = 'token';
|
||||
const ANILIST_DEFAULT_CLIENT_ID = '36084';
|
||||
const ANILIST_REDIRECT_URI = 'https://anilist.subminer.moe/';
|
||||
const ANILIST_DEVELOPER_SETTINGS_URL = 'https://anilist.co/settings/developer';
|
||||
const ANILIST_UPDATE_MIN_WATCH_SECONDS = 10 * 60;
|
||||
const ANILIST_DURATION_RETRY_INTERVAL_MS = 15_000;
|
||||
const ANILIST_MAX_ATTEMPTED_UPDATE_KEYS = 1000;
|
||||
|
||||
type TrackingComposerOptions = Parameters<typeof composeAnilistTrackingHandlers>[0];
|
||||
|
||||
/**
|
||||
* What the AniList domain needs from the rest of the app. Siblings built after this assembly in
|
||||
* `main.ts` are reached through getters or callbacks, which are only called once the app runs.
|
||||
*/
|
||||
export interface AnilistAssemblyDeps {
|
||||
appState: Pick<
|
||||
AppState,
|
||||
| 'mpvClient'
|
||||
| 'currentMediaPath'
|
||||
| 'currentMediaTitle'
|
||||
| 'anilistClientSecretState'
|
||||
| 'anilistRetryQueueState'
|
||||
| 'anilistSetupPageOpened'
|
||||
| 'anilistSetupWindow'
|
||||
>;
|
||||
configService: Pick<ConfigService, 'getConfig'>;
|
||||
logger: Pick<Logger, 'info' | 'warn' | 'debug' | 'error'>;
|
||||
anilistTokenStore: ReturnType<typeof createAnilistTokenStore>;
|
||||
anilistUpdateQueue: ReturnType<typeof createAnilistUpdateQueue>;
|
||||
/** Shared with the stats cover-art fetcher, so `main.ts` owns it. */
|
||||
anilistRateLimiter: ReturnType<typeof createAnilistRateLimiter>;
|
||||
getOverlayNotifications: () => Pick<
|
||||
ReturnType<typeof createOverlayNotificationsRuntime>,
|
||||
| 'getConfiguredStatusNotificationType'
|
||||
| 'showConfiguredStatusNotification'
|
||||
| 'showOverlayNotification'
|
||||
>;
|
||||
showDesktopNotification: (title: string, options: { body?: string; icon?: string }) => void;
|
||||
resolveMediaPathForJimaku: TrackingComposerOptions['ensureMediaGuessMainDeps']['resolveMediaPathForJimaku'];
|
||||
resolvePinnedMediaId: NonNullable<
|
||||
TrackingComposerOptions['maybeRunPostWatchUpdateMainDeps']['resolvePinnedAnilistMediaId']
|
||||
>;
|
||||
createBrowserWindow: (options: BrowserWindowConstructorOptions) => BrowserWindow;
|
||||
shell: Pick<Shell, 'openExternal'>;
|
||||
app: Pick<App, 'setAsDefaultProtocolClient'>;
|
||||
}
|
||||
|
||||
export type AnilistAssembly = ReturnType<typeof createAnilistAssembly>;
|
||||
|
||||
/**
|
||||
* Owns AniList login/setup, token and client-secret state, media tracking, and post-watch
|
||||
* progress updates with their retry queue. `main.ts` builds it once and calls through the result.
|
||||
*/
|
||||
export function createAnilistAssembly(deps: AnilistAssemblyDeps) {
|
||||
const {
|
||||
appState,
|
||||
configService,
|
||||
logger,
|
||||
anilistTokenStore,
|
||||
anilistUpdateQueue,
|
||||
anilistRateLimiter,
|
||||
} = deps;
|
||||
let anilistMediaGuessRuntimeState: AnilistMediaGuessRuntimeState =
|
||||
createInitialAnilistMediaGuessRuntimeState();
|
||||
let anilistUpdateInFlightState = createInitialAnilistUpdateInFlightState();
|
||||
const anilistAttemptedUpdateKeys = new Set<string>();
|
||||
let anilistCachedAccessToken: string | null = null;
|
||||
|
||||
const anilistStateRuntime = createAnilistStateRuntime({
|
||||
getClientSecretState: () => appState.anilistClientSecretState,
|
||||
setClientSecretState: (next) => {
|
||||
appState.anilistClientSecretState = transitionAnilistClientSecretState(
|
||||
appState.anilistClientSecretState,
|
||||
next,
|
||||
);
|
||||
},
|
||||
getRetryQueueState: () => appState.anilistRetryQueueState,
|
||||
setRetryQueueState: (next) => {
|
||||
appState.anilistRetryQueueState = transitionAnilistRetryQueueState(
|
||||
appState.anilistRetryQueueState,
|
||||
next,
|
||||
);
|
||||
},
|
||||
getUpdateQueueSnapshot: () => anilistUpdateQueue.getSnapshot(),
|
||||
clearStoredToken: () => anilistTokenStore.clearToken(),
|
||||
clearCachedAccessToken: () => {
|
||||
anilistCachedAccessToken = null;
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
notifyAnilistSetup,
|
||||
consumeAnilistSetupTokenFromUrl,
|
||||
handleAnilistSetupProtocolUrl,
|
||||
registerSubminerProtocolClient,
|
||||
} = composeAnilistSetupHandlers({
|
||||
notifyDeps: {
|
||||
getNotificationType: () =>
|
||||
deps.getOverlayNotifications().getConfiguredStatusNotificationType(),
|
||||
hasMpvClient: () => Boolean(appState.mpvClient),
|
||||
showMpvOsd: (message) =>
|
||||
deps
|
||||
.getOverlayNotifications()
|
||||
.showConfiguredStatusNotification(message, { title: 'AniList' }),
|
||||
showOverlayNotification: (payload) =>
|
||||
deps.getOverlayNotifications().showOverlayNotification(payload),
|
||||
showDesktopNotification: (title, options) => deps.showDesktopNotification(title, options),
|
||||
logInfo: (message) => logger.info(message),
|
||||
},
|
||||
consumeTokenDeps: {
|
||||
consumeAnilistSetupCallbackUrl,
|
||||
saveToken: (token) => anilistTokenStore.saveToken(token),
|
||||
setCachedToken: (token) => {
|
||||
anilistCachedAccessToken = token;
|
||||
},
|
||||
setResolvedState: (resolvedAt) => {
|
||||
anilistStateRuntime.setClientSecretState({
|
||||
status: 'resolved',
|
||||
source: 'stored',
|
||||
message: 'saved token from AniList login',
|
||||
resolvedAt,
|
||||
errorAt: null,
|
||||
});
|
||||
},
|
||||
setSetupPageOpened: (opened) => {
|
||||
appState.anilistSetupPageOpened = opened;
|
||||
},
|
||||
onSuccess: () => {
|
||||
notifyAnilistSetup('AniList login success');
|
||||
},
|
||||
closeWindow: () => {
|
||||
if (appState.anilistSetupWindow && !appState.anilistSetupWindow.isDestroyed()) {
|
||||
appState.anilistSetupWindow.close();
|
||||
}
|
||||
},
|
||||
},
|
||||
handleProtocolDeps: {
|
||||
consumeAnilistSetupTokenFromUrl: (rawUrl) => consumeAnilistSetupTokenFromUrl(rawUrl),
|
||||
logWarn: (message, details) => logger.warn(message, details),
|
||||
},
|
||||
registerProtocolClientDeps: {
|
||||
isDefaultApp: () => Boolean(process.defaultApp),
|
||||
getArgv: () => process.argv,
|
||||
execPath: process.execPath,
|
||||
resolvePath: (value) => path.resolve(value),
|
||||
setAsDefaultProtocolClient: (scheme, appPath, args) =>
|
||||
appPath
|
||||
? deps.app.setAsDefaultProtocolClient(scheme, appPath, args)
|
||||
: deps.app.setAsDefaultProtocolClient(scheme),
|
||||
logDebug: (message, details) => logger.debug(message, details),
|
||||
},
|
||||
});
|
||||
|
||||
const maybeFocusExistingAnilistSetupWindow = createMaybeFocusExistingAnilistSetupWindowHandler({
|
||||
getSetupWindow: () => appState.anilistSetupWindow,
|
||||
});
|
||||
const openAnilistSetupWindowHandler = createOpenAnilistSetupWindowHandler({
|
||||
maybeFocusExistingSetupWindow: maybeFocusExistingAnilistSetupWindow,
|
||||
createSetupWindow: createCreateAnilistSetupWindowHandler({
|
||||
createBrowserWindow: (options) => deps.createBrowserWindow(options),
|
||||
}),
|
||||
buildAuthorizeUrl: () =>
|
||||
buildAnilistSetupUrl({
|
||||
authorizeUrl: ANILIST_SETUP_CLIENT_ID_URL,
|
||||
clientId: ANILIST_DEFAULT_CLIENT_ID,
|
||||
responseType: ANILIST_SETUP_RESPONSE_TYPE,
|
||||
}),
|
||||
consumeCallbackUrl: (rawUrl) => consumeAnilistSetupTokenFromUrl(rawUrl),
|
||||
openSetupInBrowser: (authorizeUrl) =>
|
||||
openAnilistSetupInBrowser({
|
||||
authorizeUrl,
|
||||
openExternal: (url) => deps.shell.openExternal(url),
|
||||
logError: (message, error) => logger.error(message, error),
|
||||
}),
|
||||
loadManualTokenEntry: (setupWindow, authorizeUrl) =>
|
||||
loadAnilistManualTokenEntry({
|
||||
setupWindow: setupWindow as BrowserWindow,
|
||||
authorizeUrl,
|
||||
developerSettingsUrl: ANILIST_DEVELOPER_SETTINGS_URL,
|
||||
logWarn: (message, data) => logger.warn(message, data),
|
||||
}),
|
||||
redirectUri: ANILIST_REDIRECT_URI,
|
||||
developerSettingsUrl: ANILIST_DEVELOPER_SETTINGS_URL,
|
||||
isAllowedExternalUrl: (url) => isAllowedAnilistExternalUrl(url),
|
||||
isAllowedNavigationUrl: (url) => isAllowedAnilistSetupNavigationUrl(url),
|
||||
logWarn: (message, details) => logger.warn(message, details),
|
||||
logError: (message, details) => logger.error(message, details),
|
||||
clearSetupWindow: () => {
|
||||
appState.anilistSetupWindow = null;
|
||||
},
|
||||
setSetupPageOpened: (opened) => {
|
||||
appState.anilistSetupPageOpened = opened;
|
||||
},
|
||||
setSetupWindow: (setupWindow) => {
|
||||
appState.anilistSetupWindow = setupWindow as BrowserWindow;
|
||||
},
|
||||
openExternal: (url) => {
|
||||
void deps.shell.openExternal(url);
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
refreshAnilistClientSecretState,
|
||||
getCurrentAnilistMediaKey,
|
||||
resetAnilistMediaTracking,
|
||||
getAnilistMediaGuessRuntimeState,
|
||||
setAnilistMediaGuessRuntimeState,
|
||||
recordAnilistMediaDuration,
|
||||
resetAnilistMediaGuessState,
|
||||
maybeProbeAnilistDuration,
|
||||
ensureAnilistMediaGuess,
|
||||
processNextAnilistRetryUpdate,
|
||||
maybeRunAnilistPostWatchUpdate,
|
||||
} = composeAnilistTrackingHandlers({
|
||||
refreshClientSecretMainDeps: {
|
||||
getResolvedConfig: () => configService.getConfig(),
|
||||
isAnilistTrackingEnabled: (config) => isAnilistTrackingEnabled(config as ResolvedConfig),
|
||||
getCachedAccessToken: () => anilistCachedAccessToken,
|
||||
setCachedAccessToken: (token) => {
|
||||
anilistCachedAccessToken = token;
|
||||
},
|
||||
saveStoredToken: (token) => {
|
||||
anilistTokenStore.saveToken(token);
|
||||
},
|
||||
loadStoredToken: () => anilistTokenStore.loadToken(),
|
||||
setClientSecretState: (state) => {
|
||||
anilistStateRuntime.setClientSecretState(state);
|
||||
},
|
||||
getAnilistSetupPageOpened: () => appState.anilistSetupPageOpened,
|
||||
setAnilistSetupPageOpened: (opened) => {
|
||||
appState.anilistSetupPageOpened = opened;
|
||||
},
|
||||
openAnilistSetupWindow: () => {
|
||||
openAnilistSetupWindowHandler();
|
||||
},
|
||||
now: () => Date.now(),
|
||||
},
|
||||
getCurrentMediaKeyMainDeps: {
|
||||
getCurrentMediaPath: () => appState.currentMediaPath,
|
||||
},
|
||||
resetMediaTrackingMainDeps: {
|
||||
setMediaKey: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaKey: value },
|
||||
);
|
||||
},
|
||||
setMediaDurationSec: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaDurationSec: value },
|
||||
);
|
||||
},
|
||||
setMediaGuess: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaGuess: value },
|
||||
);
|
||||
},
|
||||
setMediaGuessPromise: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaGuessPromise: value },
|
||||
);
|
||||
},
|
||||
setLastDurationProbeAtMs: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ lastDurationProbeAtMs: value },
|
||||
);
|
||||
},
|
||||
},
|
||||
getMediaGuessRuntimeStateMainDeps: {
|
||||
getMediaKey: () => anilistMediaGuessRuntimeState.mediaKey,
|
||||
getMediaDurationSec: () => anilistMediaGuessRuntimeState.mediaDurationSec,
|
||||
getMediaGuess: () => anilistMediaGuessRuntimeState.mediaGuess,
|
||||
getMediaGuessPromise: () => anilistMediaGuessRuntimeState.mediaGuessPromise,
|
||||
getLastDurationProbeAtMs: () => anilistMediaGuessRuntimeState.lastDurationProbeAtMs,
|
||||
},
|
||||
setMediaGuessRuntimeStateMainDeps: {
|
||||
setMediaKey: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaKey: value },
|
||||
);
|
||||
},
|
||||
setMediaDurationSec: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaDurationSec: value },
|
||||
);
|
||||
},
|
||||
setMediaGuess: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaGuess: value },
|
||||
);
|
||||
},
|
||||
setMediaGuessPromise: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaGuessPromise: value },
|
||||
);
|
||||
},
|
||||
setLastDurationProbeAtMs: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ lastDurationProbeAtMs: value },
|
||||
);
|
||||
},
|
||||
},
|
||||
recordMediaDurationMainDeps: {
|
||||
getCurrentMediaKey: () => getCurrentAnilistMediaKey(),
|
||||
getState: () => getAnilistMediaGuessRuntimeState(),
|
||||
setState: (state) => {
|
||||
setAnilistMediaGuessRuntimeState(state);
|
||||
},
|
||||
},
|
||||
resetMediaGuessStateMainDeps: {
|
||||
setMediaGuess: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaGuess: value },
|
||||
);
|
||||
},
|
||||
setMediaGuessPromise: (value) => {
|
||||
anilistMediaGuessRuntimeState = transitionAnilistMediaGuessRuntimeState(
|
||||
anilistMediaGuessRuntimeState,
|
||||
{ mediaGuessPromise: value },
|
||||
);
|
||||
},
|
||||
},
|
||||
maybeProbeDurationMainDeps: {
|
||||
getState: () => getAnilistMediaGuessRuntimeState(),
|
||||
setState: (state) => {
|
||||
setAnilistMediaGuessRuntimeState(state);
|
||||
},
|
||||
durationRetryIntervalMs: ANILIST_DURATION_RETRY_INTERVAL_MS,
|
||||
now: () => Date.now(),
|
||||
requestMpvDuration: async () => appState.mpvClient?.requestProperty('duration'),
|
||||
logWarn: (message, error) => logger.warn(message, error),
|
||||
},
|
||||
ensureMediaGuessMainDeps: {
|
||||
getState: () => getAnilistMediaGuessRuntimeState(),
|
||||
setState: (state) => {
|
||||
setAnilistMediaGuessRuntimeState(state);
|
||||
},
|
||||
resolveMediaPathForJimaku: (currentMediaPath) =>
|
||||
deps.resolveMediaPathForJimaku(currentMediaPath),
|
||||
getCurrentMediaPath: () => appState.currentMediaPath,
|
||||
getCurrentMediaTitle: () => appState.currentMediaTitle,
|
||||
guessAnilistMediaInfo: (mediaPath, mediaTitle) =>
|
||||
guessAnilistMediaInfo(mediaPath, mediaTitle),
|
||||
},
|
||||
processNextRetryUpdateMainDeps: {
|
||||
nextReady: () => anilistUpdateQueue.nextReady(),
|
||||
refreshRetryQueueState: () => anilistStateRuntime.refreshRetryQueueState(),
|
||||
setLastAttemptAt: (value) => {
|
||||
appState.anilistRetryQueueState = transitionAnilistRetryQueueLastAttemptAt(
|
||||
appState.anilistRetryQueueState,
|
||||
value,
|
||||
);
|
||||
},
|
||||
setLastError: (value) => {
|
||||
appState.anilistRetryQueueState = transitionAnilistRetryQueueLastError(
|
||||
appState.anilistRetryQueueState,
|
||||
value,
|
||||
);
|
||||
},
|
||||
refreshAnilistClientSecretState: () => refreshAnilistClientSecretState(),
|
||||
updateAnilistPostWatchProgress: (accessToken, title, episode, season, mediaId) =>
|
||||
updateAnilistPostWatchProgress(accessToken, title, episode, {
|
||||
rateLimiter: anilistRateLimiter,
|
||||
season,
|
||||
mediaId,
|
||||
logInfo: (message) => logger.info(message),
|
||||
}),
|
||||
markSuccess: (key) => {
|
||||
anilistUpdateQueue.markSuccess(key);
|
||||
},
|
||||
rememberAttemptedUpdateKey: (key) => {
|
||||
rememberAnilistAttemptedUpdate(key);
|
||||
},
|
||||
markFailure: (key, message) => {
|
||||
anilistUpdateQueue.markFailure(key, message);
|
||||
},
|
||||
logInfo: (message) => logger.info(message),
|
||||
now: () => Date.now(),
|
||||
},
|
||||
maybeRunPostWatchUpdateMainDeps: {
|
||||
getInFlight: () => anilistUpdateInFlightState.inFlight,
|
||||
setInFlight: (value) => {
|
||||
anilistUpdateInFlightState = transitionAnilistUpdateInFlightState(
|
||||
anilistUpdateInFlightState,
|
||||
value,
|
||||
);
|
||||
},
|
||||
getResolvedConfig: () => configService.getConfig(),
|
||||
isAnilistTrackingEnabled: (config) => isAnilistTrackingEnabled(config as ResolvedConfig),
|
||||
getCurrentMediaKey: () => getCurrentAnilistMediaKey(),
|
||||
hasMpvClient: () => Boolean(appState.mpvClient),
|
||||
getTrackedMediaKey: () => anilistMediaGuessRuntimeState.mediaKey,
|
||||
resetTrackedMedia: (mediaKey) => {
|
||||
resetAnilistMediaTracking(mediaKey);
|
||||
},
|
||||
getWatchedSeconds: () => appState.mpvClient?.currentTimePos ?? Number.NaN,
|
||||
maybeProbeAnilistDuration: (mediaKey, options) =>
|
||||
maybeProbeAnilistDuration(mediaKey, options),
|
||||
ensureAnilistMediaGuess: (mediaKey) => ensureAnilistMediaGuess(mediaKey),
|
||||
hasAttemptedUpdateKey: (key) => anilistAttemptedUpdateKeys.has(key),
|
||||
processNextAnilistRetryUpdate: () => processNextAnilistRetryUpdate(),
|
||||
refreshAnilistClientSecretState: () => refreshAnilistClientSecretState(),
|
||||
enqueueRetry: (key, title, episode, season, mediaId) => {
|
||||
anilistUpdateQueue.enqueue(key, title, episode, season, mediaId);
|
||||
},
|
||||
getCurrentMediaTitle: () => appState.currentMediaTitle,
|
||||
resolvePinnedAnilistMediaId: ({ mediaPath, mediaTitle, guess }) =>
|
||||
deps.resolvePinnedMediaId({ mediaPath, mediaTitle, guess }),
|
||||
markRetryFailure: (key, message) => {
|
||||
anilistUpdateQueue.markFailure(key, message);
|
||||
},
|
||||
markRetrySuccess: (key) => {
|
||||
anilistUpdateQueue.markSuccess(key);
|
||||
},
|
||||
refreshRetryQueueState: () => anilistStateRuntime.refreshRetryQueueState(),
|
||||
updateAnilistPostWatchProgress: (accessToken, title, episode, season, mediaId) =>
|
||||
updateAnilistPostWatchProgress(accessToken, title, episode, {
|
||||
rateLimiter: anilistRateLimiter,
|
||||
season,
|
||||
mediaId,
|
||||
logInfo: (message) => logger.info(message),
|
||||
}),
|
||||
rememberAttemptedUpdateKey: (key) => {
|
||||
rememberAnilistAttemptedUpdate(key);
|
||||
},
|
||||
showMpvOsd: (message) =>
|
||||
deps
|
||||
.getOverlayNotifications()
|
||||
.showConfiguredStatusNotification(message, { title: 'AniList' }),
|
||||
logInfo: (message) => logger.info(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
minWatchSeconds: ANILIST_UPDATE_MIN_WATCH_SECONDS,
|
||||
minWatchRatio: DEFAULT_MIN_WATCH_RATIO,
|
||||
},
|
||||
});
|
||||
|
||||
function refreshAnilistClientSecretStateIfEnabled(options?: {
|
||||
force?: boolean;
|
||||
allowSetupPrompt?: boolean;
|
||||
}): Promise<string | null> {
|
||||
if (!isAnilistTrackingEnabled(configService.getConfig())) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
return refreshAnilistClientSecretState(options);
|
||||
}
|
||||
|
||||
const rememberAnilistAttemptedUpdate = (key: string): void => {
|
||||
rememberAnilistAttemptedUpdateKey(
|
||||
anilistAttemptedUpdateKeys,
|
||||
key,
|
||||
ANILIST_MAX_ATTEMPTED_UPDATE_KEYS,
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
stateRuntime: anilistStateRuntime,
|
||||
openSetupWindow: openAnilistSetupWindowHandler,
|
||||
handleAnilistSetupProtocolUrl,
|
||||
registerSubminerProtocolClient,
|
||||
refreshClientSecretStateIfEnabled: refreshAnilistClientSecretStateIfEnabled,
|
||||
getCurrentAnilistMediaKey,
|
||||
resetAnilistMediaTracking,
|
||||
recordAnilistMediaDuration,
|
||||
resetAnilistMediaGuessState,
|
||||
maybeProbeAnilistDuration,
|
||||
ensureAnilistMediaGuess,
|
||||
processNextAnilistRetryUpdate,
|
||||
maybeRunAnilistPostWatchUpdate,
|
||||
/** Duration of the media AniList is tracking, used as Discord presence's fallback. */
|
||||
getMediaDurationSec: () => anilistMediaGuessRuntimeState.mediaDurationSec,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
createCharacterDictionaryAssembly,
|
||||
type CharacterDictionaryAssemblyDeps,
|
||||
} from './character-dictionary';
|
||||
|
||||
// Every callback throws, so a test fails if the assembly calls a dep it should only call later.
|
||||
function makeDeps(): CharacterDictionaryAssemblyDeps {
|
||||
const lazy = (name: string) => (): never => {
|
||||
throw new Error(`${name} called unexpectedly`);
|
||||
};
|
||||
return {
|
||||
userDataPath: '/tmp/subminer-user-data',
|
||||
appState: {
|
||||
currentMediaPath: null,
|
||||
mpvClient: null,
|
||||
currentMediaTitle: null,
|
||||
mecabTokenizer: null,
|
||||
yomitanParserWindow: null,
|
||||
currentSubText: '',
|
||||
},
|
||||
getConfig: lazy('getConfig'),
|
||||
logger: { info: lazy('info'), warn: lazy('warn'), error: lazy('error') },
|
||||
startupOsdSequencer: {
|
||||
notifyCharacterDictionaryStatus: lazy('notifyCharacterDictionaryStatus'),
|
||||
},
|
||||
resolveMediaPathForJimaku: lazy('resolveMediaPathForJimaku'),
|
||||
getYomitanProfilePolicy: lazy('getYomitanProfilePolicy'),
|
||||
isYoutubePlaybackActive: lazy('isYoutubePlaybackActive'),
|
||||
waitForMediaTokenizationReady: lazy('waitForMediaTokenizationReady'),
|
||||
ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'),
|
||||
getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'),
|
||||
getOverlayNotifications: lazy('getOverlayNotifications'),
|
||||
showMpvOsd: lazy('showMpvOsd'),
|
||||
showDesktopNotification: lazy('showDesktopNotification'),
|
||||
invalidateTokenizationCache: lazy('invalidateTokenizationCache'),
|
||||
refreshCurrentSubtitle: lazy('refreshCurrentSubtitle'),
|
||||
refreshSubtitlePrefetch: lazy('refreshSubtitlePrefetch'),
|
||||
refreshCurrentSubtitleAnnotations: lazy('refreshCurrentSubtitleAnnotations'),
|
||||
};
|
||||
}
|
||||
|
||||
// main.ts builds the assembly before most siblings exist, so construction must stay lazy.
|
||||
test('createCharacterDictionaryAssembly does not call its deps while constructing', () => {
|
||||
const characterDictionary = createCharacterDictionaryAssembly(makeDeps());
|
||||
assert.equal(characterDictionary.autoSync.getCurrentMediaId(), null);
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
import {
|
||||
clearYomitanParserCachesForWindow,
|
||||
deleteYomitanDictionaryByTitle,
|
||||
getYomitanDictionaryInfo,
|
||||
importYomitanDictionaryFromZip,
|
||||
upsertYomitanDictionarySettings,
|
||||
} from '../../core/services';
|
||||
import { guessAnilistMediaInfo } from '../../core/services/anilist/anilist-updater';
|
||||
import type { Logger } from '../../logger';
|
||||
import type { ResolvedConfig } from '../../types';
|
||||
import { createCharacterDictionaryRuntimeService } from '../character-dictionary-runtime';
|
||||
import { createCharacterDictionaryImageLookup } from '../character-dictionary-runtime/image-lookup';
|
||||
import { createCharacterNameCandidateLookup } from '../character-dictionary-runtime/name-candidates';
|
||||
import { createCharacterDictionaryAutoSyncRuntimeService } from '../runtime/character-dictionary-auto-sync';
|
||||
import { handleCharacterDictionaryAutoSyncComplete } from '../runtime/character-dictionary-auto-sync-completion';
|
||||
import {
|
||||
notifyCharacterDictionaryAutoSyncStatus,
|
||||
type CharacterDictionaryAutoSyncNotificationDeps,
|
||||
} from '../runtime/character-dictionary-auto-sync-notifications';
|
||||
import type { createOverlayNotificationsRuntime } from '../runtime/overlay-notifications-runtime';
|
||||
import { assertYomitanDictionaryMutationSafe } from '../runtime/yomitan-dictionary-integrity';
|
||||
import type { createYomitanProfilePolicy } from '../runtime/yomitan-profile-policy';
|
||||
import { formatSkippedYomitanWriteAction } from '../runtime/yomitan-read-only-log';
|
||||
import type { AppState } from '../state';
|
||||
|
||||
type YomitanParserRuntimeDeps = Parameters<typeof getYomitanDictionaryInfo>[0];
|
||||
|
||||
/**
|
||||
* What the character dictionary needs from the rest of the app. Siblings built after this
|
||||
* assembly in `main.ts` are reached through getters or callbacks, which run only once the app does.
|
||||
*/
|
||||
export interface CharacterDictionaryAssemblyDeps {
|
||||
userDataPath: string;
|
||||
appState: Pick<
|
||||
AppState,
|
||||
| 'currentMediaPath'
|
||||
| 'mpvClient'
|
||||
| 'currentMediaTitle'
|
||||
| 'mecabTokenizer'
|
||||
| 'yomitanParserWindow'
|
||||
| 'currentSubText'
|
||||
>;
|
||||
getConfig: () => ResolvedConfig;
|
||||
logger: Pick<Logger, 'info' | 'warn' | 'error'>;
|
||||
startupOsdSequencer: CharacterDictionaryAutoSyncNotificationDeps['startupOsdSequencer'];
|
||||
resolveMediaPathForJimaku: (mediaPath: string | null) => string | null;
|
||||
getYomitanProfilePolicy: () => Pick<
|
||||
ReturnType<typeof createYomitanProfilePolicy>,
|
||||
'isCharacterDictionaryEnabled' | 'isExternalReadOnlyMode' | 'logSkippedWrite'
|
||||
>;
|
||||
isYoutubePlaybackActive: () => boolean;
|
||||
waitForMediaTokenizationReady: (mediaPath: string | null) => Promise<void>;
|
||||
ensureYomitanExtensionLoaded: () => Promise<unknown>;
|
||||
getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps;
|
||||
getOverlayNotifications: () => Pick<
|
||||
ReturnType<typeof createOverlayNotificationsRuntime>,
|
||||
'getConfiguredStatusNotificationType' | 'showOverlayNotification'
|
||||
>;
|
||||
showMpvOsd: (message: string) => void;
|
||||
showDesktopNotification: CharacterDictionaryAutoSyncNotificationDeps['showDesktopNotification'];
|
||||
invalidateTokenizationCache: () => void;
|
||||
refreshCurrentSubtitle: (text: string) => void;
|
||||
/** Re-runs subtitle prefetch from the current playback position. */
|
||||
refreshSubtitlePrefetch: () => void;
|
||||
refreshCurrentSubtitleAnnotations: () => void;
|
||||
}
|
||||
|
||||
export type CharacterDictionaryAssembly = ReturnType<typeof createCharacterDictionaryAssembly>;
|
||||
|
||||
/**
|
||||
* Owns the AniList character dictionary: snapshot generation, auto-sync into Yomitan, and the
|
||||
* portrait and name-candidate lookups the overlay reads. `main.ts` builds it once.
|
||||
*/
|
||||
export function createCharacterDictionaryAssembly(deps: CharacterDictionaryAssemblyDeps) {
|
||||
const { appState, logger } = deps;
|
||||
|
||||
const runtime = createCharacterDictionaryRuntimeService({
|
||||
userDataPath: deps.userDataPath,
|
||||
getCurrentMediaPath: () => appState.currentMediaPath,
|
||||
getCurrentVideoPath: () => appState.mpvClient?.currentVideoPath,
|
||||
getCurrentMediaTitle: () => appState.currentMediaTitle,
|
||||
resolveMediaPathForJimaku: (mediaPath) => deps.resolveMediaPathForJimaku(mediaPath),
|
||||
guessAnilistMediaInfo: (mediaPath, mediaTitle) => guessAnilistMediaInfo(mediaPath, mediaTitle),
|
||||
getNameMatchImagesEnabled: () => deps.getConfig().subtitleStyle.nameMatchImagesEnabled,
|
||||
getCollapsibleSectionOpenState: (section) =>
|
||||
deps.getConfig().anilist.characterDictionary.collapsibleSections[section],
|
||||
tokenizeJapaneseName: async (text) => (await appState.mecabTokenizer?.tokenize(text)) ?? null,
|
||||
getJapaneseNameTokenizerAvailable: () => {
|
||||
const status = appState.mecabTokenizer?.getStatus();
|
||||
return status?.available === true && status.enabled === true;
|
||||
},
|
||||
now: () => Date.now(),
|
||||
logInfo: (message) => logger.info(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
});
|
||||
|
||||
const autoSync = createCharacterDictionaryAutoSyncRuntimeService({
|
||||
userDataPath: deps.userDataPath,
|
||||
getConfig: () => {
|
||||
const config = deps.getConfig().anilist.characterDictionary;
|
||||
return {
|
||||
enabled:
|
||||
deps.getConfig().subtitleStyle.nameMatchEnabled &&
|
||||
deps.getYomitanProfilePolicy().isCharacterDictionaryEnabled() &&
|
||||
!deps.isYoutubePlaybackActive(),
|
||||
maxLoaded: config.maxLoaded,
|
||||
profileScope: config.profileScope,
|
||||
};
|
||||
},
|
||||
getOrCreateCurrentSnapshot: (targetPath, progress) =>
|
||||
runtime.getOrCreateCurrentSnapshot(targetPath, progress),
|
||||
buildMergedDictionary: (mediaIds) => runtime.buildMergedDictionary(mediaIds),
|
||||
waitForYomitanMutationReady: () =>
|
||||
deps.waitForMediaTokenizationReady(
|
||||
appState.currentMediaPath?.trim() || appState.mpvClient?.currentVideoPath?.trim() || null,
|
||||
),
|
||||
getYomitanDictionaryInfo: async () => {
|
||||
await deps.ensureYomitanExtensionLoaded();
|
||||
const dictionaries = await getYomitanDictionaryInfo(deps.getYomitanParserRuntimeDeps(), {
|
||||
error: (message, ...args) => logger.error(message, ...args),
|
||||
info: (message, ...args) => logger.info(message, ...args),
|
||||
});
|
||||
assertYomitanDictionaryMutationSafe(deps.userDataPath, dictionaries.length);
|
||||
return dictionaries;
|
||||
},
|
||||
importYomitanDictionary: async (zipPath) => {
|
||||
const yomitanProfilePolicy = deps.getYomitanProfilePolicy();
|
||||
if (yomitanProfilePolicy.isExternalReadOnlyMode()) {
|
||||
yomitanProfilePolicy.logSkippedWrite(
|
||||
formatSkippedYomitanWriteAction('importYomitanDictionary', zipPath),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
await deps.ensureYomitanExtensionLoaded();
|
||||
return await importYomitanDictionaryFromZip(zipPath, deps.getYomitanParserRuntimeDeps(), {
|
||||
error: (message, ...args) => logger.error(message, ...args),
|
||||
info: (message, ...args) => logger.info(message, ...args),
|
||||
warn: (message, ...args) => logger.warn(message, ...args),
|
||||
});
|
||||
},
|
||||
dictionaryImportReplacesExisting: () =>
|
||||
deps.getYomitanParserRuntimeDeps().getYomitanExt()?.name === 'Hachidori',
|
||||
deleteYomitanDictionary: async (dictionaryTitle) => {
|
||||
const yomitanProfilePolicy = deps.getYomitanProfilePolicy();
|
||||
if (yomitanProfilePolicy.isExternalReadOnlyMode()) {
|
||||
yomitanProfilePolicy.logSkippedWrite(
|
||||
formatSkippedYomitanWriteAction('deleteYomitanDictionary', dictionaryTitle),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
await deps.ensureYomitanExtensionLoaded();
|
||||
return await deleteYomitanDictionaryByTitle(
|
||||
dictionaryTitle,
|
||||
deps.getYomitanParserRuntimeDeps(),
|
||||
{
|
||||
error: (message, ...args) => logger.error(message, ...args),
|
||||
info: (message, ...args) => logger.info(message, ...args),
|
||||
},
|
||||
);
|
||||
},
|
||||
upsertYomitanDictionarySettings: async (dictionaryTitle, profileScope) => {
|
||||
const yomitanProfilePolicy = deps.getYomitanProfilePolicy();
|
||||
if (yomitanProfilePolicy.isExternalReadOnlyMode()) {
|
||||
yomitanProfilePolicy.logSkippedWrite(
|
||||
formatSkippedYomitanWriteAction('upsertYomitanDictionarySettings', dictionaryTitle),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
await deps.ensureYomitanExtensionLoaded();
|
||||
return await upsertYomitanDictionarySettings(
|
||||
dictionaryTitle,
|
||||
profileScope,
|
||||
deps.getYomitanParserRuntimeDeps(),
|
||||
{
|
||||
error: (message, ...args) => logger.error(message, ...args),
|
||||
info: (message, ...args) => logger.info(message, ...args),
|
||||
},
|
||||
);
|
||||
},
|
||||
now: () => Date.now(),
|
||||
schedule: (fn, delayMs) => setTimeout(fn, delayMs),
|
||||
clearSchedule: (timer) => clearTimeout(timer),
|
||||
logInfo: (message) => logger.info(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
onSyncStatus: (event) => {
|
||||
const notifications = deps.getOverlayNotifications();
|
||||
notifyCharacterDictionaryAutoSyncStatus(event, {
|
||||
getNotificationType: () => notifications.getConfiguredStatusNotificationType(),
|
||||
showOsd: (message) => deps.showMpvOsd(message),
|
||||
showOverlayNotification: (payload) => notifications.showOverlayNotification(payload),
|
||||
showDesktopNotification: (title, options) => deps.showDesktopNotification(title, options),
|
||||
startupOsdSequencer: deps.startupOsdSequencer,
|
||||
});
|
||||
},
|
||||
onSyncComplete: ({ mediaId, mediaTitle, changed }) => {
|
||||
handleCharacterDictionaryAutoSyncComplete(
|
||||
{
|
||||
mediaId,
|
||||
mediaTitle,
|
||||
changed,
|
||||
},
|
||||
{
|
||||
hasParserWindow: () => Boolean(appState.yomitanParserWindow),
|
||||
invalidateCharacterDictionaryLookups: () => {
|
||||
imageLookup.invalidate();
|
||||
nameCandidates.invalidate();
|
||||
},
|
||||
clearParserCaches: () => {
|
||||
if (appState.yomitanParserWindow) {
|
||||
clearYomitanParserCachesForWindow(appState.yomitanParserWindow);
|
||||
}
|
||||
},
|
||||
invalidateTokenizationCache: () => {
|
||||
deps.invalidateTokenizationCache();
|
||||
},
|
||||
refreshSubtitlePrefetch: () => {
|
||||
deps.refreshSubtitlePrefetch();
|
||||
},
|
||||
refreshCurrentSubtitle: () => {
|
||||
deps.refreshCurrentSubtitle(appState.currentSubText);
|
||||
},
|
||||
logInfo: (message) => logger.info(message),
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const imageLookup = createCharacterDictionaryImageLookup({
|
||||
userDataPath: deps.userDataPath,
|
||||
getCurrentMediaId: () => autoSync.getCurrentMediaId(),
|
||||
onIndexReady: () => deps.refreshCurrentSubtitleAnnotations(),
|
||||
onIndexReadyError: (error) =>
|
||||
logger.warn(
|
||||
'Failed to refresh subtitle annotations after character portrait index became ready.',
|
||||
error,
|
||||
),
|
||||
});
|
||||
|
||||
// Lets the Yomitan scan runtime skip name lookups at positions where no
|
||||
// character name can start; absent candidates just mean the exhaustive scan.
|
||||
const nameCandidates = createCharacterNameCandidateLookup({
|
||||
userDataPath: deps.userDataPath,
|
||||
getCurrentMediaId: () => autoSync.getCurrentMediaId(),
|
||||
});
|
||||
|
||||
return { runtime, autoSync, imageLookup, nameCandidates };
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createDictionariesAssembly, type DictionariesAssemblyDeps } from './dictionaries';
|
||||
|
||||
// Every callback throws, so a test fails if the assembly calls a dep it should only call later.
|
||||
function makeDeps(): DictionariesAssemblyDeps {
|
||||
const lazy = (name: string) => (): never => {
|
||||
throw new Error(`${name} called unexpectedly`);
|
||||
};
|
||||
return {
|
||||
roots: {
|
||||
platform: 'linux',
|
||||
dirname: '/tmp/subminer-main',
|
||||
appPath: '/tmp/subminer-app',
|
||||
resourcesPath: '/tmp/subminer-resources',
|
||||
userDataPath: '/tmp/subminer-user-data',
|
||||
appUserDataPath: '/tmp/subminer-app-user-data',
|
||||
homeDir: '/tmp/subminer-home',
|
||||
cwd: '/tmp/subminer-cwd',
|
||||
joinPath: lazy('joinPath'),
|
||||
},
|
||||
appState: { jlptLevelLookup: () => null, frequencyRankLookup: () => null },
|
||||
getConfig: lazy('getConfig'),
|
||||
logger: { info: lazy('info') },
|
||||
};
|
||||
}
|
||||
|
||||
// main.ts builds the assembly before most siblings exist, so construction must stay lazy.
|
||||
test('createDictionariesAssembly does not call its deps while constructing', () => {
|
||||
const dictionaries = createDictionariesAssembly(makeDeps());
|
||||
assert.equal(typeof dictionaries.jlpt.ensureJlptDictionaryLookup, 'function');
|
||||
assert.equal(typeof dictionaries.frequency.ensureFrequencyDictionaryLookup, 'function');
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { ResolvedConfig } from '../../types';
|
||||
import type { Logger } from '../../logger';
|
||||
import {
|
||||
createFrequencyDictionaryRuntimeService,
|
||||
getFrequencyDictionarySearchPaths,
|
||||
} from '../frequency-dictionary-runtime';
|
||||
import { createJlptDictionaryRuntimeService, getJlptDictionarySearchPaths } from '../jlpt-runtime';
|
||||
import { createBuildDictionaryRootsHandler } from '../runtime/dictionary-roots';
|
||||
import type { AppState } from '../state';
|
||||
|
||||
/**
|
||||
* What the bundled annotation dictionaries need. `roots` holds the install and user paths
|
||||
* searched for each dictionary's vendor folder; `main.ts` resolves them when it builds this.
|
||||
*/
|
||||
export interface DictionariesAssemblyDeps {
|
||||
roots: Omit<Parameters<typeof createBuildDictionaryRootsHandler>[0], 'vendorDirName'>;
|
||||
appState: Pick<AppState, 'jlptLevelLookup' | 'frequencyRankLookup'>;
|
||||
getConfig: () => ResolvedConfig;
|
||||
logger: Pick<Logger, 'info'>;
|
||||
}
|
||||
|
||||
export type DictionariesAssembly = ReturnType<typeof createDictionariesAssembly>;
|
||||
|
||||
/**
|
||||
* Owns the JLPT and frequency dictionary lookups that subtitle annotations read. `main.ts` builds
|
||||
* it once; tokenization calls `jlpt`/`frequency` to load each lookup on first use.
|
||||
*/
|
||||
export function createDictionariesAssembly(deps: DictionariesAssemblyDeps) {
|
||||
const { appState, logger } = deps;
|
||||
|
||||
const buildJlptDictionaryRootsHandler = createBuildDictionaryRootsHandler({
|
||||
...deps.roots,
|
||||
vendorDirName: 'yomitan-jlpt-vocab',
|
||||
});
|
||||
const buildFrequencyDictionaryRootsHandler = createBuildDictionaryRootsHandler({
|
||||
...deps.roots,
|
||||
vendorDirName: 'frequency-dictionary',
|
||||
});
|
||||
|
||||
const jlpt = createJlptDictionaryRuntimeService({
|
||||
isJlptEnabled: () => deps.getConfig().subtitleStyle.enableJlpt,
|
||||
getSearchPaths: () =>
|
||||
getJlptDictionarySearchPaths({ getDictionaryRoots: () => buildJlptDictionaryRootsHandler() }),
|
||||
setJlptLevelLookup: (lookup) => {
|
||||
appState.jlptLevelLookup = lookup;
|
||||
},
|
||||
log: (message) => logger.info(`[JLPT] ${message}`),
|
||||
});
|
||||
|
||||
const frequency = createFrequencyDictionaryRuntimeService({
|
||||
isFrequencyDictionaryEnabled: () => deps.getConfig().subtitleStyle.frequencyDictionary.enabled,
|
||||
getSearchPaths: () =>
|
||||
getFrequencyDictionarySearchPaths({
|
||||
getDictionaryRoots: () =>
|
||||
buildFrequencyDictionaryRootsHandler().filter((dictionaryRoot) => dictionaryRoot),
|
||||
getSourcePath: () => deps.getConfig().subtitleStyle.frequencyDictionary.sourcePath,
|
||||
}),
|
||||
setFrequencyRankLookup: (lookup) => {
|
||||
appState.frequencyRankLookup = lookup;
|
||||
},
|
||||
log: (message) => logger.info(`[Frequency] ${message}`),
|
||||
});
|
||||
|
||||
return { jlpt, frequency };
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
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 {
|
||||
createDefaultSetupState,
|
||||
getSetupStatePath,
|
||||
writeSetupState,
|
||||
} from '../../shared/setup-state';
|
||||
import { createFirstRunSetupAssembly, type FirstRunSetupAssemblyDeps } from './first-run-setup';
|
||||
|
||||
// Every callback throws, so a test fails if the assembly calls a dep it should only call later.
|
||||
function makeDeps(configDir: string): FirstRunSetupAssemblyDeps {
|
||||
const lazy = (name: string) => (): never => {
|
||||
throw new Error(`${name} called unexpectedly`);
|
||||
};
|
||||
return {
|
||||
appState: {
|
||||
firstRunSetupCompleted: false,
|
||||
firstRunSetupWindow: null,
|
||||
backgroundMode: false,
|
||||
initialArgs: null,
|
||||
},
|
||||
configService: { getConfig: lazy('getConfig'), patchRawConfig: lazy('patchRawConfig') },
|
||||
logger: { error: lazy('error'), info: lazy('info') },
|
||||
configDir,
|
||||
userDataPath: configDir,
|
||||
dictionaryBackend: 'yomitan',
|
||||
ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'),
|
||||
getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'),
|
||||
createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'),
|
||||
getAppPath: lazy('getAppPath'),
|
||||
trashItem: lazy('trashItem'),
|
||||
writeShortcutLink: lazy('writeShortcutLink'),
|
||||
createBrowserWindow: lazy('createBrowserWindow'),
|
||||
openDictionarySettings: lazy('openDictionarySettings'),
|
||||
openConfigSettingsWindow: lazy('openConfigSettingsWindow'),
|
||||
onSetupStateChanged: lazy('onSetupStateChanged'),
|
||||
requestAppQuit: lazy('requestAppQuit'),
|
||||
};
|
||||
}
|
||||
|
||||
function makeConfigDir(t: { after: (fn: () => void) => void }): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-first-run-assembly-test-'));
|
||||
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
return dir;
|
||||
}
|
||||
|
||||
// main.ts builds the assembly before most siblings exist, so construction must stay lazy.
|
||||
test('createFirstRunSetupAssembly does not call its deps while constructing', (t) => {
|
||||
const firstRunSetup = createFirstRunSetupAssembly(makeDeps(makeConfigDir(t)));
|
||||
assert.equal(typeof firstRunSetup.service.isSetupCompleted, 'function');
|
||||
assert.equal(typeof firstRunSetup.openWindow, 'function');
|
||||
});
|
||||
|
||||
test('openWindow skips a completed setup unless forced', (t) => {
|
||||
const configDir = makeConfigDir(t);
|
||||
writeSetupState(getSetupStatePath(configDir), {
|
||||
...createDefaultSetupState(),
|
||||
status: 'completed',
|
||||
});
|
||||
const firstRunSetup = createFirstRunSetupAssembly(makeDeps(configDir));
|
||||
|
||||
firstRunSetup.openWindow();
|
||||
assert.throws(() => firstRunSetup.openWindow(true), /createBrowserWindow called unexpectedly/);
|
||||
});
|
||||
@@ -0,0 +1,371 @@
|
||||
import os from 'node:os';
|
||||
import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron';
|
||||
import type { ConfigService } from '../../config/service';
|
||||
import { getYomitanDictionaryInfo } from '../../core/services';
|
||||
import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime';
|
||||
import type { Logger } from '../../logger';
|
||||
import { resolveDefaultMpvInstallPaths } from '../../shared/setup-state';
|
||||
import type { DictionaryBackend } from '../../types/config';
|
||||
import {
|
||||
detectCommandLineLauncher,
|
||||
installBun as installCommandLineBun,
|
||||
installLauncher as installCommandLineLauncher,
|
||||
} from '../runtime/command-line-launcher';
|
||||
import {
|
||||
detectInstalledFirstRunPlugin,
|
||||
detectInstalledFirstRunPluginCandidates,
|
||||
removeLegacyMpvPluginCandidates,
|
||||
} from '../runtime/first-run-setup-plugin';
|
||||
import {
|
||||
createFirstRunSetupService,
|
||||
getFirstRunSetupCompletionMessage,
|
||||
isStandaloneFirstRunSetupCommand,
|
||||
} from '../runtime/first-run-setup-service';
|
||||
import {
|
||||
buildFirstRunSetupHtml,
|
||||
createMaybeFocusExistingFirstRunSetupWindowHandler,
|
||||
createOpenFirstRunSetupWindowHandler,
|
||||
parseFirstRunSetupSubmissionUrl,
|
||||
type FirstRunSetupSubmission,
|
||||
} from '../runtime/first-run-setup-window';
|
||||
import { createCreateFirstRunSetupWindowHandler } from '../runtime/setup-window-factory';
|
||||
import { getConfiguredWindowsMpvPathStatus } from '../runtime/windows-mpv-launch';
|
||||
import {
|
||||
applyWindowsMpvShortcuts,
|
||||
detectWindowsMpvShortcuts,
|
||||
resolveWindowsMpvShortcutPaths,
|
||||
} from '../runtime/windows-mpv-shortcuts';
|
||||
import { observeYomitanDictionaryCount } from '../runtime/yomitan-dictionary-integrity';
|
||||
import type { AppState } from '../state';
|
||||
|
||||
type YomitanParserRuntimeDeps = Parameters<typeof requestHachidoriSharing>[1];
|
||||
type CommandLineLauncherRuntimeOptions = NonNullable<
|
||||
Parameters<typeof detectCommandLineLauncher>[0]
|
||||
>;
|
||||
|
||||
/**
|
||||
* What the first-run setup flow needs from the rest of the app. Siblings built after this
|
||||
* assembly in `main.ts` are reached through callbacks.
|
||||
*/
|
||||
export interface FirstRunSetupAssemblyDeps {
|
||||
appState: Pick<
|
||||
AppState,
|
||||
'firstRunSetupCompleted' | 'firstRunSetupWindow' | 'backgroundMode' | 'initialArgs'
|
||||
>;
|
||||
configService: Pick<ConfigService, 'getConfig' | 'patchRawConfig'>;
|
||||
logger: Pick<Logger, 'error' | 'info'>;
|
||||
configDir: string;
|
||||
userDataPath: string;
|
||||
/** Fixed for the process lifetime; backend changes apply on restart. */
|
||||
dictionaryBackend: DictionaryBackend;
|
||||
ensureYomitanExtensionLoaded: () => Promise<unknown>;
|
||||
getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps;
|
||||
/** Resolves the launcher options after the login-shell PATH is applied. */
|
||||
createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>;
|
||||
getAppPath: (name: 'appData' | 'desktop') => string;
|
||||
trashItem: (targetPath: string) => Promise<void>;
|
||||
writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink'];
|
||||
createBrowserWindow: (options: BrowserWindowConstructorOptions) => BrowserWindow;
|
||||
openDictionarySettings: () => boolean;
|
||||
openConfigSettingsWindow: () => boolean;
|
||||
/** Called when setup state changes, so the tray menu can refresh its setup entry. */
|
||||
onSetupStateChanged: () => void;
|
||||
requestAppQuit: () => void;
|
||||
}
|
||||
|
||||
export type FirstRunSetupAssembly = ReturnType<typeof createFirstRunSetupAssembly>;
|
||||
|
||||
/**
|
||||
* Owns the first-run setup service and its window, plus the status message shown in that
|
||||
* window. `main.ts` initializes setup state during app-ready and opens the window from there,
|
||||
* the tray and the CLI.
|
||||
*/
|
||||
export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
|
||||
const { appState, configService, logger } = deps;
|
||||
let firstRunSetupMessage: string | null = null;
|
||||
const resolveWindowsMpvShortcutRuntimePaths = () =>
|
||||
resolveWindowsMpvShortcutPaths({
|
||||
appDataDir: deps.getAppPath('appData'),
|
||||
desktopDir: deps.getAppPath('desktop'),
|
||||
});
|
||||
|
||||
const firstRunSetupService = createFirstRunSetupService({
|
||||
getDictionaryBackend: () => deps.dictionaryBackend,
|
||||
getHachidoriHostStatus: async () => {
|
||||
await deps.ensureYomitanExtensionLoaded();
|
||||
return requestHachidoriSharing(
|
||||
{ type: 'hd_sharing_status' },
|
||||
deps.getYomitanParserRuntimeDeps(),
|
||||
logger,
|
||||
);
|
||||
},
|
||||
platform: process.platform,
|
||||
configDir: deps.configDir,
|
||||
getYomitanDictionaryCount: async () => {
|
||||
await deps.ensureYomitanExtensionLoaded();
|
||||
const dictionaries = await getYomitanDictionaryInfo(deps.getYomitanParserRuntimeDeps(), {
|
||||
error: (message, ...args) => logger.error(message, ...args),
|
||||
info: (message, ...args) => logger.info(message, ...args),
|
||||
});
|
||||
const integrity = observeYomitanDictionaryCount(deps.userDataPath, dictionaries.length);
|
||||
if (!integrity.safe) {
|
||||
logger.error(`[dictionary:integrity] ${integrity.message}`);
|
||||
}
|
||||
return dictionaries.length;
|
||||
},
|
||||
isExternalYomitanConfigured: () =>
|
||||
configService.getConfig().yomitan.externalProfilePath.trim().length > 0,
|
||||
detectPluginInstalled: () => {
|
||||
const candidates = detectInstalledFirstRunPluginCandidates({
|
||||
platform: process.platform,
|
||||
homeDir: os.homedir(),
|
||||
xdgConfigHome: process.env.XDG_CONFIG_HOME,
|
||||
appDataDir: deps.getAppPath('appData'),
|
||||
mpvExecutablePath: configService.getConfig().mpv.executablePath,
|
||||
});
|
||||
if (candidates.length > 0) {
|
||||
return true;
|
||||
}
|
||||
const installPaths = resolveDefaultMpvInstallPaths(
|
||||
process.platform,
|
||||
os.homedir(),
|
||||
process.env.XDG_CONFIG_HOME,
|
||||
);
|
||||
return detectInstalledFirstRunPlugin(installPaths);
|
||||
},
|
||||
detectLegacyMpvPluginCandidates: () =>
|
||||
detectInstalledFirstRunPluginCandidates({
|
||||
platform: process.platform,
|
||||
homeDir: os.homedir(),
|
||||
xdgConfigHome: process.env.XDG_CONFIG_HOME,
|
||||
appDataDir: deps.getAppPath('appData'),
|
||||
mpvExecutablePath: configService.getConfig().mpv.executablePath,
|
||||
}),
|
||||
removeLegacyMpvPlugins: (candidates) =>
|
||||
removeLegacyMpvPluginCandidates({
|
||||
candidates,
|
||||
trashItem: (candidatePath) => deps.trashItem(candidatePath),
|
||||
}),
|
||||
detectWindowsMpvShortcuts: () => {
|
||||
if (process.platform !== 'win32') {
|
||||
return {
|
||||
startMenuInstalled: false,
|
||||
desktopInstalled: false,
|
||||
};
|
||||
}
|
||||
return detectWindowsMpvShortcuts(resolveWindowsMpvShortcutRuntimePaths());
|
||||
},
|
||||
applyWindowsMpvShortcuts: async (preferences) => {
|
||||
if (process.platform !== 'win32') {
|
||||
return {
|
||||
ok: true,
|
||||
status: 'unknown' as const,
|
||||
message: '',
|
||||
};
|
||||
}
|
||||
return applyWindowsMpvShortcuts({
|
||||
preferences,
|
||||
paths: resolveWindowsMpvShortcutRuntimePaths(),
|
||||
exePath: process.execPath,
|
||||
writeShortcutLink: (shortcutPath, operation, details) =>
|
||||
deps.writeShortcutLink(shortcutPath, operation, details),
|
||||
});
|
||||
},
|
||||
detectCommandLineLauncher: async () =>
|
||||
detectCommandLineLauncher(await deps.createCommandLineLauncherRuntimeOptions()),
|
||||
installBun: async () => {
|
||||
const snapshot = await installCommandLineBun(
|
||||
await deps.createCommandLineLauncherRuntimeOptions(),
|
||||
);
|
||||
return {
|
||||
ok: snapshot.status === 'ready',
|
||||
message:
|
||||
snapshot.message ??
|
||||
(snapshot.status === 'ready'
|
||||
? 'Bun is ready. Open a new terminal.'
|
||||
: 'Bun installation failed.'),
|
||||
};
|
||||
},
|
||||
installCommandLineLauncher: async () => {
|
||||
const snapshot = await installCommandLineLauncher(
|
||||
await deps.createCommandLineLauncherRuntimeOptions(),
|
||||
);
|
||||
const ok = snapshot.status === 'ready' || snapshot.status === 'not_on_path';
|
||||
return {
|
||||
ok,
|
||||
installPath: snapshot.installPath,
|
||||
message:
|
||||
snapshot.message ??
|
||||
(ok
|
||||
? 'Command-line launcher installed. Open a new terminal.'
|
||||
: 'Command-line launcher installation failed.'),
|
||||
};
|
||||
},
|
||||
onStateChanged: (state) => {
|
||||
appState.firstRunSetupCompleted = state.status === 'completed';
|
||||
deps.onSetupStateChanged();
|
||||
},
|
||||
});
|
||||
|
||||
const maybeFocusExistingFirstRunSetupWindow = createMaybeFocusExistingFirstRunSetupWindowHandler({
|
||||
getSetupWindow: () => appState.firstRunSetupWindow,
|
||||
});
|
||||
const openFirstRunSetupWindowHandler = createOpenFirstRunSetupWindowHandler({
|
||||
maybeFocusExistingSetupWindow: maybeFocusExistingFirstRunSetupWindow,
|
||||
createSetupWindow: createCreateFirstRunSetupWindowHandler({
|
||||
createBrowserWindow: (options) => deps.createBrowserWindow(options),
|
||||
}),
|
||||
getSetupSnapshot: async () => {
|
||||
const snapshot = await firstRunSetupService.getSetupStatus();
|
||||
const mpvExecutablePath = configService.getConfig().mpv.executablePath;
|
||||
return {
|
||||
configReady: snapshot.configReady,
|
||||
dictionaryCount: snapshot.dictionaryCount,
|
||||
dictionaryBackend: snapshot.dictionaryBackend,
|
||||
hachidoriHost: snapshot.hachidoriHost,
|
||||
canFinish: snapshot.canFinish,
|
||||
externalYomitanConfigured: snapshot.externalYomitanConfigured,
|
||||
pluginStatus: snapshot.pluginStatus,
|
||||
pluginInstallPathSummary: snapshot.pluginInstallPathSummary,
|
||||
legacyMpvPluginPaths: snapshot.legacyMpvPluginPaths,
|
||||
mpvExecutablePath,
|
||||
mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath),
|
||||
windowsMpvShortcuts: snapshot.windowsMpvShortcuts,
|
||||
commandLineLauncher: snapshot.commandLineLauncher,
|
||||
message: firstRunSetupMessage,
|
||||
};
|
||||
},
|
||||
buildSetupHtml: (model) => buildFirstRunSetupHtml(model),
|
||||
parseSubmissionUrl: (rawUrl) => parseFirstRunSetupSubmissionUrl(rawUrl),
|
||||
handleAction: async (submission: FirstRunSetupSubmission) => {
|
||||
if (
|
||||
submission.action === 'link-hachidori-host' ||
|
||||
submission.action === 'unlink-hachidori-host'
|
||||
) {
|
||||
try {
|
||||
if (deps.dictionaryBackend !== 'hachidori')
|
||||
throw new Error('Select Hachidori and restart SubMiner before linking a host.');
|
||||
await deps.ensureYomitanExtensionLoaded();
|
||||
const status = await requestHachidoriSharing(
|
||||
submission.action === 'link-hachidori-host'
|
||||
? { type: 'hd_sharing_client_link', address: submission.address }
|
||||
: { type: 'hd_sharing_client_unlink' },
|
||||
deps.getYomitanParserRuntimeDeps(),
|
||||
logger,
|
||||
);
|
||||
firstRunSetupMessage =
|
||||
status.kind === 'local'
|
||||
? 'Using dictionaries installed in SubMiner.'
|
||||
: status.kind === 'connected'
|
||||
? `Linked to ${status.name}. Anki mining stays in SubMiner.`
|
||||
: status.message;
|
||||
} catch (error) {
|
||||
firstRunSetupMessage =
|
||||
error instanceof Error ? error.message : 'Could not update the dictionary host.';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'remove-legacy-plugin') {
|
||||
const snapshot = await firstRunSetupService.removeLegacyMpvPlugin();
|
||||
firstRunSetupMessage = snapshot.message;
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'configure-mpv-executable-path') {
|
||||
const mpvExecutablePath = submission.mpvExecutablePath?.trim() ?? '';
|
||||
const pathStatus = getConfiguredWindowsMpvPathStatus(mpvExecutablePath);
|
||||
configService.patchRawConfig({
|
||||
mpv: {
|
||||
executablePath: mpvExecutablePath,
|
||||
},
|
||||
});
|
||||
firstRunSetupMessage =
|
||||
pathStatus === 'invalid'
|
||||
? `Saved mpv executable path, but the file was not found: ${mpvExecutablePath}`
|
||||
: mpvExecutablePath
|
||||
? `Saved mpv executable path: ${mpvExecutablePath}`
|
||||
: 'Cleared mpv executable path. SubMiner will auto-discover mpv.exe from SUBMINER_MPV_PATH or PATH.';
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'configure-windows-mpv-shortcuts') {
|
||||
const snapshot = await firstRunSetupService.configureWindowsMpvShortcuts({
|
||||
startMenuEnabled: submission.startMenuEnabled === true,
|
||||
desktopEnabled: submission.desktopEnabled === true,
|
||||
});
|
||||
firstRunSetupMessage = snapshot.message;
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'install-bun') {
|
||||
const snapshot = await firstRunSetupService.installBun();
|
||||
firstRunSetupMessage = snapshot.message;
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'install-command-line-launcher') {
|
||||
const snapshot = await firstRunSetupService.installCommandLineLauncher();
|
||||
firstRunSetupMessage = snapshot.message;
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'open-yomitan-settings') {
|
||||
firstRunSetupMessage = deps.openDictionarySettings()
|
||||
? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.`
|
||||
: 'Yomitan settings are unavailable while external read-only profile mode is enabled.';
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'open-config-settings') {
|
||||
const opened = deps.openConfigSettingsWindow();
|
||||
firstRunSetupMessage = opened
|
||||
? 'Opened SubMiner settings.'
|
||||
: 'SubMiner settings are unavailable.';
|
||||
if (opened) {
|
||||
return { skipRender: true };
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (submission.action === 'refresh') {
|
||||
const snapshot = await firstRunSetupService.refreshStatus('Status refreshed.');
|
||||
firstRunSetupMessage = snapshot.message;
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await firstRunSetupService.markSetupCompleted();
|
||||
if (snapshot.state.status === 'completed') {
|
||||
firstRunSetupMessage = null;
|
||||
return { closeWindow: true };
|
||||
}
|
||||
firstRunSetupMessage =
|
||||
getFirstRunSetupCompletionMessage(snapshot) ??
|
||||
'Finish setup requires the mpv plugin and Yomitan dictionaries.';
|
||||
return;
|
||||
},
|
||||
markSetupInProgress: async () => {
|
||||
firstRunSetupMessage = null;
|
||||
await firstRunSetupService.markSetupInProgress();
|
||||
},
|
||||
markSetupCancelled: async () => {
|
||||
firstRunSetupMessage = null;
|
||||
await firstRunSetupService.markSetupCancelled();
|
||||
},
|
||||
isSetupCompleted: () => firstRunSetupService.isSetupCompleted(),
|
||||
shouldQuitWhenClosedIncomplete: () => !appState.backgroundMode,
|
||||
shouldQuitWhenClosedCompleted: () =>
|
||||
Boolean(appState.initialArgs && isStandaloneFirstRunSetupCommand(appState.initialArgs)),
|
||||
quitApp: () => deps.requestAppQuit(),
|
||||
clearSetupWindow: () => {
|
||||
appState.firstRunSetupWindow = null;
|
||||
},
|
||||
setSetupWindow: (window) => {
|
||||
appState.firstRunSetupWindow = window as BrowserWindow;
|
||||
},
|
||||
encodeURIComponent: (value) => encodeURIComponent(value),
|
||||
logError: (message, error) => logger.error(message, error),
|
||||
});
|
||||
|
||||
/** Opens the setup window; without `force` it is a no-op once setup has completed. */
|
||||
function openWindow(force = false): void {
|
||||
if (!force && firstRunSetupService.isSetupCompleted()) {
|
||||
return;
|
||||
}
|
||||
openFirstRunSetupWindowHandler();
|
||||
}
|
||||
|
||||
return { service: firstRunSetupService, openWindow };
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createJellyfinAssembly, type JellyfinAssemblyDeps } from './jellyfin';
|
||||
|
||||
// Every callback throws, so a test fails if the assembly calls a dep it should only call later.
|
||||
function makeDeps(): JellyfinAssemblyDeps {
|
||||
const lazy = (name: string) => (): never => {
|
||||
throw new Error(`${name} called unexpectedly`);
|
||||
};
|
||||
return {
|
||||
appState: {
|
||||
mpvClient: null,
|
||||
mpvSocketPath: '/tmp/subminer-test.sock',
|
||||
immersionTracker: null,
|
||||
jellyfinRemoteSession: null,
|
||||
jellyfinSetupWindow: null,
|
||||
},
|
||||
configService: { getConfig: lazy('getConfig'), patchRawConfig: lazy('patchRawConfig') },
|
||||
jellyfinTokenStore: {
|
||||
loadSession: lazy('loadSession'),
|
||||
saveSession: lazy('saveSession'),
|
||||
clearSession: lazy('clearSession'),
|
||||
},
|
||||
logger: { info: () => {}, warn: () => {}, debug: () => {}, error: () => {} },
|
||||
defaultMpvLogPath: '/tmp/mpv.log',
|
||||
getAppDataPath: lazy('getAppDataPath'),
|
||||
getRuntimePluginEntrypoint: lazy('getRuntimePluginEntrypoint'),
|
||||
getMpvPluginRuntimeConfig: lazy('getMpvPluginRuntimeConfig'),
|
||||
createMpvClient: lazy('createMpvClient'),
|
||||
initSubtitlePrefetch: lazy('initSubtitlePrefetch'),
|
||||
showVisibleOverlay: lazy('showVisibleOverlay'),
|
||||
getOverlayNotifications: lazy('getOverlayNotifications'),
|
||||
updateCurrentMediaTitle: lazy('updateCurrentMediaTitle'),
|
||||
ensureImmersionTrackerStarted: lazy('ensureImmersionTrackerStarted'),
|
||||
refreshTrayMenu: lazy('refreshTrayMenu'),
|
||||
setupPreloadPath: '/tmp/preload-jellyfin-setup.js',
|
||||
createBrowserWindow: lazy('createBrowserWindow'),
|
||||
ipcMain: { handle: lazy('ipcMain.handle'), removeHandler: lazy('ipcMain.removeHandler') },
|
||||
};
|
||||
}
|
||||
|
||||
// main.ts builds the assembly before several siblings exist, so construction must stay lazy.
|
||||
test('createJellyfinAssembly does not call its deps while constructing', () => {
|
||||
const jellyfin = createJellyfinAssembly(makeDeps());
|
||||
assert.equal(jellyfin.getActivePlayback(), null);
|
||||
assert.equal(jellyfin.getQuitOnDisconnectArmed(), false);
|
||||
});
|
||||
@@ -0,0 +1,457 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import type { BrowserWindow, BrowserWindowConstructorOptions, IpcMain } from 'electron';
|
||||
import { DEFAULT_CONFIG } from '../../config/definitions';
|
||||
import type { ConfigService } from '../../config/service';
|
||||
import {
|
||||
authenticateWithPasswordRuntime,
|
||||
JellyfinPlaybackReporter,
|
||||
JellyfinRemoteSessionService,
|
||||
jellyfinTicksToSecondsRuntime,
|
||||
listJellyfinItemsRuntime,
|
||||
listJellyfinLibrariesRuntime,
|
||||
listJellyfinSubtitleTracksRuntime,
|
||||
resolveJellyfinPlaybackPlanRuntime,
|
||||
sendMpvCommandRuntime,
|
||||
type MpvIpcClient,
|
||||
} from '../../core/services';
|
||||
import type { JellyfinTokenStore } from '../../core/services/jellyfin-token-store';
|
||||
import type { Logger } from '../../logger';
|
||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
||||
import { writeJellyfinCliResponse } from '../../shared/jellyfin-cli-response';
|
||||
import { isLogFileEnabled } from '../../shared/log-files';
|
||||
import { composeJellyfinRuntimeHandlers } from '../runtime/composers';
|
||||
import {
|
||||
buildJellyfinSetupFormHtml,
|
||||
createApplyJellyfinMpvDefaultsHandler,
|
||||
getConfiguredJellyfinSession,
|
||||
mergeJellyfinRecentServers,
|
||||
parseJellyfinSetupSubmissionUrl,
|
||||
persistJellyfinAuthSession,
|
||||
type ActiveJellyfinRemotePlaybackState,
|
||||
} from '../runtime/domains/jellyfin';
|
||||
import { detectInstalledMpvPlugin } from '../runtime/first-run-setup-plugin';
|
||||
import {
|
||||
DEFAULT_JELLYFIN_CLIENT_NAME,
|
||||
DEFAULT_JELLYFIN_CLIENT_VERSION,
|
||||
createHostDerivedJellyfinDeviceId,
|
||||
resolveJellyfinRemoteDeviceName,
|
||||
} from '../runtime/jellyfin-device-identity';
|
||||
import { createJellyfinSubtitleCacheIo } from '../runtime/jellyfin-subtitle-cache-io';
|
||||
import { clearJellyfinAuthSessionAndRefreshTray as clearJellyfinAuthSessionAndRefreshTrayRuntime } from '../runtime/jellyfin-tray-discovery';
|
||||
import { resolveMpvExecutablePath, spawnMpvProcess } from '../runtime/mpv-process';
|
||||
import type { createOverlayNotificationsRuntime } from '../runtime/overlay-notifications-runtime';
|
||||
import { createCreateJellyfinSetupWindowHandler } from '../runtime/setup-window-factory';
|
||||
import type { AppState } from '../state';
|
||||
|
||||
const JELLYFIN_LANG_PREF = 'ja,jp,jpn,japanese,en,eng,english,enUS,en-US';
|
||||
const JELLYFIN_TICKS_PER_SECOND = 10_000_000;
|
||||
const JELLYFIN_REMOTE_PROGRESS_INTERVAL_MS = 3000;
|
||||
const JELLYFIN_REMOTE_STARTUP_STOP_GRACE_MS = 10_000;
|
||||
const JELLYFIN_MPV_CONNECT_TIMEOUT_MS = 3000;
|
||||
const JELLYFIN_MPV_AUTO_LAUNCH_TIMEOUT_MS = 20000;
|
||||
const MPV_JELLYFIN_DEFAULT_ARGS = [
|
||||
'--sub-auto=no',
|
||||
'--sub-file-paths=.;subs;subtitles',
|
||||
'--sid=no',
|
||||
'--secondary-sid=no',
|
||||
'--sub-visibility=no',
|
||||
'--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',
|
||||
] as const;
|
||||
|
||||
type JellyfinComposerOptions = Parameters<typeof composeJellyfinRuntimeHandlers>[0];
|
||||
type LaunchMpvIdleDeps = JellyfinComposerOptions['launchMpvIdleForJellyfinPlaybackMainDeps'];
|
||||
|
||||
/**
|
||||
* What the Jellyfin domain needs from the rest of the app. Siblings built after this assembly in
|
||||
* `main.ts` are reached through getters or callbacks, which are only called once the app runs.
|
||||
*/
|
||||
export interface JellyfinAssemblyDeps {
|
||||
appState: Pick<
|
||||
AppState,
|
||||
| 'mpvClient'
|
||||
| 'mpvSocketPath'
|
||||
| 'immersionTracker'
|
||||
| 'jellyfinRemoteSession'
|
||||
| 'jellyfinSetupWindow'
|
||||
>;
|
||||
configService: Pick<ConfigService, 'getConfig' | 'patchRawConfig'>;
|
||||
jellyfinTokenStore: JellyfinTokenStore;
|
||||
logger: Pick<Logger, 'info' | 'warn' | 'debug' | 'error'>;
|
||||
defaultMpvLogPath: string;
|
||||
getAppDataPath: () => string;
|
||||
getRuntimePluginEntrypoint: NonNullable<LaunchMpvIdleDeps['getRuntimePluginEntrypoint']>;
|
||||
getMpvPluginRuntimeConfig: NonNullable<LaunchMpvIdleDeps['getPluginRuntimeConfig']>;
|
||||
createMpvClient: () => MpvIpcClient;
|
||||
initSubtitlePrefetch: NonNullable<
|
||||
JellyfinComposerOptions['preloadJellyfinExternalSubtitlesMainDeps']['initSubtitlePrefetch']
|
||||
>;
|
||||
showVisibleOverlay: () => void;
|
||||
getOverlayNotifications: () => Pick<
|
||||
ReturnType<typeof createOverlayNotificationsRuntime>,
|
||||
'showConfiguredStatusNotification'
|
||||
>;
|
||||
updateCurrentMediaTitle: (title: string) => void;
|
||||
ensureImmersionTrackerStarted: () => void;
|
||||
refreshTrayMenu: () => void;
|
||||
setupPreloadPath: string;
|
||||
createBrowserWindow: (options: BrowserWindowConstructorOptions) => BrowserWindow;
|
||||
ipcMain: Pick<IpcMain, 'handle' | 'removeHandler'>;
|
||||
}
|
||||
|
||||
export type JellyfinAssembly = ReturnType<typeof createJellyfinAssembly>;
|
||||
|
||||
/**
|
||||
* Owns Jellyfin playback, remote-control session, CLI commands, setup window and tray discovery,
|
||||
* plus the playback state they share. `main.ts` builds it once and calls through the result.
|
||||
*/
|
||||
export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
|
||||
const { appState, configService, jellyfinTokenStore, logger } = deps;
|
||||
|
||||
const jellyfinSubtitleCacheIo = createJellyfinSubtitleCacheIo({
|
||||
tmpDir: () => os.tmpdir(),
|
||||
makeTempDir: (prefix) => fs.promises.mkdtemp(prefix),
|
||||
writeFile: (filePath, bytes) => fs.promises.writeFile(filePath, bytes),
|
||||
removeDir: (dir, options) => {
|
||||
fs.rmSync(dir, options);
|
||||
},
|
||||
fetch: (url) => fetch(url),
|
||||
});
|
||||
|
||||
let jellyfinPlayQuitOnDisconnectArmed = false;
|
||||
let activeJellyfinRemotePlayback: ActiveJellyfinRemotePlaybackState | null = null;
|
||||
let jellyfinRemoteLastProgressAtMs = 0;
|
||||
let jellyfinMpvAutoLaunchInFlight: Promise<boolean> | null = null;
|
||||
|
||||
const applyJellyfinMpvDefaultsHandler = createApplyJellyfinMpvDefaultsHandler({
|
||||
sendMpvCommandRuntime: (client, command) => sendMpvCommandRuntime(client, command),
|
||||
jellyfinLangPref: JELLYFIN_LANG_PREF,
|
||||
});
|
||||
|
||||
const {
|
||||
getResolvedJellyfinConfig,
|
||||
reportJellyfinRemoteProgress,
|
||||
reportJellyfinRemoteStopped,
|
||||
startJellyfinRemoteSession,
|
||||
stopJellyfinRemoteSession,
|
||||
cleanupJellyfinSubtitleCache,
|
||||
runJellyfinCommand,
|
||||
openJellyfinSetupWindow,
|
||||
ensureMpvConnectedForPlayback,
|
||||
} = composeJellyfinRuntimeHandlers({
|
||||
getResolvedJellyfinConfigMainDeps: {
|
||||
getResolvedConfig: () => configService.getConfig(),
|
||||
loadStoredSession: () => jellyfinTokenStore.loadSession(),
|
||||
getEnv: (name) => process.env[name],
|
||||
},
|
||||
getJellyfinClientInfoMainDeps: {
|
||||
getResolvedJellyfinConfig: () => getResolvedJellyfinConfig(),
|
||||
getHostName: () => os.hostname(),
|
||||
defaultClientName: DEFAULT_JELLYFIN_CLIENT_NAME,
|
||||
defaultClientVersion: DEFAULT_JELLYFIN_CLIENT_VERSION,
|
||||
},
|
||||
waitForMpvConnectedMainDeps: {
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
now: () => Date.now(),
|
||||
sleep: (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),
|
||||
},
|
||||
launchMpvIdleForJellyfinPlaybackMainDeps: {
|
||||
getMpvExecutablePath: () =>
|
||||
resolveMpvExecutablePath(configService.getConfig().mpv.executablePath),
|
||||
getSocketPath: () => appState.mpvSocketPath,
|
||||
getLaunchMode: () => configService.getConfig().mpv.launchMode,
|
||||
platform: process.platform,
|
||||
execPath: process.execPath,
|
||||
getRuntimePluginEntrypoint: () => deps.getRuntimePluginEntrypoint(),
|
||||
getInstalledPluginDetection: (mpvExecutablePath) =>
|
||||
detectInstalledMpvPlugin({
|
||||
platform: process.platform,
|
||||
homeDir: os.homedir(),
|
||||
xdgConfigHome: process.env.XDG_CONFIG_HOME,
|
||||
appDataDir: deps.getAppDataPath(),
|
||||
mpvExecutablePath,
|
||||
}),
|
||||
getPluginRuntimeConfig: () => deps.getMpvPluginRuntimeConfig(),
|
||||
getDefaultMpvLogPath: () => (isLogFileEnabled('mpv') ? deps.defaultMpvLogPath : ''),
|
||||
defaultMpvArgs: MPV_JELLYFIN_DEFAULT_ARGS,
|
||||
removeSocketPath: (socketPath) => {
|
||||
fs.rmSync(socketPath, { force: true });
|
||||
},
|
||||
spawnMpv: spawnMpvProcess,
|
||||
logWarn: (message, error) => logger.warn(message, error),
|
||||
logInfo: (message) => logger.info(message),
|
||||
},
|
||||
ensureMpvConnectedForJellyfinPlaybackMainDeps: {
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
setMpvClient: (client) => {
|
||||
appState.mpvClient = client as MpvIpcClient | null;
|
||||
},
|
||||
createMpvClient: () => deps.createMpvClient(),
|
||||
getAutoLaunchInFlight: () => jellyfinMpvAutoLaunchInFlight,
|
||||
setAutoLaunchInFlight: (promise) => {
|
||||
jellyfinMpvAutoLaunchInFlight = promise;
|
||||
},
|
||||
connectTimeoutMs: JELLYFIN_MPV_CONNECT_TIMEOUT_MS,
|
||||
autoLaunchTimeoutMs: JELLYFIN_MPV_AUTO_LAUNCH_TIMEOUT_MS,
|
||||
},
|
||||
preloadJellyfinExternalSubtitlesMainDeps: {
|
||||
listJellyfinSubtitleTracks: (session, clientInfo, itemId) =>
|
||||
listJellyfinSubtitleTracksRuntime(session, clientInfo, itemId),
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
sendMpvCommand: (command) => {
|
||||
sendMpvCommandRuntime(appState.mpvClient, command);
|
||||
},
|
||||
wait: (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
|
||||
cacheSubtitleTrack: (track) => jellyfinSubtitleCacheIo.cacheSubtitleTrack(track),
|
||||
cleanupCachedSubtitles: (dirs) => jellyfinSubtitleCacheIo.cleanupCachedSubtitles(dirs),
|
||||
initSubtitlePrefetch: (sourcePath) => deps.initSubtitlePrefetch(sourcePath),
|
||||
logDebug: (message, error) => {
|
||||
logger.debug(message, error);
|
||||
},
|
||||
},
|
||||
playJellyfinItemInMpvMainDeps: {
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
resolvePlaybackPlan: (params) =>
|
||||
resolveJellyfinPlaybackPlanRuntime(
|
||||
params.session,
|
||||
params.clientInfo,
|
||||
params.jellyfinConfig as ReturnType<typeof getResolvedJellyfinConfig>,
|
||||
{
|
||||
itemId: params.itemId,
|
||||
audioStreamIndex: params.audioStreamIndex ?? undefined,
|
||||
subtitleStreamIndex: params.subtitleStreamIndex ?? undefined,
|
||||
},
|
||||
),
|
||||
applyJellyfinMpvDefaults: (mpvClient) => applyJellyfinMpvDefaultsHandler(mpvClient),
|
||||
showVisibleOverlay: () => deps.showVisibleOverlay(),
|
||||
sendMpvCommand: (command) => sendMpvCommandRuntime(appState.mpvClient, command),
|
||||
armQuitOnDisconnect: () => {
|
||||
jellyfinPlayQuitOnDisconnectArmed = false;
|
||||
setTimeout(() => {
|
||||
jellyfinPlayQuitOnDisconnectArmed = true;
|
||||
}, 3000);
|
||||
},
|
||||
schedule: (callback, delayMs) => {
|
||||
setTimeout(callback, delayMs);
|
||||
},
|
||||
convertTicksToSeconds: (ticks) => jellyfinTicksToSecondsRuntime(ticks),
|
||||
setActivePlayback: (state) => {
|
||||
activeJellyfinRemotePlayback = {
|
||||
...(state as ActiveJellyfinRemotePlaybackState),
|
||||
stopReportsAfterMs:
|
||||
state.stopReportsAfterMs ?? Date.now() + JELLYFIN_REMOTE_STARTUP_STOP_GRACE_MS,
|
||||
};
|
||||
},
|
||||
setLastProgressAtMs: (value) => {
|
||||
jellyfinRemoteLastProgressAtMs = value;
|
||||
},
|
||||
// Same device identity as the cast session, so Jellyfin attributes reports to one session.
|
||||
createPlaybackReporter: ({ session, clientInfo }) =>
|
||||
new JellyfinPlaybackReporter({
|
||||
serverUrl: session.serverUrl,
|
||||
accessToken: session.accessToken,
|
||||
deviceId: clientInfo.deviceId,
|
||||
clientName: clientInfo.clientName,
|
||||
clientVersion: clientInfo.clientVersion,
|
||||
deviceName: resolveJellyfinRemoteDeviceName({ hostName: os.hostname() }),
|
||||
logWarn: (message, details) => logger.warn(message, details),
|
||||
}),
|
||||
showMpvOsd: (text) => {
|
||||
deps
|
||||
.getOverlayNotifications()
|
||||
.showConfiguredStatusNotification(text, { title: 'Jellyfin' });
|
||||
},
|
||||
updateCurrentMediaTitle: (title) => {
|
||||
deps.updateCurrentMediaTitle(title);
|
||||
},
|
||||
recordJellyfinPlaybackMetadata: (metadata) => {
|
||||
deps.ensureImmersionTrackerStarted();
|
||||
appState.immersionTracker?.recordJellyfinPlaybackMetadata(metadata);
|
||||
},
|
||||
},
|
||||
remoteComposerOptions: {
|
||||
getConfiguredSession: () => getConfiguredJellyfinSession(getResolvedJellyfinConfig()),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
sendMpvCommand: (client, command) => sendMpvCommandRuntime(client as MpvIpcClient, command),
|
||||
jellyfinTicksToSeconds: (ticks) => jellyfinTicksToSecondsRuntime(ticks),
|
||||
getActivePlayback: () => activeJellyfinRemotePlayback,
|
||||
clearActivePlayback: () => {
|
||||
activeJellyfinRemotePlayback = null;
|
||||
},
|
||||
getNow: () => Date.now(),
|
||||
getLastProgressAtMs: () => jellyfinRemoteLastProgressAtMs,
|
||||
setLastProgressAtMs: (value) => {
|
||||
jellyfinRemoteLastProgressAtMs = value;
|
||||
},
|
||||
progressIntervalMs: JELLYFIN_REMOTE_PROGRESS_INTERVAL_MS,
|
||||
ticksPerSecond: JELLYFIN_TICKS_PER_SECOND,
|
||||
logDebug: (message, error) => logger.debug(message, error),
|
||||
},
|
||||
handleJellyfinAuthCommandsMainDeps: {
|
||||
patchRawConfig: (patch) => {
|
||||
configService.patchRawConfig(patch);
|
||||
deps.refreshTrayMenu();
|
||||
},
|
||||
authenticateWithPassword: (serverUrl, username, password, clientInfo) =>
|
||||
authenticateWithPasswordRuntime(serverUrl, username, password, clientInfo),
|
||||
saveStoredSession: (session) => jellyfinTokenStore.saveSession(session),
|
||||
clearStoredSession: () =>
|
||||
clearJellyfinAuthSessionAndRefreshTrayRuntime(getJellyfinTrayDiscoveryDeps()),
|
||||
logInfo: (message) => logger.info(message),
|
||||
},
|
||||
handleJellyfinListCommandsMainDeps: {
|
||||
listJellyfinLibraries: (session, clientInfo) =>
|
||||
listJellyfinLibrariesRuntime(session, clientInfo),
|
||||
listJellyfinItems: (session, clientInfo, params) =>
|
||||
listJellyfinItemsRuntime(session, clientInfo, params),
|
||||
listJellyfinSubtitleTracks: (session, clientInfo, itemId) =>
|
||||
listJellyfinSubtitleTracksRuntime(session, clientInfo, itemId),
|
||||
writeJellyfinResponse: writeJellyfinCliResponse,
|
||||
logInfo: (message) => logger.info(message),
|
||||
},
|
||||
handleJellyfinPlayCommandMainDeps: {
|
||||
logWarn: (message) => logger.warn(message),
|
||||
},
|
||||
handleJellyfinRemoteAnnounceCommandMainDeps: {
|
||||
getRemoteSession: () => appState.jellyfinRemoteSession,
|
||||
logInfo: (message) => logger.info(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
},
|
||||
startJellyfinRemoteSessionMainDeps: {
|
||||
getCurrentSession: () => appState.jellyfinRemoteSession,
|
||||
setCurrentSession: (session) => {
|
||||
appState.jellyfinRemoteSession = session as typeof appState.jellyfinRemoteSession;
|
||||
},
|
||||
createRemoteSessionService: (options) => new JellyfinRemoteSessionService(options),
|
||||
getHostName: () => os.hostname(),
|
||||
defaultDeviceId: createHostDerivedJellyfinDeviceId(os.hostname()),
|
||||
defaultClientName: DEFAULT_JELLYFIN_CLIENT_NAME,
|
||||
defaultClientVersion: DEFAULT_JELLYFIN_CLIENT_VERSION,
|
||||
logInfo: (message) => logger.info(message),
|
||||
logWarn: (message, details) => logger.warn(message, details),
|
||||
onSessionStateChanged: () => deps.refreshTrayMenu(),
|
||||
},
|
||||
stopJellyfinRemoteSessionMainDeps: {
|
||||
getCurrentSession: () => appState.jellyfinRemoteSession,
|
||||
setCurrentSession: (session) => {
|
||||
appState.jellyfinRemoteSession = session as typeof appState.jellyfinRemoteSession;
|
||||
},
|
||||
clearActivePlayback: () => {
|
||||
activeJellyfinRemotePlayback = null;
|
||||
},
|
||||
onSessionStateChanged: () => deps.refreshTrayMenu(),
|
||||
},
|
||||
runJellyfinCommandMainDeps: {
|
||||
defaultServerUrl: DEFAULT_CONFIG.jellyfin.serverUrl,
|
||||
writeJellyfinResponse: writeJellyfinCliResponse,
|
||||
},
|
||||
maybeFocusExistingJellyfinSetupWindowMainDeps: {
|
||||
getSetupWindow: () => appState.jellyfinSetupWindow,
|
||||
},
|
||||
openJellyfinSetupWindowMainDeps: {
|
||||
createSetupWindow: createCreateJellyfinSetupWindowHandler({
|
||||
createBrowserWindow: (options) => deps.createBrowserWindow(options),
|
||||
preloadPath: deps.setupPreloadPath,
|
||||
}),
|
||||
buildSetupFormHtml: (state) => buildJellyfinSetupFormHtml(state),
|
||||
parseSubmissionUrl: (rawUrl) => parseJellyfinSetupSubmissionUrl(rawUrl),
|
||||
authenticateWithPassword: (server, username, password, clientInfo) =>
|
||||
authenticateWithPasswordRuntime(server, username, password, clientInfo),
|
||||
saveStoredSession: (session) => jellyfinTokenStore.saveSession(session),
|
||||
clearStoredSession: () =>
|
||||
clearJellyfinAuthSessionAndRefreshTrayRuntime(getJellyfinTrayDiscoveryDeps()),
|
||||
patchJellyfinConfig: (session) => {
|
||||
const recentServers = mergeJellyfinRecentServers(
|
||||
session.serverUrl,
|
||||
configService.getConfig().jellyfin.recentServers || [],
|
||||
);
|
||||
configService.patchRawConfig({
|
||||
jellyfin: {
|
||||
enabled: true,
|
||||
serverUrl: session.serverUrl,
|
||||
username: session.username,
|
||||
recentServers,
|
||||
},
|
||||
});
|
||||
deps.refreshTrayMenu();
|
||||
},
|
||||
persistAuthenticatedSession: (session, clientInfo) =>
|
||||
persistJellyfinAuthSession({
|
||||
session,
|
||||
clientInfo,
|
||||
existingRecentServers: configService.getConfig().jellyfin.recentServers || [],
|
||||
saveStoredSession: (storedSession) => jellyfinTokenStore.saveSession(storedSession),
|
||||
patchRawConfig: (patch) => {
|
||||
configService.patchRawConfig(patch);
|
||||
deps.refreshTrayMenu();
|
||||
},
|
||||
}),
|
||||
logInfo: (message) => logger.info(message),
|
||||
logError: (message, error) => logger.error(message, error),
|
||||
showMpvOsd: (message) =>
|
||||
deps
|
||||
.getOverlayNotifications()
|
||||
.showConfiguredStatusNotification(message, { title: 'Jellyfin' }),
|
||||
clearSetupWindow: () => {
|
||||
appState.jellyfinSetupWindow = null;
|
||||
},
|
||||
setSetupWindow: (window) => {
|
||||
appState.jellyfinSetupWindow = window as BrowserWindow;
|
||||
},
|
||||
registerSetupIpcHandler: (handler) => {
|
||||
const channel = IPC_CHANNELS.request.jellyfinSetupSubmit;
|
||||
deps.ipcMain.removeHandler(channel);
|
||||
deps.ipcMain.handle(channel, async (event, payload) => {
|
||||
const setupWindow = appState.jellyfinSetupWindow;
|
||||
if (!setupWindow || event.sender !== setupWindow.webContents) {
|
||||
return {
|
||||
handled: false,
|
||||
statusMessage: 'This Jellyfin setup window is no longer active.',
|
||||
statusKind: 'error',
|
||||
};
|
||||
}
|
||||
return handler(payload);
|
||||
});
|
||||
return () => {
|
||||
deps.ipcMain.removeHandler(channel);
|
||||
};
|
||||
},
|
||||
encodeURIComponent: (value) => encodeURIComponent(value),
|
||||
defaultServerUrl: DEFAULT_CONFIG.jellyfin.serverUrl || 'http://127.0.0.1:8096',
|
||||
hasStoredSession: () => Boolean(jellyfinTokenStore.loadSession()),
|
||||
},
|
||||
});
|
||||
|
||||
function getJellyfinTrayDiscoveryDeps() {
|
||||
return {
|
||||
getResolvedJellyfinConfig: () => getResolvedJellyfinConfig(),
|
||||
getRemoteSession: () => appState.jellyfinRemoteSession,
|
||||
clearStoredSession: () => jellyfinTokenStore.clearSession(),
|
||||
stopRemoteSession: () => stopJellyfinRemoteSession(),
|
||||
startRemoteSession: (options: { explicit: true }) => startJellyfinRemoteSession(options),
|
||||
refreshTrayMenu: () => deps.refreshTrayMenu(),
|
||||
logger,
|
||||
showMpvOsd: (message: string) =>
|
||||
deps
|
||||
.getOverlayNotifications()
|
||||
.showConfiguredStatusNotification(message, { title: 'Jellyfin' }),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
reportJellyfinRemoteProgress,
|
||||
reportJellyfinRemoteStopped,
|
||||
startJellyfinRemoteSession,
|
||||
stopJellyfinRemoteSession,
|
||||
cleanupJellyfinSubtitleCache,
|
||||
runJellyfinCommand,
|
||||
openJellyfinSetupWindow,
|
||||
ensureMpvConnectedForPlayback,
|
||||
getTrayDiscoveryDeps: getJellyfinTrayDiscoveryDeps,
|
||||
getActivePlayback: () => activeJellyfinRemotePlayback,
|
||||
getQuitOnDisconnectArmed: () => jellyfinPlayQuitOnDisconnectArmed,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createOverlayModalsAssembly, type OverlayModalsAssemblyDeps } from './overlay-modals';
|
||||
|
||||
type StatusCall = { message: string; title?: string; variant?: string };
|
||||
|
||||
// Every callback throws, so a test fails if the assembly calls a dep it should only call later.
|
||||
function makeDeps(overrides: Partial<OverlayModalsAssemblyDeps> = {}): OverlayModalsAssemblyDeps {
|
||||
const lazy = (name: string) => (): never => {
|
||||
throw new Error(`${name} called unexpectedly`);
|
||||
};
|
||||
return {
|
||||
appState: { mpvClient: null, currentMediaPath: null },
|
||||
getConfig: lazy('getConfig'),
|
||||
logger: { warn: () => {}, error: () => {} },
|
||||
overlayModalRuntime: { waitForModalOpen: lazy('waitForModalOpen') },
|
||||
getOverlayNotifications: lazy('getOverlayNotifications'),
|
||||
ensureOverlayStartupPrereqs: lazy('ensureOverlayStartupPrereqs'),
|
||||
ensureOverlayWindowsReadyForVisibilityActions: lazy(
|
||||
'ensureOverlayWindowsReadyForVisibilityActions',
|
||||
),
|
||||
sendToActiveOverlayWindow: lazy('sendToActiveOverlayWindow'),
|
||||
showMpvOsd: lazy('showMpvOsd'),
|
||||
showDesktopNotification: lazy('showDesktopNotification'),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// main.ts builds the assembly before most siblings exist, so construction must stay lazy.
|
||||
test('createOverlayModalsAssembly does not call its deps while constructing', () => {
|
||||
createOverlayModalsAssembly(makeDeps());
|
||||
});
|
||||
|
||||
test('playlist browser warns instead of opening when mpv is not connected', () => {
|
||||
const calls: StatusCall[] = [];
|
||||
const overlayModals = createOverlayModalsAssembly(
|
||||
makeDeps({
|
||||
getOverlayNotifications: () => ({
|
||||
getConfiguredStatusNotificationType: () => 'overlay',
|
||||
showConfiguredStatusNotification: (message, options) => {
|
||||
calls.push({ message, title: options?.title, variant: options?.variant });
|
||||
},
|
||||
showOverlayNotification: () => {},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
// The lazy overlay deps throw if the opener gets past the playback guard.
|
||||
overlayModals.openPlaylistBrowser();
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
message: 'Playlist browser requires active playback.',
|
||||
title: 'Playlist browser',
|
||||
variant: 'warning',
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
import type { Logger } from '../../logger';
|
||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
||||
import type { ResolvedConfig } from '../../types';
|
||||
import type { OverlayModalRuntime } from '../overlay-runtime';
|
||||
import { openChangelogModal as openChangelogModalRuntime } from '../runtime/changelog-open';
|
||||
import { openCharacterDictionaryManagerWithConfigGate } from '../runtime/character-dictionary-manager-gate';
|
||||
import { openCharacterDictionaryManagerModal as openCharacterDictionaryManagerModalRuntime } from '../runtime/character-dictionary-open';
|
||||
import { openControllerDebugModal as openControllerDebugModalRuntime } from '../runtime/controller-debug-open';
|
||||
import { openControllerSelectModal as openControllerSelectModalRuntime } from '../runtime/controller-select-open';
|
||||
import { openJimakuModal as openJimakuModalRuntime } from '../runtime/jimaku-open';
|
||||
import type { createOverlayNotificationsRuntime } from '../runtime/overlay-notifications-runtime';
|
||||
import { openPlaylistBrowser as openPlaylistBrowserRuntime } from '../runtime/playlist-browser-open';
|
||||
import { openRuntimeOptionsModal as openRuntimeOptionsModalRuntime } from '../runtime/runtime-options-open';
|
||||
import { openSessionHelpModal as openSessionHelpModalRuntime } from '../runtime/session-help-open';
|
||||
import { openSubtitleGenerationModal } from '../runtime/subtitle-generation-open';
|
||||
import { openTsukihimeModal as openTsukihimeModalRuntime } from '../runtime/tsukihime-open';
|
||||
import type { AppState } from '../state';
|
||||
|
||||
type OverlayNotifications = Pick<
|
||||
ReturnType<typeof createOverlayNotificationsRuntime>,
|
||||
| 'getConfiguredStatusNotificationType'
|
||||
| 'showConfiguredStatusNotification'
|
||||
| 'showOverlayNotification'
|
||||
>;
|
||||
|
||||
/** What the overlay-hosted modal openers need from the rest of the app. */
|
||||
export interface OverlayModalsAssemblyDeps {
|
||||
appState: Pick<AppState, 'mpvClient' | 'currentMediaPath'>;
|
||||
getConfig: () => ResolvedConfig;
|
||||
logger: Pick<Logger, 'warn' | 'error'>;
|
||||
overlayModalRuntime: Pick<OverlayModalRuntime, 'waitForModalOpen'>;
|
||||
getOverlayNotifications: () => OverlayNotifications;
|
||||
ensureOverlayStartupPrereqs: () => void;
|
||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
||||
sendToActiveOverlayWindow: OverlayModalRuntime['sendToActiveOverlayWindow'];
|
||||
showMpvOsd: (text: string) => void;
|
||||
showDesktopNotification: (title: string, options: { body?: string }) => void;
|
||||
}
|
||||
|
||||
export type OverlayModalsAssembly = ReturnType<typeof createOverlayModalsAssembly>;
|
||||
|
||||
/**
|
||||
* Opens the overlay-hosted modals (runtime options, Jimaku, session help, playlist browser, ...)
|
||||
* and reports through the configured status notification when one cannot open.
|
||||
*/
|
||||
export function createOverlayModalsAssembly(deps: OverlayModalsAssemblyDeps) {
|
||||
const { appState, logger } = deps;
|
||||
|
||||
function createOverlayHostedModalOpenDeps(): {
|
||||
ensureOverlayStartupPrereqs: () => void;
|
||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
||||
sendToActiveOverlayWindow: OverlayModalRuntime['sendToActiveOverlayWindow'];
|
||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
||||
logWarn: (message: string) => void;
|
||||
} {
|
||||
return {
|
||||
ensureOverlayStartupPrereqs: () => deps.ensureOverlayStartupPrereqs(),
|
||||
ensureOverlayWindowsReadyForVisibilityActions: () =>
|
||||
deps.ensureOverlayWindowsReadyForVisibilityActions(),
|
||||
sendToActiveOverlayWindow: (channel, payload, runtimeOptions) =>
|
||||
deps.sendToActiveOverlayWindow(channel, payload, runtimeOptions),
|
||||
waitForModalOpen: (modal, timeoutMs) =>
|
||||
deps.overlayModalRuntime.waitForModalOpen(modal, timeoutMs),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
};
|
||||
}
|
||||
|
||||
function openOverlayHostedModalWithOsd(
|
||||
openModal: (deps: ReturnType<typeof createOverlayHostedModalOpenDeps>) => Promise<boolean>,
|
||||
unavailableMessage: string,
|
||||
failureLogMessage: string,
|
||||
): void {
|
||||
void openModal(createOverlayHostedModalOpenDeps())
|
||||
.then((opened) => {
|
||||
if (!opened) {
|
||||
deps.getOverlayNotifications().showConfiguredStatusNotification(unavailableMessage, {
|
||||
variant: 'warning',
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error(failureLogMessage, error);
|
||||
deps.getOverlayNotifications().showConfiguredStatusNotification(unavailableMessage, {
|
||||
variant: 'error',
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function openRuntimeOptionsPalette(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openRuntimeOptionsModalRuntime,
|
||||
'Runtime options overlay unavailable.',
|
||||
'Failed to open runtime options overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
function openJimakuOverlay(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openJimakuModalRuntime,
|
||||
'Jimaku overlay unavailable.',
|
||||
'Failed to open Jimaku overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
function openTsukihimeOverlay(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openTsukihimeModalRuntime,
|
||||
'TsukiHime overlay unavailable.',
|
||||
'Failed to open TsukiHime overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
function openSubtitleGenerationOverlay(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openSubtitleGenerationModal,
|
||||
'Subtitle generation overlay unavailable.',
|
||||
'Failed to open subtitle generation overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
// currentMediaPath follows every mpv path change and is cleared on disconnect; the
|
||||
// client's currentVideoPath outlives the connection, so a reconnect could reuse it.
|
||||
function isMediaPlaybackActive(): boolean {
|
||||
return appState.mpvClient?.connected === true && Boolean(appState.currentMediaPath?.trim());
|
||||
}
|
||||
|
||||
function openSessionHelpOverlay(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
(modalDeps) => openSessionHelpModalRuntime({ ...modalDeps, isMediaPlaybackActive }),
|
||||
'Session help overlay unavailable.',
|
||||
'Failed to open session help overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
function openChangelogOverlay(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openChangelogModalRuntime,
|
||||
'Changelog overlay unavailable.',
|
||||
'Failed to open changelog overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
function openCharacterDictionaryManagerOverlay(): void {
|
||||
openCharacterDictionaryManagerWithConfigGate({
|
||||
isCharacterDictionaryEnabled: () => deps.getConfig().subtitleStyle.nameMatchEnabled,
|
||||
getNotificationType: () =>
|
||||
deps.getOverlayNotifications().getConfiguredStatusNotificationType(),
|
||||
openManager: () => {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openCharacterDictionaryManagerModalRuntime,
|
||||
'Character dictionary manager unavailable.',
|
||||
'Failed to open character dictionary manager.',
|
||||
);
|
||||
},
|
||||
showOsd: (message) => deps.showMpvOsd(message),
|
||||
showOverlayNotification: (payload) =>
|
||||
deps.getOverlayNotifications().showOverlayNotification(payload),
|
||||
showDesktopNotification: (title, options) => deps.showDesktopNotification(title, options),
|
||||
logWarn: (message, error) => logger.warn(message, error),
|
||||
});
|
||||
}
|
||||
|
||||
function openControllerSelectOverlay(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openControllerSelectModalRuntime,
|
||||
'Controller select overlay unavailable.',
|
||||
'Failed to open controller select overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
function openControllerDebugOverlay(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openControllerDebugModalRuntime,
|
||||
'Controller debug overlay unavailable.',
|
||||
'Failed to open controller debug overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
function openPlaylistBrowser(): void {
|
||||
if (!appState.mpvClient?.connected) {
|
||||
deps
|
||||
.getOverlayNotifications()
|
||||
.showConfiguredStatusNotification('Playlist browser requires active playback.', {
|
||||
title: 'Playlist browser',
|
||||
variant: 'warning',
|
||||
});
|
||||
return;
|
||||
}
|
||||
openOverlayHostedModalWithOsd(
|
||||
openPlaylistBrowserRuntime,
|
||||
'Playlist browser overlay unavailable.',
|
||||
'Failed to open playlist browser overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
createOverlayHostedModalOpenDeps,
|
||||
openOverlayHostedModalWithOsd,
|
||||
openRuntimeOptionsPalette,
|
||||
openJimakuOverlay,
|
||||
openTsukihimeOverlay,
|
||||
openSubtitleGenerationOverlay,
|
||||
openSessionHelpOverlay,
|
||||
openChangelogOverlay,
|
||||
openCharacterDictionaryManagerOverlay,
|
||||
openControllerSelectOverlay,
|
||||
openControllerDebugOverlay,
|
||||
openPlaylistBrowser,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test, { type TestContext } from 'node:test';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import type { HyprlandPlacementStatus } from '../../core/services/hyprland-window-placement';
|
||||
import type { WindowGeometry } from '../../types';
|
||||
import { createAppState } from '../state';
|
||||
import { createOverlayAssembly, type OverlayAssemblyDeps } from './overlay';
|
||||
|
||||
type Call = { name: string; args: unknown[] };
|
||||
type OverlayWindowOptions = Parameters<OverlayAssemblyDeps['createOverlayWindowCore']>[1];
|
||||
type Overlay = ReturnType<typeof createOverlayAssembly>;
|
||||
|
||||
/** Records every dep call by name, in order; each dep still returns an inert value. */
|
||||
function createRecorder() {
|
||||
const calls: Call[] = [];
|
||||
const spy =
|
||||
<A extends unknown[], R>(name: string, impl: (...args: A) => R) =>
|
||||
(...args: A): R => {
|
||||
calls.push({ name, args });
|
||||
return impl(...args);
|
||||
};
|
||||
const names = () => calls.map((call) => call.name);
|
||||
return { calls, spy, names };
|
||||
}
|
||||
|
||||
type Recorder = ReturnType<typeof createRecorder>;
|
||||
|
||||
/** Test-controlled state the fakes read from. */
|
||||
type FixtureState = {
|
||||
visible: boolean;
|
||||
trackedGeometry: WindowGeometry | null;
|
||||
/** Window returned by window creation; null makes creation throw after recording options. */
|
||||
window: BrowserWindow | null;
|
||||
};
|
||||
|
||||
const WINDOW_CREATION_STOPPED = 'window creation stopped by test';
|
||||
const NO_PLACEMENT: HyprlandPlacementStatus = {
|
||||
applicable: false,
|
||||
clientFound: false,
|
||||
dispatched: false,
|
||||
};
|
||||
|
||||
function makeDeps(recorder: Recorder, state: FixtureState) {
|
||||
const { spy } = recorder;
|
||||
const noop = () => {};
|
||||
const resolved = async () => {};
|
||||
const windowOptions: OverlayWindowOptions[] = [];
|
||||
const deps: OverlayAssemblyDeps = {
|
||||
appState: createAppState({
|
||||
mpvSocketPath: '/tmp/subminer-overlay-test.sock',
|
||||
texthookerPort: 0,
|
||||
}),
|
||||
logger: {
|
||||
debug: spy('logger.debug', noop),
|
||||
info: spy('logger.info', noop),
|
||||
warn: spy('logger.warn', noop),
|
||||
},
|
||||
overlayManager: {
|
||||
getMainWindow: spy('overlay.getMainWindow', () => null),
|
||||
setMainWindow: spy('overlay.setMainWindow', noop),
|
||||
getModalWindow: spy('overlay.getModalWindow', () => null),
|
||||
setModalWindow: spy('overlay.setModalWindow', noop),
|
||||
getVisibleOverlayVisible: spy('overlay.getVisibleOverlayVisible', () => state.visible),
|
||||
setVisibleOverlayVisible: spy('overlay.setVisibleOverlayVisible', (visible: boolean) => {
|
||||
state.visible = visible;
|
||||
}),
|
||||
setOverlayWindowBounds: spy('overlay.setOverlayWindowBounds', () => NO_PLACEMENT),
|
||||
setModalWindowBounds: spy('overlay.setModalWindowBounds', () => NO_PLACEMENT),
|
||||
},
|
||||
overlayModalInputState: { getModalInputExclusive: spy('modal.getInputExclusive', () => false) },
|
||||
autoplayReadyGate: {
|
||||
markCurrentMediaAutoplayReady: spy('autoplay.markCurrentMediaReady', noop),
|
||||
flushPendingAutoplayReadySignal: spy('autoplay.flushPending', noop),
|
||||
},
|
||||
screen: {
|
||||
getCursorScreenPoint: spy('screen.getCursorScreenPoint', () => ({ x: 0, y: 0 })),
|
||||
getDisplayNearestPoint: spy('screen.getDisplayNearestPoint', (): never => {
|
||||
throw new Error('display fallback used');
|
||||
}),
|
||||
},
|
||||
isDev: false,
|
||||
createOverlayWindowCore: spy('createOverlayWindowCore', (_kind, options): BrowserWindow => {
|
||||
windowOptions.push(options);
|
||||
if (!state.window) throw new Error(WINDOW_CREATION_STOPPED);
|
||||
return state.window;
|
||||
}),
|
||||
getYomitanSession: spy('getYomitanSession', () => null),
|
||||
getVisibleOverlayInteraction: spy('getVisibleOverlayInteraction', () => ({
|
||||
getLinuxOverlayInputShapeActive: spy('interaction.getLinuxInputShapeActive', () => false),
|
||||
getMacOSVisibleOverlayForegroundProbeActive: spy('interaction.getMacProbe', () => false),
|
||||
getVisibleOverlayInteractionActive: spy('interaction.getActive', () => false),
|
||||
getWindowsNativeWindowHandleNumber: spy('interaction.getWindowsHandle', () => 0),
|
||||
primeLinuxOverlayPointerInteractionAfterFirstMeasurement: spy(
|
||||
'interaction.primePointerAfterFirstMeasurement',
|
||||
noop,
|
||||
),
|
||||
requestLinuxOverlayZOrderFollow: spy('interaction.requestLinuxZOrderFollow', noop),
|
||||
requestWindowsVisibleOverlayZOrderSync: spy('interaction.requestWindowsZOrderSync', noop),
|
||||
resetLinuxVisibleOverlayStartupInputPrimer: spy('interaction.resetStartupPrimer', noop),
|
||||
resetVisibleOverlayInputState: spy('interaction.resetInputState', noop),
|
||||
restoreVisibleOverlayWindowShapeForShow: spy('interaction.restoreShapeForShow', noop),
|
||||
scheduleVisibleOverlayBlurRefresh: spy('interaction.scheduleBlurRefresh', noop),
|
||||
startLinuxVisibleOverlayStartupInputGrace: spy('interaction.startStartupGrace', noop),
|
||||
})),
|
||||
getOverlayGeometry: spy('getOverlayGeometry', () => ({
|
||||
enforceOverlayLayerOrder: spy('geometry.enforceLayerOrder', noop),
|
||||
ensureOverlayWindowLevel: spy('geometry.ensureWindowLevel', noop),
|
||||
getCurrentOverlayGeometry: spy('geometry.getCurrentOverlayGeometry', () => ({
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
})),
|
||||
getCurrentTrackedOverlayGeometry: spy(
|
||||
'geometry.getCurrentTrackedOverlayGeometry',
|
||||
() => state.trackedGeometry,
|
||||
),
|
||||
syncPrimaryOverlayWindowLayer: spy('geometry.syncPrimaryLayer', noop),
|
||||
updateVisibleOverlayBounds: spy('geometry.updateVisibleBounds', () => 'not-applicable'),
|
||||
})),
|
||||
getOverlayShortcuts: spy('getOverlayShortcuts', () => ({
|
||||
syncOverlayShortcuts: spy('shortcuts.sync', noop),
|
||||
tryHandleOverlayShortcutLocalFallback: spy('shortcuts.localFallback', () => false),
|
||||
})),
|
||||
getOverlayNotifications: spy('getOverlayNotifications', () => ({
|
||||
showOverlayLoadingStatusNotification: spy('notifications.showLoading', noop),
|
||||
dismissOverlayLoadingStatusNotification: spy('notifications.dismissLoading', noop),
|
||||
flushQueuedOverlayNotifications: spy('notifications.flushQueued', noop),
|
||||
maybeStartOverlayLoadingOsd: spy('notifications.maybeStartLoadingOsd', noop),
|
||||
})),
|
||||
getOverlayVisibilityComposer: spy('getOverlayVisibilityComposer', () => ({
|
||||
broadcastRuntimeOptionsChanged: spy('composer.broadcastRuntimeOptions', noop),
|
||||
setOverlayDebugVisualizationEnabled: spy('composer.setDebugVisualization', noop),
|
||||
})),
|
||||
getMediaTimingReviewRuntime: spy('getMediaTimingReviewRuntime', () => ({
|
||||
dispose: spy('mediaTimingReview.dispose', resolved),
|
||||
})),
|
||||
getSubtitleProcessingController: spy('getSubtitleProcessingController', () => ({
|
||||
refreshCurrentSubtitle: spy('subtitle.refreshCurrent', () => true),
|
||||
})),
|
||||
getAutoplaySubtitlePriming: spy('getAutoplaySubtitlePriming', () => ({
|
||||
cancelVisibleOverlaySubtitleRefreshAfterFirstPaint: spy('priming.cancelFirstPaint', noop),
|
||||
primeCurrentSubtitleForVisibleOverlay: spy('priming.prime', resolved),
|
||||
})),
|
||||
ensureOverlayMpvSubtitlesHidden: spy('ensureOverlayMpvSubtitlesHidden', resolved),
|
||||
syncOverlayMpvSubtitleSuppression: spy('syncOverlayMpvSubtitleSuppression', noop),
|
||||
initializeOverlayRuntime: spy('initializeOverlayRuntime', noop),
|
||||
};
|
||||
return { deps, windowOptions };
|
||||
}
|
||||
|
||||
/** Builds the assembly, optionally with `process.platform` overridden for the test. */
|
||||
function setup(t: TestContext, options: { platform?: NodeJS.Platform; visible?: boolean } = {}) {
|
||||
if (options.platform) {
|
||||
const originalPlatform = process.platform;
|
||||
Object.defineProperty(process, 'platform', { value: options.platform, configurable: true });
|
||||
t.after(() => Object.defineProperty(process, 'platform', { value: originalPlatform }));
|
||||
}
|
||||
const recorder = createRecorder();
|
||||
const state: FixtureState = {
|
||||
visible: options.visible ?? false,
|
||||
trackedGeometry: null,
|
||||
window: null,
|
||||
};
|
||||
const { deps, windowOptions } = makeDeps(recorder, state);
|
||||
const overlay = createOverlayAssembly(deps);
|
||||
return { recorder, state, overlay, windowOptions };
|
||||
}
|
||||
|
||||
/** Asserts each name was called, in this relative order. */
|
||||
function assertCalledInOrder(names: string[], expected: string[]): void {
|
||||
let previous = -1;
|
||||
for (const name of expected) {
|
||||
const index = names.indexOf(name, previous + 1);
|
||||
assert.ok(index > previous, `${name} was not called after the previous step`);
|
||||
previous = index;
|
||||
}
|
||||
}
|
||||
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
// main.ts builds the assembly before most siblings exist, so construction must stay lazy.
|
||||
test('createOverlayAssembly does not call its deps while constructing', (t) => {
|
||||
const { recorder, overlay } = setup(t);
|
||||
assert.deepEqual(recorder.names(), []);
|
||||
assert.equal(typeof overlay.setVisibleOverlayVisible, 'function');
|
||||
});
|
||||
|
||||
const hidePaths: Array<{ label: string; hide: (overlay: Overlay) => void; order: string[] }> = [
|
||||
{
|
||||
label: 'setVisibleOverlayVisible(false)',
|
||||
hide: (overlay) => overlay.setVisibleOverlayVisible(false),
|
||||
order: [
|
||||
'autoplay.markCurrentMediaReady',
|
||||
'priming.cancelFirstPaint',
|
||||
'interaction.resetInputState',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'toggleVisibleOverlay() while shown',
|
||||
hide: (overlay) => overlay.toggleVisibleOverlay(),
|
||||
order: [
|
||||
'autoplay.markCurrentMediaReady',
|
||||
'priming.cancelFirstPaint',
|
||||
'interaction.resetInputState',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'setOverlayVisible(false)',
|
||||
hide: (overlay) => overlay.setOverlayVisible(false),
|
||||
order: [
|
||||
'priming.cancelFirstPaint',
|
||||
'interaction.resetInputState',
|
||||
'autoplay.markCurrentMediaReady',
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
for (const { label, hide, order } of hidePaths) {
|
||||
test(`${label} dismisses the loading OSD, releases autoplay and clears input state`, (t) => {
|
||||
const { recorder, overlay } = setup(t, { visible: true });
|
||||
|
||||
hide(overlay);
|
||||
|
||||
const names = recorder.names();
|
||||
assertCalledInOrder(names, ['notifications.dismissLoading', ...order]);
|
||||
assert.ok(!names.includes('priming.prime'));
|
||||
});
|
||||
|
||||
test(`${label} cancels a pending Linux fullscreen refresh burst`, async (t) => {
|
||||
const { recorder, overlay } = setup(t, { platform: 'linux', visible: true });
|
||||
overlay.handleMpvFullscreenChange(true);
|
||||
|
||||
hide(overlay);
|
||||
const afterHide = recorder.calls.length;
|
||||
await sleep(20);
|
||||
|
||||
// A burst that survived the hide would re-sync the overlay on its 0ms tick.
|
||||
assert.equal(recorder.calls.length, afterHide);
|
||||
});
|
||||
}
|
||||
|
||||
// Control for the cancellation tests above: the same tick does run when nothing cancels it.
|
||||
test('an uncancelled Linux fullscreen refresh burst runs on its first tick', async (t) => {
|
||||
const { recorder, overlay } = setup(t, { platform: 'linux' });
|
||||
t.after(() => overlay.clearLinuxFullscreenOverlayRefresh());
|
||||
overlay.handleMpvFullscreenChange(true);
|
||||
const afterSchedule = recorder.calls.length;
|
||||
|
||||
await sleep(20);
|
||||
|
||||
assert.ok(recorder.calls.length > afterSchedule);
|
||||
});
|
||||
|
||||
const showPaths: Array<{ label: string; show: (overlay: Overlay) => void }> = [
|
||||
{
|
||||
label: 'setVisibleOverlayVisible(true)',
|
||||
show: (overlay) => overlay.setVisibleOverlayVisible(true),
|
||||
},
|
||||
{
|
||||
label: 'toggleVisibleOverlay() while hidden',
|
||||
show: (overlay) => overlay.toggleVisibleOverlay(),
|
||||
},
|
||||
{ label: 'setOverlayVisible(true)', show: (overlay) => overlay.setOverlayVisible(true) },
|
||||
];
|
||||
|
||||
for (const { label, show } of showPaths) {
|
||||
test(`${label} starts the loading OSD and input grace before priming, keeping autoplay held`, (t) => {
|
||||
const { recorder, overlay } = setup(t);
|
||||
|
||||
show(overlay);
|
||||
|
||||
const names = recorder.names();
|
||||
assertCalledInOrder(names, [
|
||||
'notifications.maybeStartLoadingOsd',
|
||||
'interaction.resetStartupPrimer',
|
||||
'interaction.startStartupGrace',
|
||||
'priming.prime',
|
||||
]);
|
||||
assert.ok(!names.includes('autoplay.markCurrentMediaReady'));
|
||||
assert.ok(!names.includes('interaction.resetInputState'));
|
||||
});
|
||||
}
|
||||
|
||||
test('visible overlay content-ready flushes notifications and autoplay without tokenizing', (t) => {
|
||||
const { recorder, overlay, windowOptions } = setup(t, { visible: true });
|
||||
assert.throws(() => overlay.createMainWindow(), new RegExp(WINDOW_CREATION_STOPPED));
|
||||
const onContentReady = windowOptions[0]?.onWindowContentReady;
|
||||
assert.ok(onContentReady);
|
||||
const before = recorder.calls.length;
|
||||
|
||||
onContentReady();
|
||||
|
||||
const names = recorder.names().slice(before);
|
||||
assertCalledInOrder(names, [
|
||||
'notifications.dismissLoading',
|
||||
'notifications.flushQueued',
|
||||
'interaction.primePointerAfterFirstMeasurement',
|
||||
'autoplay.flushPending',
|
||||
]);
|
||||
// The first subtitle waits for the first content measurement, not for content-ready.
|
||||
assert.ok(!names.includes('subtitle.refreshCurrent'));
|
||||
});
|
||||
|
||||
for (const trackedGeometry of [null, { x: 10, y: 20, width: 1280, height: 720 }]) {
|
||||
test(`Linux fullscreen recreation resets input first and ${trackedGeometry ? 'applies tracked mpv bounds' : 'keeps bounds without tracked geometry'}`, (t) => {
|
||||
const { recorder, state, overlay } = setup(t, { platform: 'linux', visible: true });
|
||||
state.trackedGeometry = trackedGeometry;
|
||||
// An opaque token: the assembly only hands the created window to the overlay manager.
|
||||
state.window = {} as BrowserWindow;
|
||||
|
||||
overlay.linuxOverlayModeRuntime.sync(true);
|
||||
|
||||
const names = recorder.names();
|
||||
assertCalledInOrder(names, [
|
||||
'interaction.resetInputState',
|
||||
'createOverlayWindowCore',
|
||||
'geometry.getCurrentTrackedOverlayGeometry',
|
||||
'ensureOverlayMpvSubtitlesHidden',
|
||||
]);
|
||||
const boundsCalls = recorder.calls.filter(
|
||||
(call) => call.name === 'overlay.setOverlayWindowBounds',
|
||||
);
|
||||
assert.deepEqual(
|
||||
boundsCalls.map((call) => call.args[0]),
|
||||
trackedGeometry ? [trackedGeometry] : [],
|
||||
);
|
||||
// Recreation must never fall back to display bounds before mpv geometry is known.
|
||||
assert.ok(!names.includes('geometry.getCurrentOverlayGeometry'));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
import type { BrowserWindow, Screen, Session } from 'electron';
|
||||
import {
|
||||
type createOverlayWindow as createOverlayWindowCoreFn,
|
||||
sendMpvCommandRuntime,
|
||||
setVisibleOverlayVisible as setVisibleOverlayVisibleCore,
|
||||
type createOverlayManager,
|
||||
} from '../../core/services';
|
||||
import type { Logger } from '../../logger';
|
||||
import type { WindowGeometry } from '../../types';
|
||||
import { ensureWindowsOverlayTransparency } from '../../window-trackers/windows-helper';
|
||||
import type { createOverlayShortcutsRuntimeService } from '../overlay-shortcuts-runtime';
|
||||
import { createOverlayVisibilityRuntimeService } from '../overlay-visibility-runtime';
|
||||
import type { createAutoplayReadyGate } from '../runtime/autoplay-ready-gate';
|
||||
import type { composeOverlayVisibilityRuntime } from '../runtime/composers';
|
||||
import { createOverlayVisibilityRuntime } from '../runtime/domains/overlay';
|
||||
import {
|
||||
type CancelLinuxMpvFullscreenOverlayRefreshBurst,
|
||||
clearLinuxMpvFullscreenOverlayRefreshTimeouts,
|
||||
updateLinuxMpvFullscreenOverlayRefreshBurst,
|
||||
} from '../runtime/linux-mpv-fullscreen-overlay-refresh';
|
||||
import { createLinuxOverlayModeRuntime } from '../runtime/linux-overlay-mode-runtime';
|
||||
import { shouldRunLinuxOverlayZOrderKeepAlive } from '../runtime/linux-overlay-zorder-keepalive';
|
||||
import type { createMediaTimingReviewRuntime } from '../runtime/media-timing-review';
|
||||
import type { createOverlayModalInputState } from '../runtime/overlay-modal-input-state';
|
||||
import type { createOverlayGeometryRuntime } from '../runtime/overlay-geometry-runtime';
|
||||
import type { createOverlayNotificationsRuntime } from '../runtime/overlay-notifications-runtime';
|
||||
import { createOverlayWindowRuntimeHandlers } from '../runtime/overlay-window-runtime-handlers';
|
||||
import type { VisibleOverlayInteractionRuntime } from '../runtime/visible-overlay-interaction-runtime';
|
||||
import type { AppState } from '../state';
|
||||
import type { PlaybackAssembly } from './playback';
|
||||
|
||||
type OverlayManager = ReturnType<typeof createOverlayManager>;
|
||||
|
||||
/**
|
||||
* What overlay core needs from the rest of `main.ts`. Everything here except the getters and
|
||||
* callbacks is built before the assembly; siblings built later are reached through getters, and
|
||||
* construction calls none of them.
|
||||
*/
|
||||
export interface OverlayAssemblyDeps {
|
||||
appState: AppState;
|
||||
logger: Pick<Logger, 'debug' | 'info' | 'warn'>;
|
||||
overlayManager: Pick<
|
||||
OverlayManager,
|
||||
| 'getMainWindow'
|
||||
| 'setMainWindow'
|
||||
| 'getModalWindow'
|
||||
| 'setModalWindow'
|
||||
| 'getVisibleOverlayVisible'
|
||||
| 'setVisibleOverlayVisible'
|
||||
| 'setOverlayWindowBounds'
|
||||
| 'setModalWindowBounds'
|
||||
>;
|
||||
overlayModalInputState: Pick<
|
||||
ReturnType<typeof createOverlayModalInputState>,
|
||||
'getModalInputExclusive'
|
||||
>;
|
||||
autoplayReadyGate: Pick<
|
||||
ReturnType<typeof createAutoplayReadyGate>,
|
||||
'markCurrentMediaAutoplayReady' | 'flushPendingAutoplayReadySignal'
|
||||
>;
|
||||
screen: Pick<Screen, 'getCursorScreenPoint' | 'getDisplayNearestPoint'>;
|
||||
isDev: boolean;
|
||||
/** Builds an Electron overlay window; injected so the assembly stays free of Electron calls. */
|
||||
createOverlayWindowCore: typeof createOverlayWindowCoreFn;
|
||||
getYomitanSession: () => Session | null;
|
||||
/** Pointer interaction and geometry stay in `main.ts`: both import Electron at module load. */
|
||||
getVisibleOverlayInteraction: () => Pick<
|
||||
VisibleOverlayInteractionRuntime,
|
||||
| 'getLinuxOverlayInputShapeActive'
|
||||
| 'getMacOSVisibleOverlayForegroundProbeActive'
|
||||
| 'getVisibleOverlayInteractionActive'
|
||||
| 'getWindowsNativeWindowHandleNumber'
|
||||
| 'primeLinuxOverlayPointerInteractionAfterFirstMeasurement'
|
||||
| 'requestLinuxOverlayZOrderFollow'
|
||||
| 'requestWindowsVisibleOverlayZOrderSync'
|
||||
| 'resetLinuxVisibleOverlayStartupInputPrimer'
|
||||
| 'resetVisibleOverlayInputState'
|
||||
| 'restoreVisibleOverlayWindowShapeForShow'
|
||||
| 'scheduleVisibleOverlayBlurRefresh'
|
||||
| 'startLinuxVisibleOverlayStartupInputGrace'
|
||||
>;
|
||||
getOverlayGeometry: () => Pick<
|
||||
ReturnType<typeof createOverlayGeometryRuntime>,
|
||||
| 'enforceOverlayLayerOrder'
|
||||
| 'ensureOverlayWindowLevel'
|
||||
| 'getCurrentOverlayGeometry'
|
||||
| 'getCurrentTrackedOverlayGeometry'
|
||||
| 'syncPrimaryOverlayWindowLayer'
|
||||
| 'updateVisibleOverlayBounds'
|
||||
>;
|
||||
getOverlayShortcuts: () => Pick<
|
||||
ReturnType<typeof createOverlayShortcutsRuntimeService>,
|
||||
'syncOverlayShortcuts' | 'tryHandleOverlayShortcutLocalFallback'
|
||||
>;
|
||||
getOverlayNotifications: () => Pick<
|
||||
ReturnType<typeof createOverlayNotificationsRuntime>,
|
||||
| 'showOverlayLoadingStatusNotification'
|
||||
| 'dismissOverlayLoadingStatusNotification'
|
||||
| 'flushQueuedOverlayNotifications'
|
||||
| 'maybeStartOverlayLoadingOsd'
|
||||
>;
|
||||
getOverlayVisibilityComposer: () => Pick<
|
||||
ReturnType<typeof composeOverlayVisibilityRuntime>,
|
||||
'broadcastRuntimeOptionsChanged' | 'setOverlayDebugVisualizationEnabled'
|
||||
>;
|
||||
getMediaTimingReviewRuntime: () => Pick<
|
||||
ReturnType<typeof createMediaTimingReviewRuntime>,
|
||||
'dispose'
|
||||
>;
|
||||
getSubtitleProcessingController: () => Pick<
|
||||
PlaybackAssembly['subtitleProcessingController'],
|
||||
'refreshCurrentSubtitle'
|
||||
>;
|
||||
getAutoplaySubtitlePriming: () => Pick<
|
||||
PlaybackAssembly['autoplaySubtitlePrimingRuntime'],
|
||||
'cancelVisibleOverlaySubtitleRefreshAfterFirstPaint' | 'primeCurrentSubtitleForVisibleOverlay'
|
||||
>;
|
||||
ensureOverlayMpvSubtitlesHidden: () => Promise<void>;
|
||||
syncOverlayMpvSubtitleSuppression: () => void;
|
||||
initializeOverlayRuntime: () => void;
|
||||
}
|
||||
|
||||
export type OverlayAssembly = ReturnType<typeof createOverlayAssembly>;
|
||||
|
||||
/**
|
||||
* Owns overlay core: the visible/modal windows, their visibility, the Linux fullscreen window
|
||||
* mode and refresh burst, and the show/hide paths. `main.ts` builds it once and reaches the
|
||||
* runtimes through the result; overlay bootstrap, pointer interaction and geometry stay there.
|
||||
*/
|
||||
export function createOverlayAssembly(deps: OverlayAssemblyDeps) {
|
||||
const { appState, logger, overlayManager, overlayModalInputState, autoplayReadyGate } = deps;
|
||||
|
||||
let cancelLinuxMpvFullscreenOverlayRefreshBurst: CancelLinuxMpvFullscreenOverlayRefreshBurst | null =
|
||||
null;
|
||||
const linuxOverlayModeRuntime = createLinuxOverlayModeRuntime({
|
||||
isEnabled: shouldRunLinuxOverlayZOrderKeepAlive,
|
||||
isVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
getWindow: () => overlayManager.getMainWindow(),
|
||||
clearWindow: () => overlayManager.setMainWindow(null),
|
||||
createWindow: () => {
|
||||
deps.getVisibleOverlayInteraction().resetVisibleOverlayInputState();
|
||||
createMainWindow();
|
||||
},
|
||||
refreshWindow: () => {
|
||||
const trackedGeometry = deps.getOverlayGeometry().getCurrentTrackedOverlayGeometry();
|
||||
if (trackedGeometry) overlayManager.setOverlayWindowBounds(trackedGeometry);
|
||||
overlayVisibilityRuntime.updateVisibleOverlayVisibility();
|
||||
void deps.ensureOverlayMpvSubtitlesHidden();
|
||||
if (appState.currentSubText.trim()) {
|
||||
deps.getSubtitleProcessingController().refreshCurrentSubtitle(appState.currentSubText);
|
||||
}
|
||||
},
|
||||
now: Date.now,
|
||||
logDebug: (message) => logger.debug(message),
|
||||
});
|
||||
function cancelPendingLinuxMpvFullscreenOverlayRefreshBurst(): void {
|
||||
cancelLinuxMpvFullscreenOverlayRefreshBurst?.();
|
||||
cancelLinuxMpvFullscreenOverlayRefreshBurst = null;
|
||||
}
|
||||
|
||||
const overlayVisibilityRuntime = createOverlayVisibilityRuntimeService({
|
||||
getMainWindow: () => overlayManager.getMainWindow(),
|
||||
getModalActive: () => overlayModalInputState.getModalInputExclusive(),
|
||||
getVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
getForceMousePassthrough: () => appState.statsOverlayVisible,
|
||||
getNonNativeInputRegionActive: () =>
|
||||
process.platform === 'linux' &&
|
||||
deps.getVisibleOverlayInteraction().getLinuxOverlayInputShapeActive(),
|
||||
getSuspendVisibleOverlay: () => appState.statsOverlayVisible,
|
||||
getOverlayInteractionActive: () =>
|
||||
deps.getVisibleOverlayInteraction().getVisibleOverlayInteractionActive(),
|
||||
getWindowTracker: () => appState.windowTracker,
|
||||
getMacOSForegroundProbeActive: () =>
|
||||
deps.getVisibleOverlayInteraction().getMacOSVisibleOverlayForegroundProbeActive(),
|
||||
getTrackerNotReadyWarningShown: () => appState.trackerNotReadyWarningShown,
|
||||
setTrackerNotReadyWarningShown: (shown: boolean) => {
|
||||
appState.trackerNotReadyWarningShown = shown;
|
||||
},
|
||||
updateVisibleOverlayBounds: (geometry: WindowGeometry) =>
|
||||
deps.getOverlayGeometry().updateVisibleOverlayBounds(geometry),
|
||||
ensureOverlayWindowLevel: (window) => {
|
||||
deps.getOverlayGeometry().ensureOverlayWindowLevel(window);
|
||||
},
|
||||
syncWindowsOverlayToMpvZOrder: (_window) => {
|
||||
deps.getVisibleOverlayInteraction().requestWindowsVisibleOverlayZOrderSync();
|
||||
},
|
||||
syncPrimaryOverlayWindowLayer: (layer) => {
|
||||
deps.getOverlayGeometry().syncPrimaryOverlayWindowLayer(layer);
|
||||
},
|
||||
enforceOverlayLayerOrder: () => {
|
||||
deps.getOverlayGeometry().enforceOverlayLayerOrder();
|
||||
},
|
||||
syncOverlayShortcuts: () => {
|
||||
deps.getOverlayShortcuts().syncOverlayShortcuts();
|
||||
},
|
||||
isMacOSPlatform: () => process.platform === 'darwin',
|
||||
isWindowsPlatform: () => process.platform === 'win32',
|
||||
showOverlayLoadingOsd: (_message: string) => {
|
||||
deps.getOverlayNotifications().showOverlayLoadingStatusNotification();
|
||||
},
|
||||
dismissOverlayLoadingOsd: () => {
|
||||
deps.getOverlayNotifications().dismissOverlayLoadingStatusNotification();
|
||||
},
|
||||
hideNonNativeOverlayWhenTargetUnfocused: () =>
|
||||
shouldRunLinuxOverlayZOrderKeepAlive() &&
|
||||
linuxOverlayModeRuntime.mode === 'fullscreen-override',
|
||||
resolveFallbackBounds: () => {
|
||||
const cursorPoint = deps.screen.getCursorScreenPoint();
|
||||
const display = deps.screen.getDisplayNearestPoint(cursorPoint);
|
||||
const fallbackBounds = display.workArea;
|
||||
return {
|
||||
x: fallbackBounds.x,
|
||||
y: fallbackBounds.y,
|
||||
width: fallbackBounds.width,
|
||||
height: fallbackBounds.height,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
function createModalWindow(): BrowserWindow {
|
||||
const existingWindow = overlayManager.getModalWindow();
|
||||
if (existingWindow && !existingWindow.isDestroyed()) {
|
||||
return existingWindow;
|
||||
}
|
||||
const window = createModalWindowHandler();
|
||||
overlayManager.setModalWindowBounds(deps.getOverlayGeometry().getCurrentOverlayGeometry());
|
||||
return window;
|
||||
}
|
||||
|
||||
function createMainWindow(): BrowserWindow {
|
||||
const window = createMainWindowHandler();
|
||||
if (process.platform === 'win32') {
|
||||
const overlayHwnd = deps
|
||||
.getVisibleOverlayInteraction()
|
||||
.getWindowsNativeWindowHandleNumber(window);
|
||||
if (!ensureWindowsOverlayTransparency(overlayHwnd)) {
|
||||
logger.warn('Failed to eagerly extend Windows overlay transparency via koffi');
|
||||
}
|
||||
}
|
||||
return window;
|
||||
}
|
||||
|
||||
const {
|
||||
setVisibleOverlayVisible: setVisibleOverlayVisibleHandler,
|
||||
toggleVisibleOverlay: toggleVisibleOverlayHandler,
|
||||
setOverlayVisible: setOverlayVisibleHandler,
|
||||
} = createOverlayVisibilityRuntime({
|
||||
setVisibleOverlayVisibleDeps: {
|
||||
setVisibleOverlayVisibleCore,
|
||||
setVisibleOverlayVisibleState: (nextVisible) => {
|
||||
overlayManager.setVisibleOverlayVisible(nextVisible);
|
||||
},
|
||||
updateVisibleOverlayVisibility: () =>
|
||||
overlayVisibilityRuntime.updateVisibleOverlayVisibility(),
|
||||
},
|
||||
getVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
});
|
||||
|
||||
const { createMainWindow: createMainWindowHandler, createModalWindow: createModalWindowHandler } =
|
||||
createOverlayWindowRuntimeHandlers<BrowserWindow>({
|
||||
createOverlayWindowDeps: {
|
||||
createOverlayWindowCore: (kind, options) => deps.createOverlayWindowCore(kind, options),
|
||||
isDev: deps.isDev,
|
||||
ensureOverlayWindowLevel: (window) =>
|
||||
deps.getOverlayGeometry().ensureOverlayWindowLevel(window),
|
||||
onRuntimeOptionsChanged: () =>
|
||||
deps.getOverlayVisibilityComposer().broadcastRuntimeOptionsChanged(),
|
||||
setOverlayDebugVisualizationEnabled: (enabled) =>
|
||||
deps.getOverlayVisibilityComposer().setOverlayDebugVisualizationEnabled(enabled),
|
||||
isOverlayVisible: (windowKind) =>
|
||||
windowKind === 'visible' ? overlayManager.getVisibleOverlayVisible() : false,
|
||||
getYomitanSession: () => deps.getYomitanSession(),
|
||||
tryHandleOverlayShortcutLocalFallback: (input) =>
|
||||
deps.getOverlayShortcuts().tryHandleOverlayShortcutLocalFallback(input),
|
||||
forwardTabToMpv: () => sendMpvCommandRuntime(appState.mpvClient, ['keypress', 'TAB']),
|
||||
getLinuxX11FullscreenOverlay: () =>
|
||||
shouldRunLinuxOverlayZOrderKeepAlive() &&
|
||||
linuxOverlayModeRuntime.fullscreen &&
|
||||
linuxOverlayModeRuntime.mode === 'fullscreen-override',
|
||||
onVisibleWindowBlurred: () =>
|
||||
deps.getVisibleOverlayInteraction().scheduleVisibleOverlayBlurRefresh(),
|
||||
onVisibleWindowFocused: () =>
|
||||
deps.getVisibleOverlayInteraction().requestLinuxOverlayZOrderFollow(),
|
||||
onWindowDidFinishLoad: () => {
|
||||
deps.getOverlayNotifications().flushQueuedOverlayNotifications();
|
||||
},
|
||||
onWindowContentReady: () => {
|
||||
deps.getOverlayNotifications().dismissOverlayLoadingStatusNotification();
|
||||
deps.getOverlayNotifications().flushQueuedOverlayNotifications();
|
||||
overlayVisibilityRuntime.updateVisibleOverlayVisibility();
|
||||
deps
|
||||
.getVisibleOverlayInteraction()
|
||||
.primeLinuxOverlayPointerInteractionAfterFirstMeasurement();
|
||||
autoplayReadyGate.flushPendingAutoplayReadySignal();
|
||||
},
|
||||
onWindowClosed: (windowKind, window) => {
|
||||
if (windowKind === 'visible') {
|
||||
if (overlayManager.getMainWindow() !== window) {
|
||||
return;
|
||||
}
|
||||
cancelPendingLinuxMpvFullscreenOverlayRefreshBurst();
|
||||
overlayManager.setMainWindow(null);
|
||||
} else {
|
||||
if (overlayManager.getModalWindow() !== window) {
|
||||
return;
|
||||
}
|
||||
void deps.getMediaTimingReviewRuntime().dispose();
|
||||
overlayManager.setModalWindow(null);
|
||||
}
|
||||
},
|
||||
},
|
||||
getMainWindow: () => overlayManager.getMainWindow(),
|
||||
isWindowDestroyed: (window) => window.isDestroyed(),
|
||||
setMainWindow: (window) => overlayManager.setMainWindow(window),
|
||||
setModalWindow: (window) => overlayManager.setModalWindow(window),
|
||||
});
|
||||
|
||||
function ensureOverlayWindowsReadyForVisibilityActions(): void {
|
||||
if (!appState.overlayRuntimeInitialized) {
|
||||
deps.initializeOverlayRuntime();
|
||||
return;
|
||||
}
|
||||
|
||||
const mainWindow = overlayManager.getMainWindow();
|
||||
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||
createMainWindow();
|
||||
}
|
||||
}
|
||||
|
||||
function notifyMpvPluginVisibleOverlayVisibility(visible: boolean): void {
|
||||
sendMpvCommandRuntime(appState.mpvClient, [
|
||||
'script-message',
|
||||
visible ? 'subminer-visible-overlay-shown' : 'subminer-visible-overlay-hidden',
|
||||
]);
|
||||
}
|
||||
|
||||
function setVisibleOverlayVisible(visible: boolean): void {
|
||||
ensureOverlayWindowsReadyForVisibilityActions();
|
||||
if (!visible) {
|
||||
deps.getOverlayNotifications().dismissOverlayLoadingStatusNotification();
|
||||
autoplayReadyGate.markCurrentMediaAutoplayReady();
|
||||
deps.getAutoplaySubtitlePriming().cancelVisibleOverlaySubtitleRefreshAfterFirstPaint();
|
||||
cancelPendingLinuxMpvFullscreenOverlayRefreshBurst();
|
||||
deps.getVisibleOverlayInteraction().resetVisibleOverlayInputState();
|
||||
}
|
||||
if (visible) {
|
||||
deps.getOverlayNotifications().maybeStartOverlayLoadingOsd();
|
||||
deps.getVisibleOverlayInteraction().resetLinuxVisibleOverlayStartupInputPrimer();
|
||||
deps.getVisibleOverlayInteraction().startLinuxVisibleOverlayStartupInputGrace();
|
||||
deps.getVisibleOverlayInteraction().restoreVisibleOverlayWindowShapeForShow();
|
||||
void deps.ensureOverlayMpvSubtitlesHidden();
|
||||
void deps.getAutoplaySubtitlePriming().primeCurrentSubtitleForVisibleOverlay();
|
||||
}
|
||||
setVisibleOverlayVisibleHandler(visible);
|
||||
notifyMpvPluginVisibleOverlayVisibility(visible);
|
||||
deps.syncOverlayMpvSubtitleSuppression();
|
||||
}
|
||||
|
||||
function toggleVisibleOverlay(): void {
|
||||
ensureOverlayWindowsReadyForVisibilityActions();
|
||||
const nextVisible = !overlayManager.getVisibleOverlayVisible();
|
||||
if (!nextVisible) {
|
||||
deps.getOverlayNotifications().dismissOverlayLoadingStatusNotification();
|
||||
autoplayReadyGate.markCurrentMediaAutoplayReady();
|
||||
deps.getAutoplaySubtitlePriming().cancelVisibleOverlaySubtitleRefreshAfterFirstPaint();
|
||||
cancelPendingLinuxMpvFullscreenOverlayRefreshBurst();
|
||||
deps.getVisibleOverlayInteraction().resetVisibleOverlayInputState();
|
||||
} else {
|
||||
deps.getOverlayNotifications().maybeStartOverlayLoadingOsd();
|
||||
deps.getVisibleOverlayInteraction().resetLinuxVisibleOverlayStartupInputPrimer();
|
||||
deps.getVisibleOverlayInteraction().startLinuxVisibleOverlayStartupInputGrace();
|
||||
deps.getVisibleOverlayInteraction().restoreVisibleOverlayWindowShapeForShow();
|
||||
void deps.ensureOverlayMpvSubtitlesHidden();
|
||||
void deps.getAutoplaySubtitlePriming().primeCurrentSubtitleForVisibleOverlay();
|
||||
}
|
||||
toggleVisibleOverlayHandler();
|
||||
notifyMpvPluginVisibleOverlayVisibility(nextVisible);
|
||||
deps.syncOverlayMpvSubtitleSuppression();
|
||||
}
|
||||
function setOverlayVisible(visible: boolean): void {
|
||||
if (!visible) {
|
||||
deps.getOverlayNotifications().dismissOverlayLoadingStatusNotification();
|
||||
deps.getAutoplaySubtitlePriming().cancelVisibleOverlaySubtitleRefreshAfterFirstPaint();
|
||||
deps.getVisibleOverlayInteraction().resetVisibleOverlayInputState();
|
||||
autoplayReadyGate.markCurrentMediaAutoplayReady();
|
||||
cancelPendingLinuxMpvFullscreenOverlayRefreshBurst();
|
||||
}
|
||||
if (visible) {
|
||||
deps.getOverlayNotifications().maybeStartOverlayLoadingOsd();
|
||||
deps.getVisibleOverlayInteraction().resetLinuxVisibleOverlayStartupInputPrimer();
|
||||
deps.getVisibleOverlayInteraction().startLinuxVisibleOverlayStartupInputGrace();
|
||||
deps.getVisibleOverlayInteraction().restoreVisibleOverlayWindowShapeForShow();
|
||||
void deps.ensureOverlayMpvSubtitlesHidden();
|
||||
void deps.getAutoplaySubtitlePriming().primeCurrentSubtitleForVisibleOverlay();
|
||||
}
|
||||
setOverlayVisibleHandler(visible);
|
||||
notifyMpvPluginVisibleOverlayVisibility(visible);
|
||||
deps.syncOverlayMpvSubtitleSuppression();
|
||||
}
|
||||
|
||||
function handleMpvFullscreenChange(fullscreen: boolean): void {
|
||||
cancelLinuxMpvFullscreenOverlayRefreshBurst = updateLinuxMpvFullscreenOverlayRefreshBurst(
|
||||
fullscreen,
|
||||
{
|
||||
overlayManager: {
|
||||
getMainWindow: () => overlayManager.getMainWindow(),
|
||||
getVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
},
|
||||
overlayVisibilityRuntime,
|
||||
syncVisibleOverlayMpvFullscreenMode: (nextFullscreen) =>
|
||||
linuxOverlayModeRuntime.sync(nextFullscreen),
|
||||
getOverlayInteractionActive: () =>
|
||||
deps.getVisibleOverlayInteraction().getVisibleOverlayInteractionActive() ||
|
||||
deps.getVisibleOverlayInteraction().getLinuxOverlayInputShapeActive(),
|
||||
ensureOverlayWindowLevel: (window) =>
|
||||
deps.getOverlayGeometry().ensureOverlayWindowLevel(window),
|
||||
},
|
||||
cancelLinuxMpvFullscreenOverlayRefreshBurst,
|
||||
);
|
||||
}
|
||||
|
||||
/** Quit cleanup: drops any pending Linux fullscreen transition and refresh burst. */
|
||||
function clearLinuxFullscreenOverlayRefresh(): void {
|
||||
linuxOverlayModeRuntime.cancelPendingTransition();
|
||||
cancelLinuxMpvFullscreenOverlayRefreshBurst = null;
|
||||
clearLinuxMpvFullscreenOverlayRefreshTimeouts();
|
||||
}
|
||||
|
||||
return {
|
||||
linuxOverlayModeRuntime,
|
||||
overlayVisibilityRuntime,
|
||||
createMainWindow,
|
||||
createModalWindow,
|
||||
ensureOverlayWindowsReadyForVisibilityActions,
|
||||
setVisibleOverlayVisible,
|
||||
toggleVisibleOverlay,
|
||||
setOverlayVisible,
|
||||
handleMpvFullscreenChange,
|
||||
clearLinuxFullscreenOverlayRefresh,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { DEFAULT_CONFIG } from '../../config/definitions';
|
||||
import type { SubtitlePrefetchService } from '../../core/services/subtitle-prefetch';
|
||||
import type { SubtitleData } from '../../types';
|
||||
import { createAppState } from '../state';
|
||||
import { createPlaybackAssembly, type PlaybackAssemblyDeps } from './playback';
|
||||
|
||||
type Call = { name: string; args: unknown[] };
|
||||
|
||||
/** Records every dep call by name, in order; each dep still returns an inert value. */
|
||||
function createRecorder() {
|
||||
const calls: Call[] = [];
|
||||
const spy =
|
||||
<A extends unknown[], R>(name: string, impl: (...args: A) => R) =>
|
||||
(...args: A): R => {
|
||||
calls.push({ name, args });
|
||||
return impl(...args);
|
||||
};
|
||||
const names = () => calls.map((call) => call.name);
|
||||
return { calls, spy, names };
|
||||
}
|
||||
|
||||
type Recorder = ReturnType<typeof createRecorder>;
|
||||
|
||||
function createFakePrefetchService(recorder: Recorder): SubtitlePrefetchService {
|
||||
const { spy } = recorder;
|
||||
return {
|
||||
start: spy('prefetch.start', () => {}),
|
||||
stop: spy('prefetch.stop', () => {}),
|
||||
onSeek: spy('prefetch.onSeek', () => {}),
|
||||
pause: spy('prefetch.pause', () => {}),
|
||||
resume: spy('prefetch.resume', () => {}),
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeps(recorder: Recorder): PlaybackAssemblyDeps {
|
||||
const { spy } = recorder;
|
||||
const noop = () => {};
|
||||
const resolved = async () => {};
|
||||
return {
|
||||
appState: createAppState({
|
||||
mpvSocketPath: '/tmp/subminer-playback-test.sock',
|
||||
texthookerPort: 0,
|
||||
}),
|
||||
configService: { getConfig: spy('getConfig', () => DEFAULT_CONFIG) },
|
||||
logger: {
|
||||
debug: spy('logger.debug', noop),
|
||||
info: spy('logger.info', noop),
|
||||
warn: spy('logger.warn', noop),
|
||||
error: spy('logger.error', noop),
|
||||
},
|
||||
overlayManager: {
|
||||
broadcastToOverlayWindows: spy('overlay.broadcast', noop),
|
||||
getVisibleOverlayVisible: spy('overlay.getVisibleOverlayVisible', () => false),
|
||||
},
|
||||
subtitleWsService: { broadcast: spy('subtitleWs.broadcast', noop) },
|
||||
annotationSubtitleWsService: { broadcast: spy('annotationWs.broadcast', noop) },
|
||||
autoplayReadyGate: {
|
||||
maybeSignalPluginAutoplayReady: spy('autoplay.maybeSignal', noop),
|
||||
flushPendingAutoplayReadySignal: spy('autoplay.flushPending', noop),
|
||||
invalidatePendingAutoplayReadyFallbacks: spy('autoplay.invalidateFallbacks', noop),
|
||||
},
|
||||
currentMediaTokenizationGate: {
|
||||
updateCurrentMediaPath: spy('tokenizationGate.updateCurrentMediaPath', noop),
|
||||
markReady: spy('tokenizationGate.markReady', noop),
|
||||
},
|
||||
startupOsdSequencer: {
|
||||
reset: spy('startupOsd.reset', noop),
|
||||
markTokenizationReady: spy('startupOsd.markTokenizationReady', noop),
|
||||
showTokenizationLoading: spy('startupOsd.showTokenizationLoading', noop),
|
||||
showAnnotationLoading: spy('startupOsd.showAnnotationLoading', noop),
|
||||
markAnnotationLoadingComplete: spy('startupOsd.markAnnotationLoadingComplete', noop),
|
||||
},
|
||||
managedLocalSubtitleSelectionRuntime: {
|
||||
handleMediaPathChange: spy('localSubtitles.handleMediaPathChange', noop),
|
||||
handleSubtitleTrackListChange: spy('localSubtitles.handleSubtitleTrackListChange', noop),
|
||||
},
|
||||
mediaTimingReviewRuntime: {
|
||||
deferPlaybackResume: spy('timingReview.deferPlaybackResume', () => false),
|
||||
cancelPlaybackResume: spy('timingReview.cancelPlaybackResume', noop),
|
||||
},
|
||||
discordPresenceRuntime: { publishDiscordPresence: spy('discord.publish', noop) },
|
||||
immersionMediaRuntime: { syncFromCurrentMediaState: spy('immersion.sync', noop) },
|
||||
mediaRuntime: {
|
||||
updateCurrentMediaPath: spy('media.updateCurrentMediaPath', noop),
|
||||
updateCurrentMediaTitle: spy('media.updateCurrentMediaTitle', noop),
|
||||
},
|
||||
overlayNotificationsRuntime: {
|
||||
showConfiguredStatusNotification: spy('notifications.showStatus', noop),
|
||||
getConfiguredStatusNotificationType: spy('notifications.getType', () => 'osd' as const),
|
||||
},
|
||||
youtube: {
|
||||
isPlaybackActiveNow: spy('youtube.isPlaybackActiveNow', () => false),
|
||||
playback: { getQuitOnDisconnectArmed: spy('youtube.getQuitOnDisconnectArmed', () => false) },
|
||||
primarySubtitleNotification: {
|
||||
handleMediaPathChange: spy('youtube.notification.handleMediaPathChange', noop),
|
||||
handleSubtitleTrackChange: spy('youtube.notification.handleSubtitleTrackChange', noop),
|
||||
handleSubtitleTrackListChange: spy('youtube.notification.handleTrackListChange', noop),
|
||||
},
|
||||
mediaCachePlayback: { handleMediaPathChange: spy('youtube.mediaCache', resolved) },
|
||||
browserPlayback: { handleMediaPathChange: spy('youtube.browser', noop) },
|
||||
flow: { handleMediaPathChange: spy('youtube.flow', noop) },
|
||||
},
|
||||
jellyfin: {
|
||||
getQuitOnDisconnectArmed: spy('jellyfin.getQuitOnDisconnectArmed', () => false),
|
||||
reportJellyfinRemoteStopped: spy('jellyfin.reportStopped', resolved),
|
||||
reportJellyfinRemoteProgress: spy('jellyfin.reportProgress', resolved),
|
||||
getActivePlayback: spy('jellyfin.getActivePlayback', () => null),
|
||||
startJellyfinRemoteSession: spy('jellyfin.startRemoteSession', resolved),
|
||||
},
|
||||
anilist: {
|
||||
maybeRunAnilistPostWatchUpdate: spy('anilist.postWatch', resolved),
|
||||
recordAnilistMediaDuration: spy('anilist.recordDuration', noop),
|
||||
getCurrentAnilistMediaKey: spy('anilist.getMediaKey', () => null),
|
||||
resetAnilistMediaTracking: spy('anilist.resetTracking', noop),
|
||||
maybeProbeAnilistDuration: spy('anilist.probeDuration', async () => null),
|
||||
ensureAnilistMediaGuess: spy('anilist.ensureGuess', async () => null),
|
||||
resetAnilistMediaGuessState: spy('anilist.resetGuess', noop),
|
||||
},
|
||||
characterDictionary: {
|
||||
autoSync: {
|
||||
scheduleSync: spy('characterDictionary.scheduleSync', noop),
|
||||
getCurrentMediaId: spy('characterDictionary.getCurrentMediaId', () => null),
|
||||
},
|
||||
imageLookup: { get: spy('characterDictionary.imageLookup', () => null) },
|
||||
nameCandidates: { get: spy('characterDictionary.nameCandidates', () => null) },
|
||||
},
|
||||
dictionaries: {
|
||||
jlpt: { ensureJlptDictionaryLookup: spy('dictionaries.jlpt', resolved) },
|
||||
frequency: { ensureFrequencyDictionaryLookup: spy('dictionaries.frequency', resolved) },
|
||||
},
|
||||
getSubtitleGenerationRuntime: spy('getSubtitleGenerationRuntime', () => ({
|
||||
handleMediaPathChange: noop,
|
||||
})),
|
||||
isCharacterDictionaryEnabled: spy('isCharacterDictionaryEnabled', () => false),
|
||||
hasTray: spy('hasTray', () => false),
|
||||
loadSubtitleSourceText: spy('loadSubtitleSourceText', async () => ''),
|
||||
createSubtitlePrefetchService: spy('createSubtitlePrefetchService', () =>
|
||||
createFakePrefetchService(recorder),
|
||||
),
|
||||
requestAppQuit: spy('requestAppQuit', noop),
|
||||
maybeStartOverlayLoadingOsd: spy('maybeStartOverlayLoadingOsd', noop),
|
||||
flushQueuedMpvOsdNotifications: spy('flushQueuedMpvOsdNotifications', noop),
|
||||
refreshMpvSessionBindings: spy('refreshMpvSessionBindings', resolved),
|
||||
ensureImmersionTrackerStarted: spy('ensureImmersionTrackerStarted', noop),
|
||||
restoreOverlayMpvSubtitles: spy('restoreOverlayMpvSubtitles', noop),
|
||||
resetSubtitleSidebarEmbeddedLayoutRuntime: spy('resetSubtitleSidebarLayout', noop),
|
||||
syncOverlayMpvSubtitleSuppression: spy('syncOverlayMpvSubtitleSuppression', noop),
|
||||
setOverlayVisible: spy('setOverlayVisible', noop),
|
||||
ensureYomitanExtensionLoaded: spy('ensureYomitanExtensionLoaded', async () => null),
|
||||
shouldInitializeMecabForAnnotations: spy('shouldInitializeMecabForAnnotations', () => false),
|
||||
// Every annotation off, so tokenization warmups need no MeCab or dictionaries.
|
||||
getRuntimeBooleanOption: spy('getRuntimeBooleanOption', () => false),
|
||||
onFullscreenChange: spy('onFullscreenChange', noop),
|
||||
};
|
||||
}
|
||||
|
||||
/** Binds the assembly's mpv event handlers to a fake client; returns an `emit` driver. */
|
||||
function bindMpvEvents(playback: ReturnType<typeof createPlaybackAssembly>) {
|
||||
const handlers = new Map<string, (payload: unknown) => void>();
|
||||
playback.bindMpvClientEventHandlers({
|
||||
on: (event, handler) => {
|
||||
handlers.set(event, handler as (payload: unknown) => void);
|
||||
},
|
||||
});
|
||||
return (event: string, payload: unknown): void => {
|
||||
const handler = handlers.get(event);
|
||||
assert.ok(handler, `no handler bound for ${event}`);
|
||||
handler(payload);
|
||||
};
|
||||
}
|
||||
|
||||
function setup(overrides: Partial<PlaybackAssemblyDeps> = {}) {
|
||||
const recorder = createRecorder();
|
||||
const deps = { ...makeDeps(recorder), ...overrides };
|
||||
const playback = createPlaybackAssembly(deps);
|
||||
const emit = bindMpvEvents(playback);
|
||||
return { recorder, deps, appState: deps.appState, playback, emit };
|
||||
}
|
||||
|
||||
/** Sets up with a fake prefetch service, installed by a real prefetch init over one SRT cue. */
|
||||
async function setupWithFakePrefetch() {
|
||||
const ctx = setup({
|
||||
loadSubtitleSourceText: async () => '1\n00:00:01,000 --> 00:00:02,000\n一行目\n',
|
||||
});
|
||||
await ctx.playback.subtitlePrefetchRuntime.initSubtitlePrefetch('/subs/episode.srt', 0);
|
||||
assert.ok(ctx.playback.getSubtitlePrefetchService());
|
||||
ctx.recorder.calls.length = 0;
|
||||
return ctx;
|
||||
}
|
||||
|
||||
const flushAsync = async (): Promise<void> => {
|
||||
for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
};
|
||||
|
||||
// main.ts builds the assembly before some siblings exist, so construction must stay lazy.
|
||||
test('createPlaybackAssembly does not call its deps while constructing', () => {
|
||||
const recorder = createRecorder();
|
||||
createPlaybackAssembly(makeDeps(recorder));
|
||||
assert.deepEqual(recorder.names(), []);
|
||||
});
|
||||
|
||||
test('mpv connection starts the loading OSD and flushes queued OSD notifications before session work', () => {
|
||||
const { recorder, emit } = setup();
|
||||
|
||||
emit('connection-change', { connected: true });
|
||||
|
||||
const names = recorder.names();
|
||||
const osdIndex = names.indexOf('maybeStartOverlayLoadingOsd');
|
||||
assert.ok(osdIndex >= 0);
|
||||
assert.deepEqual(recorder.calls[osdIndex]?.args, []);
|
||||
assert.ok(osdIndex < names.indexOf('flushQueuedMpvOsdNotifications'));
|
||||
assert.ok(
|
||||
names.indexOf('flushQueuedMpvOsdNotifications') < names.indexOf('refreshMpvSessionBindings'),
|
||||
);
|
||||
});
|
||||
|
||||
test('media path change starts the loading OSD, then clears rendered subtitle state before broadcasting', (t) => {
|
||||
const { recorder, deps, appState, playback, emit } = setup();
|
||||
t.after(() => playback.subtitlePrefetchRuntime.clearScheduledSubtitlePrefetchRefresh());
|
||||
appState.currentMediaPath = '/videos/a.mkv';
|
||||
appState.currentSubText = 'old line';
|
||||
appState.currentSubtitleData = { text: 'old line', tokens: null };
|
||||
appState.activeParsedSubtitleCues = [{ startTime: 1, endTime: 2, text: 'old line' }];
|
||||
appState.activeParsedSubtitleSource = '/subs/a.srt';
|
||||
appState.activeParsedSubtitleMediaPath = '/videos/a.mkv';
|
||||
emit('time-pos-change', { time: 42 });
|
||||
assert.equal(playback.getLastObservedTimePos(), 42);
|
||||
let subtitleDataAtBroadcast: SubtitleData | null | undefined;
|
||||
deps.overlayManager.broadcastToOverlayWindows = (channel) => {
|
||||
if (channel === 'subtitle:set') subtitleDataAtBroadcast = appState.currentSubtitleData;
|
||||
};
|
||||
recorder.calls.length = 0;
|
||||
|
||||
emit('media-path-change', { path: '/videos/b.mkv' });
|
||||
|
||||
assert.deepEqual(recorder.calls[0], {
|
||||
name: 'maybeStartOverlayLoadingOsd',
|
||||
args: ['/videos/b.mkv'],
|
||||
});
|
||||
assert.equal(subtitleDataAtBroadcast, null);
|
||||
assert.equal(appState.currentSubText, '');
|
||||
assert.equal(appState.currentSubtitleData, null);
|
||||
assert.deepEqual(appState.activeParsedSubtitleCues, []);
|
||||
assert.equal(appState.activeParsedSubtitleSource, null);
|
||||
assert.equal(appState.activeParsedSubtitleMediaPath, null);
|
||||
assert.equal(playback.getLastObservedTimePos(), 0);
|
||||
const resetPayload = { text: '', tokens: null };
|
||||
const wsCalls = recorder.calls.filter((call) => call.name.endsWith('Ws.broadcast'));
|
||||
assert.deepEqual(
|
||||
wsCalls.map((call) => [call.name, call.args[0]]),
|
||||
[
|
||||
['subtitleWs.broadcast', resetPayload],
|
||||
['annotationWs.broadcast', resetPayload],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('media path change to the same YouTube video keeps its parsed cues', (t) => {
|
||||
const { appState, playback, emit } = setup();
|
||||
t.after(() => playback.subtitlePrefetchRuntime.clearScheduledSubtitlePrefetchRefresh());
|
||||
const cues = [{ startTime: 1, endTime: 2, text: '字幕' }];
|
||||
appState.currentMediaPath = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
|
||||
appState.currentSubText = '字幕';
|
||||
appState.activeParsedSubtitleCues = cues;
|
||||
appState.activeParsedSubtitleSource = 'youtube:ja';
|
||||
appState.activeParsedSubtitleMediaPath = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
|
||||
|
||||
emit('media-path-change', { path: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=30' });
|
||||
|
||||
assert.equal(appState.currentSubText, '');
|
||||
assert.equal(appState.activeParsedSubtitleCues, cues);
|
||||
assert.equal(appState.activeParsedSubtitleSource, 'youtube:ja');
|
||||
assert.equal(
|
||||
appState.activeParsedSubtitleMediaPath,
|
||||
'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
|
||||
);
|
||||
});
|
||||
|
||||
test('same media path update keeps autoplay fallbacks; a new path invalidates them first', (t) => {
|
||||
const { recorder, appState, playback, emit } = setup();
|
||||
t.after(() => playback.subtitlePrefetchRuntime.clearScheduledSubtitlePrefetchRefresh());
|
||||
appState.currentMediaPath = '/videos/a.mkv';
|
||||
|
||||
emit('media-path-change', { path: '/videos/a.mkv' });
|
||||
assert.ok(!recorder.names().includes('autoplay.invalidateFallbacks'));
|
||||
assert.ok(recorder.names().includes('tokenizationGate.updateCurrentMediaPath'));
|
||||
|
||||
recorder.calls.length = 0;
|
||||
emit('media-path-change', { path: '/videos/b.mkv' });
|
||||
const names = recorder.names();
|
||||
assert.ok(names.includes('autoplay.invalidateFallbacks'));
|
||||
assert.ok(
|
||||
names.indexOf('autoplay.invalidateFallbacks') <
|
||||
names.indexOf('tokenizationGate.updateCurrentMediaPath'),
|
||||
);
|
||||
});
|
||||
|
||||
test('subtitle change pauses prefetch without reseeking it, and resumes on a repeated line', async () => {
|
||||
const ctx = await setupWithFakePrefetch();
|
||||
const prefetchCalls = () => ctx.recorder.names().filter((name) => name.startsWith('prefetch.'));
|
||||
|
||||
// The controller already holds the empty line, so nothing will settle to resume prefetch.
|
||||
ctx.emit('subtitle-change', { text: '' });
|
||||
assert.deepEqual(prefetchCalls(), ['prefetch.pause', 'prefetch.resume']);
|
||||
|
||||
ctx.recorder.calls.length = 0;
|
||||
ctx.emit('subtitle-change', { text: '新しい行' });
|
||||
// A new line is still tokenizing, so its settle (not this handler) resumes prefetch.
|
||||
assert.deepEqual(prefetchCalls(), ['prefetch.pause']);
|
||||
await flushAsync();
|
||||
});
|
||||
|
||||
test('annotation refresh invalidates cached tokenizations and reseeks prefetch', async () => {
|
||||
const ctx = await setupWithFakePrefetch();
|
||||
const generation = ctx.playback.subtitleProcessingController.getCacheGeneration();
|
||||
|
||||
ctx.playback.refreshCurrentSubtitleAnnotations();
|
||||
|
||||
assert.equal(ctx.playback.subtitleProcessingController.getCacheGeneration(), generation + 1);
|
||||
// No current line: nothing will settle, so the refresh resumes prefetch itself.
|
||||
assert.deepEqual(
|
||||
ctx.recorder.calls.filter((call) => call.name.startsWith('prefetch.')),
|
||||
[
|
||||
{ name: 'prefetch.onSeek', args: [0] },
|
||||
{ name: 'prefetch.resume', args: [] },
|
||||
],
|
||||
);
|
||||
|
||||
ctx.recorder.calls.length = 0;
|
||||
ctx.appState.currentSubText = '現在の行';
|
||||
ctx.playback.refreshCurrentSubtitleAnnotations();
|
||||
assert.deepEqual(
|
||||
ctx.recorder.names().filter((name) => name.startsWith('prefetch.')),
|
||||
['prefetch.pause', 'prefetch.onSeek'],
|
||||
);
|
||||
await flushAsync();
|
||||
});
|
||||
|
||||
test('annotation upgrade of the shown line skips the duplicate plain websocket event', () => {
|
||||
const { recorder, appState, playback, emit } = setup();
|
||||
// Emitted payloads always carry their timing, and an upgrade must match it.
|
||||
appState.currentSubtitleData = { text: '同じ行', tokens: null, startTime: null, endTime: null };
|
||||
playback.subtitleProcessingController.preCacheTokenization('同じ行', {
|
||||
text: '同じ行',
|
||||
tokens: [],
|
||||
});
|
||||
|
||||
emit('subtitle-change', { text: '同じ行' });
|
||||
|
||||
const names = recorder.names();
|
||||
assert.ok(!names.includes('subtitleWs.broadcast'));
|
||||
assert.equal(names.filter((name) => name === 'annotationWs.broadcast').length, 1);
|
||||
assert.equal(
|
||||
recorder.calls.filter(
|
||||
(call) => call.name === 'overlay.broadcast' && call.args[0] === 'subtitle:set',
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
assert.deepEqual(appState.currentSubtitleData?.tokens, []);
|
||||
});
|
||||
|
||||
test('warm tokenization releases autoplay with a warm signal before the first subtitle', async (t) => {
|
||||
const { recorder, appState, playback, emit } = setup();
|
||||
t.after(() => playback.subtitlePrefetchRuntime.clearScheduledSubtitlePrefetchRefresh());
|
||||
appState.currentMediaPath = '/videos/a.mkv';
|
||||
appState.currentSubText = '';
|
||||
|
||||
emit('media-path-change', { path: '/videos/a.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
const signals = recorder.calls.filter((call) => call.name === 'autoplay.maybeSignal');
|
||||
assert.deepEqual(signals.at(-1)?.args, [
|
||||
{ text: '__warm__', tokens: null },
|
||||
{ forceWhilePaused: true },
|
||||
]);
|
||||
const names = recorder.names();
|
||||
assert.ok(names.lastIndexOf('autoplay.flushPending') < names.lastIndexOf('autoplay.maybeSignal'));
|
||||
});
|
||||
|
||||
test('warm tokenization releases autoplay with the current subtitle when it is shown', async (t) => {
|
||||
const { recorder, appState, playback, emit } = setup();
|
||||
t.after(() => playback.subtitlePrefetchRuntime.clearScheduledSubtitlePrefetchRefresh());
|
||||
const current: SubtitleData = { text: '最初の行', tokens: null };
|
||||
appState.currentMediaPath = '/videos/a.mkv';
|
||||
appState.currentSubText = '最初の行';
|
||||
appState.currentSubtitleData = current;
|
||||
|
||||
emit('media-path-change', { path: '/videos/a.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
const signals = recorder.calls.filter((call) => call.name === 'autoplay.maybeSignal');
|
||||
assert.deepEqual(signals.at(-1)?.args, [current, { forceWhilePaused: true }]);
|
||||
});
|
||||
@@ -0,0 +1,981 @@
|
||||
import {
|
||||
MpvIpcClient,
|
||||
applyMpvSubtitleRenderMetricsPatch,
|
||||
createTokenizerDepsRuntime,
|
||||
isSubtitleAnnotationUpgrade,
|
||||
resolveSanitizedSubtitleSeekCommand,
|
||||
sendMpvCommandRuntime,
|
||||
toSubtitleClock,
|
||||
tokenizeSubtitle as tokenizeSubtitleCore,
|
||||
} from '../../core/services';
|
||||
import { parseSubtitleCues } from '../../core/services/subtitle-cue-parser';
|
||||
import { createAutoplaySubtitlePrimingRuntime } from '../runtime/autoplay-subtitle-priming-runtime';
|
||||
import { createAutoplayTokenizationWarmRelease } from '../runtime/autoplay-tokenization-warm-release';
|
||||
import { composeMpvRuntimeHandlers } from '../runtime/composers';
|
||||
import { createCachedInternalSubtitleTrackExtractor } from '../runtime/internal-subtitle-extraction';
|
||||
import {
|
||||
markJellyfinRemotePlaybackLoaded as markJellyfinRemotePlaybackLoadedState,
|
||||
shouldAutoLoadSecondarySubTrackForJellyfinPlayback,
|
||||
} from '../runtime/jellyfin-remote-playback';
|
||||
import { buildSubtitleTrackDiagnostics } from '../runtime/mpv-track-diagnostics';
|
||||
import { createRemoteMediaPathDetector } from '../runtime/network-media-path';
|
||||
import { resolveCanonicalPrimarySubtitle } from '../runtime/primary-subtitle-text';
|
||||
import { createSecondarySubtitleTrackController } from '../runtime/secondary-subtitle-track';
|
||||
import { shouldQuitOnMpvShutdownForTrayState } from '../runtime/startup-tray-policy';
|
||||
import { createSubtitlePrefetchInitController } from '../runtime/subtitle-prefetch-init';
|
||||
import {
|
||||
createRefreshSubtitlePrefetchFromActiveTrackHandler,
|
||||
createResolveActiveSubtitleSidebarSourceHandler,
|
||||
} from '../runtime/subtitle-prefetch-runtime';
|
||||
import { createPrefetchAwareSubtitleProcessingController } from '../runtime/subtitle-processing-runtime';
|
||||
import { isSameYoutubeMediaPath, isYoutubeMediaPath } from '../runtime/youtube-playback';
|
||||
import { MecabTokenizer } from '../../mecab-tokenizer';
|
||||
import type {
|
||||
MpvSubtitleRenderMetrics,
|
||||
SubtitleCue,
|
||||
SubtitleData,
|
||||
SubtitleSidebarPlaybackState,
|
||||
} from '../../types';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import type { ConfigService } from '../../config/service';
|
||||
import type { createOverlayManager, SubtitleWebSocket } from '../../core/services';
|
||||
import type {
|
||||
SubtitlePrefetchService,
|
||||
SubtitlePrefetchServiceDeps,
|
||||
} from '../../core/services/subtitle-prefetch';
|
||||
import type { Logger } from '../../logger';
|
||||
import type { createMediaRuntimeService } from '../media-runtime';
|
||||
import type { createAutoplayReadyGate } from '../runtime/autoplay-ready-gate';
|
||||
import type { createCurrentMediaTokenizationGate } from '../runtime/current-media-tokenization-gate';
|
||||
import type { createDiscordPresenceRuntime } from '../runtime/discord-presence-runtime';
|
||||
import type { createImmersionMediaRuntime } from '../runtime/domains/startup';
|
||||
import type { loadSubtitleSourceText } from '../runtime/internal-subtitle-extraction';
|
||||
import type { createManagedLocalSubtitleSelectionRuntime } from '../runtime/local-subtitle-selection';
|
||||
import type { createMediaTimingReviewRuntime } from '../runtime/media-timing-review';
|
||||
import type { createOverlayNotificationsRuntime } from '../runtime/overlay-notifications-runtime';
|
||||
import type { createStartupOsdSequencer } from '../runtime/startup-osd-sequencer';
|
||||
import type { createSubtitleGenerationRuntime } from '../runtime/subtitle-generation-runtime';
|
||||
import type { RuntimeOptionId } from '../../types/runtime-options';
|
||||
import type { AppState } from '../state';
|
||||
import type { AnilistAssembly } from './anilist';
|
||||
import type { CharacterDictionaryAssembly } from './character-dictionary';
|
||||
import type { DictionariesAssembly } from './dictionaries';
|
||||
import type { JellyfinAssembly } from './jellyfin';
|
||||
import type { YoutubeAssembly } from './youtube';
|
||||
|
||||
type SubtitleWsBroadcaster = Pick<SubtitleWebSocket, 'broadcast'>;
|
||||
type OverlayNotificationsRuntime = ReturnType<typeof createOverlayNotificationsRuntime>;
|
||||
type AnnotationRuntimeOptionId = Extract<
|
||||
RuntimeOptionId,
|
||||
| 'subtitle.annotation.knownWords.highlightEnabled'
|
||||
| 'subtitle.annotation.nPlusOne'
|
||||
| 'subtitle.annotation.jlpt'
|
||||
| 'subtitle.annotation.frequency'
|
||||
>;
|
||||
|
||||
/**
|
||||
* What the playback assembly needs from the rest of `main.ts`. Everything here except the
|
||||
* getters is built before the assembly; siblings built later are reached through getters, and
|
||||
* construction calls none of them.
|
||||
*/
|
||||
export interface PlaybackAssemblyDeps {
|
||||
appState: AppState;
|
||||
configService: Pick<ConfigService, 'getConfig'>;
|
||||
logger: Pick<Logger, 'debug' | 'info' | 'warn' | 'error'>;
|
||||
overlayManager: Pick<
|
||||
ReturnType<typeof createOverlayManager>,
|
||||
'broadcastToOverlayWindows' | 'getVisibleOverlayVisible'
|
||||
>;
|
||||
subtitleWsService: SubtitleWsBroadcaster;
|
||||
annotationSubtitleWsService: SubtitleWsBroadcaster;
|
||||
autoplayReadyGate: Pick<
|
||||
ReturnType<typeof createAutoplayReadyGate>,
|
||||
| 'maybeSignalPluginAutoplayReady'
|
||||
| 'flushPendingAutoplayReadySignal'
|
||||
| 'invalidatePendingAutoplayReadyFallbacks'
|
||||
>;
|
||||
currentMediaTokenizationGate: Pick<
|
||||
ReturnType<typeof createCurrentMediaTokenizationGate>,
|
||||
'updateCurrentMediaPath' | 'markReady'
|
||||
>;
|
||||
startupOsdSequencer: Pick<
|
||||
ReturnType<typeof createStartupOsdSequencer>,
|
||||
| 'reset'
|
||||
| 'markTokenizationReady'
|
||||
| 'showTokenizationLoading'
|
||||
| 'showAnnotationLoading'
|
||||
| 'markAnnotationLoadingComplete'
|
||||
>;
|
||||
managedLocalSubtitleSelectionRuntime: Pick<
|
||||
ReturnType<typeof createManagedLocalSubtitleSelectionRuntime>,
|
||||
'handleMediaPathChange' | 'handleSubtitleTrackListChange'
|
||||
>;
|
||||
mediaTimingReviewRuntime: Pick<
|
||||
ReturnType<typeof createMediaTimingReviewRuntime>,
|
||||
'deferPlaybackResume' | 'cancelPlaybackResume'
|
||||
>;
|
||||
discordPresenceRuntime: Pick<
|
||||
ReturnType<typeof createDiscordPresenceRuntime>,
|
||||
'publishDiscordPresence'
|
||||
>;
|
||||
immersionMediaRuntime: Pick<
|
||||
ReturnType<typeof createImmersionMediaRuntime>,
|
||||
'syncFromCurrentMediaState'
|
||||
>;
|
||||
mediaRuntime: Pick<
|
||||
ReturnType<typeof createMediaRuntimeService>,
|
||||
'updateCurrentMediaPath' | 'updateCurrentMediaTitle'
|
||||
>;
|
||||
overlayNotificationsRuntime: Pick<
|
||||
OverlayNotificationsRuntime,
|
||||
'showConfiguredStatusNotification' | 'getConfiguredStatusNotificationType'
|
||||
>;
|
||||
youtube: Pick<YoutubeAssembly, 'isPlaybackActiveNow'> & {
|
||||
playback: Pick<YoutubeAssembly['playback'], 'getQuitOnDisconnectArmed'>;
|
||||
primarySubtitleNotification: Pick<
|
||||
YoutubeAssembly['primarySubtitleNotification'],
|
||||
'handleMediaPathChange' | 'handleSubtitleTrackChange' | 'handleSubtitleTrackListChange'
|
||||
>;
|
||||
mediaCachePlayback: Pick<YoutubeAssembly['mediaCachePlayback'], 'handleMediaPathChange'>;
|
||||
browserPlayback: Pick<YoutubeAssembly['browserPlayback'], 'handleMediaPathChange'>;
|
||||
flow: Pick<YoutubeAssembly['flow'], 'handleMediaPathChange'>;
|
||||
};
|
||||
jellyfin: Pick<
|
||||
JellyfinAssembly,
|
||||
| 'getQuitOnDisconnectArmed'
|
||||
| 'reportJellyfinRemoteStopped'
|
||||
| 'reportJellyfinRemoteProgress'
|
||||
| 'getActivePlayback'
|
||||
| 'startJellyfinRemoteSession'
|
||||
>;
|
||||
anilist: Pick<
|
||||
AnilistAssembly,
|
||||
| 'maybeRunAnilistPostWatchUpdate'
|
||||
| 'recordAnilistMediaDuration'
|
||||
| 'getCurrentAnilistMediaKey'
|
||||
| 'resetAnilistMediaTracking'
|
||||
| 'maybeProbeAnilistDuration'
|
||||
| 'ensureAnilistMediaGuess'
|
||||
| 'resetAnilistMediaGuessState'
|
||||
>;
|
||||
characterDictionary: {
|
||||
autoSync: Pick<CharacterDictionaryAssembly['autoSync'], 'scheduleSync' | 'getCurrentMediaId'>;
|
||||
imageLookup: Pick<CharacterDictionaryAssembly['imageLookup'], 'get'>;
|
||||
nameCandidates: Pick<CharacterDictionaryAssembly['nameCandidates'], 'get'>;
|
||||
};
|
||||
dictionaries: {
|
||||
jlpt: Pick<DictionariesAssembly['jlpt'], 'ensureJlptDictionaryLookup'>;
|
||||
frequency: Pick<DictionariesAssembly['frequency'], 'ensureFrequencyDictionaryLookup'>;
|
||||
};
|
||||
getSubtitleGenerationRuntime: () => Pick<
|
||||
ReturnType<typeof createSubtitleGenerationRuntime>,
|
||||
'handleMediaPathChange'
|
||||
>;
|
||||
isCharacterDictionaryEnabled: () => boolean;
|
||||
/** Whether the tray icon exists; mpv shutdown keeps the app alive when it does. */
|
||||
hasTray: () => boolean;
|
||||
loadSubtitleSourceText: typeof loadSubtitleSourceText;
|
||||
createSubtitlePrefetchService: (
|
||||
serviceDeps: SubtitlePrefetchServiceDeps,
|
||||
) => SubtitlePrefetchService;
|
||||
requestAppQuit: () => void;
|
||||
maybeStartOverlayLoadingOsd: OverlayNotificationsRuntime['maybeStartOverlayLoadingOsd'];
|
||||
flushQueuedMpvOsdNotifications: OverlayNotificationsRuntime['flushQueuedMpvOsdNotifications'];
|
||||
refreshMpvSessionBindings: () => Promise<void>;
|
||||
ensureImmersionTrackerStarted: () => void;
|
||||
restoreOverlayMpvSubtitles: () => void;
|
||||
resetSubtitleSidebarEmbeddedLayoutRuntime: () => void;
|
||||
syncOverlayMpvSubtitleSuppression: () => void;
|
||||
setOverlayVisible: (visible: boolean) => void;
|
||||
ensureYomitanExtensionLoaded: () => Promise<unknown>;
|
||||
shouldInitializeMecabForAnnotations: () => boolean;
|
||||
getRuntimeBooleanOption: (id: AnnotationRuntimeOptionId, fallback: boolean) => boolean;
|
||||
/** Linux fullscreen overlay refresh lives with the overlay window code in `main.ts`. */
|
||||
onFullscreenChange: (fullscreen: boolean) => void;
|
||||
}
|
||||
|
||||
export type PlaybackAssembly = ReturnType<typeof createPlaybackAssembly>;
|
||||
|
||||
/**
|
||||
* Owns the subtitle pipeline around mpv playback: the mpv client runtime and its event
|
||||
* handlers, subtitle tokenization and warmups, subtitle prefetch, the subtitle sidebar's cached
|
||||
* playback state, secondary subtitles and autoplay subtitle priming. `main.ts` builds it once and
|
||||
* starts warmups and the mpv client from its startup code.
|
||||
*/
|
||||
export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
const {
|
||||
appState,
|
||||
configService,
|
||||
logger,
|
||||
overlayManager,
|
||||
subtitleWsService,
|
||||
annotationSubtitleWsService,
|
||||
autoplayReadyGate,
|
||||
currentMediaTokenizationGate,
|
||||
startupOsdSequencer,
|
||||
managedLocalSubtitleSelectionRuntime,
|
||||
mediaTimingReviewRuntime,
|
||||
discordPresenceRuntime,
|
||||
immersionMediaRuntime,
|
||||
mediaRuntime,
|
||||
overlayNotificationsRuntime,
|
||||
youtube,
|
||||
jellyfin,
|
||||
anilist,
|
||||
characterDictionary,
|
||||
dictionaries,
|
||||
loadSubtitleSourceText,
|
||||
createSubtitlePrefetchService,
|
||||
} = deps;
|
||||
let backgroundWarmupsStarted = false;
|
||||
let tokenizeSubtitleDeferred: ((text: string) => Promise<SubtitleData>) | null = null;
|
||||
|
||||
function withCurrentSubtitleTiming(payload: SubtitleData): SubtitleData {
|
||||
const canonical = resolveCanonicalPrimarySubtitle({
|
||||
liveText: payload.text,
|
||||
currentTimeSec: toSubtitleClock(
|
||||
Number(appState.mpvClient?.currentTimePos),
|
||||
appState.mpvClient?.currentSubDelay ?? 0,
|
||||
),
|
||||
cues: appState.activeParsedSubtitleCues,
|
||||
});
|
||||
return {
|
||||
...payload,
|
||||
startTime: canonical?.startTime ?? appState.mpvClient?.currentSubStart ?? null,
|
||||
endTime: canonical?.endTime ?? appState.mpvClient?.currentSubEnd ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function emitSubtitlePayload(
|
||||
payload: SubtitleData,
|
||||
options?: { resumePrefetch?: boolean },
|
||||
): void {
|
||||
const timedPayload = withCurrentSubtitleTiming(payload);
|
||||
const currentSubtitleData = appState.currentSubtitleData;
|
||||
const isAnnotationUpgrade = isSubtitleAnnotationUpgrade(currentSubtitleData, timedPayload);
|
||||
const frequencyDictionary = configService.getConfig().subtitleStyle.frequencyDictionary;
|
||||
const frequencyOptions = {
|
||||
enabled: frequencyDictionary.enabled,
|
||||
topX: frequencyDictionary.topX,
|
||||
mode: frequencyDictionary.mode,
|
||||
};
|
||||
appState.currentSubtitleData = timedPayload;
|
||||
overlayManager.broadcastToOverlayWindows('subtitle:set', timedPayload);
|
||||
if (!isAnnotationUpgrade) {
|
||||
subtitleWsService.broadcast(timedPayload, frequencyOptions);
|
||||
}
|
||||
annotationSubtitleWsService.broadcast(timedPayload, frequencyOptions);
|
||||
autoplayReadyGate.maybeSignalPluginAutoplayReady(timedPayload, { forceWhilePaused: true });
|
||||
// resumePrefetch: false marks an emit that is not the end of the work for
|
||||
// this line; prefetch stays paused until the subtitle processing controller
|
||||
// settles so it does not compete with the on-screen line for the single
|
||||
// Yomitan parser window.
|
||||
if (options?.resumePrefetch !== false) {
|
||||
subtitlePrefetchService?.resume();
|
||||
}
|
||||
}
|
||||
function getCurrentAutoplaySubtitlePayload(): SubtitleData | null {
|
||||
const payload = appState.currentSubtitleData;
|
||||
if (!payload?.text.trim()) {
|
||||
return null;
|
||||
}
|
||||
if (payload.text !== appState.currentSubText) {
|
||||
return null;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
function signalCurrentSubtitleAutoplayReady(): void {
|
||||
autoplayReadyGate.flushPendingAutoplayReadySignal();
|
||||
const payload = getCurrentAutoplaySubtitlePayload();
|
||||
if (payload) {
|
||||
autoplayReadyGate.maybeSignalPluginAutoplayReady(payload, { forceWhilePaused: true });
|
||||
return;
|
||||
}
|
||||
if (!appState.currentSubText.trim()) {
|
||||
autoplayReadyGate.maybeSignalPluginAutoplayReady(
|
||||
{ text: '__warm__', tokens: null },
|
||||
{ forceWhilePaused: true },
|
||||
);
|
||||
}
|
||||
}
|
||||
const subtitleProcessingController = createPrefetchAwareSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text: string) =>
|
||||
tokenizeSubtitleDeferred ? await tokenizeSubtitleDeferred(text) : { text, tokens: null },
|
||||
emitSubtitlePayload: (payload, options) => emitSubtitlePayload(payload, options),
|
||||
resumePrefetch: () => {
|
||||
subtitlePrefetchService?.resume();
|
||||
},
|
||||
logDebug: (message) => {
|
||||
logger.debug(`[subtitle-processing] ${message}`);
|
||||
},
|
||||
now: () => Date.now(),
|
||||
});
|
||||
|
||||
let subtitlePrefetchService: SubtitlePrefetchService | null = null;
|
||||
let lastObservedTimePos = 0;
|
||||
let lastObservedPrimarySubtitleTrackId: number | null = null;
|
||||
let subtitleSidebarCuesRef: SubtitleCue[] | null = null;
|
||||
let subtitleSidebarCuesRevision = 0;
|
||||
|
||||
/**
|
||||
* Cheap sidebar state polled ~12x/s while the sidebar is open. Reads only cached state, no
|
||||
* mpv round-trips. `cuesRevision` bumps whenever a new parsed cue array is swapped in, so a
|
||||
* re-parse of the same source still tells the renderer to fetch the full snapshot.
|
||||
*/
|
||||
function getSubtitleSidebarPlaybackState(): SubtitleSidebarPlaybackState {
|
||||
if (appState.activeParsedSubtitleCues !== subtitleSidebarCuesRef) {
|
||||
subtitleSidebarCuesRef = appState.activeParsedSubtitleCues;
|
||||
subtitleSidebarCuesRevision += 1;
|
||||
}
|
||||
const subDelay = appState.mpvClient?.currentSubDelay ?? 0;
|
||||
return {
|
||||
sourceKey: JSON.stringify([
|
||||
appState.activeParsedSubtitleMediaPath,
|
||||
appState.activeParsedSubtitleSource,
|
||||
]),
|
||||
cuesRevision: subtitleSidebarCuesRevision,
|
||||
currentTimeSec:
|
||||
appState.mpvClient?.currentTimePos === undefined
|
||||
? null
|
||||
: toSubtitleClock(appState.mpvClient.currentTimePos, subDelay),
|
||||
subDelay,
|
||||
currentSubtitle: {
|
||||
text: appState.currentSubText,
|
||||
startTime: appState.mpvClient?.currentSubStart ?? null,
|
||||
endTime: appState.mpvClient?.currentSubEnd ?? null,
|
||||
},
|
||||
};
|
||||
}
|
||||
const SEEK_THRESHOLD_SECONDS = 3;
|
||||
const EXPLICIT_SEEK_INTENT_TTL_MS = 2000;
|
||||
let explicitSeekIntentExpiresAtMs = 0;
|
||||
|
||||
function isExplicitMpvSeekCommand(command: readonly (string | number)[]): boolean {
|
||||
return command[0] === 'seek' || command[0] === 'sub-seek';
|
||||
}
|
||||
|
||||
function getMpvPauseCommandValue(command: readonly (string | number)[]): 'yes' | 'no' | null {
|
||||
if ((command[0] !== 'set_property' && command[0] !== 'set') || command[1] !== 'pause') {
|
||||
return null;
|
||||
}
|
||||
return command[2] === 'yes' || command[2] === 'no' ? command[2] : null;
|
||||
}
|
||||
|
||||
function sendRendererMpvCommand(rawCommand: (string | number)[]): void {
|
||||
// Overlay auto-pause releases (popup closed, hover left) must not resume playback
|
||||
// behind an open timing review; the review applies them when it closes. A pause
|
||||
// request during the review keeps playback paused after it closes.
|
||||
const pauseValue = getMpvPauseCommandValue(rawCommand);
|
||||
if (pauseValue === 'no' && mediaTimingReviewRuntime.deferPlaybackResume()) {
|
||||
return;
|
||||
}
|
||||
if (pauseValue === 'yes') {
|
||||
mediaTimingReviewRuntime.cancelPlaybackResume();
|
||||
}
|
||||
const command =
|
||||
resolveSanitizedSubtitleSeekCommand(
|
||||
rawCommand,
|
||||
appState.activeParsedSubtitleCues,
|
||||
appState.mpvClient?.currentTimePos ?? Number.NaN,
|
||||
appState.mpvClient?.currentSubDelay ?? 0,
|
||||
) ?? rawCommand;
|
||||
if (isExplicitMpvSeekCommand(command)) {
|
||||
explicitSeekIntentExpiresAtMs = Date.now() + EXPLICIT_SEEK_INTENT_TTL_MS;
|
||||
}
|
||||
sendMpvCommandRuntime(appState.mpvClient, command);
|
||||
}
|
||||
|
||||
function consumeExplicitSeekIntent(): boolean {
|
||||
const pending = explicitSeekIntentExpiresAtMs >= Date.now();
|
||||
explicitSeekIntentExpiresAtMs = 0;
|
||||
return pending;
|
||||
}
|
||||
|
||||
const autoplaySubtitlePrimingRuntime = createAutoplaySubtitlePrimingRuntime({
|
||||
getCurrentMediaPath: () => appState.currentMediaPath,
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
setCurrentSubText: (text) => {
|
||||
appState.currentSubText = text;
|
||||
},
|
||||
getCurrentSubText: () => appState.currentSubText,
|
||||
getCurrentSubtitleData: () => appState.currentSubtitleData,
|
||||
getActiveParsedSubtitleCues: () => appState.activeParsedSubtitleCues,
|
||||
setActiveParsedSubtitleMediaPath: (mediaPath) => {
|
||||
appState.activeParsedSubtitleMediaPath = mediaPath;
|
||||
},
|
||||
subtitleProcessingController,
|
||||
emitSubtitlePayload: (payload, options) => emitSubtitlePayload(payload, options),
|
||||
getSubtitlePrefetchService: () => subtitlePrefetchService,
|
||||
getLastObservedTimePos: () => lastObservedTimePos,
|
||||
getVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
emitSecondarySubtitle: (text) => {
|
||||
secondarySubtitleTrackController.handleLiveText(text);
|
||||
},
|
||||
initSubtitlePrefetch: (sourcePath, currentTimePos, sourceKey) =>
|
||||
subtitlePrefetchInitController.initSubtitlePrefetch(sourcePath, currentTimePos, sourceKey),
|
||||
refreshSubtitlePrefetchFromActiveTrack: () => refreshSubtitlePrefetchFromActiveTrackHandler(),
|
||||
logDebug: (message) => {
|
||||
logger.debug(message);
|
||||
},
|
||||
});
|
||||
|
||||
const subtitlePrefetchInitController = createSubtitlePrefetchInitController({
|
||||
getCurrentService: () => subtitlePrefetchService,
|
||||
setCurrentService: (service) => {
|
||||
subtitlePrefetchService = service;
|
||||
},
|
||||
loadSubtitleSourceText,
|
||||
parseSubtitleCues: (content, filename) => parseSubtitleCues(content, filename),
|
||||
createSubtitlePrefetchService: (serviceDeps) => createSubtitlePrefetchService(serviceDeps),
|
||||
tokenizeSubtitle: async (text) =>
|
||||
tokenizeSubtitleDeferred ? await tokenizeSubtitleDeferred(text) : null,
|
||||
preCacheTokenization: (text, data) => {
|
||||
subtitleProcessingController.preCacheTokenization(text, data);
|
||||
},
|
||||
hasCachedTokenization: (text) => subtitleProcessingController.hasCachedSubtitle(text),
|
||||
getCacheGeneration: () => subtitleProcessingController.getCacheGeneration(),
|
||||
logInfo: (message) => logger.info(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
onParsedSubtitleCuesChanged: (cues, sourceKey) => {
|
||||
appState.activeParsedSubtitleCues = cues ?? [];
|
||||
appState.activeParsedSubtitleSource = sourceKey;
|
||||
if (!cues?.length) {
|
||||
appState.activeParsedSubtitleMediaPath = null;
|
||||
}
|
||||
const mediaPath = autoplaySubtitlePrimingRuntime.getCurrentAutoplayMediaPath();
|
||||
if (mediaPath && cues?.length) {
|
||||
void autoplaySubtitlePrimingRuntime
|
||||
.primeAutoplaySubtitleFromParsedCues(mediaPath, cues)
|
||||
.catch((error) => {
|
||||
logger.debug(
|
||||
`[autoplay-subtitle-prime] failed to prime from parsed cues: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
const cachedInternalSubtitleTrackExtractor = createCachedInternalSubtitleTrackExtractor();
|
||||
const detectRemoteMediaPath = createRemoteMediaPathDetector();
|
||||
const resolveActiveSubtitleSidebarSourceHandler = createResolveActiveSubtitleSidebarSourceHandler(
|
||||
{
|
||||
getFfmpegPath: () => configService.getConfig().subsync.ffmpeg_path.trim() || 'ffmpeg',
|
||||
extractInternalSubtitleTrack: (ffmpegPath, videoPath, track) =>
|
||||
cachedInternalSubtitleTrackExtractor.extract(ffmpegPath, videoPath, track),
|
||||
logDebug: (message) => logger.debug(message),
|
||||
},
|
||||
);
|
||||
|
||||
const secondarySubtitleTrackController = createSecondarySubtitleTrackController({
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
getCurrentTimePos: () => appState.mpvClient?.currentTimePos ?? lastObservedTimePos,
|
||||
resolveSubtitleSource: (input) => resolveActiveSubtitleSidebarSourceHandler(input),
|
||||
loadSubtitleSourceText,
|
||||
parseSubtitleCues: (content, filename) => parseSubtitleCues(content, filename),
|
||||
setCurrentSecondaryText: (text) => {
|
||||
if (appState.mpvClient) {
|
||||
appState.mpvClient.currentSecondarySubText = text;
|
||||
}
|
||||
},
|
||||
broadcastSecondaryText: (text) => {
|
||||
overlayManager.broadcastToOverlayWindows('secondary-subtitle:set', text);
|
||||
},
|
||||
logDebug: (message) => logger.debug(message),
|
||||
logWarn: (message, error) => logger.warn(message, error),
|
||||
});
|
||||
|
||||
const refreshSubtitlePrefetchFromActiveTrackHandler =
|
||||
createRefreshSubtitlePrefetchFromActiveTrackHandler({
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
getLastObservedTimePos: () => lastObservedTimePos,
|
||||
// Remote media has no extractable on-disk track to fall back to, so a transient
|
||||
// resolve miss (sid briefly 'no', a cycle onto an embedded stream track) would
|
||||
// otherwise drop a working cue list for the rest of the episode.
|
||||
shouldKeepExistingCuesOnMissingSource: async (videoPath) =>
|
||||
isYoutubeMediaPath(videoPath) || (await detectRemoteMediaPath(videoPath)),
|
||||
subtitlePrefetchInitController,
|
||||
resolveActiveSubtitleSidebarSource: (input) =>
|
||||
resolveActiveSubtitleSidebarSourceHandler(input),
|
||||
logDebug: (message) => logger.debug(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
});
|
||||
|
||||
const subtitlePrefetchRuntime = {
|
||||
cancelPendingInit: () => subtitlePrefetchInitController.cancelPendingInit(),
|
||||
initSubtitlePrefetch: subtitlePrefetchInitController.initSubtitlePrefetch,
|
||||
refreshSubtitleSidebarFromSource: (sourcePath: string, mediaPath?: string) =>
|
||||
autoplaySubtitlePrimingRuntime.refreshSubtitleSidebarFromSource(sourcePath, mediaPath),
|
||||
refreshSubtitlePrefetchFromActiveTrack: () => refreshSubtitlePrefetchFromActiveTrackHandler(),
|
||||
scheduleSubtitlePrefetchRefresh: (delayMs?: number) =>
|
||||
autoplaySubtitlePrimingRuntime.scheduleSubtitlePrefetchRefresh(delayMs),
|
||||
clearScheduledSubtitlePrefetchRefresh: () =>
|
||||
autoplaySubtitlePrimingRuntime.clearScheduledSubtitlePrefetchRefresh(),
|
||||
} as const;
|
||||
|
||||
function refreshCurrentSubtitleAnnotations(): void {
|
||||
const hasCurrentSubtitle = appState.currentSubText.trim().length > 0;
|
||||
if (hasCurrentSubtitle) {
|
||||
subtitlePrefetchService?.pause();
|
||||
}
|
||||
subtitleProcessingController.invalidateTokenizationCache();
|
||||
subtitlePrefetchService?.onSeek(lastObservedTimePos);
|
||||
if (!subtitleProcessingController.refreshCurrentSubtitle(appState.currentSubText)) {
|
||||
// Idle controller: no settle is coming to release the pause above.
|
||||
subtitlePrefetchService?.resume();
|
||||
}
|
||||
}
|
||||
|
||||
let signalAutoplayReadyFromWarmTokenization: ((path: string | null | undefined) => void) | null =
|
||||
null;
|
||||
|
||||
const {
|
||||
bindMpvClientEventHandlers,
|
||||
createMpvClientRuntimeService: createMpvClientRuntimeServiceHandler,
|
||||
updateMpvSubtitleRenderMetrics: updateMpvSubtitleRenderMetricsHandler,
|
||||
tokenizeSubtitle: tokenizeSubtitleRuntime,
|
||||
createMecabTokenizerAndCheck,
|
||||
prewarmSubtitleDictionaries,
|
||||
startBackgroundWarmups,
|
||||
startTokenizationWarmups,
|
||||
isTokenizationWarmupReady,
|
||||
} = composeMpvRuntimeHandlers<
|
||||
MpvIpcClient,
|
||||
ReturnType<typeof createTokenizerDepsRuntime>,
|
||||
SubtitleData
|
||||
>({
|
||||
bindMpvMainEventHandlersMainDeps: {
|
||||
appState,
|
||||
getQuitOnDisconnectArmed: () =>
|
||||
jellyfin.getQuitOnDisconnectArmed() || youtube.playback.getQuitOnDisconnectArmed(),
|
||||
scheduleQuitCheck: (callback) => {
|
||||
setTimeout(callback, 500);
|
||||
},
|
||||
quitApp: () => deps.requestAppQuit(),
|
||||
reportJellyfinRemoteStopped: () => {
|
||||
void jellyfin.reportJellyfinRemoteStopped();
|
||||
},
|
||||
onMpvConnected: () => {
|
||||
deps.maybeStartOverlayLoadingOsd();
|
||||
deps.flushQueuedMpvOsdNotifications();
|
||||
secondarySubtitleTrackController.scheduleRefresh(0);
|
||||
void deps.refreshMpvSessionBindings();
|
||||
if (appState.sessionBindingsInitialized) {
|
||||
sendMpvCommandRuntime(appState.mpvClient, [
|
||||
'script-message',
|
||||
'subminer-reload-session-bindings',
|
||||
]);
|
||||
}
|
||||
if (appState.currentSubText.trim()) {
|
||||
subtitleProcessingController.refreshCurrentSubtitle(appState.currentSubText);
|
||||
}
|
||||
},
|
||||
maybeRunAnilistPostWatchUpdate: (options) => anilist.maybeRunAnilistPostWatchUpdate(options),
|
||||
recordAnilistMediaDuration: (durationSec) => {
|
||||
anilist.recordAnilistMediaDuration(durationSec);
|
||||
},
|
||||
logSubtitleTimingError: (message, error) => logger.error(message, error),
|
||||
broadcastToOverlayWindows: (channel, payload) => {
|
||||
overlayManager.broadcastToOverlayWindows(channel, payload);
|
||||
},
|
||||
onSecondarySubtitleChange: (text) => {
|
||||
secondarySubtitleTrackController.handleLiveText(text);
|
||||
},
|
||||
getImmediateSubtitlePayload: (text) =>
|
||||
subtitleProcessingController.consumeCachedSubtitle(text),
|
||||
emitImmediateSubtitle: (payload) => {
|
||||
emitSubtitlePayload(payload);
|
||||
},
|
||||
onSubtitleChange: (text) => {
|
||||
// Pause only; restarting the prefetch run here would discard in-flight
|
||||
// tokenization work on every line. Real seeks restart via onTimePosUpdate.
|
||||
subtitlePrefetchService?.pause();
|
||||
if (!subtitleProcessingController.onSubtitleChange(text)) {
|
||||
// Repeat of the current text: the controller is idle, so no settle is
|
||||
// coming to release the pause. Resume now instead of idling prefetch
|
||||
// for the rest of the cue.
|
||||
subtitlePrefetchService?.resume();
|
||||
}
|
||||
},
|
||||
refreshDiscordPresence: () => {
|
||||
discordPresenceRuntime.publishDiscordPresence();
|
||||
},
|
||||
logSubtitleProcessingDebug: (message: string) => logger.debug(message),
|
||||
ensureImmersionTrackerInitialized: () => {
|
||||
deps.ensureImmersionTrackerStarted();
|
||||
},
|
||||
tokenizeSubtitleForImmersion: async (text): Promise<SubtitleData | null> =>
|
||||
tokenizeSubtitleDeferred ? await tokenizeSubtitleDeferred(text) : null,
|
||||
updateCurrentMediaPath: (path) => {
|
||||
const normalizedPath = path.trim();
|
||||
deps.maybeStartOverlayLoadingOsd(normalizedPath);
|
||||
const previousPath = appState.currentMediaPath?.trim() || null;
|
||||
const preserveParsedSubtitleCues = isSameYoutubeMediaPath(
|
||||
normalizedPath,
|
||||
appState.activeParsedSubtitleMediaPath,
|
||||
);
|
||||
if ((normalizedPath || null) !== previousPath) {
|
||||
cachedInternalSubtitleTrackExtractor.clear();
|
||||
secondarySubtitleTrackController.reset();
|
||||
const resetSubtitlePayload = { text: '', tokens: null };
|
||||
const frequencyDictionary = configService.getConfig().subtitleStyle.frequencyDictionary;
|
||||
const frequencyOptions = {
|
||||
enabled: frequencyDictionary.enabled,
|
||||
topX: frequencyDictionary.topX,
|
||||
mode: frequencyDictionary.mode,
|
||||
};
|
||||
autoplaySubtitlePrimingRuntime.resetAutoplaySubtitlePrime();
|
||||
lastObservedTimePos = 0;
|
||||
appState.currentSubText = '';
|
||||
appState.currentSubtitleData = null;
|
||||
if (!preserveParsedSubtitleCues) {
|
||||
appState.activeParsedSubtitleCues = [];
|
||||
appState.activeParsedSubtitleSource = null;
|
||||
appState.activeParsedSubtitleMediaPath = null;
|
||||
}
|
||||
overlayManager.broadcastToOverlayWindows('subtitle:set', resetSubtitlePayload);
|
||||
subtitleWsService.broadcast(resetSubtitlePayload, frequencyOptions);
|
||||
annotationSubtitleWsService.broadcast(resetSubtitlePayload, frequencyOptions);
|
||||
autoplayReadyGate.invalidatePendingAutoplayReadyFallbacks();
|
||||
}
|
||||
currentMediaTokenizationGate.updateCurrentMediaPath(path);
|
||||
managedLocalSubtitleSelectionRuntime.handleMediaPathChange(path);
|
||||
startupOsdSequencer.reset();
|
||||
subtitlePrefetchRuntime.clearScheduledSubtitlePrefetchRefresh();
|
||||
if (!preserveParsedSubtitleCues) {
|
||||
subtitlePrefetchRuntime.cancelPendingInit();
|
||||
}
|
||||
youtube.primarySubtitleNotification.handleMediaPathChange(path);
|
||||
void youtube.mediaCachePlayback.handleMediaPathChange(path);
|
||||
youtube.browserPlayback.handleMediaPathChange(path);
|
||||
youtube.flow.handleMediaPathChange(path);
|
||||
deps.getSubtitleGenerationRuntime().handleMediaPathChange(path);
|
||||
if (path) {
|
||||
deps.ensureImmersionTrackerStarted();
|
||||
secondarySubtitleTrackController.scheduleRefresh();
|
||||
void subtitlePrefetchRuntime.refreshSubtitlePrefetchFromActiveTrack();
|
||||
// Retry after a short delay because MPV can populate track-list after path.
|
||||
subtitlePrefetchRuntime.scheduleSubtitlePrefetchRefresh(500);
|
||||
}
|
||||
mediaRuntime.updateCurrentMediaPath(path);
|
||||
},
|
||||
restoreMpvSubVisibility: () => {
|
||||
deps.restoreOverlayMpvSubtitles();
|
||||
},
|
||||
resetSubtitleSidebarEmbeddedLayout: () => {
|
||||
deps.resetSubtitleSidebarEmbeddedLayoutRuntime();
|
||||
},
|
||||
getCurrentAnilistMediaKey: () => anilist.getCurrentAnilistMediaKey(),
|
||||
resetAnilistMediaTracking: (mediaKey) => {
|
||||
anilist.resetAnilistMediaTracking(mediaKey);
|
||||
},
|
||||
maybeProbeAnilistDuration: (mediaKey) => {
|
||||
void anilist.maybeProbeAnilistDuration(mediaKey);
|
||||
},
|
||||
ensureAnilistMediaGuess: (mediaKey) => {
|
||||
void anilist.ensureAnilistMediaGuess(mediaKey);
|
||||
},
|
||||
syncImmersionMediaState: () => {
|
||||
immersionMediaRuntime.syncFromCurrentMediaState();
|
||||
},
|
||||
signalAutoplayReadyIfWarm: (path) => signalAutoplayReadyFromWarmTokenization?.(path),
|
||||
markJellyfinRemotePlaybackLoaded: (path) => {
|
||||
markJellyfinRemotePlaybackLoadedState(jellyfin.getActivePlayback(), path);
|
||||
},
|
||||
scheduleCharacterDictionarySync: () => {
|
||||
if (
|
||||
!configService.getConfig().subtitleStyle.nameMatchEnabled ||
|
||||
!deps.isCharacterDictionaryEnabled() ||
|
||||
youtube.isPlaybackActiveNow()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
characterDictionary.autoSync.scheduleSync();
|
||||
},
|
||||
updateCurrentMediaTitle: (title) => {
|
||||
mediaRuntime.updateCurrentMediaTitle(title);
|
||||
},
|
||||
resetAnilistMediaGuessState: () => {
|
||||
anilist.resetAnilistMediaGuessState();
|
||||
},
|
||||
reportJellyfinRemoteProgress: (forceImmediate) => {
|
||||
void jellyfin.reportJellyfinRemoteProgress(forceImmediate);
|
||||
},
|
||||
consumeExplicitSeek: () => consumeExplicitSeekIntent(),
|
||||
onTimePosUpdate: (time) => {
|
||||
const delta = time - lastObservedTimePos;
|
||||
if (subtitlePrefetchService && (delta > SEEK_THRESHOLD_SECONDS || delta < 0)) {
|
||||
subtitlePrefetchService.onSeek(time);
|
||||
}
|
||||
lastObservedTimePos = time;
|
||||
secondarySubtitleTrackController.handleTimePos(time);
|
||||
},
|
||||
onFullscreenChange: (fullscreen) => deps.onFullscreenChange(fullscreen),
|
||||
onSubtitleTrackChange: (sid) => {
|
||||
lastObservedPrimarySubtitleTrackId = sid;
|
||||
logger.info('[mpv-subtitles] primary subtitle track changed', { sid });
|
||||
autoplaySubtitlePrimingRuntime.scheduleSubtitlePrefetchRefresh();
|
||||
youtube.primarySubtitleNotification.handleSubtitleTrackChange(sid);
|
||||
},
|
||||
onSecondarySubtitleTrackChange: () => {
|
||||
secondarySubtitleTrackController.handleTrackChange();
|
||||
secondarySubtitleTrackController.scheduleRefresh(0);
|
||||
},
|
||||
onSecondarySubtitleDelayChange: (delay) => {
|
||||
secondarySubtitleTrackController.handleDelayChange(delay);
|
||||
},
|
||||
onSubtitleTrackListChange: (trackList) => {
|
||||
const diagnostics = buildSubtitleTrackDiagnostics(
|
||||
lastObservedPrimarySubtitleTrackId,
|
||||
trackList,
|
||||
);
|
||||
if (!diagnostics.trackListReadable) {
|
||||
logger.warn(
|
||||
'[mpv-subtitles] mpv reported an unreadable subtitle track list',
|
||||
diagnostics,
|
||||
);
|
||||
} else if (diagnostics.subtitleTrackCount === 0) {
|
||||
logger.warn('[mpv-subtitles] mpv reported no subtitle tracks', diagnostics);
|
||||
} else {
|
||||
logger.info('[mpv-subtitles] subtitle track list updated', diagnostics);
|
||||
}
|
||||
managedLocalSubtitleSelectionRuntime.handleSubtitleTrackListChange(trackList);
|
||||
secondarySubtitleTrackController.scheduleRefresh(0);
|
||||
autoplaySubtitlePrimingRuntime.scheduleSubtitlePrefetchRefresh();
|
||||
youtube.primarySubtitleNotification.handleSubtitleTrackListChange(trackList);
|
||||
},
|
||||
updateSubtitleRenderMetrics: (patch) => {
|
||||
updateMpvSubtitleRenderMetricsHandler(patch as Partial<MpvSubtitleRenderMetrics>);
|
||||
},
|
||||
syncOverlayMpvSubtitleSuppression: () => {
|
||||
deps.syncOverlayMpvSubtitleSuppression();
|
||||
},
|
||||
},
|
||||
mpvClientRuntimeServiceFactoryMainDeps: {
|
||||
createClient: MpvIpcClient,
|
||||
getSocketPath: () => appState.mpvSocketPath,
|
||||
getResolvedConfig: () => configService.getConfig(),
|
||||
isAutoStartOverlayEnabled: () => appState.autoStartOverlay,
|
||||
setOverlayVisible: (visible: boolean) => deps.setOverlayVisible(visible),
|
||||
isVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
getReconnectTimer: () => appState.reconnectTimer,
|
||||
setReconnectTimer: (timer: ReturnType<typeof setTimeout> | null) => {
|
||||
appState.reconnectTimer = timer;
|
||||
},
|
||||
shouldAutoLoadSecondarySubTrack: (path: string) =>
|
||||
shouldAutoLoadSecondarySubTrackForJellyfinPlayback(jellyfin.getActivePlayback(), path),
|
||||
shouldQuitOnMpvShutdown: () =>
|
||||
shouldQuitOnMpvShutdownForTrayState({
|
||||
managedPlayback: appState.initialArgs?.managedPlayback === true,
|
||||
backgroundMode: appState.backgroundMode,
|
||||
hasTray: deps.hasTray(),
|
||||
}),
|
||||
requestAppQuit: () => deps.requestAppQuit(),
|
||||
},
|
||||
updateMpvSubtitleRenderMetricsMainDeps: {
|
||||
getCurrentMetrics: () => appState.mpvSubtitleRenderMetrics,
|
||||
setCurrentMetrics: (metrics) => {
|
||||
appState.mpvSubtitleRenderMetrics = metrics;
|
||||
},
|
||||
applyPatch: (current, patch) => applyMpvSubtitleRenderMetricsPatch(current, patch),
|
||||
broadcastMetrics: () => {
|
||||
// no renderer consumer for subtitle render metrics updates at present
|
||||
},
|
||||
},
|
||||
tokenizer: {
|
||||
buildTokenizerDepsMainDeps: {
|
||||
getYomitanExt: () => appState.yomitanExt,
|
||||
getYomitanSession: () => appState.yomitanSession,
|
||||
getYomitanParserWindow: () => appState.yomitanParserWindow,
|
||||
setYomitanParserWindow: (window) => {
|
||||
appState.yomitanParserWindow = window as BrowserWindow | null;
|
||||
},
|
||||
getYomitanParserReadyPromise: () => appState.yomitanParserReadyPromise,
|
||||
setYomitanParserReadyPromise: (promise) => {
|
||||
appState.yomitanParserReadyPromise = promise;
|
||||
},
|
||||
getYomitanParserInitPromise: () => appState.yomitanParserInitPromise,
|
||||
setYomitanParserInitPromise: (promise) => {
|
||||
appState.yomitanParserInitPromise = promise;
|
||||
},
|
||||
isKnownWord: (text, reading, options) =>
|
||||
Boolean(appState.ankiIntegration?.isKnownWord(text, reading, options)),
|
||||
getKnownWordTier: (text, reading, options) =>
|
||||
appState.ankiIntegration?.getKnownWordTier(text, reading, options) ?? null,
|
||||
recordLookup: (hit) => {
|
||||
deps.ensureImmersionTrackerStarted();
|
||||
appState.immersionTracker?.recordLookup(hit);
|
||||
},
|
||||
getKnownWordMatchMode: () =>
|
||||
appState.ankiIntegration?.getKnownWordMatchMode() ??
|
||||
configService.getConfig().ankiConnect.knownWords.matchMode,
|
||||
getKnownWordsEnabled: () =>
|
||||
deps.getRuntimeBooleanOption(
|
||||
'subtitle.annotation.knownWords.highlightEnabled',
|
||||
configService.getConfig().ankiConnect.knownWords.highlightEnabled,
|
||||
),
|
||||
getNPlusOneEnabled: () =>
|
||||
deps.getRuntimeBooleanOption(
|
||||
'subtitle.annotation.nPlusOne',
|
||||
configService.getConfig().ankiConnect.nPlusOne.enabled,
|
||||
),
|
||||
getMinSentenceWordsForNPlusOne: () =>
|
||||
configService.getConfig().ankiConnect.nPlusOne.minSentenceWords,
|
||||
getJlptLevel: (text) => appState.jlptLevelLookup(text),
|
||||
getJlptEnabled: () =>
|
||||
deps.getRuntimeBooleanOption(
|
||||
'subtitle.annotation.jlpt',
|
||||
configService.getConfig().subtitleStyle.enableJlpt,
|
||||
),
|
||||
getCharacterDictionaryEnabled: () =>
|
||||
configService.getConfig().subtitleStyle.nameMatchEnabled &&
|
||||
deps.isCharacterDictionaryEnabled() &&
|
||||
!youtube.isPlaybackActiveNow(),
|
||||
getNameMatchEnabled: () => configService.getConfig().subtitleStyle.nameMatchEnabled,
|
||||
getNameMatchImagesEnabled: () =>
|
||||
configService.getConfig().subtitleStyle.nameMatchImagesEnabled,
|
||||
getCharacterNameImage: (term) => characterDictionary.imageLookup.get(term),
|
||||
getCurrentCharacterDictionaryMediaId: () =>
|
||||
characterDictionary.autoSync.getCurrentMediaId(),
|
||||
getCharacterNameCandidates: () => characterDictionary.nameCandidates.get(),
|
||||
getFrequencyDictionaryEnabled: () =>
|
||||
deps.getRuntimeBooleanOption(
|
||||
'subtitle.annotation.frequency',
|
||||
configService.getConfig().subtitleStyle.frequencyDictionary.enabled,
|
||||
),
|
||||
getFrequencyDictionaryMatchMode: () =>
|
||||
configService.getConfig().subtitleStyle.frequencyDictionary.matchMode,
|
||||
getFrequencyRank: (text) => appState.frequencyRankLookup(text),
|
||||
getYomitanGroupDebugEnabled: () => appState.overlayDebugVisualizationEnabled,
|
||||
getMecabTokenizer: () => appState.mecabTokenizer,
|
||||
onTokenizationReady: () => {
|
||||
currentMediaTokenizationGate.markReady(
|
||||
appState.currentMediaPath?.trim() ||
|
||||
appState.mpvClient?.currentVideoPath?.trim() ||
|
||||
null,
|
||||
);
|
||||
startupOsdSequencer.markTokenizationReady();
|
||||
},
|
||||
},
|
||||
createTokenizerRuntimeDeps: (tokenizerDeps) => createTokenizerDepsRuntime(tokenizerDeps),
|
||||
tokenizeSubtitle: (text, tokenizerDeps) => tokenizeSubtitleCore(text, tokenizerDeps),
|
||||
createMecabTokenizerAndCheckMainDeps: {
|
||||
getMecabTokenizer: () => appState.mecabTokenizer,
|
||||
setMecabTokenizer: (tokenizer) => {
|
||||
appState.mecabTokenizer = tokenizer as MecabTokenizer | null;
|
||||
},
|
||||
createMecabTokenizer: () => new MecabTokenizer(),
|
||||
checkAvailability: async (tokenizer) => (tokenizer as MecabTokenizer).checkAvailability(),
|
||||
},
|
||||
prewarmSubtitleDictionariesMainDeps: {
|
||||
ensureJlptDictionaryLookup: () => dictionaries.jlpt.ensureJlptDictionaryLookup(),
|
||||
ensureFrequencyDictionaryLookup: () =>
|
||||
dictionaries.frequency.ensureFrequencyDictionaryLookup(),
|
||||
showMpvOsd: (message: string) =>
|
||||
overlayNotificationsRuntime.showConfiguredStatusNotification(message),
|
||||
showLoadingOsd: (message: string) => startupOsdSequencer.showAnnotationLoading(message),
|
||||
showLoadedOsd: (message: string) =>
|
||||
startupOsdSequencer.markAnnotationLoadingComplete(message),
|
||||
shouldShowOsdNotification: () => {
|
||||
const type = overlayNotificationsRuntime.getConfiguredStatusNotificationType();
|
||||
return type === 'osd' || type === 'osd-system';
|
||||
},
|
||||
},
|
||||
},
|
||||
warmups: {
|
||||
launchBackgroundWarmupTaskMainDeps: {
|
||||
now: () => Date.now(),
|
||||
logDebug: (message) => logger.debug(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
},
|
||||
startBackgroundWarmupsMainDeps: {
|
||||
getStarted: () => backgroundWarmupsStarted,
|
||||
setStarted: (started) => {
|
||||
backgroundWarmupsStarted = started;
|
||||
},
|
||||
isTexthookerOnlyMode: () => appState.texthookerOnlyMode,
|
||||
ensureYomitanExtensionLoaded: () => deps.ensureYomitanExtensionLoaded().then(() => {}),
|
||||
shouldWarmupMecab: () => {
|
||||
const startupWarmups = configService.getConfig().startupWarmups;
|
||||
if (startupWarmups.lowPowerMode) {
|
||||
return false;
|
||||
}
|
||||
if (!startupWarmups.mecab) {
|
||||
return false;
|
||||
}
|
||||
return deps.shouldInitializeMecabForAnnotations();
|
||||
},
|
||||
shouldWarmupYomitanExtension: () =>
|
||||
configService.getConfig().startupWarmups.yomitanExtension,
|
||||
shouldWarmupSubtitleDictionaries: () => {
|
||||
const startupWarmups = configService.getConfig().startupWarmups;
|
||||
if (startupWarmups.lowPowerMode) {
|
||||
return false;
|
||||
}
|
||||
return startupWarmups.subtitleDictionaries;
|
||||
},
|
||||
shouldWarmupJellyfinRemoteSession: () => {
|
||||
const startupWarmups = configService.getConfig().startupWarmups;
|
||||
if (startupWarmups.lowPowerMode) {
|
||||
return false;
|
||||
}
|
||||
return startupWarmups.jellyfinRemoteSession;
|
||||
},
|
||||
shouldAutoConnectJellyfinRemote: () => {
|
||||
const jellyfin = configService.getConfig().jellyfin;
|
||||
return (
|
||||
jellyfin.enabled && jellyfin.remoteControlEnabled && jellyfin.remoteControlAutoConnect
|
||||
);
|
||||
},
|
||||
startJellyfinRemoteSession: () => jellyfin.startJellyfinRemoteSession(),
|
||||
logDebug: (message) => logger.debug(message),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
async function tokenizeSubtitle(text: string): Promise<SubtitleData> {
|
||||
if (!isTokenizationWarmupReady()) {
|
||||
startupOsdSequencer.showTokenizationLoading('Loading subtitle tokenization...');
|
||||
}
|
||||
return await tokenizeSubtitleRuntime(text);
|
||||
}
|
||||
|
||||
signalAutoplayReadyFromWarmTokenization = createAutoplayTokenizationWarmRelease({
|
||||
isTokenizationWarmupReady: () => isTokenizationWarmupReady(),
|
||||
startTokenizationWarmups: async () => {
|
||||
await startTokenizationWarmups();
|
||||
},
|
||||
getCurrentMediaPath: () =>
|
||||
appState.currentMediaPath?.trim() || appState.mpvClient?.currentVideoPath?.trim() || null,
|
||||
primeCurrentSubtitle: (mediaPath) =>
|
||||
autoplaySubtitlePrimingRuntime.primeCurrentSubtitleForAutoplay(mediaPath),
|
||||
signalAutoplayReady: () => signalCurrentSubtitleAutoplayReady(),
|
||||
warn: (message, error) => logger.warn(message, error),
|
||||
});
|
||||
tokenizeSubtitleDeferred = tokenizeSubtitle;
|
||||
|
||||
return {
|
||||
subtitleProcessingController,
|
||||
autoplaySubtitlePrimingRuntime,
|
||||
secondarySubtitleTrackController,
|
||||
subtitlePrefetchRuntime,
|
||||
cachedInternalSubtitleTrackExtractor,
|
||||
resolveActiveSubtitleSidebarSourceHandler,
|
||||
withCurrentSubtitleTiming,
|
||||
getSubtitleSidebarPlaybackState,
|
||||
sendRendererMpvCommand,
|
||||
refreshCurrentSubtitleAnnotations,
|
||||
tokenizeSubtitle,
|
||||
bindMpvClientEventHandlers,
|
||||
createMpvClientRuntimeServiceHandler,
|
||||
createMecabTokenizerAndCheck,
|
||||
prewarmSubtitleDictionaries,
|
||||
startBackgroundWarmups,
|
||||
startTokenizationWarmups,
|
||||
isTokenizationWarmupReady,
|
||||
getSubtitlePrefetchService: () => subtitlePrefetchService,
|
||||
getLastObservedTimePos: () => lastObservedTimePos,
|
||||
getTokenizeSubtitleDeferred: () => tokenizeSubtitleDeferred,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createSettingsAssembly, type SettingsAssemblyDeps } from './settings';
|
||||
|
||||
// Every callback throws, so a test fails if the assembly calls a dep it should only call later.
|
||||
function makeDeps(): SettingsAssemblyDeps {
|
||||
const lazy = (name: string) => (): never => {
|
||||
throw new Error(`${name} called unexpectedly`);
|
||||
};
|
||||
return {
|
||||
appState: { configSettingsWindow: null },
|
||||
configService: {
|
||||
getConfig: lazy('getConfig'),
|
||||
getConfigPath: lazy('getConfigPath'),
|
||||
getRawConfig: lazy('getRawConfig'),
|
||||
getWarnings: lazy('getWarnings'),
|
||||
reloadConfigStrict: lazy('reloadConfigStrict'),
|
||||
},
|
||||
logger: { error: lazy('error') },
|
||||
getOverlayNotifications: lazy('getOverlayNotifications'),
|
||||
showMpvOsd: lazy('showMpvOsd'),
|
||||
showDesktopNotification: lazy('showDesktopNotification'),
|
||||
hotReloadApplied: {
|
||||
setKeybindings: lazy('setKeybindings'),
|
||||
setSessionBindings: lazy('setSessionBindings'),
|
||||
refreshGlobalAndOverlayShortcuts: lazy('refreshGlobalAndOverlayShortcuts'),
|
||||
setSecondarySubMode: lazy('setSecondarySubMode'),
|
||||
broadcastToOverlayWindows: lazy('broadcastToOverlayWindows'),
|
||||
applyAnkiRuntimeConfigPatch: lazy('applyAnkiRuntimeConfigPatch'),
|
||||
},
|
||||
getYomitanAnkiDeckName: lazy('getYomitanAnkiDeckName'),
|
||||
showErrorBox: lazy('showErrorBox'),
|
||||
createBrowserWindow: lazy('createBrowserWindow'),
|
||||
mainDirname: '/tmp/subminer-main',
|
||||
openPath: lazy('openPath'),
|
||||
ipcMain: { handle: lazy('ipcMain.handle') },
|
||||
};
|
||||
}
|
||||
|
||||
// main.ts builds the assembly before most siblings exist, so construction must stay lazy.
|
||||
test('createSettingsAssembly does not call its deps while constructing', () => {
|
||||
const settings = createSettingsAssembly(makeDeps());
|
||||
assert.equal(typeof settings.hotReload.start, 'function');
|
||||
assert.equal(typeof settings.window.registerHandlers, 'function');
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron';
|
||||
import { AnkiConnectClient } from '../../anki-connect';
|
||||
import { DEFAULT_CONFIG } from '../../config/definitions';
|
||||
import type { ConfigService } from '../../config/service';
|
||||
import { buildConfigSettingsRegistry } from '../../config/settings/registry';
|
||||
import {
|
||||
createConfigHotReloadRuntime,
|
||||
promoteSettingsWindowAboveOverlay,
|
||||
} from '../../core/services';
|
||||
import type { Logger } from '../../logger';
|
||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
||||
import {
|
||||
buildConfigWarningDialogDetails,
|
||||
buildConfigWarningNotificationBody,
|
||||
} from '../config-validation';
|
||||
import {
|
||||
buildRestartRequiredConfigMessage,
|
||||
createConfigHotReloadAppliedHandler,
|
||||
createConfigHotReloadMessageHandler,
|
||||
createWatchConfigPathHandler,
|
||||
} from '../runtime/config-hot-reload-handlers';
|
||||
import {
|
||||
createConfigSettingsRuntime,
|
||||
type ConfigSettingsIpcMainLike,
|
||||
} from '../runtime/config-settings-runtime';
|
||||
import type { createOverlayNotificationsRuntime } from '../runtime/overlay-notifications-runtime';
|
||||
import { createCreateConfigSettingsWindowHandler } from '../runtime/setup-window-factory';
|
||||
import type { AppState } from '../state';
|
||||
|
||||
type ConfigHotReloadMessageDeps = Parameters<typeof createConfigHotReloadMessageHandler>[0];
|
||||
|
||||
/**
|
||||
* What config hot-reload and the settings window need from the rest of the app. Siblings built
|
||||
* after this assembly in `main.ts` are reached through getters or callbacks.
|
||||
*/
|
||||
export interface SettingsAssemblyDeps {
|
||||
appState: Pick<AppState, 'configSettingsWindow'>;
|
||||
configService: Pick<
|
||||
ConfigService,
|
||||
'getConfig' | 'getConfigPath' | 'getRawConfig' | 'getWarnings' | 'reloadConfigStrict'
|
||||
>;
|
||||
logger: Pick<Logger, 'error'>;
|
||||
getOverlayNotifications: () => Pick<
|
||||
ReturnType<typeof createOverlayNotificationsRuntime>,
|
||||
'getConfiguredStatusNotificationType' | 'showOverlayNotification'
|
||||
>;
|
||||
showMpvOsd: (message: string) => void;
|
||||
showDesktopNotification: ConfigHotReloadMessageDeps['showDesktopNotification'];
|
||||
/** Applies a reloaded config to the running app; shared by file hot-reload and the settings window. */
|
||||
hotReloadApplied: Parameters<typeof createConfigHotReloadAppliedHandler>[0];
|
||||
getYomitanAnkiDeckName: () => Promise<string>;
|
||||
showErrorBox: (title: string, content: string) => void;
|
||||
createBrowserWindow: (options: BrowserWindowConstructorOptions) => BrowserWindow;
|
||||
/** Directory of the main bundle; the settings preload and page live next to it. */
|
||||
mainDirname: string;
|
||||
openPath: (targetPath: string) => Promise<string>;
|
||||
ipcMain: ConfigSettingsIpcMainLike;
|
||||
}
|
||||
|
||||
export type SettingsAssembly = ReturnType<typeof createSettingsAssembly>;
|
||||
|
||||
/**
|
||||
* Owns config file hot-reload and the settings window, which both apply reloaded config through
|
||||
* the same handler. `main.ts` starts/stops hot-reload and registers the settings IPC handlers.
|
||||
*/
|
||||
export function createSettingsAssembly(deps: SettingsAssemblyDeps) {
|
||||
const { appState, configService, logger } = deps;
|
||||
const configSettingsFields = buildConfigSettingsRegistry(DEFAULT_CONFIG);
|
||||
|
||||
const notifyConfigHotReloadMessage = createConfigHotReloadMessageHandler({
|
||||
getNotificationType: () => deps.getOverlayNotifications().getConfiguredStatusNotificationType(),
|
||||
showMpvOsd: (message) => deps.showMpvOsd(message),
|
||||
showOverlayNotification: (payload) =>
|
||||
deps.getOverlayNotifications().showOverlayNotification(payload),
|
||||
showDesktopNotification: (title, options) => deps.showDesktopNotification(title, options),
|
||||
});
|
||||
const watchConfigPathHandler = createWatchConfigPathHandler({
|
||||
fileExists: (targetPath) => fs.existsSync(targetPath),
|
||||
dirname: (targetPath) => path.dirname(targetPath),
|
||||
watchPath: (targetPath, listener) => fs.watch(targetPath, listener),
|
||||
});
|
||||
const applyConfigHotReloadDiff = createConfigHotReloadAppliedHandler(deps.hotReloadApplied);
|
||||
const configHotReloadRuntime = createConfigHotReloadRuntime({
|
||||
getCurrentConfig: () => configService.getConfig(),
|
||||
reloadConfigStrict: () => configService.reloadConfigStrict(),
|
||||
watchConfigPath: (configPath, onChange) => watchConfigPathHandler(configPath, onChange),
|
||||
setTimeout: (callback, delayMs) => setTimeout(callback, delayMs),
|
||||
clearTimeout: (timeout) => clearTimeout(timeout),
|
||||
debounceMs: 250,
|
||||
onHotReloadApplied: applyConfigHotReloadDiff,
|
||||
onRestartRequired: (fields) =>
|
||||
notifyConfigHotReloadMessage(buildRestartRequiredConfigMessage(fields)),
|
||||
onInvalidConfig: notifyConfigHotReloadMessage,
|
||||
onValidationWarnings: (configPath, warnings) => {
|
||||
deps.showDesktopNotification('SubMiner', {
|
||||
body: buildConfigWarningNotificationBody(configPath, warnings),
|
||||
});
|
||||
if (process.platform === 'darwin') {
|
||||
deps.showErrorBox(
|
||||
'SubMiner config validation warning',
|
||||
buildConfigWarningDialogDetails(configPath, warnings),
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const configSettingsRuntime = createConfigSettingsRuntime({
|
||||
fields: configSettingsFields,
|
||||
getConfigPath: () => configService.getConfigPath(),
|
||||
getRawConfig: () => configService.getRawConfig(),
|
||||
getConfig: () => configService.getConfig(),
|
||||
getWarnings: () => configService.getWarnings(),
|
||||
reloadConfigStrict: () => configService.reloadConfigStrict(),
|
||||
onHotReloadApplied: applyConfigHotReloadDiff,
|
||||
defaultAnkiConnectUrl: DEFAULT_CONFIG.ankiConnect.url,
|
||||
createAnkiClient: (url) => new AnkiConnectClient(url),
|
||||
getYomitanAnkiDeckName: deps.getYomitanAnkiDeckName,
|
||||
getSettingsWindow: () => appState.configSettingsWindow,
|
||||
setSettingsWindow: (window) => {
|
||||
appState.configSettingsWindow = window as BrowserWindow | null;
|
||||
},
|
||||
createSettingsWindow: createCreateConfigSettingsWindowHandler({
|
||||
createBrowserWindow: (options) => deps.createBrowserWindow(options),
|
||||
preloadPath: path.join(deps.mainDirname, 'preload-settings.js'),
|
||||
}),
|
||||
settingsHtmlPath: path.join(deps.mainDirname, 'settings', 'index.html'),
|
||||
promoteSettingsWindowAboveOverlay: (window) =>
|
||||
promoteSettingsWindowAboveOverlay(window as BrowserWindow),
|
||||
openPath: (targetPath) => deps.openPath(targetPath),
|
||||
ipcMain: deps.ipcMain,
|
||||
ipcChannels: IPC_CHANNELS.request,
|
||||
log: (message) => logger.error(message),
|
||||
});
|
||||
|
||||
return {
|
||||
hotReload: configHotReloadRuntime,
|
||||
window: configSettingsRuntime,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createSyncAssembly, type SyncAssemblyDeps } from './sync';
|
||||
|
||||
// Every callback throws, so a test fails if the assembly calls a dep it should only call later.
|
||||
function makeDeps(): SyncAssemblyDeps {
|
||||
const lazy = (name: string) => (): never => {
|
||||
throw new Error(`${name} called unexpectedly`);
|
||||
};
|
||||
return {
|
||||
appState: { syncUiWindow: null, initialArgs: null },
|
||||
configService: { getConfig: lazy('getConfig') },
|
||||
logger: { info: lazy('info'), error: lazy('error') },
|
||||
userDataPath: '/tmp/subminer-user-data',
|
||||
defaultImmersionDbPath: '/tmp/subminer-user-data/immersion.sqlite',
|
||||
getOverlayNotifications: lazy('getOverlayNotifications'),
|
||||
requestAppQuit: lazy('requestAppQuit'),
|
||||
createBrowserWindow: lazy('createBrowserWindow'),
|
||||
mainDirname: '/tmp/subminer-main',
|
||||
ipcMain: { handle: lazy('ipcMain.handle') },
|
||||
isPackaged: lazy('isPackaged'),
|
||||
getAppPath: lazy('getAppPath'),
|
||||
pickSnapshotFile: lazy('pickSnapshotFile'),
|
||||
revealPath: lazy('revealPath'),
|
||||
};
|
||||
}
|
||||
|
||||
// main.ts builds the assembly before most siblings exist, so construction must stay lazy.
|
||||
test('createSyncAssembly does not call its deps while constructing', () => {
|
||||
const sync = createSyncAssembly(makeDeps());
|
||||
assert.equal(sync.runtime.isRunning(), false);
|
||||
});
|
||||
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user