init
This commit is contained in:
134 files changed
+18678
No files matched your search
@@ -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;
|
||||
}
|
||||
@@ -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'];
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from './catalog-sync.js';
|
||||
export * from './client.js';
|
||||
export * from './job-status.js';
|
||||
export * from './schema.js';
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
Reference in new issue
Block a user