feat: support categorized archives and selectable quality variants
This commit is contained in:
45 files changed
+932
-92
No files matched your search
@@ -0,0 +1,25 @@
|
||||
CREATE TYPE "release_window" AS ENUM ('SPRING', 'SUMMER', 'FALL', 'WINTER', 'MOVIE');
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "titles" ADD COLUMN "category" varchar(100);
|
||||
ALTER TABLE "titles" ADD COLUMN "category_slug" varchar(100);
|
||||
ALTER TABLE "titles" ADD COLUMN "release_window" "release_window";
|
||||
ALTER TABLE "media_items" ADD COLUMN "logical_key" varchar(80);
|
||||
ALTER TABLE "media_items" ADD COLUMN "variants" jsonb DEFAULT '[]'::jsonb NOT NULL;
|
||||
ALTER TABLE "source_files" ADD COLUMN "quality_label" varchar(64);
|
||||
ALTER TABLE "source_files" ADD COLUMN "width" integer;
|
||||
ALTER TABLE "source_files" ADD COLUMN "height" integer;
|
||||
ALTER TABLE "source_files" ADD COLUMN "video_codec" varchar(64);
|
||||
ALTER TABLE "source_files" ADD COLUMN "duration_seconds" double precision;
|
||||
ALTER TABLE "source_files" ADD COLUMN "compatibility" "compatibility_class" DEFAULT 'INVALID' NOT NULL;
|
||||
ALTER TABLE "source_files" ADD COLUMN "compatibility_reason" text;
|
||||
ALTER TABLE "media_packages" ADD COLUMN "variant_id" uuid;
|
||||
ALTER TABLE "playback_sessions" ADD COLUMN "variant_id" uuid;
|
||||
--> statement-breakpoint
|
||||
UPDATE "media_items"
|
||||
SET "logical_key" = CASE
|
||||
WHEN "kind" = 'MOVIE' THEN 'movie'
|
||||
ELSE 's' || COALESCE("season_number", 1)::text || 'e' || COALESCE("episode_number", 0)::text
|
||||
END;
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "media_items_logical_uidx" ON "media_items" ("title_id", "logical_key");
|
||||
CREATE INDEX "titles_category_idx" ON "titles" ("category_slug", "release_year", "release_window");
|
||||
@@ -15,6 +15,13 @@
|
||||
"when": 1784016000000,
|
||||
"tag": "0001_playback_generation_external",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1784073600000,
|
||||
"tag": "0002_archive_variants",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CatalogSnapshotSchema, type CatalogSnapshot } from '@easy-stream/contracts';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { inArray, notInArray, sql } from 'drizzle-orm';
|
||||
import type { Database } from './client.js';
|
||||
import { mediaItems, titles } from './schema.js';
|
||||
|
||||
@@ -15,6 +15,7 @@ export interface PreparedCatalogSync {
|
||||
export interface CatalogSyncResult {
|
||||
titlesSeen: number;
|
||||
mediaItemsSeen: number;
|
||||
mediaIdMap: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,6 +54,9 @@ export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
|
||||
posterUrl: title.posterUrl ?? null,
|
||||
backdropUrl: title.backdropUrl ?? null,
|
||||
releaseYear: title.year ?? null,
|
||||
category: title.category ?? null,
|
||||
categorySlug: title.categorySlug ?? null,
|
||||
releaseWindow: title.releaseWindow ?? null,
|
||||
published,
|
||||
publishedAt: published ? scannedAt : null,
|
||||
createdAt: scannedAt,
|
||||
@@ -68,12 +72,14 @@ export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
|
||||
id: item.id,
|
||||
titleId: title.id,
|
||||
kind: item.kind,
|
||||
logicalKey: item.kind === 'MOVIE' ? 'movie' : `s${item.seasonNumber ?? 1}e${item.episodeNumber ?? 0}`,
|
||||
seasonNumber: item.seasonNumber ?? null,
|
||||
episodeNumber: item.episodeNumber ?? null,
|
||||
nameFa: item.name?.fa ?? null,
|
||||
nameEn: item.name?.en ?? null,
|
||||
durationSeconds: item.durationSeconds,
|
||||
compatibility: item.compatibility,
|
||||
variants: item.variants ?? [],
|
||||
published: item.published,
|
||||
publishedAt: item.published ? scannedAt : null,
|
||||
createdAt: scannedAt,
|
||||
@@ -93,8 +99,10 @@ export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
|
||||
export async function syncCatalogSnapshot(
|
||||
db: Database,
|
||||
snapshot: unknown,
|
||||
options: { authoritative?: boolean } = {},
|
||||
): Promise<CatalogSyncResult> {
|
||||
const prepared = prepareCatalogSync(snapshot);
|
||||
const mediaIdMap: Record<string, string> = {};
|
||||
await db.transaction(async (transaction) => {
|
||||
// Prevent two worker processes from interleaving catalog snapshots.
|
||||
await transaction.execute(sql`select pg_advisory_xact_lock(hashtext('easy-stream.catalog-sync'))`);
|
||||
@@ -108,12 +116,44 @@ export async function syncCatalogSnapshot(
|
||||
set: {
|
||||
slug: sql`excluded.slug`,
|
||||
kind: sql`excluded.kind`,
|
||||
category: sql`excluded.category`,
|
||||
categorySlug: sql`excluded.category_slug`,
|
||||
releaseWindow: sql`excluded.release_window`,
|
||||
releaseYear: sql`coalesce(${titles.releaseYear}, excluded.release_year)`,
|
||||
posterUrl: sql`case when ${titles.posterUrl} is null or ${titles.posterUrl} like '/images/archive/%' then excluded.poster_url else ${titles.posterUrl} end`,
|
||||
updatedAt: prepared.scannedAt,
|
||||
},
|
||||
setWhere: sql`${titles.slug} is distinct from excluded.slug or ${titles.kind} is distinct from excluded.kind`,
|
||||
setWhere: sql`${titles.slug} is distinct from excluded.slug
|
||||
or ${titles.kind} is distinct from excluded.kind
|
||||
or ${titles.category} is distinct from excluded.category
|
||||
or ${titles.categorySlug} is distinct from excluded.category_slug
|
||||
or ${titles.releaseWindow} is distinct from excluded.release_window
|
||||
or (${titles.releaseYear} is null and excluded.release_year is not null)
|
||||
or ((${titles.posterUrl} is null or ${titles.posterUrl} like '/images/archive/%') and ${titles.posterUrl} is distinct from excluded.poster_url)`,
|
||||
});
|
||||
}
|
||||
|
||||
if (prepared.titleRows.length > 0) {
|
||||
const existing = await transaction.select({
|
||||
id: mediaItems.id,
|
||||
titleId: mediaItems.titleId,
|
||||
logicalKey: mediaItems.logicalKey,
|
||||
seasonNumber: mediaItems.seasonNumber,
|
||||
episodeNumber: mediaItems.episodeNumber,
|
||||
kind: mediaItems.kind,
|
||||
}).from(mediaItems).where(inArray(mediaItems.titleId, prepared.titleRows.map((row) => row.id as string)));
|
||||
const byLogicalKey = new Map(existing.map((row) => [
|
||||
`${row.titleId}:${row.logicalKey ?? (row.kind === 'MOVIE' ? 'movie' : `s${row.seasonNumber ?? 1}e${row.episodeNumber ?? 0}`)}`,
|
||||
row.id,
|
||||
]));
|
||||
for (const row of prepared.mediaItemRows) {
|
||||
const current = byLogicalKey.get(`${row.titleId}:${row.logicalKey}`);
|
||||
if (!current || current === row.id) continue;
|
||||
mediaIdMap[String(row.id)] = current;
|
||||
row.id = current;
|
||||
}
|
||||
}
|
||||
|
||||
for (const batch of batches(prepared.mediaItemRows, UPSERT_BATCH_SIZE)) {
|
||||
await transaction
|
||||
.insert(mediaItems)
|
||||
@@ -123,26 +163,40 @@ export async function syncCatalogSnapshot(
|
||||
set: {
|
||||
titleId: sql`excluded.title_id`,
|
||||
kind: sql`excluded.kind`,
|
||||
logicalKey: sql`excluded.logical_key`,
|
||||
seasonNumber: sql`excluded.season_number`,
|
||||
episodeNumber: sql`excluded.episode_number`,
|
||||
durationSeconds: sql`excluded.duration_seconds`,
|
||||
compatibility: sql`excluded.compatibility`,
|
||||
variants: sql`excluded.variants`,
|
||||
updatedAt: prepared.scannedAt,
|
||||
},
|
||||
setWhere: sql`
|
||||
${mediaItems.titleId} is distinct from excluded.title_id
|
||||
or ${mediaItems.kind} is distinct from excluded.kind
|
||||
or ${mediaItems.logicalKey} is distinct from excluded.logical_key
|
||||
or ${mediaItems.seasonNumber} is distinct from excluded.season_number
|
||||
or ${mediaItems.episodeNumber} is distinct from excluded.episode_number
|
||||
or ${mediaItems.durationSeconds} is distinct from excluded.duration_seconds
|
||||
or ${mediaItems.compatibility} is distinct from excluded.compatibility
|
||||
or ${mediaItems.variants} is distinct from excluded.variants
|
||||
`,
|
||||
});
|
||||
}
|
||||
|
||||
if (options.authoritative) {
|
||||
const seenMediaIds = prepared.mediaItemRows.map((row) => row.id as string);
|
||||
const seenTitleIds = prepared.titleRows.map((row) => row.id as string);
|
||||
await transaction.update(mediaItems).set({ published: false, publishedAt: null, updatedAt: prepared.scannedAt })
|
||||
.where(seenMediaIds.length ? notInArray(mediaItems.id, seenMediaIds) : sql`true`);
|
||||
await transaction.update(titles).set({ published: false, publishedAt: null, updatedAt: prepared.scannedAt })
|
||||
.where(seenTitleIds.length ? notInArray(titles.id, seenTitleIds) : sql`true`);
|
||||
}
|
||||
});
|
||||
return {
|
||||
titlesSeen: prepared.titleRows.length,
|
||||
mediaItemsSeen: prepared.mediaItemRows.length,
|
||||
mediaIdMap,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from 'drizzle-orm/pg-core';
|
||||
|
||||
export const titleKind = pgEnum('title_kind', ['MOVIE', 'SERIES']);
|
||||
export const releaseWindow = pgEnum('release_window', ['SPRING', 'SUMMER', 'FALL', 'WINTER', 'MOVIE']);
|
||||
export const mediaKind = pgEnum('media_kind', ['MOVIE', 'EPISODE']);
|
||||
export const streamKind = pgEnum('stream_kind', ['VIDEO', 'AUDIO']);
|
||||
export const compatibilityClass = pgEnum('compatibility_class', [
|
||||
@@ -64,6 +65,9 @@ export const titles = pgTable(
|
||||
posterUrl: text('poster_url'),
|
||||
backdropUrl: text('backdrop_url'),
|
||||
releaseYear: integer('release_year'),
|
||||
category: varchar('category', { length: 100 }),
|
||||
categorySlug: varchar('category_slug', { length: 100 }),
|
||||
releaseWindow: releaseWindow('release_window'),
|
||||
tmdbId: integer('tmdb_id'),
|
||||
published: boolean('published').notNull().default(false),
|
||||
publishedAt: timestamp('published_at', { withTimezone: true }),
|
||||
@@ -84,6 +88,7 @@ export const mediaItems = pgTable(
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: 'cascade' }),
|
||||
kind: mediaKind('kind').notNull(),
|
||||
logicalKey: varchar('logical_key', { length: 80 }),
|
||||
seasonNumber: integer('season_number'),
|
||||
episodeNumber: integer('episode_number'),
|
||||
nameFa: text('name_fa'),
|
||||
@@ -91,12 +96,23 @@ export const mediaItems = pgTable(
|
||||
durationSeconds: doublePrecision('duration_seconds'),
|
||||
compatibility: compatibilityClass('compatibility').notNull().default('INVALID'),
|
||||
compatibilityReason: text('compatibility_reason'),
|
||||
variants: jsonb('variants').$type<Array<{
|
||||
id: string;
|
||||
label: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
videoCodec?: string;
|
||||
compatibility: string;
|
||||
available: boolean;
|
||||
isDefault: boolean;
|
||||
}>>().notNull().default([]),
|
||||
published: boolean('published').notNull().default(false),
|
||||
publishedAt: timestamp('published_at', { withTimezone: true }),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [
|
||||
index('media_items_title_idx').on(table.titleId),
|
||||
uniqueIndex('media_items_logical_uidx').on(table.titleId, table.logicalKey),
|
||||
uniqueIndex('media_items_episode_uidx').on(
|
||||
table.titleId,
|
||||
table.seasonNumber,
|
||||
@@ -120,6 +136,13 @@ export const sourceFiles = pgTable(
|
||||
headHash: varchar('head_hash', { length: 128 }).notNull(),
|
||||
tailHash: varchar('tail_hash', { length: 128 }).notNull(),
|
||||
fingerprint: varchar('fingerprint', { length: 128 }).notNull(),
|
||||
qualityLabel: varchar('quality_label', { length: 64 }),
|
||||
width: integer('width'),
|
||||
height: integer('height'),
|
||||
videoCodec: varchar('video_codec', { length: 64 }),
|
||||
durationSeconds: doublePrecision('duration_seconds'),
|
||||
compatibility: compatibilityClass('compatibility').notNull().default('INVALID'),
|
||||
compatibilityReason: text('compatibility_reason'),
|
||||
probeJson: jsonb('probe_json').$type<Record<string, unknown>>(),
|
||||
present: boolean('present').notNull().default(true),
|
||||
lastSeenAt: timestamp('last_seen_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
@@ -217,6 +240,8 @@ export const mediaPackages = pgTable(
|
||||
mediaItemId: uuid('media_item_id')
|
||||
.notNull()
|
||||
.references(() => mediaItems.id, { onDelete: 'cascade' }),
|
||||
// Scanner variant IDs are deterministic external identifiers, like generation IDs.
|
||||
variantId: uuid('variant_id'),
|
||||
sourceFingerprint: varchar('source_fingerprint', { length: 128 }).notNull(),
|
||||
profileVersion: varchar('profile_version', { length: 64 }).notNull(),
|
||||
state: packageState('state').notNull().default('QUEUED'),
|
||||
@@ -296,6 +321,7 @@ export const playbackSessions = pgTable(
|
||||
mediaItemId: uuid('media_item_id')
|
||||
.notNull()
|
||||
.references(() => mediaItems.id, { onDelete: 'cascade' }),
|
||||
variantId: uuid('variant_id'),
|
||||
// Packaging generation IDs are deterministic UUIDs owned by the media worker. They are
|
||||
// deliberately not media_packages.id, so this column must not reference that primary key.
|
||||
generationId: uuid('generation_id'),
|
||||
|
||||
@@ -57,6 +57,9 @@ describe('catalog snapshot synchronization', () => {
|
||||
const conflicts: Array<{ table: unknown; set: Record<string, unknown> }> = [];
|
||||
const transaction = {
|
||||
async execute() {},
|
||||
select() {
|
||||
return { from() { return { async where() { return []; } }; } };
|
||||
},
|
||||
insert(table: unknown) {
|
||||
return {
|
||||
values() {
|
||||
@@ -78,16 +81,18 @@ describe('catalog snapshot synchronization', () => {
|
||||
await syncCatalogSnapshot(database, snapshot);
|
||||
|
||||
expect(Object.keys(conflicts.find((entry) => entry.table === titles)!.set).sort())
|
||||
.toEqual(['kind', 'slug', 'updatedAt']);
|
||||
.toEqual(['category', 'categorySlug', 'kind', 'posterUrl', 'releaseWindow', 'releaseYear', 'slug', 'updatedAt']);
|
||||
expect(Object.keys(conflicts.find((entry) => entry.table === mediaItems)!.set).sort())
|
||||
.toEqual([
|
||||
'compatibility',
|
||||
'durationSeconds',
|
||||
'episodeNumber',
|
||||
'kind',
|
||||
'logicalKey',
|
||||
'seasonNumber',
|
||||
'titleId',
|
||||
'updatedAt',
|
||||
'variants',
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user