Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion projects/client/i18n/meta/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -6067,7 +6067,7 @@
"description": "Import guidelines: note before the list of id prefix values (trakt_id, imdb_id, …). Shared by the JSON and CSV guides."
},
"import_guide_field_type_description": {
"default": "Specifies what the ID refers to. Optional but recommended.",
"default": "Specifies what the ID refers to. Optional, but rows without a type are imported as movies, so shows, seasons and episodes need it.",
"description": "Import guidelines: description of the type field. Shared by the JSON and CSV guides."
},
"import_guide_field_type_note": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export interface UniversalImportItem {
// parsers/utils/toEpisodeIds.ts.
showTvdb?: number;
showImdb?: string;
showTmdb?: number;
// For action 'list': the source list this item belongs to. Items are grouped
// by listName at sync time; listIsPublic maps to the created list's privacy.
listName?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,63 @@ describe('buildHistoryPayload', () => {
expect(result.episodes).toHaveLength(0);
});

it('should resolve positionally via show tmdb when the show has no tvdb or imdb', () => {
const items: UniversalImportItem[] = [
{
action: 'history',
type: 'episode',
ids: {},
showTmdb: 5000,
season: 1,
episode: 1,
watched_at,
},
{
action: 'history',
type: 'episode',
ids: {},
showTmdb: 5000,
season: 1,
episode: 2,
watched_at,
},
];

const result = buildHistoryPayload(items);

expect(result.shows).toEqual([
{
ids: { tmdb: 5000 },
seasons: [
{
number: 1,
episodes: [
{ number: 1, watched_at },
{ number: 2, watched_at },
],
},
],
},
]);
expect(result.episodes).toHaveLength(0);
});

it('should keep shows with different tmdb ids apart', () => {
const items: UniversalImportItem[] = [5000, 5001].map((showTmdb) => ({
action: 'history',
type: 'episode',
ids: {},
showTmdb,
season: 1,
episode: 1,
watched_at,
}));

expect(buildHistoryPayload(items).shows?.map((show) => show.ids)).toEqual(
[{ tmdb: 5000 }, { tmdb: 5001 }],
);
});

it('should merge one show when items carry differing show ids', () => {
const items: UniversalImportItem[] = [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function hasEpisodeId(item: UniversalImportItem): boolean {
}

type PositionalEpisode = { number: number; watched_at?: string };
type ShowIds = { tvdb?: number; imdb?: string };
type ShowIds = { tvdb?: number; imdb?: string; tmdb?: number };
type ShowGroup = { ids: ShowIds; seasons: Map<number, PositionalEpisode[]> };
type PositionalShow = {
ids: ShowIds;
Expand All @@ -61,22 +61,29 @@ function toShowIds(item: UniversalImportItem): ShowIds {
return {
...(item.showTvdb != null ? { tvdb: item.showTvdb } : {}),
...(item.showImdb != null ? { imdb: item.showImdb } : {}),
...(item.showTmdb != null ? { tmdb: item.showTmdb } : {}),
};
}

function toShowKey(item: UniversalImportItem): string {
if (item.showTvdb != null) return `tvdb:${item.showTvdb}`;
if (item.showImdb != null) return `imdb:${item.showImdb}`;
return `tmdb:${item.showTmdb}`;
}

// Fold positional episodes into `shows`: one entry per show carrying its
// watched seasons -> episodes-by-number, each keeping its own watched_at. The
// show id block merges tvdb and/or imdb across items so shows missing a TVDB id
// still resolve. Keyed on tvdb (else imdb) so the same show grouped from two
// serializations - one carrying imdb, one not - collapses into one entry.
// show id block merges tvdb, imdb and/or tmdb across items so shows missing a
// TVDB id still resolve. Keyed on tvdb (else imdb, else tmdb) so the same show
// grouped from two serializations - one carrying imdb, one not - collapses into
// one entry.
function toPositionalShows(
items: ReadonlyArray<
UniversalImportItem & { season: number; episode: number }
>,
): PositionalShow[] {
const byShow = items.reduce((shows, item) => {
const key =
item.showTvdb != null ? `tvdb:${item.showTvdb}` : `imdb:${item.showImdb}`;
const key = toShowKey(item);
const group = shows.get(key) ?? {
ids: {} as ShowIds,
seasons: new Map<number, PositionalEpisode[]>(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import type { UniversalImportItem } from '../ImportTypes.ts';
import { findNotFoundItems } from './findNotFoundItems.ts';

function episode(
overrides: Partial<UniversalImportItem> = {},
): UniversalImportItem {
return {
action: 'history',
type: 'episode',
ids: {},
season: 1,
episode: 2,
...overrides,
};
}

function notFoundShow(ids: Record<string, unknown>, season = 1, number = 2) {
return {
not_found: {
shows: [{ ids, seasons: [{ number: season, episodes: [{ number }] }] }],
},
};
}

describe('engine: findNotFoundItems', () => {
it('should match a positional episode by its show tmdb id', () => {
const item = episode({ showTmdb: 5000 });

expect(
findNotFoundItems({ items: [item], body: notFoundShow({ tmdb: 5000 }) }),
).toEqual([item]);
});

it('should not match a positional episode of another show', () => {
const item = episode({ showTmdb: 5000 });

expect(
findNotFoundItems({ items: [item], body: notFoundShow({ tmdb: 5001 }) }),
).toEqual([]);
});

it('should not match a positional episode on another season or number', () => {
const item = episode({ showTmdb: 5000 });

expect(
findNotFoundItems({
items: [item],
body: notFoundShow({ tmdb: 5000 }, 1, 3),
}),
).toEqual([]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ function isPositionalEntryFor(
item: UniversalImportItem,
entry: NotFoundEntry,
): boolean {
const showIds: ImportIds = { tvdb: item.showTvdb, imdb: item.showImdb };
const showIds: ImportIds = {
tvdb: item.showTvdb,
imdb: item.showImdb,
tmdb: item.showTmdb,
};
if (!hasSharedId(showIds, entry.ids)) return false;

return (entry.seasons ?? []).some(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ describe('engine: resolveShowIds', () => {
items: [
episode({ showTvdb: 5 }),
episode({ showImdb: 'tt0000002' }),
episode({ showTmdb: 6 }),
episode({ ids: { tvdb: 9 } }),
],
match,
Expand All @@ -193,6 +194,99 @@ describe('engine: resolveShowIds', () => {
expect(match).not.toHaveBeenCalled();
});

describe('rated shows', () => {
function ratedShow(
overrides: Partial<UniversalImportItem> = {},
): UniversalImportItem {
return {
action: 'ratings',
type: 'show',
ids: {},
title: 'Made Up Show',
year: 2010,
rating: 8,
...overrides,
};
}

it('should set the show ids on a rated show with only title and year', async () => {
const match = matcher({
'Made Up Show': [candidate({ imdb: 'tt0000001' })],
});

const { items, unresolved } = await resolveShowIds({
items: [ratedShow()],
match,
});

expect(items[0]).toMatchObject({
ids: { tvdb: 111, imdb: 'tt0000001' },
rating: 8,
});
expect(items[0]?.showTvdb).toBeUndefined();
expect(unresolved).toHaveLength(0);
});

it('should report a rated show it cannot match as unresolved', async () => {
const { items, unresolved } = await resolveShowIds({
items: [ratedShow()],
match: matcher({}),
});

expect(items[0]?.ids).toEqual({});
expect(unresolved).toEqual([ratedShow()]);
});

it('should not match a rated show on a different year', async () => {
const match = matcher({ 'Made Up Show': [candidate({ year: 1990 })] });

const { unresolved } = await resolveShowIds({
items: [ratedShow()],
match,
});

expect(unresolved).toHaveLength(1);
});

it('should not look up a rated show that already carries an id', async () => {
const match = matcher({});

await resolveShowIds({
items: [ratedShow({ ids: { tmdb: 5 } })],
match,
});

expect(match).not.toHaveBeenCalled();
});

it('should not look up shows that are not ratings', async () => {
const match = matcher({});

await resolveShowIds({
items: [
ratedShow({ action: 'history' }),
ratedShow({ action: 'watchlist' }),
],
match,
});

expect(match).not.toHaveBeenCalled();
});

it('should share one lookup between a rated show and its episodes', async () => {
const match = matcher({ 'Made Up Show': [candidate()] });

const { items } = await resolveShowIds({
items: [ratedShow({ year: undefined }), episode()],
match,
});

expect(match).toHaveBeenCalledTimes(1);
expect(items[0]?.ids).toEqual({ tvdb: 111 });
expect(items[1]?.showTvdb).toBe(111);
});
});

it('should not look up movies or shows', async () => {
const match = matcher({});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type {
ShowMatchQuery,
ShowMatchResult,
} from './matchShows.ts';
import { pickIds, toEpisodeIdPriority } from './pickIds.ts';
import { pickIds, SHOW_IDS, toEpisodeIdPriority } from './pickIds.ts';

const SHOW_LOOKUP_CONCURRENCY = 5;

Expand All @@ -25,18 +25,32 @@ export type ResolvedShows = {
unresolved: UniversalImportItem[];
};

function needsResolution(item: UniversalImportItem): boolean {
function needsEpisodeShow(item: UniversalImportItem): boolean {
return (
item.type === 'episode' &&
Boolean(item.title) &&
item.season != null &&
item.episode != null &&
item.showTvdb == null &&
item.showImdb == null &&
item.showTmdb == null &&
pickIds(item.ids, toEpisodeIdPriority(item)) == null
);
}

function needsRatedShowIds(item: UniversalImportItem): boolean {
return (
item.type === 'show' &&
item.action === 'ratings' &&
Boolean(item.title) &&
pickIds(item.ids, SHOW_IDS) == null
);
}

function needsResolution(item: UniversalImportItem): boolean {
return needsEpisodeShow(item) || needsRatedShowIds(item);
}

function normalizeTitle(title: string): string {
return title
.normalize('NFKD')
Expand Down Expand Up @@ -69,6 +83,25 @@ function pickUnambiguousShow(
return only;
}

function withMatchedShow(
item: UniversalImportItem,
show: ShowMatchCandidate,
): UniversalImportItem {
const showIds = {
...(show.tvdb != null ? { tvdb: show.tvdb } : {}),
...(show.imdb != null ? { imdb: show.imdb } : {}),
};

if (item.type === 'show')
return { ...item, ids: { ...item.ids, ...showIds } };

return {
...item,
...(showIds.tvdb != null ? { showTvdb: showIds.tvdb } : {}),
...(showIds.imdb != null ? { showImdb: showIds.imdb } : {}),
};
}

export async function resolveShowIds({
items,
match,
Expand Down Expand Up @@ -115,11 +148,7 @@ export async function resolveShowIds({
const show = query && showsByIndex.get(query.index);
if (!show) return item;

return {
...item,
...(show.tvdb != null ? { showTvdb: show.tvdb } : {}),
...(show.imdb != null ? { showImdb: show.imdb } : {}),
};
return withMatchedShow(item, show);
});

return { items: resolved, unresolved: resolved.filter(needsResolution) };
Expand Down
Loading
Loading