feat(jellyfin): queue series neighbor episodes in the mpv playlist (#338)

This commit is contained in:
sudacode authored and GitHub committed 2026-11-24 01:45:27 -08:00
1 parent 713cdb3ef8
commit 926e6b047e
45 files changed
+2295 -197

No files matched your search

@@ -2949,6 +2949,68 @@ test('Jellyfin metadata refresh preserves a manual episode assignment', async ()
}
});
test('mpv media-title updates do not overwrite a Jellyfin video title', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath });
const streamUrl = 'http://jellyfin.local/Videos/item-3/stream?static=true&api_key=token';
tracker.recordJellyfinPlaybackMetadata({
mediaPath: streamUrl,
displayTitle: 'Show S01E03 Third',
itemTitle: 'Third',
seriesTitle: 'Show',
seasonNumber: 1,
episodeNumber: 3,
itemId: 'item-3',
});
tracker.handleMediaChange(streamUrl, 'Show S01E03 Third');
// mpv restores the previous episode's title as it leaves this playlist entry.
tracker.handleMediaTitleUpdate('Show S01E02 Second');
tracker.handleMediaChange(streamUrl, 'Show S01E02 Second');
const row = (tracker as unknown as { db: DatabaseSync }).db
.prepare('SELECT canonical_title AS title FROM imm_videos')
.get() as { title: string };
assert.equal(row.title, 'Show S01E03 Third');
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('a stale mpv title on the first media change keeps the Jellyfin video title', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath });
const streamUrl = 'http://jellyfin.local/Videos/item-3/stream?static=true&api_key=token';
tracker.recordJellyfinPlaybackMetadata({
mediaPath: streamUrl,
displayTitle: 'Show S01E03 Third',
itemTitle: 'Third',
seriesTitle: 'Show',
seasonNumber: 1,
episodeNumber: 3,
itemId: 'item-3',
});
// mpv switched to this entry but media-title still names the previous episode.
tracker.handleMediaChange(streamUrl, 'Show S01E02 Second');
const row = (tracker as unknown as { db: DatabaseSync }).db
.prepare('SELECT canonical_title AS title FROM imm_videos')
.get() as { title: string };
assert.equal(row.title, 'Show S01E03 Third');
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('startup repairs existing Jellyfin stream video links to metadata rows', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
+19 -1
View File
@@ -1767,6 +1767,16 @@ export class ImmersionTrackerService {
return row?.parserSource === 'jellyfin';
}
/** The stored title of a Jellyfin-linked video, or null when the key has no Jellyfin row. */
private getJellyfinCanonicalTitle(videoKey: string): string | null {
const row = this.db
.prepare(
"SELECT canonical_title AS title FROM imm_videos WHERE video_key = ? AND parser_source = 'jellyfin'",
)
.get(videoKey) as { title: string | null } | null;
return row?.title || null;
}
handleMediaChange(mediaPath: string | null, mediaTitle: string | null): void {
const rawPath = normalizeMediaPath(mediaPath);
const normalizedPath =
@@ -1797,7 +1807,12 @@ export class ImmersionTrackerService {
const sourceType = isRemoteSource(normalizedPath) ? SOURCE_TYPE_REMOTE : SOURCE_TYPE_LOCAL;
const videoKey = buildVideoKey(normalizedPath, sourceType);
const canonicalTitle = normalizedTitle || deriveCanonicalTitle(normalizedPath);
// Jellyfin's title is authoritative: mpv's media-title can still name the previous playlist
// entry when the path switches, and getOrCreateVideoRecord rewrites an existing row's title.
const canonicalTitle =
this.getJellyfinCanonicalTitle(videoKey) ||
normalizedTitle ||
deriveCanonicalTitle(normalizedPath);
const sourcePath = sourceType === SOURCE_TYPE_LOCAL ? normalizedPath : null;
const sourceUrl = sourceType === SOURCE_TYPE_REMOTE ? normalizedPath : null;
@@ -2464,6 +2479,9 @@ export class ImmersionTrackerService {
private updateVideoTitleForActiveSession(canonicalTitle: string): void {
if (!this.sessionState) return;
// Jellyfin's title is authoritative. mpv's media-title can still name the previous playlist
// entry while it switches files, so it must not overwrite a Jellyfin video's title.
if (this.hasJellyfinMetadata(this.sessionState.videoId)) return;
updateVideoTitleRecord(this.db, this.sessionState.videoId, canonicalTitle);
}
}
+1
View File
@@ -128,6 +128,7 @@ export {
authenticateWithPassword as authenticateWithPasswordRuntime,
listItems as listJellyfinItemsRuntime,
listLibraries as listJellyfinLibrariesRuntime,
listSeriesEpisodeIds as listJellyfinSeriesEpisodeIdsRuntime,
listSubtitleTracks as listJellyfinSubtitleTracksRuntime,
resolvePlaybackPlan as resolveJellyfinPlaybackPlanRuntime,
ticksToSeconds as jellyfinTicksToSecondsRuntime,
+35
View File
@@ -4,6 +4,7 @@ import {
authenticateWithPassword,
listItems,
listLibraries,
listSeriesEpisodeIds,
listSubtitleTracks,
resolvePlaybackPlan,
ticksToSeconds,
@@ -886,3 +887,37 @@ test('toJellyfinOriginalStreamUrl maps direct and transcoded playback to the ori
assert.equal(toJellyfinOriginalStreamUrl('https://jf/Videos/item-1/stream', 'item-1'), null);
assert.equal(toJellyfinOriginalStreamUrl('/media/item-1.mkv', 'item-1'), null);
});
test('listSeriesEpisodeIds returns playable episodes in series order', async () => {
const originalFetch = globalThis.fetch;
let requestedUrl = '';
globalThis.fetch = (async (input) => {
requestedUrl = String(input);
return new Response(
JSON.stringify({
Items: [
{ Id: 'ep-1', LocationType: 'FileSystem' },
{ Id: 'ep-2', LocationType: 'Virtual' },
{ Id: 'ep-3', LocationType: 'FileSystem' },
{ Name: 'no id' },
],
}),
{ status: 200 },
);
}) as typeof fetch;
try {
const ids = await listSeriesEpisodeIds(
{ serverUrl: 'http://jellyfin.local', accessToken: 'token', userId: 'u1', username: 'kyle' },
clientInfo,
'series-1',
);
assert.deepEqual(ids, ['ep-1', 'ep-3']);
const url = new URL(requestedUrl);
assert.equal(url.pathname, '/Shows/series-1/Episodes');
assert.equal(url.searchParams.get('UserId'), 'u1');
assert.equal(url.searchParams.get('IsMissing'), 'false');
} finally {
globalThis.fetch = originalFetch;
}
});
+32
View File
@@ -29,6 +29,8 @@ export interface JellyfinPlaybackPlan {
title: string;
itemTitle: string;
seriesTitle: string | null;
/** Set for episodes; lets playback queue the series' neighboring episodes. */
seriesId: string | null;
seasonNumber: number | null;
episodeNumber: number | null;
startTimeTicks: number;
@@ -89,6 +91,8 @@ interface JellyfinItem {
Name?: string;
Type?: string;
SeriesName?: string;
SeriesId?: string;
LocationType?: string;
ParentIndexNumber?: number;
IndexNumber?: number;
UserData?: JellyfinItemUserData;
@@ -579,6 +583,7 @@ export async function resolvePlaybackPlan(
title: getDisplayTitle(item),
itemTitle,
seriesTitle,
seriesId: item.Type === 'Episode' ? ensureString(item.SeriesId).trim() || null : null,
seasonNumber: item.Type === 'Episode' ? asIntegerOrNull(item.ParentIndexNumber) : null,
episodeNumber: item.Type === 'Episode' ? asIntegerOrNull(item.IndexNumber) : null,
startTimeTicks,
@@ -611,6 +616,33 @@ export async function resolvePlaybackPlan(
};
}
/**
* Lists a series' episode ids in playback order. The order runs across season boundaries and
* skips episodes the server only knows from metadata.
*/
export async function listSeriesEpisodeIds(
session: JellyfinAuthSession,
client: JellyfinClientInfo,
seriesId: string,
): Promise<string[]> {
const query = new URLSearchParams({
UserId: session.userId,
IsMissing: 'false',
EnableImages: 'false',
EnableUserData: 'false',
});
const payload = await jellyfinRequestJson<JellyfinItemsResponse>(
`/Shows/${encodeURIComponent(seriesId)}/Episodes?${query.toString()}`,
{ method: 'GET' },
session,
client,
);
return (Array.isArray(payload.Items) ? payload.Items : [])
.filter((item) => item.LocationType !== 'Virtual')
.map((item) => ensureString(item.Id))
.filter((id) => id.length > 0);
}
export function ticksToSeconds(ticks: number): number {
return Math.max(0, Math.floor(ticks / JELLYFIN_TICKS_PER_SECOND));
}