feat: add lightweight SQLite showcase streaming edition
This commit is contained in:
20 files changed
+918
-11
No files matched your search
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "@easy-stream/showcase",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": { "node": ">=24" },
|
||||
"scripts": {
|
||||
"cli": "node --import tsx src/cli.ts",
|
||||
"build": "corepack pnpm exec esbuild src/cli.ts --bundle --platform=node --format=esm --packages=external --outfile=dist/cli.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@easy-stream/media": "workspace:*",
|
||||
"@fastify/static": "^8.3.0",
|
||||
"fastify": "^5.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"esbuild": "^0.25.12",
|
||||
"tsx": "^4.20.6",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env node
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { assertArchive, readConfig } from './config.js';
|
||||
import { openDatabase } from './database.js';
|
||||
import { prepareSelection, printStatus, pruneMedia } from './prepare.js';
|
||||
import { scanIntoDatabase } from './scan.js';
|
||||
import { startServer } from './server.js';
|
||||
|
||||
function value(args: string[], option: string): string | undefined {
|
||||
const index = args.indexOf(option);
|
||||
return index >= 0 ? args[index + 1] : undefined;
|
||||
}
|
||||
|
||||
function help(): void {
|
||||
console.log(`Easy Stream Showcase
|
||||
|
||||
Usage:
|
||||
pnpm showcase scan
|
||||
pnpm showcase prepare --all [--force]
|
||||
pnpm showcase prepare --title <slug> [--quality <label>] [--force]
|
||||
pnpm showcase status
|
||||
pnpm showcase prune [--apply]
|
||||
pnpm showcase serve
|
||||
|
||||
Configuration is read from .env.showcase (see .env.showcase.example).`);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const args = process.argv.slice(2).filter((argument) => argument !== '--');
|
||||
const command = args[0];
|
||||
if (!command || command === 'help' || command === '--help') return help();
|
||||
const config = await readConfig();
|
||||
await mkdir(config.dataRoot, { recursive: true, mode: 0o750 });
|
||||
const db = openDatabase(config.databasePath);
|
||||
try {
|
||||
if (command === 'scan') {
|
||||
await assertArchive(config);
|
||||
const result = await scanIntoDatabase(db, config);
|
||||
console.log(`Scanned ${result.titles} title(s), ${result.media} media item(s), ${result.variants} variant(s).`);
|
||||
} else if (command === 'prepare') {
|
||||
await assertArchive(config);
|
||||
const title = value(args, '--title');
|
||||
const quality = value(args, '--quality');
|
||||
const result = await prepareSelection(db, config, {
|
||||
all: args.includes('--all'),
|
||||
...(title ? { title } : {}),
|
||||
...(quality ? { quality } : {}),
|
||||
force: args.includes('--force'),
|
||||
});
|
||||
console.log(`Prepared ${result.ready}; failed ${result.failed}.`);
|
||||
if (result.failed) process.exitCode = 1;
|
||||
} else if (command === 'status') printStatus(db);
|
||||
else if (command === 'prune') await pruneMedia(db, config, args.includes('--apply'));
|
||||
else if (command === 'serve') await startServer(db, config);
|
||||
else throw new Error(`Unknown command: ${command}`);
|
||||
} finally {
|
||||
if (command !== 'serve') db.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(`Error: ${(error as Error).message}`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { access, readFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export interface ShowcaseConfig {
|
||||
archiveRoot: string;
|
||||
dataRoot: string;
|
||||
databasePath: string;
|
||||
mediaRoot: string;
|
||||
artworkRoot: string;
|
||||
webRoot: string;
|
||||
host: string;
|
||||
port: number;
|
||||
ffmpegPath: string;
|
||||
ffprobePath: string;
|
||||
}
|
||||
|
||||
const projectRoot = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
|
||||
async function loadEnvironment(filename = path.join(projectRoot, '.env.showcase')): Promise<void> {
|
||||
try {
|
||||
const source = await readFile(filename, 'utf8');
|
||||
for (const line of source.split(/\r?\n/u)) {
|
||||
const match = line.match(/^\s*([A-Z][A-Z0-9_]*)\s*=\s*(.*)\s*$/u);
|
||||
if (!match || process.env[match[1]!] !== undefined) continue;
|
||||
let value = match[2]!;
|
||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
process.env[match[1]!] = value;
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function readConfig(): Promise<ShowcaseConfig> {
|
||||
await loadEnvironment();
|
||||
const archiveRoot = path.resolve(projectRoot, process.env.SHOWCASE_ARCHIVE_ROOT ?? './archive');
|
||||
const dataRoot = path.resolve(projectRoot, process.env.SHOWCASE_DATA_ROOT ?? './data/showcase');
|
||||
const port = Number(process.env.SHOWCASE_PORT ?? 8080);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('SHOWCASE_PORT must be between 1 and 65535');
|
||||
const webRoot = fileURLToPath(new URL('../../web/dist/', import.meta.url));
|
||||
return {
|
||||
archiveRoot,
|
||||
dataRoot,
|
||||
databasePath: path.join(dataRoot, 'showcase.sqlite'),
|
||||
mediaRoot: path.join(dataRoot, 'media'),
|
||||
artworkRoot: path.join(dataRoot, 'artwork'),
|
||||
webRoot,
|
||||
host: process.env.SHOWCASE_HOST ?? '127.0.0.1',
|
||||
port,
|
||||
ffmpegPath: process.env.SHOWCASE_FFMPEG ?? 'ffmpeg',
|
||||
ffprobePath: process.env.SHOWCASE_FFPROBE ?? 'ffprobe',
|
||||
};
|
||||
}
|
||||
|
||||
export async function assertArchive(config: ShowcaseConfig): Promise<void> {
|
||||
await access(config.archiveRoot);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
export type PackageStatus = 'UNPREPARED' | 'PREPARING' | 'READY' | 'FAILED' | 'UNSUPPORTED';
|
||||
|
||||
export interface VariantRow {
|
||||
id: string;
|
||||
media_item_id: string;
|
||||
source_path: string;
|
||||
fingerprint: string;
|
||||
label: string;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
video_codec: string | null;
|
||||
compatibility: string;
|
||||
status: PackageStatus;
|
||||
generation_id: string | null;
|
||||
manifest_path: string | null;
|
||||
audio_tracks: string;
|
||||
subtitle_tracks: string;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export function openDatabase(filename: string): DatabaseSync {
|
||||
mkdirSync(path.dirname(filename), { recursive: true, mode: 0o750 });
|
||||
const db = new DatabaseSync(filename);
|
||||
db.exec(`
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA foreign_keys = ON;
|
||||
CREATE TABLE IF NOT EXISTS titles (
|
||||
id TEXT PRIMARY KEY, slug TEXT NOT NULL UNIQUE, kind TEXT NOT NULL,
|
||||
name_fa TEXT NOT NULL, name_en TEXT, synopsis_fa TEXT, synopsis_en TEXT,
|
||||
poster_url TEXT, category TEXT, category_slug TEXT, release_year INTEGER,
|
||||
release_window TEXT, updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS media_items (
|
||||
id TEXT PRIMARY KEY, title_id TEXT NOT NULL REFERENCES titles(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, season_number INTEGER, episode_number INTEGER,
|
||||
name_fa TEXT, name_en TEXT, duration_seconds REAL NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS variants (
|
||||
id TEXT PRIMARY KEY, media_item_id TEXT NOT NULL REFERENCES media_items(id) ON DELETE CASCADE,
|
||||
source_path TEXT NOT NULL UNIQUE, fingerprint TEXT NOT NULL, label TEXT NOT NULL,
|
||||
width INTEGER, height INTEGER, video_codec TEXT, compatibility TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'UNPREPARED', generation_id TEXT, manifest_path TEXT,
|
||||
audio_tracks TEXT NOT NULL DEFAULT '[]', subtitle_tracks TEXT NOT NULL DEFAULT '[]',
|
||||
error TEXT, updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS variants_media_status ON variants(media_item_id, status);
|
||||
`);
|
||||
return db;
|
||||
}
|
||||
|
||||
export function variantRows(db: DatabaseSync, where = '', values: Array<string | number | null> = []): VariantRow[] {
|
||||
return db.prepare(`SELECT * FROM variants ${where}`).all(...values) as unknown as VariantRow[];
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { opendir, rm } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import type { DatabaseSync } from 'node:sqlite';
|
||||
import {
|
||||
classifyMedia,
|
||||
extractAndStoreFonts,
|
||||
extractSubtitleVariants,
|
||||
fingerprintSource,
|
||||
languageDisplayName,
|
||||
normalizeStreamLanguage,
|
||||
packageProgressiveHls,
|
||||
prepareCompatibilityHls,
|
||||
probeMedia,
|
||||
publishGenerationFonts,
|
||||
type SourceFingerprint,
|
||||
} from '@easy-stream/media';
|
||||
import { deterministicUuid } from '../../worker/src/catalog.js';
|
||||
import type { ShowcaseConfig } from './config.js';
|
||||
import type { VariantRow } from './database.js';
|
||||
|
||||
export interface PrepareSelection { all?: boolean; title?: string; quality?: string; force?: boolean }
|
||||
|
||||
function selectedRows(db: DatabaseSync, selection: PrepareSelection): VariantRow[] {
|
||||
const values: string[] = [];
|
||||
const clauses = ["v.compatibility NOT IN ('HOLD_HDR','INVALID')"];
|
||||
if (!selection.all) {
|
||||
if (!selection.title) throw new Error('Choose --all or --title <slug>');
|
||||
clauses.push('t.slug = ?');
|
||||
values.push(selection.title);
|
||||
}
|
||||
if (selection.quality) {
|
||||
clauses.push('lower(v.label) = lower(?)');
|
||||
values.push(selection.quality);
|
||||
}
|
||||
return db.prepare(`SELECT v.* FROM variants v JOIN media_items m ON m.id=v.media_item_id JOIN titles t ON t.id=m.title_id WHERE ${clauses.join(' AND ')} ORDER BY t.name_en,m.season_number,m.episode_number,v.height`).all(...values) as unknown as VariantRow[];
|
||||
}
|
||||
|
||||
function mediaUrl(config: ShowcaseConfig, filename: string): string {
|
||||
return `/media/${path.relative(config.mediaRoot, filename).split(path.sep).join('/')}`;
|
||||
}
|
||||
|
||||
async function prepareOne(db: DatabaseSync, config: ShowcaseConfig, row: VariantRow, force: boolean): Promise<void> {
|
||||
const original = JSON.parse(row.fingerprint) as SourceFingerprint;
|
||||
const sourcePath = path.join(config.archiveRoot, row.source_path);
|
||||
const generation = `showcase-v1-${original.digest.slice(0, 32)}`;
|
||||
const generationDirectory = path.join(config.mediaRoot, 'generations', generation);
|
||||
if (force) await rm(generationDirectory, { recursive: true, force: true });
|
||||
db.prepare("UPDATE variants SET status='PREPARING',error=NULL,updated_at=? WHERE id=?").run(new Date().toISOString(), row.id);
|
||||
try {
|
||||
const probe = await probeMedia(sourcePath, { ffprobePath: config.ffprobePath });
|
||||
const fingerprint = await fingerprintSource(config.archiveRoot, sourcePath, original.edgeBytes);
|
||||
if (fingerprint.digest !== original.digest) throw new Error('Source changed since scan; run `pnpm showcase scan` first');
|
||||
const classification = classifyMedia(probe);
|
||||
if (classification.class === 'HOLD_HDR' || classification.class === 'INVALID') throw new Error(`Unsupported source: ${classification.class}`);
|
||||
const packaged = classification.class === 'VIDEO_TRANSCODE'
|
||||
? await prepareCompatibilityHls({ archiveRoot: config.archiveRoot, derivedRoot: config.mediaRoot, sourcePath, fingerprint, probe, classification, generation, ffmpegPath: config.ffmpegPath, ffprobePath: config.ffprobePath })
|
||||
: await packageProgressiveHls({ archiveRoot: config.archiveRoot, cacheRoot: config.mediaRoot, sourcePath, fingerprint, probe, classification, generation, ffmpegPath: config.ffmpegPath, ffprobePath: config.ffprobePath });
|
||||
const subtitles = await extractSubtitleVariants(sourcePath, probe, { archiveRoot: config.archiveRoot, outputRoot: config.mediaRoot, generation: `generations/${generation}`, ffmpegPath: config.ffmpegPath });
|
||||
const storedFonts = await extractAndStoreFonts(sourcePath, probe, { archiveRoot: config.archiveRoot, fontRoot: path.join(config.mediaRoot, 'assets', 'fonts'), ffmpegPath: config.ffmpegPath });
|
||||
const fonts = await publishGenerationFonts(storedFonts, config.mediaRoot, packaged.outputDirectory);
|
||||
const fontUrls = fonts.map((font) => mediaUrl(config, font.path));
|
||||
const subtitleTracks = subtitles.map((track) => ({
|
||||
id: deterministicUuid(`showcase:subtitle:${row.id}:${track.streamIndex}`),
|
||||
language: track.language,
|
||||
label: languageDisplayName(track.language),
|
||||
default: track.default,
|
||||
forced: track.forced,
|
||||
assUrl: mediaUrl(config, track.assPath),
|
||||
vttUrl: mediaUrl(config, track.vttPath),
|
||||
fontUrls,
|
||||
}));
|
||||
const audioTracks = classification.audioStreamIndexes.map((index, position) => {
|
||||
const stream = probe.streams.find((candidate) => candidate.index === index)!;
|
||||
const language = normalizeStreamLanguage(stream);
|
||||
return { id: deterministicUuid(`showcase:audio:${row.id}:${index}`), language, label: languageDisplayName(language), default: position === 0 };
|
||||
});
|
||||
db.prepare(`UPDATE variants SET status='READY',generation_id=?,manifest_path=?,audio_tracks=?,subtitle_tracks=?,error=NULL,updated_at=? WHERE id=?`)
|
||||
.run(generation, mediaUrl(config, packaged.masterPlaylist), JSON.stringify(audioTracks), JSON.stringify(subtitleTracks), new Date().toISOString(), row.id);
|
||||
} catch (error) {
|
||||
db.prepare("UPDATE variants SET status='FAILED',error=?,updated_at=? WHERE id=?").run((error as Error).message.slice(0, 2000), new Date().toISOString(), row.id);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareSelection(db: DatabaseSync, config: ShowcaseConfig, selection: PrepareSelection): Promise<{ ready: number; failed: number }> {
|
||||
const rows = selectedRows(db, selection);
|
||||
if (!rows.length) throw new Error('No matching preparable variants. Run scan and check the title slug/quality.');
|
||||
let ready = 0;
|
||||
let failed = 0;
|
||||
for (const [index, row] of rows.entries()) {
|
||||
process.stdout.write(`[${index + 1}/${rows.length}] ${row.source_path} ... `);
|
||||
try {
|
||||
await prepareOne(db, config, row, selection.force === true);
|
||||
ready += 1;
|
||||
console.log('ready');
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
console.error(`failed: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
return { ready, failed };
|
||||
}
|
||||
|
||||
export function printStatus(db: DatabaseSync): void {
|
||||
const rows = db.prepare('SELECT status,count(*) AS count FROM variants GROUP BY status ORDER BY status').all() as Array<{ status: string; count: number }>;
|
||||
const failures = db.prepare("SELECT source_path,error FROM variants WHERE status='FAILED' ORDER BY updated_at DESC LIMIT 10").all() as Array<{ source_path: string; error: string }>;
|
||||
if (!rows.length) console.log('No archive entries. Run `pnpm showcase scan`.');
|
||||
else rows.forEach((row) => console.log(`${row.status.padEnd(12)} ${row.count}`));
|
||||
failures.forEach((row) => console.log(`FAILED ${row.source_path}: ${row.error}`));
|
||||
}
|
||||
|
||||
export async function pruneMedia(db: DatabaseSync, config: ShowcaseConfig, apply: boolean): Promise<string[]> {
|
||||
const referenced = new Set((db.prepare("SELECT generation_id FROM variants WHERE status='READY' AND generation_id IS NOT NULL").all() as Array<{ generation_id: string }>).map((row) => row.generation_id));
|
||||
const root = path.join(config.mediaRoot, 'generations');
|
||||
const stale: string[] = [];
|
||||
try {
|
||||
for await (const entry of await opendir(root)) {
|
||||
if (entry.isDirectory() && !referenced.has(entry.name)) stale.push(entry.name);
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
for (const generation of stale) {
|
||||
console.log(`${apply ? 'remove' : 'would remove'} ${generation}`);
|
||||
if (apply) await rm(path.join(root, generation), { recursive: true, force: true });
|
||||
}
|
||||
if (!stale.length) console.log('Nothing to prune.');
|
||||
return stale;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import type { DatabaseSync } from 'node:sqlite';
|
||||
import { scanArchive, parseMediaIdentity, slugify, type SnapshotTitle } from '../../worker/src/catalog.js';
|
||||
import type { ShowcaseConfig } from './config.js';
|
||||
|
||||
interface SidecarMetadata {
|
||||
title?: string;
|
||||
titleFa?: string;
|
||||
titleEn?: string;
|
||||
synopsis?: string;
|
||||
synopsisFa?: string;
|
||||
synopsisEn?: string;
|
||||
category?: string;
|
||||
year?: number;
|
||||
releaseWindow?: string;
|
||||
}
|
||||
|
||||
async function sidecar(config: ShowcaseConfig, title: SnapshotTitle): Promise<SidecarMetadata> {
|
||||
const source = title.mediaItems[0]?.variants?.[0]?.sourcePath ?? title.mediaItems[0]?.sourcePath;
|
||||
if (!source) return {};
|
||||
const identity = parseMediaIdentity(source);
|
||||
if (!identity.titleDirectory) return {};
|
||||
try {
|
||||
const value = JSON.parse(await readFile(path.join(config.archiveRoot, identity.titleDirectory, 'metadata.json'), 'utf8')) as SidecarMetadata;
|
||||
return typeof value === 'object' && value !== null ? value : {};
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {};
|
||||
throw new Error(`Invalid metadata.json for ${title.slug}: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function text(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
export async function scanIntoDatabase(db: DatabaseSync, config: ShowcaseConfig): Promise<{ titles: number; media: number; variants: number }> {
|
||||
const result = await scanArchive({
|
||||
archiveRoot: config.archiveRoot,
|
||||
artworkRoot: config.artworkRoot,
|
||||
ffmpegPath: config.ffmpegPath,
|
||||
ffprobePath: config.ffprobePath,
|
||||
onFile: (filename, number) => process.stdout.write(`\r[${number}] ${filename.slice(0, 100).padEnd(100)}`),
|
||||
});
|
||||
if (result.inventory.items.length) process.stdout.write('\n');
|
||||
const metadata = new Map<string, SidecarMetadata>();
|
||||
for (const title of result.inventory.items) metadata.set(title.id, await sidecar(config, title));
|
||||
|
||||
db.exec('BEGIN IMMEDIATE; CREATE TEMP TABLE IF NOT EXISTS seen_titles(id TEXT PRIMARY KEY); DELETE FROM seen_titles; CREATE TEMP TABLE IF NOT EXISTS seen_media(id TEXT PRIMARY KEY); DELETE FROM seen_media; CREATE TEMP TABLE IF NOT EXISTS seen_variants(id TEXT PRIMARY KEY); DELETE FROM seen_variants;');
|
||||
try {
|
||||
const markTitle = db.prepare('INSERT OR IGNORE INTO seen_titles VALUES (?)');
|
||||
const markMedia = db.prepare('INSERT OR IGNORE INTO seen_media VALUES (?)');
|
||||
const markVariant = db.prepare('INSERT OR IGNORE INTO seen_variants VALUES (?)');
|
||||
const upsertTitle = db.prepare(`INSERT INTO titles
|
||||
(id,slug,kind,name_fa,name_en,synopsis_fa,synopsis_en,poster_url,category,category_slug,release_year,release_window,updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET
|
||||
slug=excluded.slug,kind=excluded.kind,name_fa=excluded.name_fa,name_en=excluded.name_en,
|
||||
synopsis_fa=excluded.synopsis_fa,synopsis_en=excluded.synopsis_en,poster_url=excluded.poster_url,
|
||||
category=excluded.category,category_slug=excluded.category_slug,release_year=excluded.release_year,
|
||||
release_window=excluded.release_window,updated_at=excluded.updated_at`);
|
||||
const upsertMedia = db.prepare(`INSERT INTO media_items
|
||||
(id,title_id,kind,season_number,episode_number,name_fa,name_en,duration_seconds)
|
||||
VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET title_id=excluded.title_id,kind=excluded.kind,
|
||||
season_number=excluded.season_number,episode_number=excluded.episode_number,name_fa=excluded.name_fa,
|
||||
name_en=excluded.name_en,duration_seconds=excluded.duration_seconds`);
|
||||
const upsertVariant = db.prepare(`INSERT INTO variants
|
||||
(id,media_item_id,source_path,fingerprint,label,width,height,video_codec,compatibility,status,updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET
|
||||
media_item_id=excluded.media_item_id,source_path=excluded.source_path,label=excluded.label,width=excluded.width,
|
||||
height=excluded.height,video_codec=excluded.video_codec,compatibility=excluded.compatibility,
|
||||
status=CASE WHEN variants.fingerprint=excluded.fingerprint THEN variants.status ELSE excluded.status END,
|
||||
generation_id=CASE WHEN variants.fingerprint=excluded.fingerprint THEN variants.generation_id ELSE NULL END,
|
||||
manifest_path=CASE WHEN variants.fingerprint=excluded.fingerprint THEN variants.manifest_path ELSE NULL END,
|
||||
audio_tracks=CASE WHEN variants.fingerprint=excluded.fingerprint THEN variants.audio_tracks ELSE '[]' END,
|
||||
subtitle_tracks=CASE WHEN variants.fingerprint=excluded.fingerprint THEN variants.subtitle_tracks ELSE '[]' END,
|
||||
error=CASE WHEN variants.fingerprint=excluded.fingerprint THEN variants.error ELSE NULL END,
|
||||
fingerprint=excluded.fingerprint,updated_at=excluded.updated_at`);
|
||||
|
||||
for (const title of result.inventory.items) {
|
||||
const meta = metadata.get(title.id) ?? {};
|
||||
const nameEn = text(meta.titleEn ?? meta.title) ?? title.title.en;
|
||||
const nameFa = text(meta.titleFa) ?? nameEn;
|
||||
const category = text(meta.category) ?? title.category ?? null;
|
||||
const slug = text(meta.titleEn ?? meta.title) ? slugify(nameEn) : title.slug;
|
||||
markTitle.run(title.id);
|
||||
upsertTitle.run(title.id, slug, title.kind, nameFa, nameEn, text(meta.synopsisFa ?? meta.synopsis), text(meta.synopsisEn), title.posterUrl ?? null, category, category ? slugify(category) : null, meta.year ?? title.year ?? null, text(meta.releaseWindow)?.toUpperCase() ?? title.releaseWindow ?? null, result.inventory.generatedAt);
|
||||
for (const media of title.mediaItems) {
|
||||
markMedia.run(media.id);
|
||||
upsertMedia.run(media.id, title.id, media.kind, media.seasonNumber ?? null, media.episodeNumber ?? null, media.title.fa ?? media.title.en, media.title.en, media.durationSeconds);
|
||||
for (const variant of media.variants ?? [media]) {
|
||||
const unsupported = variant.compatibility === 'HOLD_HDR' || variant.compatibility === 'INVALID';
|
||||
markVariant.run(variant.id);
|
||||
upsertVariant.run(variant.id, media.id, variant.sourcePath, JSON.stringify(variant.fingerprint), variant.qualityLabel, variant.width ?? null, variant.height ?? null, variant.videoCodec ?? null, variant.compatibility, unsupported ? 'UNSUPPORTED' : 'UNPREPARED', result.inventory.generatedAt);
|
||||
}
|
||||
}
|
||||
}
|
||||
db.exec('DELETE FROM variants WHERE id NOT IN (SELECT id FROM seen_variants); DELETE FROM media_items WHERE id NOT IN (SELECT id FROM seen_media); DELETE FROM titles WHERE id NOT IN (SELECT id FROM seen_titles); COMMIT;');
|
||||
} catch (error) {
|
||||
db.exec('ROLLBACK;');
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
titles: Number((db.prepare('SELECT count(*) AS count FROM titles').get() as { count: number }).count),
|
||||
media: Number((db.prepare('SELECT count(*) AS count FROM media_items').get() as { count: number }).count),
|
||||
variants: Number((db.prepare('SELECT count(*) AS count FROM variants').get() as { count: number }).count),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import type { ShowcaseConfig } from './config.js';
|
||||
import { openDatabase } from './database.js';
|
||||
import { createServer } from './server.js';
|
||||
|
||||
const databases: ReturnType<typeof openDatabase>[] = [];
|
||||
afterEach(() => databases.splice(0).forEach((database) => database.close()));
|
||||
|
||||
describe('showcase server', () => {
|
||||
it('only exposes prepared media and creates immediate guest playback', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-showcase-'));
|
||||
const webRoot = path.join(root, 'web');
|
||||
await mkdir(webRoot);
|
||||
await writeFile(path.join(webRoot, 'index.html'), '<h1>showcase</h1>');
|
||||
const config: ShowcaseConfig = {
|
||||
archiveRoot: path.join(root, 'archive'), dataRoot: root, databasePath: path.join(root, 'db.sqlite'),
|
||||
mediaRoot: path.join(root, 'media'), artworkRoot: path.join(root, 'artwork'), webRoot,
|
||||
host: '127.0.0.1', port: 8080, ffmpegPath: 'ffmpeg', ffprobePath: 'ffprobe',
|
||||
};
|
||||
const db = openDatabase(config.databasePath);
|
||||
databases.push(db);
|
||||
db.prepare('INSERT INTO titles VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)').run('title-1', 'demo', 'MOVIE', 'Demo', 'Demo', null, null, null, 'Anime', 'anime', 2026, 'SUMMER', new Date().toISOString());
|
||||
db.prepare('INSERT INTO media_items VALUES (?,?,?,?,?,?,?,?)').run('media-1', 'title-1', 'MOVIE', null, null, 'Demo', 'Demo', 60);
|
||||
db.prepare('INSERT INTO variants VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run('variant-1', 'media-1', 'demo.mkv', '{}', '720p', 1280, 720, 'h264', 'COPY', 'READY', 'generation-1', '/media/generations/generation-1/master.m3u8', '[]', '[]', null, new Date().toISOString());
|
||||
const app = await createServer(db, config);
|
||||
const catalog = await app.inject({ method: 'GET', url: '/api/v1/catalog/sections' });
|
||||
expect(catalog.statusCode).toBe(200);
|
||||
expect(catalog.json().sections[0].items[0].slug).toBe('demo');
|
||||
const playback = await app.inject({ method: 'POST', url: '/api/v1/playback-sessions', payload: { mediaItemId: 'media-1' } });
|
||||
expect(playback.statusCode).toBe(200);
|
||||
expect(playback.json()).toMatchObject({ state: 'READY', manifestUrl: '/media/generations/generation-1/master.m3u8' });
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { access, mkdir } from 'node:fs/promises';
|
||||
import type { DatabaseSync } from 'node:sqlite';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import Fastify from 'fastify';
|
||||
import type { ShowcaseConfig } from './config.js';
|
||||
import type { VariantRow } from './database.js';
|
||||
|
||||
interface TitleRow {
|
||||
id: string; slug: string; kind: string; name_fa: string; name_en: string | null;
|
||||
synopsis_fa: string | null; synopsis_en: string | null; poster_url: string | null;
|
||||
category: string | null; category_slug: string | null; release_year: number | null;
|
||||
release_window: string | null; updated_at: string;
|
||||
}
|
||||
interface MediaRow { id: string; title_id: string; kind: string; season_number: number | null; episode_number: number | null; name_fa: string | null; name_en: string | null; duration_seconds: number }
|
||||
|
||||
function readyVariants(db: DatabaseSync, mediaId: string): VariantRow[] {
|
||||
return db.prepare("SELECT * FROM variants WHERE media_item_id=? AND status='READY' ORDER BY abs(coalesce(height,720)-720),height").all(mediaId) as unknown as VariantRow[];
|
||||
}
|
||||
|
||||
function variantJson(row: VariantRow, index: number) {
|
||||
return { id: row.id, label: row.label, width: row.width ?? undefined, height: row.height ?? undefined, videoCodec: row.video_codec ?? undefined, compatibility: row.compatibility, available: true, isDefault: index === 0 };
|
||||
}
|
||||
|
||||
function titleJson(db: DatabaseSync, title: TitleRow, detail = false) {
|
||||
const media = db.prepare('SELECT * FROM media_items WHERE title_id=? ORDER BY coalesce(season_number,0),coalesce(episode_number,0)').all(title.id) as unknown as MediaRow[];
|
||||
const playable = media.map((item) => ({ item, variants: readyVariants(db, item.id) })).filter((entry) => entry.variants.length);
|
||||
const first = playable[0];
|
||||
const seasons = new Set(playable.map(({ item }) => item.season_number).filter((value) => value !== null));
|
||||
const base = {
|
||||
id: title.id,
|
||||
slug: title.slug,
|
||||
kind: title.kind,
|
||||
name: { fa: title.name_fa, en: title.name_en ?? undefined },
|
||||
title: { fa: title.name_fa, en: title.name_en ?? undefined },
|
||||
synopsis: { fa: title.synopsis_fa ?? undefined, en: title.synopsis_en ?? undefined },
|
||||
posterUrl: title.poster_url ?? undefined,
|
||||
category: title.category ?? undefined,
|
||||
categorySlug: title.category_slug ?? undefined,
|
||||
year: title.release_year ?? undefined,
|
||||
releaseWindow: title.release_window ?? undefined,
|
||||
playable: Boolean(first),
|
||||
resumeMediaItemId: first?.item.id,
|
||||
mediaItemId: first?.item.id,
|
||||
variants: first?.variants.map(variantJson) ?? [],
|
||||
runtimeSeconds: title.kind === 'MOVIE' ? first?.item.duration_seconds : undefined,
|
||||
seasonCount: title.kind === 'SERIES' ? seasons.size : undefined,
|
||||
episodeCount: title.kind === 'SERIES' ? playable.length : undefined,
|
||||
updatedAt: title.updated_at,
|
||||
};
|
||||
if (!detail) return base;
|
||||
return {
|
||||
...base,
|
||||
mediaItems: playable.map(({ item, variants }) => ({
|
||||
id: item.id, mediaItemId: item.id, kind: item.kind,
|
||||
seasonNumber: item.season_number ?? undefined, episodeNumber: item.episode_number ?? undefined,
|
||||
name: { fa: item.name_fa ?? undefined, en: item.name_en ?? undefined },
|
||||
durationSeconds: item.duration_seconds, published: true, variants: variants.map(variantJson),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function visibleTitles(db: DatabaseSync): TitleRow[] {
|
||||
return db.prepare(`SELECT DISTINCT t.* FROM titles t JOIN media_items m ON m.title_id=t.id JOIN variants v ON v.media_item_id=m.id WHERE v.status='READY' ORDER BY t.name_en,t.name_fa`).all() as unknown as TitleRow[];
|
||||
}
|
||||
|
||||
export async function createServer(db: DatabaseSync, config: ShowcaseConfig) {
|
||||
await access(config.webRoot).catch(() => { throw new Error('Viewer build is missing. Run `pnpm showcase:build` first.'); });
|
||||
await Promise.all([mkdir(config.mediaRoot, { recursive: true }), mkdir(config.artworkRoot, { recursive: true })]);
|
||||
const app = Fastify({ logger: true });
|
||||
await app.register(fastifyStatic, { root: config.webRoot, prefix: '/', wildcard: false });
|
||||
await app.register(fastifyStatic, { root: config.mediaRoot, prefix: '/media/', decorateReply: false, setHeaders(response, filename) {
|
||||
if (filename.endsWith('.m3u8')) response.setHeader('content-type', 'application/vnd.apple.mpegurl');
|
||||
else if (filename.endsWith('.m4s') || filename.endsWith('.mp4')) response.setHeader('content-type', 'video/mp4');
|
||||
response.setHeader('cache-control', filename.endsWith('.m3u8') ? 'no-cache' : 'public, max-age=31536000, immutable');
|
||||
} });
|
||||
await app.register(fastifyStatic, { root: config.artworkRoot, prefix: '/images/archive/', decorateReply: false });
|
||||
|
||||
app.get('/healthz', async () => ({ status: 'ok', time: new Date().toISOString(), edition: 'showcase' }));
|
||||
app.get<{ Querystring: { limit?: string; category?: string } }>('/api/v1/catalog', async (request) => {
|
||||
const all = visibleTitles(db).filter((title) => !request.query.category || title.category_slug === request.query.category);
|
||||
const limit = Math.min(100, Math.max(1, Number(request.query.limit) || 40));
|
||||
return { items: all.slice(0, limit).map((title) => titleJson(db, title)), total: all.length };
|
||||
});
|
||||
app.get<{ Querystring: { limitPerSection?: string } }>('/api/v1/catalog/sections', async (request) => {
|
||||
const limit = Math.min(40, Math.max(1, Number(request.query.limitPerSection) || 12));
|
||||
const groups = new Map<string, { name: string; items: TitleRow[] }>();
|
||||
for (const title of visibleTitles(db)) {
|
||||
const slug = title.category_slug ?? 'showcase';
|
||||
const group = groups.get(slug) ?? { name: title.category ?? 'Showcase', items: [] };
|
||||
group.items.push(title);
|
||||
groups.set(slug, group);
|
||||
}
|
||||
return { sections: [...groups].map(([slug, group]) => ({ slug, name: group.name, items: group.items.slice(0, limit).map((title) => titleJson(db, title)), hasMore: group.items.length > limit })) };
|
||||
});
|
||||
app.get<{ Params: { slug: string } }>('/api/v1/titles/:slug', async (request, reply) => {
|
||||
const title = db.prepare('SELECT * FROM titles WHERE slug=?').get(request.params.slug) as unknown as TitleRow | undefined;
|
||||
if (!title || !visibleTitles(db).some((candidate) => candidate.id === title.id)) return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Title not found' } });
|
||||
return titleJson(db, title, true);
|
||||
});
|
||||
app.post<{ Body: { mediaItemId?: string; variantId?: string } }>('/api/v1/playback-sessions', async (request, reply) => {
|
||||
const mediaId = request.body?.mediaItemId;
|
||||
if (!mediaId) return reply.code(400).send({ error: { code: 'VALIDATION_ERROR', message: 'mediaItemId is required' } });
|
||||
const rows = readyVariants(db, mediaId);
|
||||
const variant = request.body.variantId ? rows.find((row) => row.id === request.body.variantId) : rows[0];
|
||||
const media = db.prepare('SELECT * FROM media_items WHERE id=?').get(mediaId) as unknown as MediaRow | undefined;
|
||||
if (!variant || !media) return reply.code(404).send({ error: { code: 'NOT_PREPARED', message: 'This media is not prepared for playback' } });
|
||||
return {
|
||||
id: randomUUID(), state: 'READY', mediaItemId: mediaId, variantId: variant.id,
|
||||
qualityLabel: variant.label, manifestUrl: variant.manifest_path, generationId: variant.generation_id,
|
||||
durationSeconds: media.duration_seconds, audioTracks: JSON.parse(variant.audio_tracks),
|
||||
subtitleTracks: JSON.parse(variant.subtitle_tracks), pollAfterMs: 1000,
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
|
||||
};
|
||||
});
|
||||
app.post('/api/v1/client-events', async (_request, reply) => reply.code(202).send({ ok: true }));
|
||||
app.setNotFoundHandler(async (request, reply) => {
|
||||
if (request.url.startsWith('/api/') || request.url.startsWith('/media/') || request.url.startsWith('/images/')) return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } });
|
||||
return reply.type('text/html').sendFile('index.html', config.webRoot);
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
export async function startServer(db: DatabaseSync, config: ShowcaseConfig): Promise<void> {
|
||||
const app = await createServer(db, config);
|
||||
await app.listen({ host: config.host, port: config.port });
|
||||
console.log(`Easy Stream Showcase: http://${config.host}:${config.port}`);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2024"],
|
||||
"types": ["node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { useSpatialNavigation } from '@/composables/spatial-navigation'
|
||||
|
||||
const appRoot = ref<HTMLElement | null>(null)
|
||||
const router = useRouter()
|
||||
const showcase = import.meta.env.VITE_APP_EDITION === 'showcase'
|
||||
useSpatialNavigation(appRoot, { onBack: () => router.back() })
|
||||
</script>
|
||||
|
||||
@@ -23,8 +24,10 @@ useSpatialNavigation(appRoot, { onBack: () => router.back() })
|
||||
<BrandMark />
|
||||
<span>Easy Stream</span>
|
||||
</span>
|
||||
<span class="footer-dot" aria-hidden="true">•</span>
|
||||
<RouterLink to="/admin">Admin</RouterLink>
|
||||
<template v-if="!showcase">
|
||||
<span class="footer-dot" aria-hidden="true">•</span>
|
||||
<RouterLink to="/admin">Admin</RouterLink>
|
||||
</template>
|
||||
</footer>
|
||||
<PlayerShell />
|
||||
</div>
|
||||
|
||||
@@ -10,6 +10,7 @@ const ui = useUiStore()
|
||||
const router = useRouter()
|
||||
const { language, t } = useI18n()
|
||||
const searchTerm = ref('')
|
||||
const showcase = import.meta.env.VITE_APP_EDITION === 'showcase'
|
||||
|
||||
function submitSearch() {
|
||||
const query = searchTerm.value.trim()
|
||||
@@ -34,12 +35,12 @@ function toggleLanguage() {
|
||||
<RouterLink class="nav-link focus-ring" data-tv-focus data-focus-id="nav-catalog" to="/">
|
||||
{{ t('home') }}
|
||||
</RouterLink>
|
||||
<RouterLink class="nav-link focus-ring" data-tv-focus data-focus-id="nav-search" to="/search">
|
||||
<RouterLink v-if="!showcase" class="nav-link focus-ring" data-tv-focus data-focus-id="nav-search" to="/search">
|
||||
{{ t('search') }}
|
||||
</RouterLink>
|
||||
</nav>
|
||||
|
||||
<form class="header-search" role="search" @submit.prevent="submitSearch">
|
||||
<form v-if="!showcase" class="header-search" role="search" @submit.prevent="submitSearch">
|
||||
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="m21 21-4.35-4.35m2.35-5.65a8 8 0 1 1-16 0 8 8 0 0 1 16 0Z" /></svg>
|
||||
<input
|
||||
v-model="searchTerm"
|
||||
|
||||
Vendored
+1
@@ -1,6 +1,7 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_EDITION?: 'production' | 'showcase'
|
||||
readonly VITE_API_BASE_URL?: string
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
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'
|
||||
|
||||
const showcase = import.meta.env.VITE_APP_EDITION === 'showcase'
|
||||
|
||||
export const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
scrollBehavior: (_to, _from, savedPosition) => savedPosition ?? { top: 0 },
|
||||
routes: [
|
||||
{ path: '/', name: 'catalog', component: CatalogView },
|
||||
{ path: '/search', name: 'search', component: SearchView },
|
||||
{ path: '/browse/:category', name: 'browse', component: BrowseView },
|
||||
...(!showcase ? [
|
||||
{ path: '/search', name: 'search', component: () => import('@/views/SearchView.vue') },
|
||||
{ path: '/browse/:category', name: 'browse', component: () => import('@/views/BrowseView.vue') },
|
||||
] : []),
|
||||
{ path: '/title/:slug', name: 'title', component: TitleView },
|
||||
{ path: '/admin', name: 'admin', component: AdminView },
|
||||
...(!showcase ? [{ path: '/admin', name: 'admin', component: () => import('@/views/AdminView.vue') }] : []),
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
],
|
||||
})
|
||||
@@ -17,6 +17,7 @@ const loading = ref(true)
|
||||
const error = ref('')
|
||||
const { localize, t } = useI18n()
|
||||
const player = usePlayerStore()
|
||||
const showcase = import.meta.env.VITE_APP_EDITION === 'showcase'
|
||||
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' })
|
||||
@@ -101,7 +102,7 @@ onMounted(() => void load())
|
||||
<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 } }">
|
||||
<RouterLink v-if="!showcase" class="secondary-button focus-ring" data-tv-focus :to="{ name: 'browse', params: { category: section.slug } }">
|
||||
{{ t('browseAll') }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user