This commit is contained in:
Meghdad committed 2026-07-14 12:51:36 +03:30
commit f035fcef4f
134 files changed
+18678

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'drizzle-kit';
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is required to run Drizzle commands');
}
export default defineConfig({
dialect: 'postgresql',
schema: './src/schema.ts',
out: './migrations',
dbCredentials: { url: process.env.DATABASE_URL },
strict: true,
});
@@ -0,0 +1,213 @@
CREATE TYPE "title_kind" AS ENUM ('MOVIE', 'SERIES');
CREATE TYPE "media_kind" AS ENUM ('MOVIE', 'EPISODE');
CREATE TYPE "stream_kind" AS ENUM ('VIDEO', 'AUDIO');
CREATE TYPE "compatibility_class" AS ENUM ('COPY', 'AUDIO_TRANSCODE', 'VIDEO_TRANSCODE', 'HOLD_HDR', 'INVALID');
CREATE TYPE "package_state" AS ENUM ('QUEUED', 'BUILDING', 'READY', 'FAILED', 'EVICTED');
CREATE TYPE "job_state" AS ENUM ('QUEUED', 'RUNNING', 'SUCCEEDED', 'FAILED', 'CANCELLED');
CREATE TYPE "playback_state" AS ENUM ('PREPARING', 'READY', 'UNSUPPORTED_CLIENT', 'FAILED');
--> statement-breakpoint
CREATE TABLE "titles" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"slug" varchar(240) NOT NULL,
"kind" "title_kind" NOT NULL,
"name_fa" text,
"name_en" text,
"synopsis_fa" text,
"synopsis_en" text,
"poster_url" text,
"backdrop_url" text,
"release_year" integer,
"tmdb_id" integer,
"published" boolean DEFAULT false NOT NULL,
"published_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "media_items" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"title_id" uuid NOT NULL,
"kind" "media_kind" NOT NULL,
"season_number" integer,
"episode_number" integer,
"name_fa" text,
"name_en" text,
"duration_seconds" double precision,
"compatibility" "compatibility_class" DEFAULT 'INVALID' NOT NULL,
"compatibility_reason" text,
"published" boolean DEFAULT false NOT NULL,
"published_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "source_files" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"media_item_id" uuid NOT NULL,
"relative_path" text NOT NULL,
"size_bytes" bigint NOT NULL,
"modified_at_ns" bigint NOT NULL,
"matroska_uid" varchar(128),
"head_hash" varchar(128) NOT NULL,
"tail_hash" varchar(128) NOT NULL,
"fingerprint" varchar(128) NOT NULL,
"probe_json" jsonb,
"present" boolean DEFAULT true NOT NULL,
"last_seen_at" timestamp with time zone DEFAULT now() NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "media_streams" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"source_file_id" uuid NOT NULL,
"stream_index" integer NOT NULL,
"kind" "stream_kind" NOT NULL,
"codec" varchar(64) NOT NULL,
"codec_string" varchar(128),
"language" varchar(35),
"label" varchar(200),
"is_default" boolean DEFAULT false NOT NULL,
"channels" integer,
"sample_rate" integer,
"width" integer,
"height" integer,
"frame_rate" varchar(32),
"bit_depth" integer,
"pixel_format" varchar(64),
"color_transfer" varchar(64),
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "subtitle_tracks" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"source_file_id" uuid NOT NULL,
"stream_index" integer NOT NULL,
"codec" varchar(64) NOT NULL,
"source_language" varchar(35),
"normalized_language" varchar(35) NOT NULL,
"label" varchar(200) NOT NULL,
"source_default" boolean DEFAULT false NOT NULL,
"source_forced" boolean DEFAULT false NOT NULL,
"is_default" boolean DEFAULT false NOT NULL,
"is_forced" boolean DEFAULT false NOT NULL,
"ass_path" text,
"webvtt_path" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "font_attachments" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"source_file_id" uuid NOT NULL,
"stream_index" integer NOT NULL,
"sha256" varchar(64) NOT NULL,
"mime_type" varchar(100) NOT NULL,
"original_name" text NOT NULL,
"storage_path" text,
"approved" boolean DEFAULT false NOT NULL,
"size_bytes" bigint NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "media_packages" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"media_item_id" uuid NOT NULL,
"source_fingerprint" varchar(128) NOT NULL,
"profile_version" varchar(64) NOT NULL,
"state" "package_state" DEFAULT 'QUEUED' NOT NULL,
"manifest_path" text,
"size_bytes" bigint DEFAULT 0 NOT NULL,
"cache_resident" boolean DEFAULT false NOT NULL,
"pinned" boolean DEFAULT false NOT NULL,
"last_accessed_at" timestamp with time zone,
"error_code" varchar(100),
"error_detail" text,
"ready_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "jobs" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"type" varchar(100) NOT NULL,
"state" "job_state" DEFAULT 'QUEUED' NOT NULL,
"progress" real DEFAULT 0 NOT NULL,
"payload" jsonb DEFAULT '{}'::jsonb NOT NULL,
"result" jsonb,
"error" text,
"attempts" integer DEFAULT 0 NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "admins" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"email" varchar(320) NOT NULL,
"password_hash" text NOT NULL,
"totp_secret_encrypted" text,
"disabled" boolean DEFAULT false NOT NULL,
"last_login_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "admin_sessions" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"admin_id" uuid NOT NULL,
"token_hash" varchar(64) NOT NULL,
"csrf_token_hash" varchar(64) NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"revoked_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "playback_sessions" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"media_item_id" uuid NOT NULL,
"generation_id" uuid,
"state" "playback_state" DEFAULT 'PREPARING' NOT NULL,
"capabilities" jsonb NOT NULL,
"reason_code" varchar(100),
"poll_after_ms" integer,
"response_json" jsonb DEFAULT '{}'::jsonb NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "media_items" ADD CONSTRAINT "media_items_title_id_titles_id_fk" FOREIGN KEY ("title_id") REFERENCES "titles"("id") ON DELETE cascade;
ALTER TABLE "source_files" ADD CONSTRAINT "source_files_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
ALTER TABLE "media_streams" ADD CONSTRAINT "media_streams_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
ALTER TABLE "subtitle_tracks" ADD CONSTRAINT "subtitle_tracks_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
ALTER TABLE "font_attachments" ADD CONSTRAINT "font_attachments_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
ALTER TABLE "media_packages" ADD CONSTRAINT "media_packages_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
ALTER TABLE "admin_sessions" ADD CONSTRAINT "admin_sessions_admin_id_admins_id_fk" FOREIGN KEY ("admin_id") REFERENCES "admins"("id") ON DELETE cascade;
ALTER TABLE "playback_sessions" ADD CONSTRAINT "playback_sessions_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
--> statement-breakpoint
CREATE UNIQUE INDEX "titles_slug_uidx" ON "titles" ("slug");
CREATE INDEX "titles_published_idx" ON "titles" ("published", "published_at");
CREATE INDEX "titles_tmdb_idx" ON "titles" ("tmdb_id");
CREATE INDEX "media_items_title_idx" ON "media_items" ("title_id");
CREATE UNIQUE INDEX "media_items_episode_uidx" ON "media_items" ("title_id", "season_number", "episode_number");
CREATE INDEX "media_items_published_idx" ON "media_items" ("published");
CREATE UNIQUE INDEX "source_files_path_uidx" ON "source_files" ("relative_path");
CREATE UNIQUE INDEX "source_files_fingerprint_uidx" ON "source_files" ("fingerprint");
CREATE INDEX "source_files_media_item_idx" ON "source_files" ("media_item_id");
CREATE UNIQUE INDEX "media_streams_source_index_uidx" ON "media_streams" ("source_file_id", "stream_index");
CREATE INDEX "media_streams_source_idx" ON "media_streams" ("source_file_id");
CREATE UNIQUE INDEX "subtitle_tracks_source_index_uidx" ON "subtitle_tracks" ("source_file_id", "stream_index");
CREATE INDEX "subtitle_tracks_source_idx" ON "subtitle_tracks" ("source_file_id");
CREATE UNIQUE INDEX "font_attachments_source_index_uidx" ON "font_attachments" ("source_file_id", "stream_index");
CREATE INDEX "font_attachments_hash_idx" ON "font_attachments" ("sha256");
CREATE UNIQUE INDEX "media_packages_generation_uidx" ON "media_packages" ("media_item_id", "source_fingerprint", "profile_version");
CREATE INDEX "media_packages_lru_idx" ON "media_packages" ("cache_resident", "pinned", "last_accessed_at");
CREATE INDEX "jobs_state_created_idx" ON "jobs" ("state", "created_at");
CREATE UNIQUE INDEX "admins_email_uidx" ON "admins" ("email");
CREATE UNIQUE INDEX "admin_sessions_token_uidx" ON "admin_sessions" ("token_hash");
CREATE INDEX "admin_sessions_admin_idx" ON "admin_sessions" ("admin_id");
CREATE INDEX "playback_sessions_media_idx" ON "playback_sessions" ("media_item_id");
CREATE INDEX "playback_sessions_generation_idx" ON "playback_sessions" ("generation_id");
CREATE INDEX "playback_sessions_expires_idx" ON "playback_sessions" ("expires_at");
@@ -0,0 +1,3 @@
ALTER TABLE "playback_sessions" DROP CONSTRAINT IF EXISTS "playback_sessions_generation_id_media_packages_id_fk";
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "playback_sessions_generation_idx" ON "playback_sessions" ("generation_id");
@@ -0,0 +1,20 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1783987200000,
"tag": "0000_initial",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1784016000000,
"tag": "0001_playback_generation_external",
"breakpoints": true
}
]
}
+37
View File
@@ -0,0 +1,37 @@
{
"name": "@easy-stream/database",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./schema": {
"types": "./dist/schema.d.ts",
"import": "./dist/schema.js"
}
},
"files": ["dist", "migrations"],
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p ../contracts/tsconfig.json && tsc -p tsconfig.json",
"test": "tsc -p ../contracts/tsconfig.json && vitest run",
"migrate": "drizzle-kit migrate",
"generate": "drizzle-kit generate"
},
"dependencies": {
"@easy-stream/contracts": "workspace:*",
"@sinclair/typebox": "^0.34.41",
"drizzle-orm": "^0.45.2",
"postgres": "^3.4.7"
},
"devDependencies": {
"drizzle-kit": "^0.31.10",
"typescript": "^5.9.3",
"vitest": "^3.2.4"
}
}
+160
View File
@@ -0,0 +1,160 @@
import { CatalogSnapshotSchema, type CatalogSnapshot } from '@easy-stream/contracts';
import { Value } from '@sinclair/typebox/value';
import { sql } from 'drizzle-orm';
import type { Database } from './client.js';
import { mediaItems, titles } from './schema.js';
const UPSERT_BATCH_SIZE = 500;
export interface PreparedCatalogSync {
scannedAt: Date;
titleRows: Array<typeof titles.$inferInsert>;
mediaItemRows: Array<typeof mediaItems.$inferInsert>;
}
export interface CatalogSyncResult {
titlesSeen: number;
mediaItemsSeen: number;
}
/**
* Validates and converts the public scan snapshot into database insert rows. Keeping this
* conversion separate also makes the scanner/database boundary testable without PostgreSQL.
*/
export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
if (!Value.Check(CatalogSnapshotSchema, snapshot)) {
const detail = [...Value.Errors(CatalogSnapshotSchema, snapshot)]
.slice(0, 8)
.map((error) => `${error.path || '/'} ${error.message}`)
.join('; ');
throw new Error(`Invalid catalog snapshot: ${detail}`);
}
const catalog = snapshot as CatalogSnapshot;
const scannedAt = new Date(catalog.generatedAt);
const titleIds = new Set<string>();
const slugs = new Set<string>();
const mediaItemIds = new Set<string>();
const titleRows: PreparedCatalogSync['titleRows'] = [];
const mediaItemRows: PreparedCatalogSync['mediaItemRows'] = [];
for (const title of catalog.titles) {
assertUnique(titleIds, title.id, 'title ID');
assertUnique(slugs, title.slug, 'title slug');
const published = title.mediaItems.some((item) => item.published);
titleRows.push({
id: title.id,
slug: title.slug,
kind: title.kind,
nameFa: title.name.fa,
nameEn: title.name.en ?? null,
synopsisFa: title.synopsis.fa ?? null,
synopsisEn: title.synopsis.en ?? null,
posterUrl: title.posterUrl ?? null,
backdropUrl: title.backdropUrl ?? null,
releaseYear: title.year ?? null,
published,
publishedAt: published ? scannedAt : null,
createdAt: scannedAt,
updatedAt: scannedAt,
});
for (const item of title.mediaItems) {
assertUnique(mediaItemIds, item.id, 'media item ID');
if ((title.kind === 'MOVIE') !== (item.kind === 'MOVIE')) {
throw new Error(`Catalog media item ${item.id} has kind ${item.kind} under ${title.kind}`);
}
mediaItemRows.push({
id: item.id,
titleId: title.id,
kind: item.kind,
seasonNumber: item.seasonNumber ?? null,
episodeNumber: item.episodeNumber ?? null,
nameFa: item.name?.fa ?? null,
nameEn: item.name?.en ?? null,
durationSeconds: item.durationSeconds,
compatibility: item.compatibility,
published: item.published,
publishedAt: item.published ? scannedAt : null,
createdAt: scannedAt,
updatedAt: scannedAt,
});
}
}
return { scannedAt, titleRows, mediaItemRows };
}
/**
* Safely imports scanner-owned catalog facts. Existing names, artwork, TMDB matches and all
* publication fields are intentionally excluded from conflict updates so an archive rescan
* cannot undo an administrator's choices. Rows absent from a snapshot are retained.
*/
export async function syncCatalogSnapshot(
db: Database,
snapshot: unknown,
): Promise<CatalogSyncResult> {
const prepared = prepareCatalogSync(snapshot);
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'))`);
for (const batch of batches(prepared.titleRows, UPSERT_BATCH_SIZE)) {
await transaction
.insert(titles)
.values(batch)
.onConflictDoUpdate({
target: titles.id,
set: {
slug: sql`excluded.slug`,
kind: sql`excluded.kind`,
updatedAt: prepared.scannedAt,
},
setWhere: sql`${titles.slug} is distinct from excluded.slug or ${titles.kind} is distinct from excluded.kind`,
});
}
for (const batch of batches(prepared.mediaItemRows, UPSERT_BATCH_SIZE)) {
await transaction
.insert(mediaItems)
.values(batch)
.onConflictDoUpdate({
target: mediaItems.id,
set: {
titleId: sql`excluded.title_id`,
kind: sql`excluded.kind`,
seasonNumber: sql`excluded.season_number`,
episodeNumber: sql`excluded.episode_number`,
durationSeconds: sql`excluded.duration_seconds`,
compatibility: sql`excluded.compatibility`,
updatedAt: prepared.scannedAt,
},
setWhere: sql`
${mediaItems.titleId} is distinct from excluded.title_id
or ${mediaItems.kind} is distinct from excluded.kind
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
`,
});
}
});
return {
titlesSeen: prepared.titleRows.length,
mediaItemsSeen: prepared.mediaItemRows.length,
};
}
function assertUnique(values: Set<string>, value: string, label: string): void {
if (values.has(value)) throw new Error(`Catalog contains duplicate ${label}: ${value}`);
values.add(value);
}
function batches<T>(values: readonly T[], size: number): T[][] {
const result: T[][] = [];
for (let index = 0; index < values.length; index += size) {
result.push(values.slice(index, index + size));
}
return result;
}
+21
View File
@@ -0,0 +1,21 @@
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema.js';
export function createDatabase(connectionString: string, options?: { max?: number }) {
const client = postgres(connectionString, {
max: options?.max ?? 10,
prepare: false,
transform: { undefined: null },
});
return {
client,
db: drizzle(client, { schema }),
async close(): Promise<void> {
await client.end({ timeout: 5 });
},
};
}
export type Database = ReturnType<typeof createDatabase>['db'];
+4
View File
@@ -0,0 +1,4 @@
export * from './catalog-sync.js';
export * from './client.js';
export * from './job-status.js';
export * from './schema.js';
+56
View File
@@ -0,0 +1,56 @@
import { and, eq, inArray, sql } from 'drizzle-orm';
import type { Database } from './client.js';
import { jobs } from './schema.js';
export async function markArchiveScanRunning(db: Database, jobId: string): Promise<boolean> {
const [updated] = await db.update(jobs).set({
state: 'RUNNING',
progress: 0,
error: null,
attempts: sql`${jobs.attempts} + 1`,
updatedAt: new Date(),
}).where(and(
eq(jobs.id, jobId),
eq(jobs.type, 'ARCHIVE_SCAN'),
// BullMQ may start a retry immediately after its failed event; accept either side of that
// transition so automatic retries can move the same logical job back to RUNNING.
inArray(jobs.state, ['QUEUED', 'RUNNING', 'FAILED']),
)).returning({ id: jobs.id });
return updated !== undefined;
}
export async function markArchiveScanSucceeded(
db: Database,
jobId: string,
result: Record<string, unknown>,
): Promise<boolean> {
const [updated] = await db.update(jobs).set({
state: 'SUCCEEDED',
progress: 1,
result,
error: null,
updatedAt: new Date(),
}).where(and(
eq(jobs.id, jobId),
eq(jobs.type, 'ARCHIVE_SCAN'),
eq(jobs.state, 'RUNNING'),
)).returning({ id: jobs.id });
return updated !== undefined;
}
export async function markArchiveScanFailed(
db: Database,
jobId: string,
error: string,
): Promise<boolean> {
const [updated] = await db.update(jobs).set({
state: 'FAILED',
error: error.slice(0, 16_000),
updatedAt: new Date(),
}).where(and(
eq(jobs.id, jobId),
eq(jobs.type, 'ARCHIVE_SCAN'),
inArray(jobs.state, ['QUEUED', 'RUNNING']),
)).returning({ id: jobs.id });
return updated !== undefined;
}
+324
View File
@@ -0,0 +1,324 @@
import {
bigint,
boolean,
doublePrecision,
index,
integer,
jsonb,
pgEnum,
pgTable,
real,
text,
timestamp,
uniqueIndex,
uuid,
varchar,
} from 'drizzle-orm/pg-core';
export const titleKind = pgEnum('title_kind', ['MOVIE', 'SERIES']);
export const mediaKind = pgEnum('media_kind', ['MOVIE', 'EPISODE']);
export const streamKind = pgEnum('stream_kind', ['VIDEO', 'AUDIO']);
export const compatibilityClass = pgEnum('compatibility_class', [
'COPY',
'AUDIO_TRANSCODE',
'VIDEO_TRANSCODE',
'HOLD_HDR',
'INVALID',
]);
export const packageState = pgEnum('package_state', [
'QUEUED',
'BUILDING',
'READY',
'FAILED',
'EVICTED',
]);
export const jobState = pgEnum('job_state', [
'QUEUED',
'RUNNING',
'SUCCEEDED',
'FAILED',
'CANCELLED',
]);
export const playbackState = pgEnum('playback_state', [
'PREPARING',
'READY',
'UNSUPPORTED_CLIENT',
'FAILED',
]);
const timestamps = {
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
};
export const titles = pgTable(
'titles',
{
id: uuid('id').primaryKey().defaultRandom(),
slug: varchar('slug', { length: 240 }).notNull(),
kind: titleKind('kind').notNull(),
nameFa: text('name_fa'),
nameEn: text('name_en'),
synopsisFa: text('synopsis_fa'),
synopsisEn: text('synopsis_en'),
posterUrl: text('poster_url'),
backdropUrl: text('backdrop_url'),
releaseYear: integer('release_year'),
tmdbId: integer('tmdb_id'),
published: boolean('published').notNull().default(false),
publishedAt: timestamp('published_at', { withTimezone: true }),
...timestamps,
},
(table) => [
uniqueIndex('titles_slug_uidx').on(table.slug),
index('titles_published_idx').on(table.published, table.publishedAt),
index('titles_tmdb_idx').on(table.tmdbId),
],
);
export const mediaItems = pgTable(
'media_items',
{
id: uuid('id').primaryKey().defaultRandom(),
titleId: uuid('title_id')
.notNull()
.references(() => titles.id, { onDelete: 'cascade' }),
kind: mediaKind('kind').notNull(),
seasonNumber: integer('season_number'),
episodeNumber: integer('episode_number'),
nameFa: text('name_fa'),
nameEn: text('name_en'),
durationSeconds: doublePrecision('duration_seconds'),
compatibility: compatibilityClass('compatibility').notNull().default('INVALID'),
compatibilityReason: text('compatibility_reason'),
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_episode_uidx').on(
table.titleId,
table.seasonNumber,
table.episodeNumber,
),
index('media_items_published_idx').on(table.published),
],
);
export const sourceFiles = pgTable(
'source_files',
{
id: uuid('id').primaryKey().defaultRandom(),
mediaItemId: uuid('media_item_id')
.notNull()
.references(() => mediaItems.id, { onDelete: 'cascade' }),
relativePath: text('relative_path').notNull(),
sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull(),
modifiedAtNs: bigint('modified_at_ns', { mode: 'bigint' }).notNull(),
matroskaUid: varchar('matroska_uid', { length: 128 }),
headHash: varchar('head_hash', { length: 128 }).notNull(),
tailHash: varchar('tail_hash', { length: 128 }).notNull(),
fingerprint: varchar('fingerprint', { length: 128 }).notNull(),
probeJson: jsonb('probe_json').$type<Record<string, unknown>>(),
present: boolean('present').notNull().default(true),
lastSeenAt: timestamp('last_seen_at', { withTimezone: true }).notNull().defaultNow(),
...timestamps,
},
(table) => [
uniqueIndex('source_files_path_uidx').on(table.relativePath),
uniqueIndex('source_files_fingerprint_uidx').on(table.fingerprint),
index('source_files_media_item_idx').on(table.mediaItemId),
],
);
export const mediaStreams = pgTable(
'media_streams',
{
id: uuid('id').primaryKey().defaultRandom(),
sourceFileId: uuid('source_file_id')
.notNull()
.references(() => sourceFiles.id, { onDelete: 'cascade' }),
streamIndex: integer('stream_index').notNull(),
kind: streamKind('kind').notNull(),
codec: varchar('codec', { length: 64 }).notNull(),
codecString: varchar('codec_string', { length: 128 }),
language: varchar('language', { length: 35 }),
label: varchar('label', { length: 200 }),
isDefault: boolean('is_default').notNull().default(false),
channels: integer('channels'),
sampleRate: integer('sample_rate'),
width: integer('width'),
height: integer('height'),
frameRate: varchar('frame_rate', { length: 32 }),
bitDepth: integer('bit_depth'),
pixelFormat: varchar('pixel_format', { length: 64 }),
colorTransfer: varchar('color_transfer', { length: 64 }),
...timestamps,
},
(table) => [
uniqueIndex('media_streams_source_index_uidx').on(table.sourceFileId, table.streamIndex),
index('media_streams_source_idx').on(table.sourceFileId),
],
);
export const subtitleTracks = pgTable(
'subtitle_tracks',
{
id: uuid('id').primaryKey().defaultRandom(),
sourceFileId: uuid('source_file_id')
.notNull()
.references(() => sourceFiles.id, { onDelete: 'cascade' }),
streamIndex: integer('stream_index').notNull(),
codec: varchar('codec', { length: 64 }).notNull(),
sourceLanguage: varchar('source_language', { length: 35 }),
normalizedLanguage: varchar('normalized_language', { length: 35 }).notNull(),
label: varchar('label', { length: 200 }).notNull(),
sourceDefault: boolean('source_default').notNull().default(false),
sourceForced: boolean('source_forced').notNull().default(false),
isDefault: boolean('is_default').notNull().default(false),
isForced: boolean('is_forced').notNull().default(false),
assPath: text('ass_path'),
webvttPath: text('webvtt_path'),
...timestamps,
},
(table) => [
uniqueIndex('subtitle_tracks_source_index_uidx').on(table.sourceFileId, table.streamIndex),
index('subtitle_tracks_source_idx').on(table.sourceFileId),
],
);
export const fontAttachments = pgTable(
'font_attachments',
{
id: uuid('id').primaryKey().defaultRandom(),
sourceFileId: uuid('source_file_id')
.notNull()
.references(() => sourceFiles.id, { onDelete: 'cascade' }),
streamIndex: integer('stream_index').notNull(),
sha256: varchar('sha256', { length: 64 }).notNull(),
mimeType: varchar('mime_type', { length: 100 }).notNull(),
originalName: text('original_name').notNull(),
storagePath: text('storage_path'),
approved: boolean('approved').notNull().default(false),
sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull(),
...timestamps,
},
(table) => [
uniqueIndex('font_attachments_source_index_uidx').on(table.sourceFileId, table.streamIndex),
index('font_attachments_hash_idx').on(table.sha256),
],
);
export const mediaPackages = pgTable(
'media_packages',
{
id: uuid('id').primaryKey().defaultRandom(),
mediaItemId: uuid('media_item_id')
.notNull()
.references(() => mediaItems.id, { onDelete: 'cascade' }),
sourceFingerprint: varchar('source_fingerprint', { length: 128 }).notNull(),
profileVersion: varchar('profile_version', { length: 64 }).notNull(),
state: packageState('state').notNull().default('QUEUED'),
manifestPath: text('manifest_path'),
sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull().default(0),
cacheResident: boolean('cache_resident').notNull().default(false),
pinned: boolean('pinned').notNull().default(false),
lastAccessedAt: timestamp('last_accessed_at', { withTimezone: true }),
errorCode: varchar('error_code', { length: 100 }),
errorDetail: text('error_detail'),
readyAt: timestamp('ready_at', { withTimezone: true }),
...timestamps,
},
(table) => [
uniqueIndex('media_packages_generation_uidx').on(
table.mediaItemId,
table.sourceFingerprint,
table.profileVersion,
),
index('media_packages_lru_idx').on(table.cacheResident, table.pinned, table.lastAccessedAt),
],
);
export const jobs = pgTable(
'jobs',
{
id: uuid('id').primaryKey().defaultRandom(),
type: varchar('type', { length: 100 }).notNull(),
state: jobState('state').notNull().default('QUEUED'),
progress: real('progress').notNull().default(0),
payload: jsonb('payload').$type<Record<string, unknown>>().notNull().default({}),
result: jsonb('result').$type<Record<string, unknown>>(),
error: text('error'),
attempts: integer('attempts').notNull().default(0),
...timestamps,
},
(table) => [index('jobs_state_created_idx').on(table.state, table.createdAt)],
);
export const admins = pgTable(
'admins',
{
id: uuid('id').primaryKey().defaultRandom(),
email: varchar('email', { length: 320 }).notNull(),
passwordHash: text('password_hash').notNull(),
totpSecretEncrypted: text('totp_secret_encrypted'),
disabled: boolean('disabled').notNull().default(false),
lastLoginAt: timestamp('last_login_at', { withTimezone: true }),
...timestamps,
},
(table) => [uniqueIndex('admins_email_uidx').on(table.email)],
);
export const adminSessions = pgTable(
'admin_sessions',
{
id: uuid('id').primaryKey().defaultRandom(),
adminId: uuid('admin_id')
.notNull()
.references(() => admins.id, { onDelete: 'cascade' }),
tokenHash: varchar('token_hash', { length: 64 }).notNull(),
csrfTokenHash: varchar('csrf_token_hash', { length: 64 }).notNull(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
revokedAt: timestamp('revoked_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex('admin_sessions_token_uidx').on(table.tokenHash),
index('admin_sessions_admin_idx').on(table.adminId),
],
);
export const playbackSessions = pgTable(
'playback_sessions',
{
id: uuid('id').primaryKey().defaultRandom(),
mediaItemId: uuid('media_item_id')
.notNull()
.references(() => mediaItems.id, { onDelete: 'cascade' }),
// 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'),
state: playbackState('state').notNull().default('PREPARING'),
capabilities: jsonb('capabilities').$type<Record<string, unknown>>().notNull(),
reasonCode: varchar('reason_code', { length: 100 }),
pollAfterMs: integer('poll_after_ms'),
responseJson: jsonb('response_json').$type<Record<string, unknown>>().notNull().default({}),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index('playback_sessions_media_idx').on(table.mediaItemId),
index('playback_sessions_generation_idx').on(table.generationId),
index('playback_sessions_expires_idx').on(table.expiresAt),
],
);
export type TitleRow = typeof titles.$inferSelect;
export type MediaItemRow = typeof mediaItems.$inferSelect;
export type SourceFileRow = typeof sourceFiles.$inferSelect;
export type MediaPackageRow = typeof mediaPackages.$inferSelect;
export type AdminRow = typeof admins.$inferSelect;
export type AdminSessionRow = typeof adminSessions.$inferSelect;
export type PlaybackSessionRow = typeof playbackSessions.$inferSelect;
+100
View File
@@ -0,0 +1,100 @@
import type { CatalogSnapshot } from '@easy-stream/contracts';
import { getTableConfig } from 'drizzle-orm/pg-core';
import { describe, expect, it } from 'vitest';
import {
prepareCatalogSync,
syncCatalogSnapshot,
type Database,
} from '../src/index.js';
import { mediaItems, playbackSessions, titles } from '../src/schema.js';
const snapshot: CatalogSnapshot = {
version: 1,
generatedAt: '2026-07-14T10:00:00.000Z',
titles: [{
id: '11111111-1111-5111-8111-111111111111',
slug: 'sample-film',
kind: 'MOVIE',
name: { fa: 'فیلم نمونه', en: 'Sample Film' },
playable: true,
resumeMediaItemId: '22222222-2222-5222-8222-222222222222',
synopsis: {},
mediaItems: [{
id: '22222222-2222-5222-8222-222222222222',
kind: 'MOVIE',
durationSeconds: 90,
compatibility: 'COPY',
published: true,
}],
updatedAt: '2026-07-14T10:00:00.000Z',
}],
};
describe('catalog snapshot synchronization', () => {
it('validates and maps deterministic scanner IDs and initial publication', () => {
const prepared = prepareCatalogSync(snapshot);
expect(prepared.titleRows).toMatchObject([{
id: snapshot.titles[0]?.id,
nameFa: 'فیلم نمونه',
nameEn: 'Sample Film',
published: true,
}]);
expect(prepared.mediaItemRows).toMatchObject([{
id: snapshot.titles[0]?.mediaItems[0]?.id,
titleId: snapshot.titles[0]?.id,
compatibility: 'COPY',
published: true,
}]);
});
it('rejects ambiguous duplicate IDs before opening a transaction', () => {
const duplicate = structuredClone(snapshot);
duplicate.titles.push({ ...structuredClone(duplicate.titles[0]!), slug: 'another-slug' });
expect(() => prepareCatalogSync(duplicate)).toThrow(/duplicate title ID/u);
});
it('only updates scanner-owned fields on conflicts', async () => {
const conflicts: Array<{ table: unknown; set: Record<string, unknown> }> = [];
const transaction = {
async execute() {},
insert(table: unknown) {
return {
values() {
return {
async onConflictDoUpdate(config: { set: Record<string, unknown> }) {
conflicts.push({ table, set: config.set });
},
};
},
};
},
};
const database = {
async transaction<T>(action: (value: typeof transaction) => Promise<T>): Promise<T> {
return action(transaction);
},
} as unknown as Database;
await syncCatalogSnapshot(database, snapshot);
expect(Object.keys(conflicts.find((entry) => entry.table === titles)!.set).sort())
.toEqual(['kind', 'slug', 'updatedAt']);
expect(Object.keys(conflicts.find((entry) => entry.table === mediaItems)!.set).sort())
.toEqual([
'compatibility',
'durationSeconds',
'episodeNumber',
'kind',
'seasonNumber',
'titleId',
'updatedAt',
]);
});
it('does not constrain a worker generation UUID to media_packages.id', () => {
const configuration = getTableConfig(playbackSessions);
const generationForeignKey = configuration.foreignKeys.some((foreignKey) =>
foreignKey.reference().columns.includes(playbackSessions.generationId));
expect(generationForeignKey).toBe(false);
});
});
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"tsBuildInfoFile": "dist/.tsbuildinfo",
"paths": {
"@easy-stream/contracts": ["packages/contracts/dist/index.d.ts"]
}
},
"include": ["src/**/*.ts"]
}