feat: support categorized archives and selectable quality variants

This commit is contained in:
Meghdad committed 2026-07-15 01:40:30 +03:30
1 parent 6ff274d8dd
commit 515b341653
45 files changed
+932 -92

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@ BUILD_NO_PROXY=localhost,127.0.0.1
DOCKER_BUILD_NETWORK=default
DATABASE_URL=
REDIS_URL=redis://localhost:6379
ARCHIVE_ROOT=./movies
ARCHIVE_ROOT=./archive
CACHE_ROOT=./data/cache
DERIVED_ROOT=./data/derived
METADATA_ROOT=./data/metadata
+10 -2
View File
@@ -42,11 +42,19 @@ corepack pnpm scan:samples
`scan:samples` writes a public `data/metadata/catalog.json` and a private `data/metadata/inventory.json`. Source paths and probe details never enter the public snapshot.
The production scanner also understands categorized, multi-quality archives:
```text
archive/<category>/<year>/<Spring|Summer|Fall|Winter|Movie>/<title>/<quality>/*.mkv
```
For example, `anime/2026/Summer/Mushoku Tensei S3/720/...mkv` becomes Anime → Mushoku Tensei → Season 3. Files for the same episode under `480`, `720`, `1080`, or codec-suffixed quality folders become selectable source variants rather than duplicate episodes. A `thumbnail.jpg`, `.jpeg`, `.png`, or `.webp` beside the quality folders is copied to the generated artwork store; the archive itself remains private and read-only. The older `Title S3/*.mkv` layout remains supported.
To package one scanned media item with the locally installed FFmpeg, copy its UUID from `inventory.json` and run:
```sh
node apps/worker/dist/cli.js package \
--root ./movies \
--root ./archive \
--cache ./data/cache \
--inventory ./data/metadata/inventory.json \
--registry ./data/metadata/package-registry.json \
@@ -103,7 +111,7 @@ docker compose exec worker node apps/worker/dist/cli.js prepare \
## Important v1 boundaries
- There is one representation, not an adaptive-bitrate ladder. A slow connection cannot switch to a lower quality.
- There is no adaptive-bitrate ladder. Viewers may manually select an available source quality; each selection is packaged independently on demand and never switches automatically.
- Compatible media still occupies temporary HLS cache space; “no duplication” means no permanent HLS copy for every title.
- Durable compatibility encoding is intentionally operator-controlled and CPU-limited to one job at a time.
- TMDB stays disabled until both an API token and explicit commercial-license confirmation are configured.
+14
View File
@@ -10,6 +10,8 @@ import {
CacheStatusSchema,
CatalogQuerySchema,
CatalogResponseSchema,
CatalogSectionsQuerySchema,
CatalogSectionsResponseSchema,
CreatePlaybackSessionSchema,
DateTimeSchema,
ErrorResponseSchema,
@@ -31,6 +33,7 @@ import {
UuidSchema,
type AdminLogin,
type CatalogQuery,
type CatalogSectionsQuery,
type CreatePlaybackSession,
type MetadataMatchBody,
type MetadataSearchQuery,
@@ -233,6 +236,17 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
async (request) => repository.listCatalog(request.query),
);
app.get<{ Querystring: CatalogSectionsQuery }>(
'/api/v1/catalog/sections',
{
schema: {
querystring: CatalogSectionsQuerySchema,
response: { 200: CatalogSectionsResponseSchema },
},
},
async (request) => ({ sections: await repository.listCatalogSections(request.query.limitPerSection ?? 12) }),
);
app.get<{ Params: Static<typeof SlugParamsSchema> }>(
'/api/v1/titles/:slug',
{
+12
View File
@@ -3,6 +3,7 @@ import type {
AudioTrack,
CacheStatus,
CatalogCard,
CatalogSection,
CatalogQuery,
ClientCapabilities,
Job,
@@ -20,6 +21,14 @@ export interface MediaItemForPlayback {
durationSeconds: number;
compatibility: 'COPY' | 'AUDIO_TRANSCODE' | 'VIDEO_TRANSCODE' | 'HOLD_HDR' | 'INVALID';
published: boolean;
variants: Array<{
id: string;
label: string;
height?: number;
compatibility: 'COPY' | 'AUDIO_TRANSCODE' | 'VIDEO_TRANSCODE' | 'HOLD_HDR' | 'INVALID';
available: boolean;
isDefault: boolean;
}>;
}
export interface CatalogPage {
@@ -29,6 +38,7 @@ export interface CatalogPage {
export interface CatalogRepository {
listCatalog(query: CatalogQuery): Promise<CatalogPage>;
listCatalogSections(limitPerSection: number): Promise<CatalogSection[]>;
searchTitles(query: SearchQuery): Promise<CatalogCard[]>;
getTitleBySlug(slug: string): Promise<TitleDetail | undefined>;
getMediaItem(id: string): Promise<MediaItemForPlayback | undefined>;
@@ -95,12 +105,14 @@ export interface MediaPreparationService {
prepare(input: {
sessionId: string;
mediaItem: MediaItemForPlayback;
variantId?: string;
capabilities: ClientCapabilities;
protectUntil?: string;
}): Promise<MediaPreparation>;
getStatus(input: {
sessionId: string;
mediaItem: MediaItemForPlayback;
variantId?: string;
protectUntil?: string;
}): Promise<MediaPreparation>;
}
+28
View File
@@ -52,6 +52,9 @@ export class InMemoryRepository implements AppRepository {
const published = [...this.titles.values()]
.filter((title) => title.mediaItems.some((item) => item.published))
.filter((title) => !query.kind || title.kind === query.kind)
.filter((title) => !query.category || (title.categorySlug ?? 'other') === query.category)
.filter((title) => !query.year || title.year === query.year)
.filter((title) => !query.releaseWindow || title.releaseWindow === query.releaseWindow)
.sort((left, right) => left.slug.localeCompare(right.slug));
const cursorId = decodeCursor(query.cursor);
const start = cursorId ? Math.max(0, published.findIndex((title) => title.id === cursorId) + 1) : 0;
@@ -63,6 +66,23 @@ export class InMemoryRepository implements AppRepository {
};
}
async listCatalogSections(limitPerSection: number) {
const groups = new Map<string, TitleDetail[]>();
for (const title of this.titles.values()) {
if (!title.mediaItems.some((item) => item.published)) continue;
const categorySlug = title.categorySlug ?? 'other';
const group = groups.get(categorySlug) ?? [];
group.push(title);
groups.set(categorySlug, group);
}
return [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([slug, titles]) => ({
slug,
name: titles[0]?.category ?? 'Other',
items: titles.slice(0, limitPerSection).map(toCard),
hasMore: titles.length > limitPerSection,
}));
}
async searchTitles(query: SearchQuery) {
const needle = normalizeSearch(query.q);
const limit = query.limit ?? 20;
@@ -94,6 +114,14 @@ export class InMemoryRepository implements AppRepository {
durationSeconds: item.durationSeconds,
compatibility: item.compatibility,
published: item.published,
variants: (item.variants ?? []).map((variant) => ({
id: variant.id,
label: variant.label,
...(variant.height ? { height: variant.height } : {}),
compatibility: variant.compatibility,
available: variant.available,
isDefault: variant.isDefault,
})),
};
}
}
+52 -2
View File
@@ -1,6 +1,7 @@
import type {
CacheStatus,
CatalogCard,
CatalogSection,
CatalogQuery,
Job,
MetadataCandidate,
@@ -17,7 +18,7 @@ import {
titles,
type Database,
} from '@easy-stream/database';
import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
import type {
AdminRecord,
AppRepository,
@@ -44,7 +45,13 @@ export class PostgresRepository implements AppRepository {
const rows = await this.db
.select()
.from(titles)
.where(and(eq(titles.published, true), query.kind ? eq(titles.kind, query.kind) : undefined))
.where(and(
eq(titles.published, true),
query.kind ? eq(titles.kind, query.kind) : undefined,
query.category ? (query.category === 'other' ? isNull(titles.categorySlug) : eq(titles.categorySlug, query.category)) : undefined,
query.year ? eq(titles.releaseYear, query.year) : undefined,
query.releaseWindow ? eq(titles.releaseWindow, query.releaseWindow) : undefined,
))
.orderBy(asc(titles.slug), asc(titles.id))
.limit(limit + 1)
.offset(offset);
@@ -56,6 +63,30 @@ export class PostgresRepository implements AppRepository {
};
}
async listCatalogSections(limitPerSection: number): Promise<CatalogSection[]> {
const rows = await this.db.select().from(titles)
.where(eq(titles.published, true))
.orderBy(asc(titles.categorySlug), desc(titles.releaseYear), asc(titles.slug));
const groups = new Map<string, typeof rows>();
for (const row of rows) {
const categorySlug = row.categorySlug ?? 'other';
const group = groups.get(categorySlug) ?? [];
group.push(row);
groups.set(categorySlug, group);
}
const result: CatalogSection[] = [];
for (const [slug, group] of groups) {
const visible = group.slice(0, limitPerSection);
result.push({
slug,
name: group[0]?.category ?? 'Other',
items: await this.cardsForRows(visible),
hasMore: group.length > visible.length,
});
}
return result;
}
async searchTitles(query: SearchQuery): Promise<CatalogCard[]> {
const needle = `%${query.q.trim().replaceAll('%', '\\%').replaceAll('_', '\\_')}%`;
const rows = await this.db
@@ -101,6 +132,14 @@ export class PostgresRepository implements AppRepository {
durationSeconds: row.media.durationSeconds ?? 0,
compatibility: row.media.compatibility,
published: row.media.published && row.titlePublished,
variants: (row.media.variants ?? []).map((variant) => ({
id: variant.id,
label: variant.label,
...(variant.height ? { height: variant.height } : {}),
compatibility: variant.compatibility as MediaItemForPlayback['compatibility'],
available: variant.available,
isDefault: variant.isDefault,
})),
};
}
@@ -156,6 +195,7 @@ export class PostgresRepository implements AppRepository {
await this.db.insert(playbackSessions).values({
id: session.id,
mediaItemId: session.mediaItemId,
...(session.variantId ? { variantId: session.variantId } : {}),
...(session.generationId ? { generationId: session.generationId } : {}),
state: session.state,
capabilities: session.capabilities,
@@ -177,6 +217,7 @@ export class PostgresRepository implements AppRepository {
return {
id: row.id,
mediaItemId: row.mediaItemId,
...(row.variantId ? { variantId: row.variantId } : {}),
state: row.state,
capabilities: row.capabilities as StoredPlaybackSession['capabilities'],
expiresAt: row.expiresAt.toISOString(),
@@ -185,6 +226,7 @@ export class PostgresRepository implements AppRepository {
...(row.pollAfterMs ? { pollAfterMs: row.pollAfterMs } : {}),
...(details.manifestUrl ? { manifestUrl: details.manifestUrl } : {}),
...(details.durationSeconds !== undefined ? { durationSeconds: details.durationSeconds } : {}),
...(details.qualityLabel ? { qualityLabel: details.qualityLabel } : {}),
...(details.audioTracks ? { audioTracks: details.audioTracks } : {}),
...(details.subtitleTracks ? { subtitleTracks: details.subtitleTracks } : {}),
};
@@ -196,6 +238,7 @@ export class PostgresRepository implements AppRepository {
.set({
state: session.state,
generationId: session.generationId ?? null,
variantId: session.variantId ?? null,
reasonCode: session.reasonCode ?? null,
pollAfterMs: session.pollAfterMs ?? null,
responseJson: publicSessionDetails(session),
@@ -344,7 +387,11 @@ function toCatalogCard(
...(title.posterUrl ? { posterUrl: title.posterUrl } : {}),
...(title.backdropUrl ? { backdropUrl: title.backdropUrl } : {}),
...(title.releaseYear !== null ? { year: title.releaseYear } : {}),
...(title.category ? { category: title.category } : {}),
...(title.categorySlug ? { categorySlug: title.categorySlug } : {}),
...(title.releaseWindow ? { releaseWindow: title.releaseWindow } : {}),
...(first ? { resumeMediaItemId: first.id } : {}),
...(first && first.variants.length ? { variants: first.variants as NonNullable<CatalogCard['variants']> } : {}),
};
}
@@ -387,6 +434,7 @@ function toTitleDetail(
durationSeconds: item.durationSeconds ?? 0,
compatibility: item.compatibility,
published: item.published,
variants: item.variants as NonNullable<TitleDetail['mediaItems'][number]['variants']>,
})),
updatedAt: title.updatedAt.toISOString(),
};
@@ -420,6 +468,8 @@ function toJob(job: typeof jobs.$inferSelect): Job {
function publicSessionDetails(session: StoredPlaybackSession): Record<string, unknown> {
return {
...(session.variantId ? { variantId: session.variantId } : {}),
...(session.qualityLabel ? { qualityLabel: session.qualityLabel } : {}),
...(session.manifestUrl ? { manifestUrl: session.manifestUrl } : {}),
...(session.durationSeconds !== undefined ? { durationSeconds: session.durationSeconds } : {}),
...(session.audioTracks ? { audioTracks: session.audioTracks } : {}),
+3
View File
@@ -167,6 +167,9 @@ export class AdminService {
const preparation = await this.media.getStatus({
sessionId: randomUUID(),
mediaItem: item,
variantId: item.variants.find((variant) => variant.available && variant.isDefault)?.id
?? item.variants.find((variant) => variant.available)?.id
?? item.id,
});
if (preparation.state !== 'READY' && !preparation.playable) {
throw new AppError(
+14 -10
View File
@@ -43,24 +43,26 @@ export class FileMediaPreparationService implements MediaPreparationService {
) {}
async prepare(input: Parameters<MediaPreparationService['prepare']>[0]) {
const status = await this.find(input.mediaItem.id);
const status = await this.find(input.mediaItem.id, input.variantId);
const requestKey = `${input.mediaItem.id}:${input.variantId ?? 'legacy'}`;
if (status) {
if (status.playable || status.state === 'READY' || status.state === 'FAILED') {
this.requested.delete(input.mediaItem.id);
this.requested.delete(requestKey);
}
await this.recordCacheAccess(input, status);
return status;
}
if (!this.requested.has(input.mediaItem.id)) {
this.requested.add(input.mediaItem.id);
if (!this.requested.has(requestKey)) {
this.requested.add(requestKey);
try {
await this.publisher.publish({
type: 'media.playback.requested',
sessionId: input.sessionId,
mediaItemId: input.mediaItem.id,
...(input.variantId ? { variantId: input.variantId } : {}),
});
} catch (error) {
this.requested.delete(input.mediaItem.id);
this.requested.delete(requestKey);
throw error;
}
}
@@ -73,9 +75,10 @@ export class FileMediaPreparationService implements MediaPreparationService {
}
async getStatus(input: Parameters<MediaPreparationService['getStatus']>[0]) {
const status = await this.find(input.mediaItem.id);
const status = await this.find(input.mediaItem.id, input.variantId);
const requestKey = `${input.mediaItem.id}:${input.variantId ?? 'legacy'}`;
if (status?.playable || status?.state === 'READY' || status?.state === 'FAILED') {
this.requested.delete(input.mediaItem.id);
this.requested.delete(requestKey);
}
const result = status ?? {
state: 'PREPARING' as const,
@@ -102,9 +105,10 @@ export class FileMediaPreparationService implements MediaPreparationService {
});
}
private async find(mediaItemId: string): Promise<MediaPreparation | undefined> {
private async find(mediaItemId: string, variantId?: string): Promise<MediaPreparation | undefined> {
const registry = await readPackageRegistry(this.registryPath);
const entry = registry?.packages.find((candidate) => candidate.mediaItemId === mediaItemId);
const entry = registry?.packages.find((candidate) => candidate.mediaItemId === mediaItemId
&& (candidate.variantId ?? candidate.mediaItemId) === (variantId ?? mediaItemId));
if (!entry) return undefined;
return {
state: entry.state,
@@ -226,7 +230,7 @@ function redisConnection(redisUrl: string): ConnectionOptions {
function commandJobId(command: MediaCommand, profile: string): string {
switch (command.type) {
case 'media.playback.requested':
return `playback-${command.mediaItemId}-${profile}`;
return `playback-${command.mediaItemId}-${command.variantId ?? 'legacy'}-${profile}`;
case 'archive.scan.requested':
return `scan-${command.jobId}`;
case 'media.publication.changed':
+35 -4
View File
@@ -23,10 +23,15 @@ export class PlaybackService {
async create(input: CreatePlaybackSession): Promise<StoredPlaybackSession> {
const item = await this.requirePlayableMedia(input.mediaItemId);
const variant = selectVariant(item, input.variantId);
if (!variant) throw new AppError(404, 'NOT_FOUND', 'Requested quality is unavailable');
const selectedItem = { ...item, compatibility: variant.compatibility };
const now = Date.now();
const base: StoredPlaybackSession = {
id: randomUUID(),
mediaItemId: item.id,
variantId: variant.id,
qualityLabel: variant.label,
state: 'PREPARING',
capabilities: input.clientCapabilities,
expiresAt: new Date(now + this.config.playbackTtlSeconds * 1000).toISOString(),
@@ -41,7 +46,7 @@ export class PlaybackService {
await this.repository.createPlaybackSession(unsupported);
return unsupported;
}
if (item.compatibility === 'HOLD_HDR') {
if (selectedItem.compatibility === 'HOLD_HDR') {
const unsupported: StoredPlaybackSession = {
...base,
state: 'UNSUPPORTED_CLIENT',
@@ -50,7 +55,7 @@ export class PlaybackService {
await this.repository.createPlaybackSession(unsupported);
return unsupported;
}
if (item.compatibility === 'INVALID') {
if (selectedItem.compatibility === 'INVALID') {
const failed: StoredPlaybackSession = {
...base,
state: 'FAILED',
@@ -63,7 +68,8 @@ export class PlaybackService {
await this.repository.createPlaybackSession(base);
const preparation = await this.media.prepare({
sessionId: base.id,
mediaItem: item,
mediaItem: selectedItem,
variantId: variant.id,
capabilities: input.clientCapabilities,
protectUntil: base.expiresAt,
});
@@ -79,9 +85,12 @@ export class PlaybackService {
}
if (session.state !== 'PREPARING') return session;
const item = await this.requirePlayableMedia(session.mediaItemId);
const variant = selectVariant(item, session.variantId);
if (!variant) throw new AppError(404, 'NOT_FOUND', 'Playback quality is no longer available');
const preparation = await this.media.getStatus({
sessionId: id,
mediaItem: item,
mediaItem: { ...item, compatibility: variant.compatibility },
variantId: variant.id,
protectUntil: session.expiresAt,
});
const updated = this.mergePreparation(session, preparation);
@@ -135,6 +144,28 @@ export class PlaybackService {
}
}
function selectVariant(item: MediaItemForPlayback, requestedId?: string) {
const available = item.variants.filter((variant) => variant.available);
if (requestedId) return available.find((variant) => variant.id === requestedId);
if (available.length === 0) {
return item.published ? {
id: item.id,
label: 'Source',
compatibility: item.compatibility,
available: true,
isDefault: true,
} : undefined;
}
return available.find((variant) => variant.isDefault)
?? [...available].sort((left, right) => {
const leftHeight = left.height ?? 0;
const rightHeight = right.height ?? 0;
const distance = Math.abs(leftHeight - 720) - Math.abs(rightHeight - 720);
if (distance !== 0) return distance;
return leftHeight <= 720 && rightHeight > 720 ? -1 : 1;
})[0];
}
function supportsHls(capabilities: ClientCapabilities): boolean {
return capabilities.nativeHls || (capabilities.mse && capabilities.hlsJs);
}
+6
View File
@@ -61,6 +61,10 @@ describe('viewer API', () => {
expect.objectContaining({ id: ids.title, playable: true }),
]);
const sections = await app.inject({ method: 'GET', url: '/api/v1/catalog/sections?limitPerSection=12' });
expect(sections.statusCode).toBe(200);
expect(sections.json().sections[0]).toEqual(expect.objectContaining({ slug: 'anime', name: 'Anime' }));
const search = await app.inject({ method: 'GET', url: '/api/v1/search?q=Sample' });
expect(search.statusCode).toBe(200);
expect(search.json().items[0].slug).toBe('sample-series');
@@ -89,6 +93,7 @@ describe('viewer API', () => {
url: '/api/v1/playback-sessions',
payload: {
mediaItemId: ids.media,
variantId: ids.variant,
clientCapabilities: capabilities(),
},
});
@@ -96,6 +101,7 @@ describe('viewer API', () => {
expect(response.json()).toEqual(
expect.objectContaining({
state: 'READY',
variantId: ids.variant,
manifestUrl: `http://localhost:8080/media/generations/${ids.generation}/master.m3u8`,
}),
);
+7
View File
@@ -7,6 +7,7 @@ export const ids = {
generation: '30000000-0000-4000-8000-000000000001',
audio: '40000000-0000-4000-8000-000000000001',
subtitle: '50000000-0000-4000-8000-000000000001',
variant: '60000000-0000-4000-8000-000000000001',
};
export const titleFixture: TitleDetail = {
@@ -16,6 +17,11 @@ export const titleFixture: TitleDetail = {
name: { fa: 'سریال نمونه', en: 'Sample Series' },
synopsis: { fa: 'خلاصه نمونه', en: 'Sample synopsis' },
playable: true,
category: 'Anime',
categorySlug: 'anime',
releaseWindow: 'SUMMER',
year: 2026,
variants: [{ id: ids.variant, label: '720p', width: 1280, height: 720, videoCodec: 'h264', compatibility: 'COPY', available: true, isDefault: true }],
resumeMediaItemId: ids.media,
seasons: [{ number: 1, episodeCount: 1 }],
mediaItems: [
@@ -28,6 +34,7 @@ export const titleFixture: TitleDetail = {
durationSeconds: 1420,
compatibility: 'COPY',
published: true,
variants: [{ id: ids.variant, label: '720p', width: 1280, height: 720, videoCodec: 'h264', compatibility: 'COPY', available: true, isDefault: true }],
},
],
updatedAt: '2026-07-14T00:00:00.000Z',
+40 -3
View File
@@ -3,6 +3,7 @@ import type {
AdminJob,
CatalogItem,
CatalogPage,
CatalogSection,
ClientCapabilities,
EpisodeItem,
LocalizedText,
@@ -10,6 +11,7 @@ import type {
PlaybackSession,
PlaybackState,
PlaybackSubtitleTrack,
QualityVariant,
SeasonItem,
TitleDetail,
} from '@/types'
@@ -67,6 +69,20 @@ function array(value: unknown): unknown[] {
return Array.isArray(value) ? value : []
}
function normalizeVariant(input: unknown): QualityVariant {
const item = record(input)
return {
id: text(item.id) ?? '',
label: text(item.label) ?? `${number(item.height) ?? 0}p`,
...(number(item.width) ? { width: number(item.width) } : {}),
...(number(item.height) ? { height: number(item.height) } : {}),
...(text(item.videoCodec) ? { videoCodec: text(item.videoCodec) } : {}),
compatibility: text(item.compatibility) ?? 'INVALID',
available: boolean(item.available),
isDefault: boolean(item.isDefault),
}
}
function normalizeCatalogItem(input: unknown): CatalogItem {
const item = record(input)
const metadata = record(item.metadata)
@@ -95,6 +111,10 @@ function normalizeCatalogItem(input: unknown): CatalogItem {
...(posterUrl ? { posterUrl } : {}),
...(backdropUrl ? { backdropUrl } : {}),
...(number(item.year ?? metadata.year) !== undefined ? { year: number(item.year ?? metadata.year) } : {}),
...(text(item.category) ? { category: text(item.category) } : {}),
...(text(item.categorySlug) ? { categorySlug: text(item.categorySlug) } : {}),
...(text(item.releaseWindow) ? { releaseWindow: text(item.releaseWindow) } : {}),
variants: array(item.variants).map(normalizeVariant).filter((variant) => variant.id),
...(number(item.runtimeSeconds ?? item.durationSeconds) !== undefined
? { runtimeSeconds: number(item.runtimeSeconds ?? item.durationSeconds) }
: {}),
@@ -121,6 +141,7 @@ function normalizeEpisode(input: unknown, seasonNumber: number): EpisodeItem {
? { durationSeconds: number(item.durationSeconds ?? item.runtimeSeconds) }
: {}),
published: item.published === undefined ? true : boolean(item.published),
variants: array(item.variants).map(normalizeVariant).filter((variant) => variant.id),
}
}
@@ -207,6 +228,8 @@ export function normalizePlaybackSession(input: unknown): PlaybackSession {
id,
state: normalizeState(payload.state ?? payload.status),
mediaItemId: text(payload.mediaItemId) ?? '',
...(text(payload.variantId) ? { variantId: text(payload.variantId) } : {}),
...(text(payload.qualityLabel) ? { qualityLabel: text(payload.qualityLabel) } : {}),
...(manifestUrl ? { manifestUrl } : {}),
...(number(payload.durationSeconds ?? payload.duration) !== undefined
? { durationSeconds: number(payload.durationSeconds ?? payload.duration) }
@@ -270,7 +293,7 @@ function withSignal(signal: AbortSignal | undefined, init: RequestInit = {}): Re
}
export const api = {
async catalog(options: { cursor?: string; limit?: number; kind?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
async catalog(options: { cursor?: string; limit?: number; kind?: string; category?: string; year?: number; releaseWindow?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
const body = await request(`/catalog${queryString({ ...options })}`, withSignal(signal))
const source = record(body)
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
@@ -284,6 +307,19 @@ export const api = {
}
},
async catalogSections(limitPerSection = 12, signal?: AbortSignal): Promise<CatalogSection[]> {
const body = record(await request(`/catalog/sections${queryString({ limitPerSection })}`, withSignal(signal)))
return array(body.sections).map((input) => {
const section = record(input)
return {
slug: text(section.slug) ?? '',
name: text(section.name) ?? text(section.slug) ?? '',
items: array(section.items).map(normalizeCatalogItem).filter((item) => item.id),
hasMore: boolean(section.hasMore),
}
}).filter((section) => section.slug && section.items.length)
},
async search(term: string, signal?: AbortSignal): Promise<CatalogPage> {
const body = await request(`/search${queryString({ q: term, limit: 40 })}`, withSignal(signal))
const source = record(body)
@@ -334,11 +370,12 @@ export const api = {
async createPlaybackSession(
mediaItemId: string,
clientCapabilities: ClientCapabilities,
variantId?: string,
signal?: AbortSignal,
): Promise<PlaybackSession> {
const body = await request('/playback-sessions', withSignal(signal, {
method: 'POST',
body: JSON.stringify({ mediaItemId, clientCapabilities }),
body: JSON.stringify({ mediaItemId, ...(variantId ? { variantId } : {}), clientCapabilities }),
}))
const session = normalizePlaybackSession(body)
return { ...session, mediaItemId: session.mediaItemId || mediaItemId }
@@ -436,7 +473,7 @@ export const api = {
const body = record(await request('/admin/scans', {
method: 'POST',
headers: { 'x-csrf-token': csrfToken },
body: JSON.stringify({ full: false }),
body: JSON.stringify({ full: true }),
}))
const jobId = text(body.id ?? body.jobId ?? record(body.data).jobId)
return { ...(jobId ? { jobId } : {}) }
@@ -14,6 +14,7 @@ const item: CatalogItem = {
title: { fa: 'فیلم نمونه', en: 'Sample movie' },
overview: {},
playable: true,
variants: [],
year: 2026,
}
+1
View File
@@ -19,6 +19,7 @@ function play() {
if (!props.item.playable || !props.item.mediaItemId) return
player.play({
mediaItemId: props.item.mediaItemId,
...(props.item.variants.length ? { variants: props.item.variants } : {}),
title: title.value,
...(props.item.posterUrl ? { posterUrl: props.item.posterUrl } : {}),
})
+39 -3
View File
@@ -36,7 +36,7 @@ const currentTime = ref(0)
const duration = ref(0)
const buffered = ref(0)
const controlsVisible = ref(true)
const menu = ref<'subtitles' | 'audio' | null>(null)
const menu = ref<'subtitles' | 'audio' | 'quality' | null>(null)
const session = ref<PlaybackSession | null>(null)
const selectedSubtitle = ref('off')
const selectedAudio = ref('')
@@ -442,7 +442,17 @@ async function start(request: PlayRequest) {
}
try {
const initial = await api.createPlaybackSession(request.mediaItemId, capabilities, requestController.signal)
const variants = (request.variants ?? []).filter((variant) => variant.available)
const selectedVariant = request.variantId
? variants.find((variant) => variant.id === request.variantId)
: variants.find((variant) => variant.height === ui.preferences.preferredQualityHeight)
?? variants.find((variant) => variant.isDefault)
const initial = await api.createPlaybackSession(
request.mediaItemId,
capabilities,
selectedVariant?.id,
requestController.signal,
)
await resolveSession(initial, sequence, requestController.signal)
} catch (error) {
if ((error as { name?: string }).name === 'AbortError' || sequence !== requestSequence) return
@@ -503,11 +513,23 @@ function toggleMute() {
void ui.setVolume(element.volume, element.muted)
}
function toggleMenu(target: 'subtitles' | 'audio') {
function toggleMenu(target: 'subtitles' | 'audio' | 'quality') {
menu.value = menu.value === target ? null : target
showControls()
}
async function chooseQuality(variant: NonNullable<PlayRequest['variants']>[number]) {
const request = currentRequest.value
if (!request || session.value?.variantId === variant.id) {
menu.value = null
return
}
await saveProgress(true)
if (variant.height) await ui.setPreferredQuality(variant.height)
menu.value = null
await start({ ...request, variantId: variant.id })
}
function formatTime(seconds: number): string {
if (!Number.isFinite(seconds) || seconds < 0) return '00:00'
const hours = Math.floor(seconds / 3600)
@@ -671,6 +693,20 @@ onBeforeUnmount(() => {
<span class="control-spacer" />
<div v-if="currentRequest?.variants?.some((variant) => variant.available)" class="control-menu-wrap">
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('quality')">{{ t('quality') }}</button>
<div v-if="menu === 'quality'" class="track-menu">
<button
v-for="variant in currentRequest.variants.filter((candidate) => candidate.available)"
:key="variant.id"
type="button"
data-tv-focus
:class="{ selected: variant.id === session?.variantId }"
@click="chooseQuality(variant)"
>{{ variant.label }}</button>
</div>
</div>
<div v-if="session?.audioTracks.length" class="control-menu-wrap">
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('audio')">{{ t('audio') }}</button>
<div v-if="menu === 'audio'" class="track-menu">
+12
View File
@@ -61,6 +61,12 @@ const fa = {
unavailable: 'ناموجود',
unsupported: 'پشتیبانی‌نشده',
year: 'سال',
quality: 'کیفیت',
browse: 'مرور',
browseAll: 'مشاهده همه',
allYears: 'همه سال‌ها',
releaseWindow: 'بازه انتشار',
allSeasons: 'همه فصل‌ها',
} as const
const en: Record<keyof typeof fa, string> = {
@@ -122,6 +128,12 @@ const en: Record<keyof typeof fa, string> = {
unavailable: 'Unavailable',
unsupported: 'Unsupported',
year: 'Year',
quality: 'Quality',
browse: 'Browse',
browseAll: 'Browse all',
allYears: 'All years',
releaseWindow: 'Release season',
allSeasons: 'All seasons',
}
export type TranslationKey = keyof typeof fa
+2
View File
@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
import AdminView from '@/views/AdminView.vue'
import CatalogView from '@/views/CatalogView.vue'
import BrowseView from '@/views/BrowseView.vue'
import SearchView from '@/views/SearchView.vue'
import TitleView from '@/views/TitleView.vue'
@@ -11,6 +12,7 @@ export const router = createRouter({
routes: [
{ path: '/', name: 'catalog', component: CatalogView },
{ path: '/search', name: 'search', component: SearchView },
{ path: '/browse/:category', name: 'browse', component: BrowseView },
{ path: '/title/:slug', name: 'title', component: TitleView },
{ path: '/admin', name: 'admin', component: AdminView },
{ path: '/:pathMatch(.*)*', redirect: '/' },
+1
View File
@@ -18,6 +18,7 @@ describe('viewer storage', () => {
audioLanguage: 'ja',
volume: 0.7,
muted: false,
preferredQualityHeight: 1080,
})
await expect(readPreferences()).resolves.toMatchObject({ uiLanguage: 'en', subtitleLanguage: 'en', volume: 0.7 })
+1
View File
@@ -11,6 +11,7 @@ export const defaultPreferences: ViewerPreferences = {
audioLanguage: 'ja',
volume: 1,
muted: false,
preferredQualityHeight: 720,
}
let databasePromise: Promise<IDBDatabase | null> | undefined
+2
View File
@@ -3,6 +3,8 @@ import { markRaw } from 'vue'
export interface PlayRequest {
mediaItemId: string
variantId?: string
variants?: import('@/types').QualityVariant[]
title: string
posterUrl?: string
}
+5
View File
@@ -43,5 +43,10 @@ export const useUiStore = defineStore('ui', {
this.preferences.muted = muted
await writePreferences({ ...this.preferences })
},
async setPreferredQuality(height: number) {
this.preferences.preferredQualityHeight = Math.max(1, Math.round(height))
await writePreferences({ ...this.preferences })
},
},
})
+46 -1
View File
@@ -39,7 +39,8 @@ body {
}
button,
input {
input,
select {
font: inherit;
}
@@ -1356,3 +1357,47 @@ button:disabled,
animation-iteration-count: 1 !important;
}
}
.section-heading,
.browse-header,
.browse-filters {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.category-rail {
display: flex;
overflow-x: auto;
overflow-y: hidden;
scroll-snap-type: x proximity;
padding-block: .5rem 1rem;
}
.category-rail > * {
flex: 0 0 clamp(10rem, 17vw, 15rem);
scroll-snap-align: start;
}
.browse-view {
padding: 7rem clamp(1rem, 4vw, 4rem) 4rem;
min-height: 100vh;
}
.browse-header { margin-bottom: 2rem; align-items: end; }
.browse-header h1 { margin: .25rem 0 0; font-size: clamp(2rem, 5vw, 4rem); }
.browse-filters select {
min-width: 10rem;
padding: .75rem 1rem;
color: var(--text);
background: var(--panel-raised);
border: 1px solid var(--line);
border-radius: .8rem;
}
@media (max-width: 700px) {
.browse-header { align-items: stretch; flex-direction: column; }
.browse-filters { align-items: stretch; }
.browse-filters select { min-width: 0; flex: 1; }
}
+26
View File
@@ -6,6 +6,17 @@ export interface LocalizedText {
en?: string | undefined
}
export interface QualityVariant {
id: string
label: string
width?: number | undefined
height?: number | undefined
videoCodec?: string | undefined
compatibility: string
available: boolean
isDefault: boolean
}
export interface CatalogItem {
id: string
mediaItemId: string
@@ -16,6 +27,10 @@ export interface CatalogItem {
posterUrl?: string | undefined
backdropUrl?: string | undefined
year?: number | undefined
category?: string | undefined
categorySlug?: string | undefined
releaseWindow?: string | undefined
variants: QualityVariant[]
runtimeSeconds?: number | undefined
seasonCount?: number | undefined
episodeCount?: number | undefined
@@ -34,6 +49,7 @@ export interface EpisodeItem {
posterUrl?: string | undefined
durationSeconds?: number | undefined
published: boolean
variants: QualityVariant[]
}
export interface SeasonItem {
@@ -54,6 +70,13 @@ export interface CatalogPage {
total?: number | undefined
}
export interface CatalogSection {
slug: string
name: string
items: CatalogItem[]
hasMore: boolean
}
export type PlaybackState = 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED'
export type SubtitleDelivery = 'ASS_JASSUB' | 'WEBVTT' | 'OFF'
@@ -79,6 +102,8 @@ export interface PlaybackSession {
id: string
state: PlaybackState
mediaItemId: string
variantId?: string | undefined
qualityLabel?: string | undefined
manifestUrl?: string | undefined
durationSeconds?: number | undefined
pollAfterMs: number
@@ -115,6 +140,7 @@ export interface ViewerPreferences {
audioLanguage: string
volume: number
muted: boolean
preferredQualityHeight: number
}
export interface AdminJob {
+74
View File
@@ -0,0 +1,74 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { api } from '@/api/client'
import LoadingState from '@/components/LoadingState.vue'
import MediaCard from '@/components/MediaCard.vue'
import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import type { CatalogItem } from '@/types'
const route = useRoute()
const root = ref<HTMLElement | null>(null)
const items = ref<CatalogItem[]>([])
const sourceItems = ref<CatalogItem[]>([])
const year = ref('')
const releaseWindow = ref('')
const loading = ref(true)
const error = ref('')
let controller: AbortController | undefined
const { t } = useI18n()
useSpatialNavigation(root, { restoreKey: 'browse-focus' })
const category = computed(() => String(route.params.category ?? ''))
const categoryName = computed(() => sourceItems.value[0]?.category ?? category.value)
const years = computed(() => [...new Set(sourceItems.value.map((item) => item.year).filter((value): value is number => value !== undefined))].sort((a, b) => b - a))
const windows = computed(() => [...new Set(sourceItems.value.map((item) => item.releaseWindow).filter((value): value is string => Boolean(value)))])
async function load() {
controller?.abort()
controller = new AbortController()
loading.value = true
error.value = ''
try {
const page = await api.catalog({
category: category.value,
limit: 100,
...(year.value ? { year: Number(year.value) } : {}),
...(releaseWindow.value ? { releaseWindow: releaseWindow.value } : {}),
}, controller.signal)
items.value = page.items
if (!year.value && !releaseWindow.value) sourceItems.value = page.items
} catch (reason) {
if ((reason as { name?: string }).name !== 'AbortError') error.value = reason instanceof Error ? reason.message : t('networkError')
} finally {
loading.value = false
}
}
watch([category, year, releaseWindow], () => void load(), { immediate: true })
onBeforeUnmount(() => controller?.abort())
</script>
<template>
<main ref="root" class="browse-view">
<header class="browse-header">
<div><p class="eyebrow">{{ t('browse') }}</p><h1>{{ categoryName }}</h1></div>
<div class="browse-filters">
<select v-model="year" data-tv-focus class="focus-ring" :aria-label="t('year')">
<option value="">{{ t('allYears') }}</option>
<option v-for="value in years" :key="value" :value="String(value)">{{ value }}</option>
</select>
<select v-model="releaseWindow" data-tv-focus class="focus-ring" :aria-label="t('releaseWindow')">
<option value="">{{ t('allSeasons') }}</option>
<option v-for="value in windows" :key="value" :value="value">{{ value }}</option>
</select>
</div>
</header>
<LoadingState v-if="loading" :label="t('loadingCatalog')" />
<section v-else-if="error" class="center-state error-state"><p>{{ error }}</p></section>
<section v-else-if="items.length" class="media-grid">
<MediaCard v-for="item in items" :key="item.id" :item="item" />
</section>
<section v-else class="center-state"><h2>{{ t('emptyCatalog') }}</h2></section>
</main>
</template>
+15 -8
View File
@@ -8,15 +8,16 @@ import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import { listProgress } from '@/storage/viewer-db'
import { usePlayerStore } from '@/stores/player'
import type { CatalogItem } from '@/types'
import type { CatalogItem, CatalogSection } from '@/types'
const root = ref<HTMLElement | null>(null)
const items = ref<CatalogItem[]>([])
const sections = ref<CatalogSection[]>([])
const progress = ref<Record<string, number>>({})
const loading = ref(true)
const error = ref('')
const { localize, t } = useI18n()
const player = usePlayerStore()
const items = computed(() => sections.value.flatMap((section) => section.items))
const featured = computed(() => items.value.find((item) => item.playable) ?? items.value[0])
const { restoreFocus } = useSpatialNavigation(root, { restoreKey: 'catalog-focus' })
@@ -25,6 +26,7 @@ function playFeatured() {
if (!item?.playable || !item.mediaItemId) return
player.play({
mediaItemId: item.mediaItemId,
...(item.variants.length ? { variants: item.variants } : {}),
title: localize(item.title, item.slug),
...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
})
@@ -34,8 +36,8 @@ async function load() {
loading.value = true
error.value = ''
try {
const [catalog, storedProgress] = await Promise.all([api.catalog({ limit: 60 }), listProgress()])
items.value = catalog.items
const [catalogSections, storedProgress] = await Promise.all([api.catalogSections(12), listProgress()])
sections.value = catalogSections
progress.value = Object.fromEntries(storedProgress.map((entry) => [
entry.mediaItemId,
entry.durationSeconds > 0 ? (entry.positionSeconds / entry.durationSeconds) * 100 : 0,
@@ -96,11 +98,16 @@ onMounted(() => void load())
</div>
</section>
<section class="catalog-section" aria-labelledby="catalog-heading">
<h2 id="catalog-heading">{{ t('allTitles') }}</h2>
<div class="media-grid">
<section v-for="section in sections" :key="section.slug" class="catalog-section">
<div class="section-heading">
<h2>{{ section.name }}</h2>
<RouterLink class="secondary-button focus-ring" data-tv-focus :to="{ name: 'browse', params: { category: section.slug } }">
{{ t('browseAll') }}
</RouterLink>
</div>
<div class="media-grid category-rail">
<MediaCard
v-for="item in items"
v-for="item in section.items"
:key="item.id"
:item="item"
:progress="progress[item.mediaItemId]"
+2
View File
@@ -31,6 +31,7 @@ function playTitle() {
if (!detail.value || !mediaItemId) return
player.play({
mediaItemId,
...(detail.value.variants.length ? { variants: detail.value.variants } : {}),
title: title.value,
...(detail.value.posterUrl ? { posterUrl: detail.value.posterUrl } : {}),
})
@@ -39,6 +40,7 @@ function playTitle() {
function playEpisode(episode: EpisodeItem) {
player.play({
mediaItemId: episode.mediaItemId,
...(episode.variants.length ? { variants: episode.variants } : {}),
title: `${title.value} · ${t('episode')} ${episode.number}`,
...(episode.posterUrl ? { posterUrl: episode.posterUrl } : {}),
})
+191 -29
View File
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto';
import { access, copyFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
import {
assDialogueText,
@@ -23,6 +24,11 @@ export interface ParsedMediaIdentity {
seasonNumber?: number;
episodeNumber?: number;
episodeTitle?: string;
category?: string;
categorySlug?: string;
year?: number;
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
titleDirectory?: string;
}
export interface SnapshotSubtitle {
@@ -38,16 +44,15 @@ export interface SnapshotSubtitle {
forced: false;
}
export interface SnapshotMediaItem {
export interface SnapshotMediaVariant {
id: string;
titleId: string;
kind: 'MOVIE' | 'EPISODE';
sourcePath: string;
durationSeconds: number;
seasonNumber?: number;
episodeNumber?: number;
title: { en: string; fa?: string };
published: boolean;
qualityLabel: string;
width?: number;
height?: number;
videoCodec?: string;
available: boolean;
compatibility: Classification['class'];
compatibilityReasons: string[];
fingerprint: SourceFingerprint;
@@ -55,6 +60,16 @@ export interface SnapshotMediaItem {
subtitles: SnapshotSubtitle[];
}
export interface SnapshotMediaItem extends SnapshotMediaVariant {
titleId: string;
kind: 'MOVIE' | 'EPISODE';
seasonNumber?: number;
episodeNumber?: number;
title: { en: string; fa?: string };
published: boolean;
variants?: SnapshotMediaVariant[];
}
export interface SnapshotSeason {
number: number;
title: { en: string };
@@ -66,6 +81,11 @@ export interface SnapshotTitle {
slug: string;
kind: CatalogKind;
title: { en: string; fa?: string };
category?: string;
categorySlug?: string;
year?: number;
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
posterUrl?: string;
published: boolean;
playable: boolean;
mediaItemId: string;
@@ -93,6 +113,16 @@ export interface PublicMediaItem {
durationSeconds: number;
compatibility: Classification['class'];
published: boolean;
variants?: Array<{
id: string;
label: string;
width?: number;
height?: number;
videoCodec?: string;
compatibility: Classification['class'];
available: boolean;
isDefault: boolean;
}>;
}
export interface PublicTitleDetail {
@@ -100,8 +130,14 @@ export interface PublicTitleDetail {
slug: string;
kind: CatalogKind;
name: { fa: string; en?: string };
posterUrl?: string;
category?: string;
categorySlug?: string;
year?: number;
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
playable: boolean;
resumeMediaItemId?: string;
variants?: PublicMediaItem['variants'];
synopsis: { fa?: string; en?: string };
seasons?: Array<{ number: number; episodeCount: number }>;
mediaItems: PublicMediaItem[];
@@ -146,16 +182,33 @@ export function slugify(value: string): string {
export function parseMediaIdentity(relativePath: string): ParsedMediaIdentity {
const extension = path.extname(relativePath);
const filename = path.basename(relativePath, extension);
const parent = path.basename(path.dirname(relativePath));
const segments = relativePath.split('/').filter(Boolean);
const immediateParent = segments.at(-2) ?? '';
const qualityDirectory = /^(?:\d{3,4}p?)(?:[\s._-]+(?:x26[45]|hevc|av1))?$|^(?:x26[45]|hevc|av1)$/iu.test(immediateParent);
const titleDirectory = segments.at(qualityDirectory ? -3 : -2) ?? immediateParent;
const titleIndex = Math.max(0, segments.length - (qualityDirectory ? 3 : 2));
const hierarchy = segments.slice(0, titleIndex);
const categorySource = hierarchy[0];
const yearSource = hierarchy.find((segment) => /^(?:18|19|20|21|22)\d{2}$/u.test(segment));
const releaseSource = hierarchy.find((segment) => /^(?:spring|summer|fall|winter|movie)$/iu.test(segment));
const releaseWindow = releaseSource?.toLocaleUpperCase('en-US') as ParsedMediaIdentity['releaseWindow'];
const category = categorySource ? cleanName(categorySource).replace(/^./u, (value) => value.toLocaleUpperCase('en-US')) : undefined;
const combined = filename.match(/\bS(?:eason)?\s*(\d{1,3})\s*E(?:p(?:isode)?)?\s*(\d{1,4})\b/iu);
const parentSeason = parent.match(/^(.*?)(?:[\s._-]+S(?:eason)?\s*(\d{1,3}))$/iu);
const parentSeason = titleDirectory.match(/^(.*?)(?:[\s._-]+S(?:eason)?\s*(\d{1,3}))$/iu);
const episode = combined?.[2]
?? filename.match(/(?:-|–)\s*(\d{1,4})(?=(?:[.\s_\[]|$))/u)?.[1]
?? filename.match(/\bE(?:p(?:isode)?)?\s*(\d{1,4})\b/iu)?.[1];
if (episode !== undefined) {
const common = {
...(category ? { category, categorySlug: slugify(category) } : {}),
...(yearSource ? { year: Number(yearSource) } : {}),
...(releaseWindow ? { releaseWindow } : {}),
...(titleDirectory ? { titleDirectory: segments.slice(0, titleIndex + 1).join('/') } : {}),
};
if (episode !== undefined && releaseWindow !== 'MOVIE') {
const season = Number(combined?.[1] ?? parentSeason?.[2] ?? 1);
const title = cleanName(parentSeason?.[1] ?? parent);
const title = cleanName(parentSeason?.[1] ?? titleDirectory);
return {
...common,
kind: 'SERIES',
title: title || cleanName(filename),
seasonNumber: season,
@@ -163,7 +216,7 @@ export function parseMediaIdentity(relativePath: string): ParsedMediaIdentity {
episodeTitle: `Episode ${Number(episode)}`,
};
}
return { kind: 'MOVIE', title: cleanName(filename) };
return { ...common, kind: 'MOVIE', title: cleanName(titleDirectory || filename) };
}
export interface ScanArchiveOptions {
@@ -171,6 +224,7 @@ export interface ScanArchiveOptions {
ffmpegPath?: string;
ffprobePath?: string;
onFile?: (relativePath: string, current: number) => void;
artworkRoot?: string;
}
const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']);
@@ -185,7 +239,7 @@ async function inspectFile(
sourcePath: string,
archiveRoot: string,
options: ScanArchiveOptions,
): Promise<{ identity: ParsedMediaIdentity; media: SnapshotMediaItem }> {
): Promise<{ identity: ParsedMediaIdentity; variant: SnapshotMediaVariant }> {
const relativePath = path.relative(archiveRoot, sourcePath).split(path.sep).join('/');
const identity = parseMediaIdentity(relativePath);
const [probe, fingerprint] = await Promise.all([
@@ -193,8 +247,7 @@ async function inspectFile(
fingerprintSource(archiveRoot, sourcePath),
]);
const compatibility = classifyMedia(probe);
const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`);
const mediaId = deterministicUuid(`media:${relativePath}`);
const variantId = deterministicUuid(`variant:${relativePath}`);
const tracks = normalizeTracks(probe);
const subtitles: SnapshotSubtitle[] = [];
for (const stream of probe.streams.filter((candidate) => candidate.codec_type === 'subtitle')) {
@@ -234,19 +287,20 @@ async function inspectFile(
});
}
const duration = Number(probe.format.duration);
const published = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class);
const video = probe.streams.find((stream) => stream.codec_type === 'video');
const available = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class);
const qualityLabel = video?.height ? `${video.height}p` : cleanName(path.basename(path.dirname(relativePath))) || 'Source';
return {
identity,
media: {
id: mediaId,
titleId,
kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE',
variant: {
id: variantId,
sourcePath: relativePath,
durationSeconds: Number.isFinite(duration) ? duration : 0,
...(identity.seasonNumber === undefined ? {} : { seasonNumber: identity.seasonNumber }),
...(identity.episodeNumber === undefined ? {} : { episodeNumber: identity.episodeNumber }),
title: { en: identity.episodeTitle ?? identity.title },
published,
qualityLabel,
...(video?.width ? { width: video.width } : {}),
...(video?.height ? { height: video.height } : {}),
...(video?.codec_name ? { videoCodec: video.codec_name } : {}),
available,
compatibility: compatibility.class,
compatibilityReasons: compatibility.reasons,
fingerprint,
@@ -258,19 +312,48 @@ async function inspectFile(
export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArchiveResult> {
const root = path.resolve(options.archiveRoot);
const grouped = new Map<string, { identity: ParsedMediaIdentity; media: SnapshotMediaItem[] }>();
const grouped = new Map<string, { identity: ParsedMediaIdentity; variants: SnapshotMediaVariant[] }>();
let current = 0;
for await (const sourcePath of walkArchive(root)) {
current += 1;
const relative = path.relative(root, sourcePath).split(path.sep).join('/');
options.onFile?.(relative, current);
const inspected = await inspectFile(sourcePath, root, options);
const key = `${inspected.identity.kind}:${inspected.identity.title.toLocaleLowerCase('en-US')}`;
const group = grouped.get(key) ?? { identity: inspected.identity, media: [] };
group.media.push(inspected.media);
const logical = inspected.identity.kind === 'MOVIE'
? 'movie'
: `s${inspected.identity.seasonNumber ?? 1}e${inspected.identity.episodeNumber ?? 0}`;
const key = `${inspected.identity.kind}:${inspected.identity.title.toLocaleLowerCase('en-US')}:${logical}`;
const group = grouped.get(key) ?? { identity: inspected.identity, variants: [] };
group.variants.push(inspected.variant);
grouped.set(key, group);
}
const items: SnapshotTitle[] = [...grouped.values()].map(({ identity, media }) => {
const logicalItems = [...grouped.values()].map(({ identity, variants }) => {
variants.sort(compareVariants);
const selected = variants[0];
if (!selected) throw new Error('Internal media group has no source variants');
const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`);
const logicalKey = identity.kind === 'MOVIE' ? 'movie' : `s${identity.seasonNumber ?? 1}e${identity.episodeNumber ?? 0}`;
const media: SnapshotMediaItem = {
...selected,
id: deterministicUuid(`media:${titleId}:${logicalKey}`),
titleId,
kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE',
...(identity.seasonNumber === undefined ? {} : { seasonNumber: identity.seasonNumber }),
...(identity.episodeNumber === undefined ? {} : { episodeNumber: identity.episodeNumber }),
title: { en: identity.episodeTitle ?? identity.title },
published: variants.some((variant) => variant.available),
variants,
};
return { identity, media };
});
const byTitle = new Map<string, { identity: ParsedMediaIdentity; media: SnapshotMediaItem[] }>();
for (const entry of logicalItems) {
const key = `${entry.identity.kind}:${entry.identity.title.toLocaleLowerCase('en-US')}`;
const title = byTitle.get(key) ?? { identity: entry.identity, media: [] };
title.media.push(entry.media);
byTitle.set(key, title);
}
const items: SnapshotTitle[] = [...byTitle.values()].map(({ identity, media }) => {
media.sort((left, right) => (left.seasonNumber ?? 0) - (right.seasonNumber ?? 0)
|| (left.episodeNumber ?? 0) - (right.episodeNumber ?? 0));
const first = media[0];
@@ -291,6 +374,10 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
slug: slugify(identity.title),
kind: identity.kind,
title: { en: identity.title },
...(identity.category ? { category: identity.category } : {}),
...(identity.categorySlug ? { categorySlug: identity.categorySlug } : {}),
...(identity.year ? { year: identity.year } : {}),
...(identity.releaseWindow ? { releaseWindow: identity.releaseWindow } : {}),
published,
playable: published,
mediaItemId: first.id,
@@ -301,6 +388,18 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
mediaItems: media,
};
});
for (const item of items) {
const identity = byTitle.get(`${item.kind}:${item.title.en.toLocaleLowerCase('en-US')}`)?.identity;
if (!identity?.titleDirectory) continue;
const source = await findThumbnail(path.join(root, identity.titleDirectory));
if (!source) continue;
const extension = path.extname(source).toLocaleLowerCase('en-US').replace('.jpeg', '.jpg');
item.posterUrl = `/images/archive/${item.id}${extension}`;
if (options.artworkRoot) {
await mkdir(options.artworkRoot, { recursive: true, mode: 0o750 });
await copyFile(source, path.join(options.artworkRoot, `${item.id}${extension}`));
}
}
items.sort((left, right) => left.title.en.localeCompare(right.title.en));
const generatedAt = new Date().toISOString();
const titles: PublicTitleDetail[] = items.map((item) => ({
@@ -309,8 +408,25 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
kind: item.kind,
// Filename-derived text is a safe temporary fallback until metadata matching supplies Persian.
name: { fa: item.title.fa ?? item.title.en, en: item.title.en },
...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
...(item.category ? { category: item.category } : {}),
...(item.categorySlug ? { categorySlug: item.categorySlug } : {}),
...(item.year ? { year: item.year } : {}),
...(item.releaseWindow ? { releaseWindow: item.releaseWindow } : {}),
playable: item.playable,
...(item.playable ? { resumeMediaItemId: item.resumeMediaItemId } : {}),
...(item.mediaItems[0]?.variants ? {
variants: item.mediaItems[0].variants.map((variant, index) => ({
id: variant.id,
label: variant.qualityLabel,
...(variant.width ? { width: variant.width } : {}),
...(variant.height ? { height: variant.height } : {}),
...(variant.videoCodec ? { videoCodec: variant.videoCodec } : {}),
compatibility: variant.compatibility,
available: variant.available,
isDefault: index === 0,
})),
} : {}),
synopsis: {},
...(item.kind === 'SERIES'
? { seasons: item.seasons.map((season) => ({ number: season.number, episodeCount: season.episodes.length })) }
@@ -324,6 +440,16 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
durationSeconds: media.durationSeconds,
compatibility: media.compatibility,
published: media.published,
variants: (media.variants ?? [media]).map((variant, index) => ({
id: variant.id,
label: variant.qualityLabel,
...(variant.width ? { width: variant.width } : {}),
...(variant.height ? { height: variant.height } : {}),
...(variant.videoCodec ? { videoCodec: variant.videoCodec } : {}),
compatibility: variant.compatibility,
available: variant.available,
isDefault: index === 0,
})),
})),
updatedAt: generatedAt,
}));
@@ -337,3 +463,39 @@ export function findMediaItem(snapshot: InventorySnapshot, idOrPath: string): Sn
return snapshot.items.flatMap((item) => item.mediaItems)
.find((media) => media.id === idOrPath || media.sourcePath === idOrPath);
}
export function findMediaVariant(
snapshot: InventorySnapshot,
mediaItemId: string,
variantId?: string,
): SnapshotMediaItem | undefined {
const media = findMediaItem(snapshot, mediaItemId);
if (!media || variantId === undefined) return media;
const variant = media.variants?.find((candidate) => candidate.id === variantId);
return variant ? { ...media, ...variant, id: media.id, ...(media.variants ? { variants: media.variants } : {}) } : undefined;
}
function compareVariants(left: SnapshotMediaVariant, right: SnapshotMediaVariant): number {
if (left.available !== right.available) return left.available ? -1 : 1;
const leftHeight = left.height ?? 0;
const rightHeight = right.height ?? 0;
const leftDistance = Math.abs(leftHeight - 720);
const rightDistance = Math.abs(rightHeight - 720);
if (leftDistance !== rightDistance) return leftDistance - rightDistance;
if ((leftHeight <= 720) !== (rightHeight <= 720)) return leftHeight <= 720 ? -1 : 1;
if (left.compatibility !== right.compatibility) return left.compatibility === 'COPY' ? -1 : 1;
return left.sourcePath.localeCompare(right.sourcePath);
}
async function findThumbnail(directory: string): Promise<string | undefined> {
for (const filename of ['thumbnail.jpg', 'thumbnail.jpeg', 'thumbnail.png', 'thumbnail.webp']) {
const candidate = path.join(directory, filename);
try {
await access(candidate);
return candidate;
} catch {
// Continue to the next supported local artwork extension.
}
}
return undefined;
}
+48 -11
View File
@@ -29,6 +29,7 @@ import {
import {
deterministicUuid,
findMediaItem,
findMediaVariant,
scanArchive,
type InventorySnapshot,
type SnapshotMediaItem,
@@ -111,12 +112,21 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
}
const result = await scanArchive({
archiveRoot,
...(output === undefined ? {} : { artworkRoot: path.join(path.dirname(output), 'artwork') }),
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
...(flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
onFile(relativePath, current) {
process.stderr.write(`[scan ${current}] ${relativePath}\n`);
},
});
// Direct scans stay portable; the long-running worker passes DATABASE_URL explicitly.
const databaseUrl = flag(arguments_, 'database');
const databaseSync = databaseUrl === undefined
? undefined
: await withDatabase(databaseUrl, (database) => syncCatalogSnapshot(database, result.catalog, {
authoritative: arguments_.flags.has('full'),
}));
if (databaseSync) applyMediaIdMap(result, databaseSync.mediaIdMap);
if (output !== undefined) {
await Promise.all([
writeJsonAtomic(output, result.catalog),
@@ -124,12 +134,6 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
]);
}
// Direct scans stay portable; the long-running worker passes DATABASE_URL explicitly.
const databaseUrl = flag(arguments_, 'database');
const databaseSync = databaseUrl === undefined
? undefined
: await withDatabase(databaseUrl, (database) => syncCatalogSnapshot(database, result.catalog));
if (output === undefined) process.stdout.write(`${JSON.stringify(result.catalog, null, 2)}\n`);
else {
process.stdout.write(`${JSON.stringify({
@@ -137,11 +141,26 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
...(inventoryOutput === undefined ? {} : { inventoryOutput: path.resolve(inventoryOutput) }),
titles: result.catalog.titles.length,
mediaItems: result.catalog.titles.reduce((sum, item) => sum + item.mediaItems.length, 0),
...(databaseSync === undefined ? {} : { databaseSync }),
...(databaseSync === undefined ? {} : { databaseSync: { titlesSeen: databaseSync.titlesSeen, mediaItemsSeen: databaseSync.mediaItemsSeen } }),
})}\n`);
}
}
function applyMediaIdMap(result: Awaited<ReturnType<typeof scanArchive>>, mediaIdMap: Record<string, string>): void {
for (const title of result.inventory.items) {
for (const media of title.mediaItems) media.id = mediaIdMap[media.id] ?? media.id;
title.mediaItemId = mediaIdMap[title.mediaItemId] ?? title.mediaItemId;
title.resumeMediaItemId = mediaIdMap[title.resumeMediaItemId] ?? title.resumeMediaItemId;
for (const season of title.seasons) {
for (const media of season.episodes) media.id = mediaIdMap[media.id] ?? media.id;
}
}
for (const title of result.catalog.titles) {
if (title.resumeMediaItemId) title.resumeMediaItemId = mediaIdMap[title.resumeMediaItemId] ?? title.resumeMediaItemId;
for (const media of title.mediaItems) media.id = mediaIdMap[media.id] ?? media.id;
}
}
async function withDatabase<T>(
connectionString: string,
action: (database: Database) => Promise<T>,
@@ -163,8 +182,9 @@ async function loadInventory(snapshotPath: string): Promise<InventorySnapshot> {
async function sourceSelection(
arguments_: Arguments,
archiveRoot: string,
): Promise<{ media: SnapshotMediaItem; sourcePath: string }> {
): Promise<{ media: SnapshotMediaItem; sourcePath: string; variantId: string }> {
const mediaItem = flag(arguments_, 'media-item');
const variantId = flag(arguments_, 'variant-id');
const requestedSource = flag(arguments_, 'source');
const inventoryPath = flag(arguments_, 'inventory', './data/inventory.json') ?? './data/inventory.json';
let inventory: InventorySnapshot | undefined;
@@ -175,9 +195,14 @@ async function sourceSelection(
}
const selected = mediaItem === undefined
? (requestedSource === undefined ? undefined : inventory === undefined ? undefined : findMediaItem(inventory, requestedSource))
: inventory === undefined ? undefined : findMediaItem(inventory, mediaItem);
: inventory === undefined ? undefined : findMediaVariant(inventory, mediaItem, variantId);
if (selected !== undefined) {
return { media: selected, sourcePath: await resolveInside(archiveRoot, path.join(archiveRoot, selected.sourcePath)) };
const selectedVariantId = selected.variants?.find((variant) => variant.sourcePath === selected.sourcePath)?.id ?? selected.id;
return {
media: selected,
variantId: selectedVariantId,
sourcePath: await resolveInside(archiveRoot, path.join(archiveRoot, selected.sourcePath)),
};
}
if (mediaItem !== undefined) throw new Error(`Media item was not found in ${inventoryPath}: ${mediaItem}`);
if (requestedSource === undefined) throw new Error('package requires --media-item ID or --source PATH');
@@ -192,12 +217,17 @@ async function sourceSelection(
const classification = classifyMedia(probe);
return {
sourcePath,
variantId: deterministicUuid(`variant:${relative}`),
media: {
id: deterministicUuid(`media:${relative}`),
titleId: deterministicUuid(`title:${relative}`),
kind: 'MOVIE',
sourcePath: relative,
durationSeconds: Number(probe.format.duration) || 0,
qualityLabel: probe.streams.find((stream) => stream.codec_type === 'video')?.height
? `${probe.streams.find((stream) => stream.codec_type === 'video')?.height}p`
: 'Source',
available: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class),
title: { en: path.basename(relative, path.extname(relative)) },
published: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class),
compatibility: classification.class,
@@ -232,6 +262,7 @@ async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): P
const preparing = async (error?: string): Promise<void> => {
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: error === undefined ? 'PREPARING' : 'FAILED',
playable: false,
@@ -304,6 +335,7 @@ async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): P
const fontUrls = fonts.map((font) => `/media/${generationPath}/fonts/${font.sha256}.${font.format}`);
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: 'READY',
playable: true,
@@ -378,6 +410,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
const generationId = deterministicUuid(`generation:compat-h264-v1:${fingerprint.digest}`);
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: 'PREPARING',
playable: false,
@@ -416,6 +449,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio');
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: 'READY',
playable: true,
@@ -442,6 +476,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
} catch (error) {
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: 'FAILED',
playable: false,
@@ -482,7 +517,8 @@ async function workCommand(arguments_: Arguments): Promise<void> {
if (command.type === 'media.playback.requested') {
await main([
'package', '--root', archiveRoot, '--cache', cacheRoot, '--inventory', inventory,
'--registry', registry, '--media-item', command.mediaItemId, ...mediaTools,
'--registry', registry, '--media-item', command.mediaItemId,
...(command.variantId ? ['--variant-id', command.variantId] : []), ...mediaTools,
], { protectedCacheKeys: () => running.protectedCacheGenerations() });
} else if (command.type === 'archive.scan.requested') {
if (databaseUrl !== undefined) {
@@ -491,6 +527,7 @@ async function workCommand(arguments_: Arguments): Promise<void> {
}
await main([
'scan', '--root', archiveRoot, '--output', catalog, '--inventory-output', inventory,
...(command.full ? ['--full'] : []),
...(databaseUrl === undefined ? [] : ['--database', databaseUrl]),
...mediaTools,
]);
+3 -1
View File
@@ -45,6 +45,7 @@ export interface RegistrySubtitleTrack {
export interface RegistryGeneration {
mediaItemId: string;
variantId?: string;
state: 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED';
generationId?: string;
manifestPath?: string;
@@ -104,7 +105,8 @@ export async function updateRegistry(
const current = previous.catch(() => undefined).then(async () => {
const registry = await readRegistry(key);
registry.updatedAt = new Date().toISOString();
const index = registry.packages.findIndex((entry) => entry.mediaItemId === mediaItemId);
const index = registry.packages.findIndex((entry) => entry.mediaItemId === mediaItemId
&& (entry.variantId ?? entry.mediaItemId) === (generation.variantId ?? generation.mediaItemId));
if (index < 0) registry.packages.push(generation);
else {
const current = registry.packages[index];
+9 -1
View File
@@ -4,7 +4,15 @@ import { deterministicUuid, parseMediaIdentity, shouldInspectSubtitleContent, sl
describe('catalog filename parsing', () => {
it('groups the supplied season folder and episode filename', () => {
expect(parseMediaIdentity('Mushoku Tensei S3/Mushoku Tensei S3 - 01.[SS][720p][MixFlixTop].mkv'))
.toEqual({ kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 1, episodeTitle: 'Episode 1' });
.toEqual({ kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 1, episodeTitle: 'Episode 1', titleDirectory: 'Mushoku Tensei S3' });
});
it('uses the title above a nested quality folder and derives archive taxonomy', () => {
expect(parseMediaIdentity('anime/2026/Summer/Mushoku Tensei S3/720/Mushoku Tensei S3 - 02.mkv'))
.toMatchObject({
kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 2,
category: 'Anime', categorySlug: 'anime', year: 2026, releaseWindow: 'SUMMER',
});
});
it('creates stable UUIDs and Unicode-safe slugs', () => {
+16
View File
@@ -12,6 +12,22 @@ import {
} from '../src/registry.js';
describe('local generation registry', () => {
it('keeps independent generations for quality variants of one episode', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-variants-'));
const registryPath = path.join(directory, 'package-registry.json');
const mediaItemId = '11111111-1111-4111-8111-111111111111';
for (const [variantId, generationId] of [
['22222222-2222-4222-8222-222222222222', '33333333-3333-4333-8333-333333333333'],
['44444444-4444-4444-8444-444444444444', '55555555-5555-4555-8555-555555555555'],
] as const) {
await updateRegistry(registryPath, mediaItemId, {
mediaItemId, variantId, generationId, state: 'READY', playable: true,
manifestPath: `/media/generations/${generationId}/master.m3u8`,
});
}
expect((await readRegistry(registryPath)).packages).toHaveLength(2);
});
it('atomically records API-loadable per-media status', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-'));
const registryPath = path.join(directory, 'package-registry.json');
+2 -1
View File
@@ -140,7 +140,7 @@ services:
CACHE_LOW_WATERMARK: ${CACHE_LOW_WATERMARK:-0.75}
MEDIA_WORKER_CONCURRENCY: ${JIT_REMUX_CONCURRENCY:-2}
volumes:
- ${ARCHIVE_ROOT:-./movies}:/archive:ro
- ${ARCHIVE_ROOT:-./archive}:/archive:ro
- ${CACHE_ROOT:-./data/cache}:/data/cache
- ${DERIVED_ROOT:-./data/derived}:/data/derived
- ${METADATA_ROOT:-./data/metadata}:/data/metadata
@@ -174,6 +174,7 @@ services:
volumes:
- ${CACHE_ROOT:-./data/cache}:/srv/easy-stream/cache:ro
- ${DERIVED_ROOT:-./data/derived}:/srv/easy-stream/derived:ro
- ${METADATA_ROOT:-./data/metadata}:/srv/easy-stream/metadata:ro
depends_on:
api:
condition: service_healthy
+3 -3
View File
@@ -29,15 +29,15 @@ The archive is never exposed over HTTP and is never writable by an application c
## Media lifecycle
1. The worker walks regular `.mkv` files under `ARCHIVE_ROOT`, rejects escaping symlinks, fingerprints the file, and records ffprobe stream metadata.
1. The worker walks regular `.mkv` files under `ARCHIVE_ROOT`, rejects escaping symlinks, derives category/year/release-window/title identity from the archive hierarchy, fingerprints each source variant, and records ffprobe stream metadata.
2. Sources are classified as `COPY`, `AUDIO_TRANSCODE`, `VIDEO_TRANSCODE`, `HOLD_HDR`, or `INVALID`.
3. Publication is allowed immediately for `COPY`; incompatible SDR media must finish its single H.264/AAC compatibility representation first. HDR is held in v1.
4. A cold playback request creates one packaging job per source/profile fingerprint. FFmpeg copies supported elementary streams to separate fragmented-MP4 HLS playlists.
4. A movie or episode may have several source-quality variants. Auto prefers 720p and viewers may change quality explicitly; a cold playback request creates one packaging job per selected source/profile fingerprint. FFmpeg copies supported elementary streams to separate fragmented-MP4 HLS playlists.
5. EVENT manifests may grow privately, but the registry remains `PREPARING` until HLS, subtitles, and generation-scoped fonts are all ready. The worker then publishes one complete `READY` record and finalizes immutable VOD playlists.
6. Compatible generations live in the 2 TB LRU cache. A playback session records a Redis lease and persistent access timestamp through the signed-cookie expiry; high/low-watermark sweeps skip leased, building, pinned, and recently touched entries. Encoded compatibility components live on separately sized durable storage and are never swept.
7. Eviction removes the matching package-registry entry so the next request regenerates it. Aged global font objects with no generation hardlinks are pruned during packaging sweeps.
There is deliberately no adaptive bitrate ladder. Slow connections or devices that reject the original resolution receive a clear compatibility/connection error rather than an undisclosed quality reduction.
There is deliberately no adaptive bitrate ladder. Quality changes are explicit, preserve the logical-media resume position, and create independent cache generations. Devices that reject every available representation receive a clear compatibility error.
## Trust boundaries
+3 -1
View File
@@ -39,7 +39,7 @@ The interactive script installs Caddy from its official Ubuntu repository, verif
- `/srv/easy-stream/archive`: read-only archive mount
- `/srv/easy-stream/cache`: 2 TB NVMe hot package cache
- `/srv/easy-stream/derived`: persistent compatibility components
- `/srv/easy-stream/metadata`: extracted subtitles, approved fonts, and cached metadata
- `/srv/easy-stream/metadata`: snapshots, copied archive artwork, extracted subtitles, approved fonts, and cached metadata
- Docker named volume `postgres-data`: PostgreSQL data (PostgreSQL 18 layout)
Use a dedicated unprivileged service account. Confirm the archive mount is read-only with `findmnt -no OPTIONS /srv/easy-stream/archive` before starting workers.
@@ -53,6 +53,8 @@ sudo install -d -o 1000 -g 1000 -m 0750 \
/srv/easy-stream/metadata
```
An administrator-initiated scan is authoritative: files no longer present in the mounted archive are removed from the public catalog without deleting historical database rows. After reorganizing archive paths, run a full scan before testing playback. Generated posters are served only from `/srv/easy-stream/metadata/artwork`; the gateway never receives an archive mount.
Use one public HTTPS origin for the SPA, API, and media routes. The v1 playback grant is a host-only, generation-path cookie, so a second media hostname will not receive it. A split hostname requires CDN-native edge authorization instead.
The API and media worker run as UID 1000, and the gateway's Nginx workers are configured to the same UID for read-only media access. Keep the bind mounts owned by that account rather than making generated media world-readable.
+13
View File
@@ -99,6 +99,19 @@ server {
include /etc/nginx/security-headers.conf;
}
location /images/archive/ {
limit_except GET HEAD { deny all; }
alias /srv/easy-stream/metadata/artwork/;
disable_symlinks on;
types {
image/jpeg jpg jpeg;
image/png png;
image/webp webp;
}
add_header Cache-Control "public, max-age=86400, stale-while-revalidate=604800" always;
include /etc/nginx/security-headers.conf;
}
location /healthz {
access_log off;
return 200 "ok\n";
+1 -1
View File
@@ -12,7 +12,7 @@
"dev": "corepack pnpm --parallel --filter @easy-stream/api --filter @easy-stream/worker --filter @easy-stream/web dev",
"test": "corepack pnpm -r --if-present test",
"typecheck": "corepack pnpm -r --if-present typecheck",
"scan:samples": "corepack pnpm --filter @easy-stream/worker scan -- --root ./movies --output ./data/metadata/catalog.json --inventory-output ./data/metadata/inventory.json",
"scan:samples": "corepack pnpm --filter @easy-stream/worker scan -- --root ./archive --output ./data/metadata/catalog.json --inventory-output ./data/metadata/inventory.json",
"migrate": "corepack pnpm --filter @easy-stream/database migrate",
"clean": "corepack pnpm -r --if-present clean"
},
+68 -7
View File
@@ -20,6 +20,36 @@ export const OptionalLocalizedTextSchema = Type.Object(
{ additionalProperties: false },
);
export const ReleaseWindowSchema = Type.Union([
Type.Literal('SPRING'),
Type.Literal('SUMMER'),
Type.Literal('FALL'),
Type.Literal('WINTER'),
Type.Literal('MOVIE'),
]);
const CatalogCompatibilityClassSchema = Type.Union([
Type.Literal('COPY'),
Type.Literal('AUDIO_TRANSCODE'),
Type.Literal('VIDEO_TRANSCODE'),
Type.Literal('HOLD_HDR'),
Type.Literal('INVALID'),
]);
export const MediaVariantSchema = Type.Object(
{
id: UuidSchema,
label: Type.String({ minLength: 1, maxLength: 64 }),
width: Type.Optional(Type.Integer({ minimum: 1 })),
height: Type.Optional(Type.Integer({ minimum: 1 })),
videoCodec: Type.Optional(Type.String({ maxLength: 64 })),
compatibility: CatalogCompatibilityClassSchema,
available: Type.Boolean(),
isDefault: Type.Boolean(),
},
{ additionalProperties: false },
);
export const CatalogCardSchema = Type.Object(
{
id: UuidSchema,
@@ -29,8 +59,12 @@ export const CatalogCardSchema = Type.Object(
posterUrl: Type.Optional(Type.String()),
backdropUrl: Type.Optional(Type.String()),
year: Type.Optional(Type.Integer()),
category: Type.Optional(Type.String({ maxLength: 100 })),
categorySlug: Type.Optional(Type.String({ maxLength: 100 })),
releaseWindow: Type.Optional(ReleaseWindowSchema),
playable: Type.Boolean(),
resumeMediaItemId: Type.Optional(UuidSchema),
variants: Type.Optional(Type.Array(MediaVariantSchema)),
},
{ additionalProperties: false },
);
@@ -43,14 +77,9 @@ export const MediaItemSummarySchema = Type.Object(
episodeNumber: Type.Optional(Type.Integer({ minimum: 0 })),
name: Type.Optional(OptionalLocalizedTextSchema),
durationSeconds: Type.Number({ minimum: 0 }),
compatibility: Type.Union([
Type.Literal('COPY'),
Type.Literal('AUDIO_TRANSCODE'),
Type.Literal('VIDEO_TRANSCODE'),
Type.Literal('HOLD_HDR'),
Type.Literal('INVALID'),
]),
compatibility: CatalogCompatibilityClassSchema,
published: Type.Boolean(),
variants: Type.Optional(Type.Array(MediaVariantSchema)),
},
{ additionalProperties: false },
);
@@ -72,8 +101,12 @@ export const TitleDetailSchema = Type.Object(
posterUrl: Type.Optional(Type.String()),
backdropUrl: Type.Optional(Type.String()),
year: Type.Optional(Type.Integer()),
category: Type.Optional(Type.String({ maxLength: 100 })),
categorySlug: Type.Optional(Type.String({ maxLength: 100 })),
releaseWindow: Type.Optional(ReleaseWindowSchema),
playable: Type.Boolean(),
resumeMediaItemId: Type.Optional(UuidSchema),
variants: Type.Optional(Type.Array(MediaVariantSchema)),
synopsis: OptionalLocalizedTextSchema,
seasons: Type.Optional(Type.Array(SeasonSummarySchema)),
mediaItems: Type.Array(MediaItemSummarySchema),
@@ -87,6 +120,9 @@ export const CatalogQuerySchema = Type.Object(
cursor: Type.Optional(Type.String({ maxLength: 512 })),
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, default: 24 })),
kind: Type.Optional(TitleKindSchema),
category: Type.Optional(Type.String({ maxLength: 100 })),
year: Type.Optional(Type.Integer({ minimum: 1888, maximum: 2200 })),
releaseWindow: Type.Optional(ReleaseWindowSchema),
},
{ additionalProperties: false },
);
@@ -107,6 +143,26 @@ export const CatalogResponseSchema = Type.Object(
{ additionalProperties: false },
);
export const CatalogSectionsQuerySchema = Type.Object(
{ limitPerSection: Type.Optional(Type.Integer({ minimum: 1, maximum: 40, default: 12 })) },
{ additionalProperties: false },
);
export const CatalogSectionSchema = Type.Object(
{
slug: Type.String(),
name: Type.String(),
items: Type.Array(CatalogCardSchema),
hasMore: Type.Boolean(),
},
{ additionalProperties: false },
);
export const CatalogSectionsResponseSchema = Type.Object(
{ sections: Type.Array(CatalogSectionSchema) },
{ additionalProperties: false },
);
export const SearchResponseSchema = Type.Object(
{ items: Type.Array(CatalogCardSchema) },
{ additionalProperties: false },
@@ -125,10 +181,15 @@ export type TitleKind = Static<typeof TitleKindSchema>;
export type MediaKind = Static<typeof MediaKindSchema>;
export type LocalizedText = Static<typeof LocalizedTextSchema>;
export type OptionalLocalizedText = Static<typeof OptionalLocalizedTextSchema>;
export type ReleaseWindow = Static<typeof ReleaseWindowSchema>;
export type MediaVariant = Static<typeof MediaVariantSchema>;
export type CatalogCard = Static<typeof CatalogCardSchema>;
export type MediaItemSummary = Static<typeof MediaItemSummarySchema>;
export type TitleDetail = Static<typeof TitleDetailSchema>;
export type CatalogQuery = Static<typeof CatalogQuerySchema>;
export type SearchQuery = Static<typeof SearchQuerySchema>;
export type CatalogResponse = Static<typeof CatalogResponseSchema>;
export type CatalogSectionsQuery = Static<typeof CatalogSectionsQuerySchema>;
export type CatalogSection = Static<typeof CatalogSectionSchema>;
export type CatalogSectionsResponse = Static<typeof CatalogSectionsResponseSchema>;
export type CatalogSnapshot = Static<typeof CatalogSnapshotSchema>;
+2
View File
@@ -8,6 +8,7 @@ export const MediaCommandSchema = Type.Union([
type: Type.Literal('media.playback.requested'),
sessionId: UuidSchema,
mediaItemId: UuidSchema,
variantId: Type.Optional(UuidSchema),
},
{ additionalProperties: false },
),
@@ -63,6 +64,7 @@ export const MediaPreparationResultSchema = Type.Object(
export const PackageRegistryEntrySchema = Type.Object(
{
mediaItemId: UuidSchema,
variantId: Type.Optional(UuidSchema),
state: Type.Union([
Type.Literal('PREPARING'),
Type.Literal('READY'),
+3
View File
@@ -61,6 +61,7 @@ export const SubtitleTrackSchema = Type.Object(
export const CreatePlaybackSessionSchema = Type.Object(
{
mediaItemId: UuidSchema,
variantId: Type.Optional(UuidSchema),
clientCapabilities: ClientCapabilitiesSchema,
},
{ additionalProperties: false },
@@ -70,6 +71,8 @@ export const PlaybackSessionSchema = Type.Object(
{
id: UuidSchema,
mediaItemId: UuidSchema,
variantId: Type.Optional(UuidSchema),
qualityLabel: Type.Optional(Type.String({ maxLength: 64 })),
state: PlaybackStateSchema,
manifestUrl: Type.Optional(Type.String()),
generationId: Type.Optional(UuidSchema),
@@ -7,6 +7,7 @@ describe('public contracts', () => {
expect(
Value.Check(CreatePlaybackSessionSchema, {
mediaItemId: '00000000-0000-4000-8000-000000000001',
variantId: '00000000-0000-4000-8000-000000000003',
clientCapabilities: {
mse: true,
nativeHls: false,
@@ -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
}
]
}
+56 -2
View File
@@ -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,
};
}
+26
View File
@@ -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'),
+6 -1
View File
@@ -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',
]);
});