feat(showcase): add portable static export for generic hosting
ci / verify (push) Successful in 5m14s
ci / verify (push) Successful in 5m14s
This commit is contained in:
17 files changed
+740
-116
No files matched your search
@@ -5,3 +5,4 @@ SHOWCASE_HOST=127.0.0.1
|
||||
SHOWCASE_PORT=8080
|
||||
SHOWCASE_FFMPEG=ffmpeg
|
||||
SHOWCASE_FFPROBE=ffprobe
|
||||
SHOWCASE_EXPORT_ROOT=./dist/showcase-static
|
||||
@@ -17,3 +17,4 @@ derived/
|
||||
*.tsbuildinfo
|
||||
playwright-report/
|
||||
test-results/
|
||||
public
|
||||
@@ -16,7 +16,7 @@ The first version targets Chrome, Firefox, and modern MSE-capable Android TV bro
|
||||
|
||||
See [architecture.md](docs/architecture.md) for the media decisions and [operations.md](docs/operations.md) for deployment gates.
|
||||
|
||||
For a small, open demo that runs as one Node process with SQLite and no Docker, PostgreSQL, Redis, worker, queue, or admin panel, use the [Showcase edition](docs/showcase.md).
|
||||
For a small, open demo that runs locally as one Node/SQLite process—or exports as a portable folder for any static host—use the [Showcase edition](docs/showcase.md).
|
||||
|
||||
## What happens to a movie
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
#!/usr/bin/env node
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { assertArchive, readConfig } from './config.js';
|
||||
import path from 'node:path';
|
||||
import { assertArchive, projectRoot, 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';
|
||||
import { exportStaticShowcase, startStaticPreview } from './static.js';
|
||||
|
||||
function value(args: string[], option: string): string | undefined {
|
||||
const index = args.indexOf(option);
|
||||
@@ -21,6 +23,8 @@ Usage:
|
||||
pnpm showcase status
|
||||
pnpm showcase prune [--apply]
|
||||
pnpm showcase serve
|
||||
pnpm showcase export-static [--output <directory>]
|
||||
pnpm showcase preview-static [--output <directory>] [--port <number>]
|
||||
|
||||
Configuration is read from .env.showcase (see .env.showcase.example).`);
|
||||
}
|
||||
@@ -30,6 +34,14 @@ async function main(): Promise<void> {
|
||||
const command = args[0];
|
||||
if (!command || command === 'help' || command === '--help') return help();
|
||||
const config = await readConfig();
|
||||
const outputOption = value(args, '--output');
|
||||
const outputRoot = outputOption ? path.resolve(projectRoot, outputOption) : config.exportRoot;
|
||||
if (command === 'preview-static') {
|
||||
const previewPort = Number(value(args, '--port') ?? config.port);
|
||||
if (!Number.isInteger(previewPort) || previewPort < 1 || previewPort > 65535) throw new Error('--port must be between 1 and 65535');
|
||||
await startStaticPreview(outputRoot, config.host, previewPort);
|
||||
return;
|
||||
}
|
||||
await mkdir(config.dataRoot, { recursive: true, mode: 0o750 });
|
||||
const db = openDatabase(config.databasePath);
|
||||
try {
|
||||
@@ -52,6 +64,16 @@ async function main(): Promise<void> {
|
||||
} 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 if (command === 'export-static') {
|
||||
await assertArchive(config);
|
||||
const scanned = await scanIntoDatabase(db, config);
|
||||
console.log(`Scanned ${scanned.titles} title(s), ${scanned.media} media item(s), ${scanned.variants} variant(s).`);
|
||||
const prepared = await prepareSelection(db, config, { all: true });
|
||||
if (prepared.failed) throw new Error(`Cannot export because ${prepared.failed} media preparation job(s) failed`);
|
||||
await pruneMedia(db, config, true);
|
||||
const result = await exportStaticShowcase(db, config, { outputRoot });
|
||||
console.log(`Static showcase exported to ${result.outputRoot} (${result.files} files, ${result.bytes} bytes).`);
|
||||
}
|
||||
else throw new Error(`Unknown command: ${command}`);
|
||||
} finally {
|
||||
if (command !== 'serve') db.close();
|
||||
|
||||
@@ -13,9 +13,10 @@ export interface ShowcaseConfig {
|
||||
port: number;
|
||||
ffmpegPath: string;
|
||||
ffprobePath: string;
|
||||
exportRoot: string;
|
||||
}
|
||||
|
||||
const projectRoot = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
export const projectRoot = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
|
||||
async function loadEnvironment(filename = path.join(projectRoot, '.env.showcase')): Promise<void> {
|
||||
try {
|
||||
@@ -52,6 +53,7 @@ export async function readConfig(): Promise<ShowcaseConfig> {
|
||||
port,
|
||||
ffmpegPath: process.env.SHOWCASE_FFMPEG ?? 'ffmpeg',
|
||||
ffprobePath: process.env.SHOWCASE_FFPROBE ?? 'ffprobe',
|
||||
exportRoot: path.resolve(projectRoot, process.env.SHOWCASE_EXPORT_ROOT ?? './dist/showcase-static'),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ describe('showcase server', () => {
|
||||
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',
|
||||
exportRoot: path.join(root, 'export'),
|
||||
};
|
||||
const db = openDatabase(config.databasePath);
|
||||
databases.push(db);
|
||||
|
||||
+17
-80
@@ -4,65 +4,7 @@ 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[];
|
||||
}
|
||||
import { buildShowcaseSnapshot } from './snapshot.js';
|
||||
|
||||
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.'); });
|
||||
@@ -78,38 +20,33 @@ export async function createServer(db: DatabaseSync, config: ShowcaseConfig) {
|
||||
|
||||
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 snapshot = buildShowcaseSnapshot(db);
|
||||
const all = snapshot.titles.filter((entry) => {
|
||||
const title = entry as { categorySlug?: string };
|
||||
return !request.query.category || title.categorySlug === 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 };
|
||||
return { items: all.slice(0, limit), 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 })) };
|
||||
const snapshot = buildShowcaseSnapshot(db);
|
||||
return { sections: snapshot.sections.map((section) => ({ ...section, items: section.items.slice(0, limit), hasMore: section.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);
|
||||
const title = buildShowcaseSnapshot(db).titles.find((entry) => (entry as { slug?: string }).slug === request.params.slug);
|
||||
if (!title) return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Title not found' } });
|
||||
return title;
|
||||
});
|
||||
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' } });
|
||||
const snapshot = buildShowcaseSnapshot(db);
|
||||
const variantId = request.body.variantId ?? snapshot.defaultVariantByMedia[mediaId];
|
||||
const playback = variantId ? snapshot.playbackByVariant[variantId] : undefined;
|
||||
if (!playback || playback.mediaItemId !== mediaId) 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,
|
||||
id: randomUUID(), state: 'READY', ...playback, pollAfterMs: 1000,
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import type { DatabaseSync } from 'node:sqlite';
|
||||
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;
|
||||
}
|
||||
|
||||
export interface ShowcasePlayback {
|
||||
mediaItemId: string;
|
||||
variantId: string;
|
||||
qualityLabel: string;
|
||||
manifestUrl: string;
|
||||
durationSeconds: number;
|
||||
audioTracks: unknown[];
|
||||
subtitleTracks: unknown[];
|
||||
}
|
||||
|
||||
export interface ShowcaseSnapshot {
|
||||
version: 1;
|
||||
generatedAt: string;
|
||||
sections: Array<{ slug: string; name: string; items: unknown[]; hasMore: boolean }>;
|
||||
titles: unknown[];
|
||||
playbackByVariant: Record<string, ShowcasePlayback>;
|
||||
defaultVariantByMedia: Record<string, string>;
|
||||
}
|
||||
|
||||
export type AssetUrlResolver = (localUrl: string) => string;
|
||||
|
||||
export 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 rewriteTrackUrls(track: unknown, resolveAssetUrl: AssetUrlResolver): unknown {
|
||||
if (track === null || typeof track !== 'object' || Array.isArray(track)) return track;
|
||||
const source = track as Record<string, unknown>;
|
||||
return {
|
||||
...source,
|
||||
...(typeof source.assUrl === 'string' ? { assUrl: resolveAssetUrl(source.assUrl) } : {}),
|
||||
...(typeof source.vttUrl === 'string' ? { vttUrl: resolveAssetUrl(source.vttUrl) } : {}),
|
||||
...(Array.isArray(source.fontUrls) ? {
|
||||
fontUrls: source.fontUrls.map((url) => typeof url === 'string' ? resolveAssetUrl(url) : url),
|
||||
} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function titleJson(db: DatabaseSync, title: TitleRow, resolveAssetUrl: AssetUrlResolver, detail: boolean) {
|
||||
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((number) => number !== 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 ? resolveAssetUrl(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 function buildShowcaseSnapshot(
|
||||
db: DatabaseSync,
|
||||
resolveAssetUrl: AssetUrlResolver = (url) => url,
|
||||
): ShowcaseSnapshot {
|
||||
const titles = visibleTitles(db);
|
||||
const details = titles.map((title) => titleJson(db, title, resolveAssetUrl, true));
|
||||
const groups = new Map<string, { name: string; items: unknown[] }>();
|
||||
for (const title of titles) {
|
||||
const slug = title.category_slug ?? 'showcase';
|
||||
const group = groups.get(slug) ?? { name: title.category ?? 'Showcase', items: [] };
|
||||
group.items.push(titleJson(db, title, resolveAssetUrl, false));
|
||||
groups.set(slug, group);
|
||||
}
|
||||
const playbackByVariant: Record<string, ShowcasePlayback> = {};
|
||||
const defaultVariantByMedia: Record<string, string> = {};
|
||||
const media = db.prepare(`SELECT m.* FROM media_items m JOIN titles t ON t.id=m.title_id WHERE t.id IN (SELECT DISTINCT m2.title_id FROM media_items m2 JOIN variants v2 ON v2.media_item_id=m2.id WHERE v2.status='READY')`)
|
||||
.all() as unknown as MediaRow[];
|
||||
for (const item of media) {
|
||||
for (const [index, variant] of readyVariants(db, item.id).entries()) {
|
||||
if (!variant.manifest_path) continue;
|
||||
if (index === 0) defaultVariantByMedia[item.id] = variant.id;
|
||||
playbackByVariant[variant.id] = {
|
||||
mediaItemId: item.id,
|
||||
variantId: variant.id,
|
||||
qualityLabel: variant.label,
|
||||
manifestUrl: resolveAssetUrl(variant.manifest_path),
|
||||
durationSeconds: item.duration_seconds,
|
||||
audioTracks: JSON.parse(variant.audio_tracks) as unknown[],
|
||||
subtitleTracks: (JSON.parse(variant.subtitle_tracks) as unknown[])
|
||||
.map((track) => rewriteTrackUrls(track, resolveAssetUrl)),
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
generatedAt: new Date().toISOString(),
|
||||
sections: [...groups].map(([slug, group]) => ({ slug, name: group.name, items: group.items, hasMore: false })),
|
||||
titles: details,
|
||||
playbackByVariant,
|
||||
defaultVariantByMedia,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { mkdtemp, mkdir, readFile, stat, 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 { createStaticPreviewServer, exportStaticShowcase } from './static.js';
|
||||
|
||||
const databases: ReturnType<typeof openDatabase>[] = [];
|
||||
afterEach(() => databases.splice(0).forEach((database) => database.close()));
|
||||
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-static-'));
|
||||
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: path.join(root, 'web'),
|
||||
exportRoot: path.join(root, 'public'), host: '127.0.0.1', port: 8080,
|
||||
ffmpegPath: 'ffmpeg', ffprobePath: 'ffprobe',
|
||||
};
|
||||
const generationRoot = path.join(config.mediaRoot, 'generations', 'generation-1');
|
||||
await mkdir(path.join(generationRoot, 'video'), { recursive: true });
|
||||
await mkdir(path.join(generationRoot, 'subtitles'), { recursive: true });
|
||||
await mkdir(config.artworkRoot, { recursive: true });
|
||||
await writeFile(path.join(generationRoot, 'master.m3u8'), '#EXTM3U\nvideo/index.m3u8\n');
|
||||
await writeFile(path.join(generationRoot, 'video', 'index.m3u8'), '#EXTM3U\nsegment-000001.m4s\n');
|
||||
await writeFile(path.join(generationRoot, 'video', 'segment-000001.m4s'), 'segment');
|
||||
await writeFile(path.join(generationRoot, 'subtitles', 'fa.vtt'), 'WEBVTT');
|
||||
await writeFile(path.join(generationRoot, '.cache-entry.json'), '{"private":true}');
|
||||
await writeFile(path.join(config.artworkRoot, 'title.jpg'), 'poster');
|
||||
const db = openDatabase(config.databasePath);
|
||||
databases.push(db);
|
||||
db.prepare('INSERT INTO titles VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)').run(
|
||||
'title-1', 'demo', 'MOVIE', 'دمو', 'Demo', null, null, '/images/archive/title.jpg',
|
||||
'Anime', 'anime', 2026, 'SUMMER', new Date().toISOString(),
|
||||
);
|
||||
db.prepare('INSERT INTO media_items VALUES (?,?,?,?,?,?,?,?)').run('media-1', 'title-1', 'MOVIE', null, null, 'دمو', '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', '[]',
|
||||
JSON.stringify([{ id: 'fa', language: 'fa', label: 'فارسی', vttUrl: '/media/generations/generation-1/subtitles/fa.vtt', fontUrls: [] }]),
|
||||
null, new Date().toISOString(),
|
||||
);
|
||||
return { root, config, db, generationRoot };
|
||||
}
|
||||
|
||||
describe('portable static showcase', () => {
|
||||
it('exports a self-contained relative catalog and only public media files', async () => {
|
||||
const { config, db, generationRoot } = await fixture();
|
||||
const result = await exportStaticShowcase(db, config, {
|
||||
buildViewer: async (outputRoot) => {
|
||||
await mkdir(path.join(outputRoot, 'assets'), { recursive: true });
|
||||
await writeFile(path.join(outputRoot, 'index.html'), '<h1>Easy Stream</h1>');
|
||||
await writeFile(path.join(outputRoot, 'assets', 'app.js'), 'console.log("showcase")');
|
||||
},
|
||||
});
|
||||
expect(result.outputRoot).toBe(config.exportRoot);
|
||||
const catalog = JSON.parse(await readFile(path.join(config.exportRoot, 'catalog.json'), 'utf8')) as {
|
||||
titles: Array<{ posterUrl: string }>;
|
||||
playbackByVariant: Record<string, { manifestUrl: string; subtitleTracks: Array<{ vttUrl: string }> }>;
|
||||
};
|
||||
expect(catalog.titles[0]?.posterUrl).toBe('./images/archive/title.jpg');
|
||||
expect(catalog.playbackByVariant['variant-1']).toMatchObject({
|
||||
manifestUrl: './media/generations/generation-1/master.m3u8',
|
||||
subtitleTracks: [{ vttUrl: './media/generations/generation-1/subtitles/fa.vtt' }],
|
||||
});
|
||||
await expect(readFile(path.join(config.exportRoot, 'media', 'generations', 'generation-1', '.cache-entry.json'))).rejects.toThrow();
|
||||
const source = await stat(path.join(generationRoot, 'master.m3u8'));
|
||||
const exported = await stat(path.join(config.exportRoot, 'media', 'generations', 'generation-1', 'master.m3u8'));
|
||||
if (source.dev === exported.dev) expect(exported.ino).toBe(source.ino);
|
||||
|
||||
const preview = await createStaticPreviewServer(config.exportRoot);
|
||||
const manifest = await preview.inject({ method: 'GET', url: '/media/generations/generation-1/master.m3u8' });
|
||||
expect(manifest.statusCode).toBe(200);
|
||||
expect(manifest.headers['content-type']).toContain('application/vnd.apple.mpegurl');
|
||||
const segment = await preview.inject({ method: 'GET', url: '/media/generations/generation-1/video/segment-000001.m4s' });
|
||||
expect(segment.headers['content-type']).toContain('video/iso.segment');
|
||||
await preview.close();
|
||||
});
|
||||
|
||||
it('refuses to replace a directory that it did not create', async () => {
|
||||
const { root, config, db } = await fixture();
|
||||
config.exportRoot = path.join(root, 'unmanaged');
|
||||
await mkdir(config.exportRoot);
|
||||
await writeFile(path.join(config.exportRoot, 'keep.txt'), 'important');
|
||||
await expect(exportStaticShowcase(db, config, { buildViewer: async () => undefined }))
|
||||
.rejects.toThrow(/Refusing to replace unmanaged directory/u);
|
||||
expect(await readFile(path.join(config.exportRoot, 'keep.txt'), 'utf8')).toBe('important');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,255 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import {
|
||||
access,
|
||||
copyFile,
|
||||
lstat,
|
||||
link,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
opendir,
|
||||
rename,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from 'node:fs/promises';
|
||||
import type { DatabaseSync } from 'node:sqlite';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import Fastify from 'fastify';
|
||||
import type { ShowcaseConfig } from './config.js';
|
||||
import { projectRoot } from './config.js';
|
||||
import { buildShowcaseSnapshot } from './snapshot.js';
|
||||
|
||||
const markerName = '.easy-stream-static-export';
|
||||
const mediaExtensions = new Set(['.m3u8', '.m4s', '.mp4', '.ass', '.vtt', '.ttf', '.otf', '.woff', '.woff2']);
|
||||
const artworkExtensions = new Set(['.jpg', '.jpeg', '.png', '.webp', '.avif']);
|
||||
|
||||
export interface StaticExportResult {
|
||||
outputRoot: string;
|
||||
files: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface StaticExportOptions {
|
||||
outputRoot?: string;
|
||||
buildViewer?: (outputRoot: string) => Promise<void>;
|
||||
}
|
||||
|
||||
interface CopyStats {
|
||||
files: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
function run(command: string, args: string[], environment: NodeJS.ProcessEnv): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, { cwd: projectRoot, env: environment, stdio: 'inherit' });
|
||||
child.once('error', reject);
|
||||
child.once('exit', (code, signal) => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`${command} failed${signal ? ` with signal ${signal}` : ` with exit code ${code ?? 'unknown'}`}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function buildStaticViewer(outputRoot: string): Promise<void> {
|
||||
const environment = {
|
||||
...process.env,
|
||||
VITE_APP_EDITION: 'showcase',
|
||||
VITE_SHOWCASE_CATALOG_URL: './catalog.json',
|
||||
VITE_SHOWCASE_STATIC: 'true',
|
||||
};
|
||||
await run('corepack', ['pnpm', '--filter', '@easy-stream/web', 'exec', 'vue-tsc', '--noEmit'], environment);
|
||||
await run('corepack', ['pnpm', '--filter', '@easy-stream/web', 'exec', 'vite', 'build', '--outDir', outputRoot, '--emptyOutDir'], environment);
|
||||
}
|
||||
|
||||
function contained(root: string, candidate: string): boolean {
|
||||
const relative = path.relative(root, candidate);
|
||||
return relative !== '' && !relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative);
|
||||
}
|
||||
|
||||
async function copyOrLink(source: string, destination: string): Promise<number> {
|
||||
await mkdir(path.dirname(destination), { recursive: true });
|
||||
try {
|
||||
await link(source, destination);
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (!['EXDEV', 'EPERM', 'EACCES', 'ENOTSUP', 'EOPNOTSUPP'].includes(code ?? '')) throw error;
|
||||
await copyFile(source, destination);
|
||||
}
|
||||
return (await stat(source)).size;
|
||||
}
|
||||
|
||||
async function copyTree(
|
||||
sourceRoot: string,
|
||||
destinationRoot: string,
|
||||
allowedExtensions: ReadonlySet<string>,
|
||||
): Promise<CopyStats> {
|
||||
const result = { files: 0, bytes: 0 };
|
||||
const directory = await opendir(sourceRoot);
|
||||
for await (const entry of directory) {
|
||||
if (entry.name.startsWith('.')) continue;
|
||||
const source = path.join(sourceRoot, entry.name);
|
||||
const destination = path.join(destinationRoot, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
const nested = await copyTree(source, destination, allowedExtensions);
|
||||
result.files += nested.files;
|
||||
result.bytes += nested.bytes;
|
||||
} else if (entry.isFile() && allowedExtensions.has(path.extname(entry.name).toLowerCase())) {
|
||||
result.bytes += await copyOrLink(source, destination);
|
||||
result.files += 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function treeStats(root: string): Promise<CopyStats> {
|
||||
const result = { files: 0, bytes: 0 };
|
||||
const directory = await opendir(root);
|
||||
for await (const entry of directory) {
|
||||
const filename = path.join(root, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
const nested = await treeStats(filename);
|
||||
result.files += nested.files;
|
||||
result.bytes += nested.bytes;
|
||||
} else if (entry.isFile()) {
|
||||
result.files += 1;
|
||||
result.bytes += (await stat(filename)).size;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function assertManagedTarget(outputRoot: string): Promise<void> {
|
||||
try {
|
||||
const target = await lstat(outputRoot);
|
||||
if (!target.isDirectory()) throw new Error(`Static export target is not a directory: ${outputRoot}`);
|
||||
await access(path.join(outputRoot, markerName));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
try {
|
||||
await access(outputRoot);
|
||||
} catch (accessError) {
|
||||
if ((accessError as NodeJS.ErrnoException).code === 'ENOENT') return;
|
||||
throw accessError;
|
||||
}
|
||||
throw new Error(`Refusing to replace unmanaged directory: ${outputRoot}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function installStaging(stagingRoot: string, outputRoot: string): Promise<void> {
|
||||
const backupRoot = `${outputRoot}.backup-${randomUUID()}`;
|
||||
let hadExisting = false;
|
||||
try {
|
||||
await rename(outputRoot, backupRoot);
|
||||
hadExisting = true;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
try {
|
||||
await rename(stagingRoot, outputRoot);
|
||||
} catch (error) {
|
||||
if (hadExisting) await rename(backupRoot, outputRoot);
|
||||
throw error;
|
||||
}
|
||||
if (hadExisting) await rm(backupRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function relativeAssetUrl(localUrl: string): string {
|
||||
if (localUrl.startsWith('/media/') || localUrl.startsWith('/images/archive/')) return `.${localUrl}`;
|
||||
throw new Error(`Cannot export non-local asset URL: ${localUrl}`);
|
||||
}
|
||||
|
||||
async function copyReadyMedia(db: DatabaseSync, config: ShowcaseConfig, stagingRoot: string): Promise<CopyStats> {
|
||||
const generations = db.prepare("SELECT DISTINCT generation_id FROM variants WHERE status='READY' AND generation_id IS NOT NULL")
|
||||
.all() as Array<{ generation_id: string }>;
|
||||
const total = { files: 0, bytes: 0 };
|
||||
for (const { generation_id: generationId } of generations) {
|
||||
const source = path.resolve(config.mediaRoot, 'generations', generationId);
|
||||
if (!contained(config.mediaRoot, source)) throw new Error(`Unsafe media generation path: ${generationId}`);
|
||||
const destination = path.join(stagingRoot, 'media', 'generations', generationId);
|
||||
const copied = await copyTree(source, destination, mediaExtensions);
|
||||
total.files += copied.files;
|
||||
total.bytes += copied.bytes;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
async function copyReadyArtwork(db: DatabaseSync, config: ShowcaseConfig, stagingRoot: string): Promise<CopyStats> {
|
||||
const posters = db.prepare(`SELECT DISTINCT t.poster_url 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' AND t.poster_url IS NOT NULL`).all() as Array<{ poster_url: string }>;
|
||||
const total = { files: 0, bytes: 0 };
|
||||
for (const { poster_url: posterUrl } of posters) {
|
||||
if (!posterUrl.startsWith('/images/archive/')) throw new Error(`Cannot export non-local poster URL: ${posterUrl}`);
|
||||
const relative = posterUrl.slice('/images/archive/'.length);
|
||||
const source = path.resolve(config.artworkRoot, relative);
|
||||
if (!contained(config.artworkRoot, source) || !artworkExtensions.has(path.extname(source).toLowerCase())) {
|
||||
throw new Error(`Unsafe artwork path: ${posterUrl}`);
|
||||
}
|
||||
total.bytes += await copyOrLink(source, path.join(stagingRoot, 'images', 'archive', relative));
|
||||
total.files += 1;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
export async function exportStaticShowcase(
|
||||
db: DatabaseSync,
|
||||
config: ShowcaseConfig,
|
||||
options: StaticExportOptions = {},
|
||||
): Promise<StaticExportResult> {
|
||||
const outputRoot = path.resolve(options.outputRoot ?? config.exportRoot);
|
||||
await assertManagedTarget(outputRoot);
|
||||
await mkdir(path.dirname(outputRoot), { recursive: true });
|
||||
const stagingRoot = await mkdtemp(path.join(path.dirname(outputRoot), `.${path.basename(outputRoot)}.staging-`));
|
||||
try {
|
||||
await (options.buildViewer ?? buildStaticViewer)(stagingRoot);
|
||||
await copyReadyMedia(db, config, stagingRoot);
|
||||
await copyReadyArtwork(db, config, stagingRoot);
|
||||
const catalog = `${JSON.stringify(buildShowcaseSnapshot(db, relativeAssetUrl), null, 2)}\n`;
|
||||
const marker = `${JSON.stringify({ format: 1, generatedAt: new Date().toISOString() })}\n`;
|
||||
await Promise.all([
|
||||
writeFile(path.join(stagingRoot, 'catalog.json'), catalog),
|
||||
writeFile(path.join(stagingRoot, markerName), marker),
|
||||
]);
|
||||
const totals = await treeStats(stagingRoot);
|
||||
await installStaging(stagingRoot, outputRoot);
|
||||
return {
|
||||
outputRoot,
|
||||
files: totals.files,
|
||||
bytes: totals.bytes,
|
||||
};
|
||||
} catch (error) {
|
||||
await rm(stagingRoot, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function setStaticHeaders(response: { setHeader(name: string, value: string): void }, filename: string): void {
|
||||
const extension = path.extname(filename).toLowerCase();
|
||||
if (extension === '.m3u8') response.setHeader('content-type', 'application/vnd.apple.mpegurl');
|
||||
else if (extension === '.m4s') response.setHeader('content-type', 'video/iso.segment');
|
||||
else if (extension === '.mp4') response.setHeader('content-type', 'video/mp4');
|
||||
else if (extension === '.vtt') response.setHeader('content-type', 'text/vtt; charset=utf-8');
|
||||
else if (extension === '.ass') response.setHeader('content-type', 'text/plain; charset=utf-8');
|
||||
response.setHeader('cache-control', ['.m3u8', '.json', '.html'].includes(extension) ? 'no-cache' : 'public, max-age=31536000, immutable');
|
||||
}
|
||||
|
||||
export async function createStaticPreviewServer(outputRoot: string) {
|
||||
await access(path.join(outputRoot, markerName)).catch(() => {
|
||||
throw new Error(`Static export is missing at ${outputRoot}. Run \`pnpm showcase export-static\` first.`);
|
||||
});
|
||||
const app = Fastify({ logger: true });
|
||||
await app.register(fastifyStatic, { root: outputRoot, prefix: '/', wildcard: false, setHeaders: setStaticHeaders });
|
||||
return app;
|
||||
}
|
||||
|
||||
export async function startStaticPreview(outputRoot: string, host: string, port: number): Promise<void> {
|
||||
const app = await createStaticPreviewServer(outputRoot);
|
||||
await app.listen({ host, port });
|
||||
const shownHost = ['0.0.0.0', '::'].includes(host) ? os.hostname() : host;
|
||||
console.log(`Easy Stream static preview: http://${shownHost}:${port}`);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const snapshot = {
|
||||
version: 1,
|
||||
generatedAt: '2026-07-15T00:00:00.000Z',
|
||||
sections: [{
|
||||
slug: 'anime', name: 'Anime', hasMore: false,
|
||||
items: [{ id: 'title-1', slug: 'demo', kind: 'MOVIE', name: { fa: 'دمو', en: 'Demo' }, playable: true, resumeMediaItemId: 'media-1', variants: [{ id: 'variant-1', label: '720p', available: true, isDefault: true, compatibility: 'COPY' }] }],
|
||||
}],
|
||||
titles: [{
|
||||
id: 'title-1', slug: 'demo', kind: 'MOVIE', name: { fa: 'دمو', en: 'Demo' }, playable: true,
|
||||
resumeMediaItemId: 'media-1', variants: [{ id: 'variant-1', label: '720p', available: true, isDefault: true, compatibility: 'COPY' }],
|
||||
mediaItems: [{ id: 'media-1', kind: 'MOVIE', name: { fa: 'دمو', en: 'Demo' }, published: true, variants: [{ id: 'variant-1', label: '720p', available: true, isDefault: true, compatibility: 'COPY' }] }],
|
||||
}],
|
||||
defaultVariantByMedia: { 'media-1': 'variant-1' },
|
||||
playbackByVariant: {
|
||||
'variant-1': { mediaItemId: 'media-1', variantId: 'variant-1', qualityLabel: '720p', manifestUrl: './media/master.m3u8', durationSeconds: 60, audioTracks: [], subtitleTracks: [] },
|
||||
},
|
||||
}
|
||||
|
||||
describe('static showcase API', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.stubEnv('VITE_APP_EDITION', 'showcase')
|
||||
vi.stubEnv('VITE_SHOWCASE_CATALOG_URL', './catalog.json')
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(snapshot), { status: 200, headers: { 'content-type': 'application/json' } })))
|
||||
vi.stubGlobal('crypto', { randomUUID: () => 'session-1' })
|
||||
})
|
||||
|
||||
it('serves catalog and playback entirely from the static snapshot', async () => {
|
||||
const { api } = await import('@/api/client')
|
||||
const sections = await api.catalogSections()
|
||||
expect(sections[0]?.items[0]).toMatchObject({ slug: 'demo', mediaItemId: 'media-1' })
|
||||
const detail = await api.title('demo')
|
||||
expect(detail.playableMediaItemId).toBe('media-1')
|
||||
const session = await api.createPlaybackSession('media-1', {
|
||||
nativeHls: false, mse: true, hlsJs: true, assRenderer: true, supportedCodecs: ['avc1', 'mp4a'],
|
||||
})
|
||||
expect(session).toMatchObject({ id: 'session-1', state: 'READY', manifestUrl: './media/master.m3u8' })
|
||||
expect(await api.playbackSession('session-1')).toEqual(session)
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
});
|
||||
+101
-30
@@ -17,6 +17,9 @@ import type {
|
||||
} from '@/types'
|
||||
|
||||
const API_BASE = (import.meta.env.VITE_API_BASE_URL ?? '/api/v1').replace(/\/$/, '')
|
||||
const SHOWCASE = import.meta.env.VITE_APP_EDITION === 'showcase'
|
||||
const SHOWCASE_CATALOG_URL = import.meta.env.VITE_SHOWCASE_CATALOG_URL
|
||||
const STATIC_SHOWCASE = SHOWCASE && Boolean(SHOWCASE_CATALOG_URL)
|
||||
const ADMIN_CSRF_KEY = 'easy-stream-admin-csrf'
|
||||
const ADMIN_EMAIL_KEY = 'easy-stream-admin-email'
|
||||
|
||||
@@ -34,6 +37,9 @@ export class ApiError extends Error {
|
||||
|
||||
type JsonRecord = Record<string, unknown>
|
||||
|
||||
let showcaseSnapshotPromise: Promise<JsonRecord> | undefined
|
||||
const showcaseSessions = new Map<string, PlaybackSession>()
|
||||
|
||||
function record(value: unknown): JsonRecord {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as JsonRecord)
|
||||
@@ -69,6 +75,22 @@ function array(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : []
|
||||
}
|
||||
|
||||
async function showcaseSnapshot(signal?: AbortSignal): Promise<JsonRecord> {
|
||||
if (!SHOWCASE_CATALOG_URL) throw new ApiError('VITE_SHOWCASE_CATALOG_URL is not configured', 500, 'SHOWCASE_CATALOG_MISSING')
|
||||
showcaseSnapshotPromise ??= fetch(SHOWCASE_CATALOG_URL, { headers: { accept: 'application/json' } }).then(async (response) => {
|
||||
if (!response.ok) throw new ApiError(`Showcase catalog failed to load (${response.status})`, response.status, 'SHOWCASE_CATALOG_LOAD_FAILED')
|
||||
const snapshot = record(await response.json())
|
||||
if (number(snapshot.version) !== 1) throw new ApiError('Unsupported Showcase catalog version', 500, 'SHOWCASE_CATALOG_VERSION')
|
||||
return snapshot
|
||||
}).catch((error) => {
|
||||
showcaseSnapshotPromise = undefined
|
||||
throw error
|
||||
})
|
||||
const snapshot = await showcaseSnapshotPromise
|
||||
if (signal?.aborted) throw new DOMException('Request aborted', 'AbortError')
|
||||
return snapshot
|
||||
}
|
||||
|
||||
function normalizeVariant(input: unknown): QualityVariant {
|
||||
const item = record(input)
|
||||
return {
|
||||
@@ -155,6 +177,39 @@ function normalizeSeason(input: unknown): SeasonItem {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTitleDetail(payload: JsonRecord): TitleDetail {
|
||||
const base = normalizeCatalogItem(payload)
|
||||
const explicitSeasons = array(payload.seasons).map(normalizeSeason)
|
||||
const mediaItems = array(payload.mediaItems).map((entry) => record(entry))
|
||||
const groupedSeasons = new Map<number, EpisodeItem[]>()
|
||||
mediaItems.forEach((entry) => {
|
||||
const seasonNumber = number(entry.seasonNumber) ?? 0
|
||||
const episodes = groupedSeasons.get(seasonNumber) ?? []
|
||||
episodes.push(normalizeEpisode(entry, seasonNumber))
|
||||
groupedSeasons.set(seasonNumber, episodes)
|
||||
})
|
||||
const seasons = explicitSeasons.some((season) => season.episodes.length)
|
||||
? explicitSeasons
|
||||
: [...groupedSeasons.entries()]
|
||||
.sort(([left], [right]) => left - right)
|
||||
.map(([seasonNumber, episodes]) => ({
|
||||
number: seasonNumber,
|
||||
title: { fa: `فصل ${seasonNumber}`, en: `Season ${seasonNumber}` },
|
||||
episodes: episodes.sort((left, right) => left.number - right.number),
|
||||
}))
|
||||
const firstPublishedMediaItem = mediaItems.find((item) => item.published !== false)
|
||||
const playableMediaItemId = text(payload.resumeMediaItemId)
|
||||
?? text(payload.playableMediaItemId)
|
||||
?? text(firstPublishedMediaItem?.id)
|
||||
return {
|
||||
...base,
|
||||
mediaItemId: playableMediaItemId ?? '',
|
||||
genres: array(payload.genres).map((genre) => localized(genre, record(genre).name)),
|
||||
seasons,
|
||||
...(playableMediaItemId ? { playableMediaItemId } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSubtitle(input: unknown, index: number): PlaybackSubtitleTrack {
|
||||
const item = record(input)
|
||||
const urls = record(item.urls)
|
||||
@@ -294,6 +349,16 @@ function withSignal(signal: AbortSignal | undefined, init: RequestInit = {}): Re
|
||||
|
||||
export const api = {
|
||||
async catalog(options: { cursor?: string; limit?: number; kind?: string; category?: string; year?: number; releaseWindow?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
|
||||
if (STATIC_SHOWCASE) {
|
||||
const snapshot = await showcaseSnapshot(signal)
|
||||
let items = array(snapshot.titles).map(normalizeCatalogItem)
|
||||
if (options.kind) items = items.filter((item) => item.kind === options.kind)
|
||||
if (options.category) items = items.filter((item) => item.categorySlug === options.category)
|
||||
if (options.year) items = items.filter((item) => item.year === options.year)
|
||||
if (options.releaseWindow) items = items.filter((item) => item.releaseWindow === options.releaseWindow)
|
||||
const limit = options.limit ?? 40
|
||||
return { items: items.slice(0, limit), total: items.length }
|
||||
}
|
||||
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
|
||||
@@ -308,6 +373,14 @@ export const api = {
|
||||
},
|
||||
|
||||
async catalogSections(limitPerSection = 12, signal?: AbortSignal): Promise<CatalogSection[]> {
|
||||
if (STATIC_SHOWCASE) {
|
||||
const snapshot = await showcaseSnapshot(signal)
|
||||
return array(snapshot.sections).map((input) => {
|
||||
const section = record(input)
|
||||
const items = array(section.items).map(normalizeCatalogItem).filter((item) => item.id)
|
||||
return { slug: text(section.slug) ?? '', name: text(section.name) ?? '', items: items.slice(0, limitPerSection), hasMore: items.length > limitPerSection }
|
||||
}).filter((section) => section.slug && section.items.length)
|
||||
}
|
||||
const body = record(await request(`/catalog/sections${queryString({ limitPerSection })}`, withSignal(signal)))
|
||||
return array(body.sections).map((input) => {
|
||||
const section = record(input)
|
||||
@@ -332,39 +405,16 @@ export const api = {
|
||||
},
|
||||
|
||||
async title(slug: string, signal?: AbortSignal): Promise<TitleDetail> {
|
||||
if (STATIC_SHOWCASE) {
|
||||
const snapshot = await showcaseSnapshot(signal)
|
||||
const payload = array(snapshot.titles).map(record).find((title) => text(title.slug) === slug)
|
||||
if (!payload) throw new ApiError('Title not found', 404, 'NOT_FOUND')
|
||||
return normalizeTitleDetail(payload)
|
||||
}
|
||||
const body = await request(`/titles/${encodeURIComponent(slug)}`, withSignal(signal))
|
||||
const source = record(body)
|
||||
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
|
||||
const base = normalizeCatalogItem(payload)
|
||||
const explicitSeasons = array(payload.seasons).map(normalizeSeason)
|
||||
const mediaItems = array(payload.mediaItems).map((entry) => record(entry))
|
||||
const groupedSeasons = new Map<number, EpisodeItem[]>()
|
||||
mediaItems.forEach((entry) => {
|
||||
const seasonNumber = number(entry.seasonNumber) ?? 0
|
||||
const episodes = groupedSeasons.get(seasonNumber) ?? []
|
||||
episodes.push(normalizeEpisode(entry, seasonNumber))
|
||||
groupedSeasons.set(seasonNumber, episodes)
|
||||
})
|
||||
const seasons = explicitSeasons.some((season) => season.episodes.length)
|
||||
? explicitSeasons
|
||||
: [...groupedSeasons.entries()]
|
||||
.sort(([left], [right]) => left - right)
|
||||
.map(([seasonNumber, episodes]) => ({
|
||||
number: seasonNumber,
|
||||
title: { fa: `فصل ${seasonNumber}`, en: `Season ${seasonNumber}` },
|
||||
episodes: episodes.sort((left, right) => left.number - right.number),
|
||||
}))
|
||||
const firstPublishedMediaItem = mediaItems.find((item) => item.published !== false)
|
||||
const playableMediaItemId = text(payload.resumeMediaItemId)
|
||||
?? text(payload.playableMediaItemId)
|
||||
?? text(firstPublishedMediaItem?.id)
|
||||
return {
|
||||
...base,
|
||||
mediaItemId: playableMediaItemId ?? '',
|
||||
genres: array(payload.genres).map((genre) => localized(genre, record(genre).name)),
|
||||
seasons,
|
||||
...(playableMediaItemId ? { playableMediaItemId } : {}),
|
||||
}
|
||||
return normalizeTitleDetail(payload)
|
||||
},
|
||||
|
||||
async createPlaybackSession(
|
||||
@@ -373,6 +423,20 @@ export const api = {
|
||||
variantId?: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PlaybackSession> {
|
||||
if (STATIC_SHOWCASE) {
|
||||
const snapshot = await showcaseSnapshot(signal)
|
||||
const defaults = record(snapshot.defaultVariantByMedia)
|
||||
const selectedVariantId = variantId ?? text(defaults[mediaItemId])
|
||||
const playback = selectedVariantId ? record(record(snapshot.playbackByVariant)[selectedVariantId]) : {}
|
||||
if (!selectedVariantId || text(playback.mediaItemId) !== mediaItemId) throw new ApiError('This media is not prepared for playback', 404, 'NOT_PREPARED')
|
||||
const id = crypto.randomUUID()
|
||||
const session = normalizePlaybackSession({
|
||||
id, state: 'READY', ...playback, pollAfterMs: 1000,
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
|
||||
})
|
||||
showcaseSessions.set(id, session)
|
||||
return session
|
||||
}
|
||||
const body = await request('/playback-sessions', withSignal(signal, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mediaItemId, ...(variantId ? { variantId } : {}), clientCapabilities }),
|
||||
@@ -382,10 +446,17 @@ export const api = {
|
||||
},
|
||||
|
||||
async playbackSession(id: string, signal?: AbortSignal): Promise<PlaybackSession> {
|
||||
if (STATIC_SHOWCASE) {
|
||||
if (signal?.aborted) throw new DOMException('Request aborted', 'AbortError')
|
||||
const session = showcaseSessions.get(id)
|
||||
if (!session) throw new ApiError('Playback session not found', 404, 'NOT_FOUND')
|
||||
return session
|
||||
}
|
||||
return normalizePlaybackSession(await request(`/playback-sessions/${encodeURIComponent(id)}`, withSignal(signal)))
|
||||
},
|
||||
|
||||
async clientEvent(event: Record<string, unknown>): Promise<void> {
|
||||
if (STATIC_SHOWCASE) return
|
||||
await request('/client-events', { method: 'POST', body: JSON.stringify(event), keepalive: true })
|
||||
},
|
||||
|
||||
|
||||
@@ -367,7 +367,7 @@ function attachManifest(activeSession: PlaybackSession) {
|
||||
maxBufferLength: 30,
|
||||
manifestLoadingTimeOut: 20_000,
|
||||
fragLoadingTimeOut: 30_000,
|
||||
xhrSetup: (xhr) => { xhr.withCredentials = true },
|
||||
xhrSetup: (xhr) => { xhr.withCredentials = !import.meta.env.VITE_SHOWCASE_CATALOG_URL },
|
||||
})
|
||||
hls.on(Events.MEDIA_ATTACHED, () => hls?.loadSource(activeSession.manifestUrl!))
|
||||
hls.on(Events.MANIFEST_PARSED, () => void onManifestReady())
|
||||
|
||||
Vendored
+2
@@ -3,6 +3,8 @@
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_EDITION?: 'production' | 'showcase'
|
||||
readonly VITE_API_BASE_URL?: string
|
||||
readonly VITE_SHOWCASE_CATALOG_URL?: string
|
||||
readonly VITE_SHOWCASE_STATIC?: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
|
||||
|
||||
import CatalogView from '@/views/CatalogView.vue'
|
||||
import TitleView from '@/views/TitleView.vue'
|
||||
|
||||
const showcase = import.meta.env.VITE_APP_EDITION === 'showcase'
|
||||
const staticShowcase = showcase && Boolean(import.meta.env.VITE_SHOWCASE_CATALOG_URL)
|
||||
|
||||
export const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
history: staticShowcase ? createWebHashHistory() : createWebHistory(),
|
||||
scrollBehavior: (_to, _from, savedPosition) => savedPosition ?? { top: 0 },
|
||||
routes: [
|
||||
{ path: '/', name: 'catalog', component: CatalogView },
|
||||
|
||||
@@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
base: process.env.VITE_SHOWCASE_STATIC === 'true' ? './' : '/',
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
|
||||
@@ -83,3 +83,41 @@ corepack pnpm showcase prune --apply
|
||||
```
|
||||
|
||||
SQLite, artwork, subtitles, fonts, and HLS generations live under `SHOWCASE_DATA_ROOT`. Back up that directory if the prepared demo state matters. The app itself does not terminate TLS; for a public domain, place Caddy or another HTTPS reverse proxy in front of port 8080.
|
||||
|
||||
## Portable static deployment
|
||||
|
||||
Create one self-contained folder with the viewer, catalog, artwork, subtitles, fonts, and converted HLS media:
|
||||
|
||||
```sh
|
||||
corepack pnpm showcase export-static
|
||||
```
|
||||
|
||||
The default output is `dist/showcase-static`. Change it in `.env.showcase` with `SHOWCASE_EXPORT_ROOT`, or for one run:
|
||||
|
||||
```sh
|
||||
corepack pnpm showcase export-static --output ./release/showcase
|
||||
```
|
||||
|
||||
This one command rescans the archive, sequentially prepares missing compatible media, removes stale generations, builds the viewer, and replaces the previous managed export. Existing files are hard-linked when the destination is on the same filesystem, so creating an export normally consumes almost no additional local disk space. Copying is used automatically when hard links are unavailable. The exported folder itself is portable; an upload tool reads the linked files just like ordinary files.
|
||||
|
||||
Preview the exact static release before uploading it:
|
||||
|
||||
```sh
|
||||
corepack pnpm showcase preview-static
|
||||
```
|
||||
|
||||
Then upload everything inside `dist/showcase-static` to Vercel static hosting, Netlify, Cloudflare Pages, an S3-compatible static bucket, shared hosting, or a normal Caddy/Nginx document root. Routes use URL hashes (`/#/title/example`), so no SPA rewrite rule is needed and the folder may be hosted below a subdirectory.
|
||||
|
||||
The host must serve the folder over HTTP or HTTPS; browsers cannot reliably stream it by opening `index.html` through `file://`. Ensure these MIME mappings are available:
|
||||
|
||||
| Extension | Content-Type |
|
||||
|---|---|
|
||||
| `.m3u8` | `application/vnd.apple.mpegurl` |
|
||||
| `.m4s` | `video/iso.segment` |
|
||||
| `.mp4` | `video/mp4` |
|
||||
| `.vtt` | `text/vtt; charset=utf-8` |
|
||||
| `.ass` | `text/plain; charset=utf-8` |
|
||||
|
||||
For Caddy, `file_server` provides the required static hosting. For Nginx, include the standard `mime.types` file and add `application/vnd.apple.mpegurl m3u8;` and `video/iso.segment m4s;` if the installed MIME table lacks them.
|
||||
|
||||
No Node.js, SQLite, Fastify, FFmpeg, API, database, or background process runs on the hosting service. All exported media is public by design; never include private or access-controlled titles in this Showcase workflow.
|
||||
Reference in new issue
Block a user