mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-07-07 13:08:54 -07:00
fFix(youtube): recover source URL for background media cache on direct mpv open (#132)
This commit is contained in:
@@ -128,6 +128,7 @@ export interface AnkiJimakuIpcRuntimeServiceDepsParams {
|
||||
getKnownWordCacheStatePath: AnkiJimakuIpcRuntimeOptions['getKnownWordCacheStatePath'];
|
||||
getCachedMediaPath?: AnkiJimakuIpcRuntimeOptions['getCachedMediaPath'];
|
||||
shouldRequireRemoteMediaCache?: AnkiJimakuIpcRuntimeOptions['shouldRequireRemoteMediaCache'];
|
||||
getYoutubeMediaSourceUrl?: AnkiJimakuIpcRuntimeOptions['getYoutubeMediaSourceUrl'];
|
||||
showDesktopNotification: AnkiJimakuIpcRuntimeOptions['showDesktopNotification'];
|
||||
showOverlayNotification?: (payload: OverlayNotificationPayload) => void;
|
||||
createFieldGroupingCallback: AnkiJimakuIpcRuntimeOptions['createFieldGroupingCallback'];
|
||||
@@ -323,6 +324,9 @@ export function createAnkiJimakuIpcRuntimeServiceDeps(
|
||||
...(params.shouldRequireRemoteMediaCache
|
||||
? { shouldRequireRemoteMediaCache: params.shouldRequireRemoteMediaCache }
|
||||
: {}),
|
||||
...(params.getYoutubeMediaSourceUrl
|
||||
? { getYoutubeMediaSourceUrl: params.getYoutubeMediaSourceUrl }
|
||||
: {}),
|
||||
showDesktopNotification: params.showDesktopNotification,
|
||||
showOverlayNotification: params.showOverlayNotification,
|
||||
createFieldGroupingCallback: params.createFieldGroupingCallback,
|
||||
|
||||
@@ -50,6 +50,16 @@ test('media path changes clear rendered subtitle state without clearing same-you
|
||||
);
|
||||
});
|
||||
|
||||
test('media path changes start the YouTube media cache coordinator', () => {
|
||||
const source = readMainSource();
|
||||
const actionBlock = source.match(
|
||||
/updateCurrentMediaPath:\s*\(path\)\s*=>\s*\{(?<body>[\s\S]*?)\n restoreMpvSubVisibility:/,
|
||||
)?.groups?.body;
|
||||
|
||||
assert.ok(actionBlock);
|
||||
assert.match(actionBlock, /youtubeMediaCachePlaybackRuntime\.handleMediaPathChange\(path\);/);
|
||||
});
|
||||
|
||||
test('same media path updates do not reset autoplay ready fallback state', () => {
|
||||
const source = readMainSource();
|
||||
const actionBlock = source.match(
|
||||
|
||||
@@ -43,6 +43,7 @@ export function createBuildInitializeOverlayRuntimeMainDepsHandler(deps: {
|
||||
getKnownWordCacheStatePath: () => string;
|
||||
getCachedMediaPath?: OverlayRuntimeOptionsMainDeps['getCachedMediaPath'];
|
||||
shouldRequireRemoteMediaCache?: OverlayRuntimeOptionsMainDeps['shouldRequireRemoteMediaCache'];
|
||||
getYoutubeMediaSourceUrl?: OverlayRuntimeOptionsMainDeps['getYoutubeMediaSourceUrl'];
|
||||
shouldStartAnkiIntegration: () => boolean;
|
||||
bindOverlayOwner?: () => void;
|
||||
releaseOverlayOwner?: () => void;
|
||||
@@ -83,6 +84,9 @@ export function createBuildInitializeOverlayRuntimeMainDepsHandler(deps: {
|
||||
...(deps.shouldRequireRemoteMediaCache
|
||||
? { shouldRequireRemoteMediaCache: deps.shouldRequireRemoteMediaCache }
|
||||
: {}),
|
||||
...(deps.getYoutubeMediaSourceUrl
|
||||
? { getYoutubeMediaSourceUrl: deps.getYoutubeMediaSourceUrl }
|
||||
: {}),
|
||||
shouldStartAnkiIntegration: () => deps.shouldStartAnkiIntegration(),
|
||||
bindOverlayOwner: deps.bindOverlayOwner,
|
||||
releaseOverlayOwner: deps.releaseOverlayOwner,
|
||||
|
||||
@@ -42,6 +42,7 @@ type OverlayRuntimeOptions = {
|
||||
kind: 'audio' | 'video',
|
||||
) => Promise<string | null>;
|
||||
shouldRequireRemoteMediaCache?: () => boolean;
|
||||
getYoutubeMediaSourceUrl?: () => Promise<string | null | undefined> | string | null | undefined;
|
||||
shouldStartAnkiIntegration: () => boolean;
|
||||
bindOverlayOwner?: () => void;
|
||||
releaseOverlayOwner?: () => void;
|
||||
@@ -81,6 +82,7 @@ export function createBuildInitializeOverlayRuntimeOptionsHandler(deps: {
|
||||
kind: 'audio' | 'video',
|
||||
) => Promise<string | null>;
|
||||
shouldRequireRemoteMediaCache?: () => boolean;
|
||||
getYoutubeMediaSourceUrl?: () => Promise<string | null | undefined> | string | null | undefined;
|
||||
shouldStartAnkiIntegration: () => boolean;
|
||||
bindOverlayOwner?: () => void;
|
||||
releaseOverlayOwner?: () => void;
|
||||
@@ -111,6 +113,9 @@ export function createBuildInitializeOverlayRuntimeOptionsHandler(deps: {
|
||||
...(deps.shouldRequireRemoteMediaCache
|
||||
? { shouldRequireRemoteMediaCache: deps.shouldRequireRemoteMediaCache }
|
||||
: {}),
|
||||
...(deps.getYoutubeMediaSourceUrl
|
||||
? { getYoutubeMediaSourceUrl: deps.getYoutubeMediaSourceUrl }
|
||||
: {}),
|
||||
shouldStartAnkiIntegration: deps.shouldStartAnkiIntegration,
|
||||
bindOverlayOwner: deps.bindOverlayOwner,
|
||||
releaseOverlayOwner: deps.releaseOverlayOwner,
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { createYoutubeMediaCachePlaybackRuntime } from './youtube-media-cache-playback';
|
||||
|
||||
function createDeferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((innerResolve) => {
|
||||
resolve = innerResolve;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
test('youtube media cache starts when mpv reports a youtube path in background mode', async () => {
|
||||
const starts: Array<{ url: string; maxHeight: number }> = [];
|
||||
const runtime = createYoutubeMediaCachePlaybackRuntime({
|
||||
getMediaCacheConfig: () => ({ mode: 'background', maxHeight: 480 }),
|
||||
startYoutubeMediaCache: (url, options) => {
|
||||
starts.push({ url, maxHeight: options.maxHeight ?? 0 });
|
||||
},
|
||||
logWarn: () => {},
|
||||
});
|
||||
|
||||
await runtime.handleMediaPathChange('https://www.youtube.com/watch?v=abc123');
|
||||
|
||||
assert.deepEqual(starts, [
|
||||
{
|
||||
url: 'https://www.youtube.com/watch?v=abc123',
|
||||
maxHeight: 480,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('youtube media cache starts from original playlist url when mpv path is a resolved stream', async () => {
|
||||
const starts: string[] = [];
|
||||
const propertyRequests: string[] = [];
|
||||
const runtime = createYoutubeMediaCachePlaybackRuntime({
|
||||
getMediaCacheConfig: () => ({ mode: 'background', maxHeight: 720 }),
|
||||
requestMpvProperty: async (name) => {
|
||||
propertyRequests.push(name);
|
||||
if (name === 'playlist-playing-pos') {
|
||||
return 0;
|
||||
}
|
||||
if (name === 'playlist') {
|
||||
return [{ filename: 'https://www.youtube.com/watch?v=abc123' }];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
startYoutubeMediaCache: (url) => {
|
||||
starts.push(url);
|
||||
},
|
||||
logWarn: () => {},
|
||||
});
|
||||
|
||||
await runtime.handleMediaPathChange(
|
||||
'https://rr1---sn.example.googlevideo.com/videoplayback?expire=1777777777',
|
||||
);
|
||||
|
||||
assert.deepEqual(propertyRequests, ['playlist-playing-pos', 'playlist']);
|
||||
assert.deepEqual(starts, ['https://www.youtube.com/watch?v=abc123']);
|
||||
assert.equal(await runtime.getActiveYoutubeSourceUrl(), 'https://www.youtube.com/watch?v=abc123');
|
||||
});
|
||||
|
||||
test('youtube media cache can recover playlist source from current playlist marker', async () => {
|
||||
const starts: string[] = [];
|
||||
const runtime = createYoutubeMediaCachePlaybackRuntime({
|
||||
getMediaCacheConfig: () => ({ mode: 'background', maxHeight: 720 }),
|
||||
requestMpvProperty: async (name) => {
|
||||
if (name === 'playlist-playing-pos') {
|
||||
return -1;
|
||||
}
|
||||
if (name === 'playlist') {
|
||||
return [
|
||||
{
|
||||
filename: 'https://example.com/other.mp4',
|
||||
},
|
||||
{
|
||||
filename: 'https://youtu.be/abc123',
|
||||
current: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
startYoutubeMediaCache: (url) => {
|
||||
starts.push(url);
|
||||
},
|
||||
logWarn: () => {},
|
||||
});
|
||||
|
||||
await runtime.handleMediaPathChange(
|
||||
'https://rr1---sn.example.googlevideo.com/videoplayback?expire=1777777777',
|
||||
);
|
||||
|
||||
assert.deepEqual(starts, ['https://youtu.be/abc123']);
|
||||
assert.equal(await runtime.getActiveYoutubeSourceUrl(), 'https://youtu.be/abc123');
|
||||
});
|
||||
|
||||
test('youtube media source getter awaits in-flight playlist recovery', async () => {
|
||||
const starts: string[] = [];
|
||||
const playlist = createDeferred<unknown>();
|
||||
const runtime = createYoutubeMediaCachePlaybackRuntime({
|
||||
getMediaCacheConfig: () => ({ mode: 'background', maxHeight: 720 }),
|
||||
requestMpvProperty: async (name) => {
|
||||
if (name === 'playlist-playing-pos') {
|
||||
return 0;
|
||||
}
|
||||
if (name === 'playlist') {
|
||||
return await playlist.promise;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
startYoutubeMediaCache: (url) => {
|
||||
starts.push(url);
|
||||
},
|
||||
logWarn: () => {},
|
||||
});
|
||||
|
||||
const pathChange = runtime.handleMediaPathChange(
|
||||
'https://rr1---sn.example.googlevideo.com/videoplayback?expire=1777777777',
|
||||
);
|
||||
const sourceUrl = runtime.getActiveYoutubeSourceUrl();
|
||||
|
||||
playlist.resolve([{ filename: 'https://www.youtube.com/watch?v=abc123' }]);
|
||||
|
||||
assert.equal(await sourceUrl, 'https://www.youtube.com/watch?v=abc123');
|
||||
await pathChange;
|
||||
assert.deepEqual(starts, ['https://www.youtube.com/watch?v=abc123']);
|
||||
});
|
||||
|
||||
test('youtube media cache ignores non-youtube paths and direct mode', async () => {
|
||||
const starts: string[] = [];
|
||||
const propertyRequests: string[] = [];
|
||||
let mode: 'direct' | 'background' = 'background';
|
||||
const runtime = createYoutubeMediaCachePlaybackRuntime({
|
||||
getMediaCacheConfig: () => ({ mode, maxHeight: 720 }),
|
||||
requestMpvProperty: async (name) => {
|
||||
propertyRequests.push(name);
|
||||
return [
|
||||
{
|
||||
filename: 'https://www.youtube.com/watch?v=abc123',
|
||||
current: true,
|
||||
},
|
||||
];
|
||||
},
|
||||
startYoutubeMediaCache: (url) => {
|
||||
starts.push(url);
|
||||
},
|
||||
logWarn: () => {},
|
||||
});
|
||||
|
||||
await runtime.handleMediaPathChange('/tmp/video.mkv');
|
||||
mode = 'direct';
|
||||
await runtime.handleMediaPathChange('https://youtu.be/abc123');
|
||||
|
||||
assert.deepEqual(propertyRequests, []);
|
||||
assert.deepEqual(starts, []);
|
||||
});
|
||||
|
||||
test('youtube media cache logs synchronous start failures from path changes', async () => {
|
||||
const warnings: string[] = [];
|
||||
const runtime = createYoutubeMediaCachePlaybackRuntime({
|
||||
getMediaCacheConfig: () => ({ mode: 'background', maxHeight: 720 }),
|
||||
startYoutubeMediaCache: () => {
|
||||
throw new Error('yt-dlp missing');
|
||||
},
|
||||
logWarn: (message) => {
|
||||
warnings.push(message);
|
||||
},
|
||||
});
|
||||
|
||||
await runtime.handleMediaPathChange('https://youtu.be/abc123');
|
||||
|
||||
assert.deepEqual(warnings, ['Failed to start YouTube media cache: yt-dlp missing']);
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { YoutubeMediaCacheMode } from '../../types/integrations';
|
||||
import { isYoutubeMediaPath } from './youtube-playback';
|
||||
|
||||
type PlaylistEntry = {
|
||||
filename: string;
|
||||
current: boolean;
|
||||
playing: boolean;
|
||||
};
|
||||
|
||||
export interface YoutubeMediaCachePlaybackRuntimeDeps {
|
||||
getMediaCacheConfig: () => {
|
||||
mode: YoutubeMediaCacheMode;
|
||||
maxHeight?: number;
|
||||
};
|
||||
requestMpvProperty?: (name: string) => Promise<unknown>;
|
||||
startYoutubeMediaCache: (
|
||||
url: string,
|
||||
options: {
|
||||
mode: YoutubeMediaCacheMode;
|
||||
maxHeight?: number;
|
||||
},
|
||||
) => void;
|
||||
logWarn: (message: string) => void;
|
||||
}
|
||||
|
||||
function trimToNonEmptyString(value: unknown): string | null {
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizePlaylistIndex(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
function isGoogleVideoStreamPath(mediaPath: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(mediaPath);
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
return host === 'googlevideo.com' || host.endsWith('.googlevideo.com');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePlaylistEntries(raw: unknown): PlaylistEntry[] {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [];
|
||||
}
|
||||
return raw.map((entry) => {
|
||||
const item = (entry ?? {}) as {
|
||||
filename?: unknown;
|
||||
current?: unknown;
|
||||
playing?: unknown;
|
||||
};
|
||||
return {
|
||||
filename: trimToNonEmptyString(item.filename) ?? '',
|
||||
current: item.current === true,
|
||||
playing: item.playing === true,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function resolvePlaylistEntry(
|
||||
playlist: PlaylistEntry[],
|
||||
playingPosValue: unknown,
|
||||
): PlaylistEntry | null {
|
||||
if (playlist.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const playingPos = normalizePlaylistIndex(playingPosValue);
|
||||
if (playingPos !== null && playingPos < playlist.length) {
|
||||
return playlist[playingPos] ?? null;
|
||||
}
|
||||
|
||||
return playlist.find((entry) => entry.current || entry.playing) ?? null;
|
||||
}
|
||||
|
||||
async function requestMpvPropertySafely(
|
||||
deps: YoutubeMediaCachePlaybackRuntimeDeps,
|
||||
name: string,
|
||||
): Promise<unknown> {
|
||||
if (!deps.requestMpvProperty) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return await deps.requestMpvProperty(name);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveYoutubeSourceFromPlaylist(
|
||||
deps: YoutubeMediaCachePlaybackRuntimeDeps,
|
||||
): Promise<string | null> {
|
||||
const [playingPosValue, playlistValue] = await Promise.all([
|
||||
requestMpvPropertySafely(deps, 'playlist-playing-pos'),
|
||||
requestMpvPropertySafely(deps, 'playlist'),
|
||||
]);
|
||||
const playlistEntry = resolvePlaylistEntry(
|
||||
normalizePlaylistEntries(playlistValue),
|
||||
playingPosValue,
|
||||
);
|
||||
return playlistEntry?.filename && isYoutubeMediaPath(playlistEntry.filename)
|
||||
? playlistEntry.filename
|
||||
: null;
|
||||
}
|
||||
|
||||
async function resolveYoutubeSourceUrl(
|
||||
deps: YoutubeMediaCachePlaybackRuntimeDeps,
|
||||
mediaPath: string,
|
||||
): Promise<string | null> {
|
||||
const directPath = trimToNonEmptyString(mediaPath);
|
||||
if (directPath && isYoutubeMediaPath(directPath)) {
|
||||
return directPath;
|
||||
}
|
||||
if (!directPath || !isGoogleVideoStreamPath(directPath)) {
|
||||
return null;
|
||||
}
|
||||
return await resolveYoutubeSourceFromPlaylist(deps);
|
||||
}
|
||||
|
||||
export function createYoutubeMediaCachePlaybackRuntime(deps: YoutubeMediaCachePlaybackRuntimeDeps) {
|
||||
let activeYoutubeSourceUrl: string | null = null;
|
||||
let activeYoutubeSourceUrlPromise: Promise<string | null> | null = null;
|
||||
let generation = 0;
|
||||
|
||||
const handleMediaPathChange = async (mediaPath: string): Promise<void> => {
|
||||
const currentGeneration = ++generation;
|
||||
const config = deps.getMediaCacheConfig();
|
||||
if (config.mode !== 'background') {
|
||||
activeYoutubeSourceUrl = null;
|
||||
activeYoutubeSourceUrlPromise = Promise.resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isYoutubeMediaPath(mediaPath)) {
|
||||
activeYoutubeSourceUrl = null;
|
||||
}
|
||||
|
||||
const sourceUrlPromise = resolveYoutubeSourceUrl(deps, mediaPath);
|
||||
activeYoutubeSourceUrlPromise = sourceUrlPromise.then((sourceUrl) =>
|
||||
currentGeneration === generation ? sourceUrl : null,
|
||||
);
|
||||
|
||||
const sourceUrl = await sourceUrlPromise;
|
||||
if (currentGeneration !== generation) {
|
||||
return;
|
||||
}
|
||||
|
||||
activeYoutubeSourceUrl = sourceUrl;
|
||||
if (!sourceUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
deps.startYoutubeMediaCache(sourceUrl, {
|
||||
mode: config.mode,
|
||||
maxHeight: config.maxHeight,
|
||||
});
|
||||
} catch (error) {
|
||||
deps.logWarn(
|
||||
`Failed to start YouTube media cache: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getActiveYoutubeSourceUrl: async (): Promise<string | null> =>
|
||||
activeYoutubeSourceUrlPromise ?? activeYoutubeSourceUrl,
|
||||
getActiveYoutubeSourceUrlSnapshot: (): string | null => activeYoutubeSourceUrl,
|
||||
handleMediaPathChange,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user