Compare commits

...
10 Commits
73 changed files with 2946 additions and 142 deletions

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
.DS_Store
.env
movies
archive
data
cache
derived
+1 -1
View File
@@ -14,7 +14,7 @@ BUILD_NO_PROXY=localhost,127.0.0.1
DOCKER_BUILD_NETWORK=default
DATABASE_URL=
REDIS_URL=redis://localhost:6379
ARCHIVE_ROOT=./movies
ARCHIVE_ROOT=./archive
CACHE_ROOT=./data/cache
DERIVED_ROOT=./data/derived
METADATA_ROOT=./data/metadata
+8
View File
@@ -0,0 +1,8 @@
# Copy to .env.showcase and edit these values.
SHOWCASE_ARCHIVE_ROOT=./archive
SHOWCASE_DATA_ROOT=./data/showcase
SHOWCASE_HOST=127.0.0.1
SHOWCASE_PORT=8080
SHOWCASE_FFMPEG=ffmpeg
SHOWCASE_FFPROBE=ffprobe
SHOWCASE_EXPORT_ROOT=./dist/showcase-static
+4 -1
View File
@@ -17,4 +17,7 @@ jobs:
- run: corepack pnpm typecheck
- run: corepack pnpm test
- run: corepack pnpm build
- run: bash -n scripts/setup-ubuntu.sh && bash scripts/test-setup-ubuntu.sh
- run: bash -n scripts/setup-ubuntu.sh
- run: bash scripts/test-setup-ubuntu.sh
- run: bash -n scripts/setup-domain.sh
- run: bash scripts/test-setup-domain.sh
+4 -1
View File
@@ -1,4 +1,5 @@
movies/
archive/
screenshots/
.DS_Store
.idea/
node_modules/
@@ -8,6 +9,7 @@ coverage/
.env
.env.*
!.env.example
!.env.showcase.example
data/
cache/
derived/
@@ -15,3 +17,4 @@ derived/
*.tsbuildinfo
playwright-report/
test-results/
public
+19 -3
View File
@@ -16,6 +16,8 @@ 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 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
| Source | v1 behavior | Storage |
@@ -42,11 +44,19 @@ corepack pnpm scan:samples
`scan:samples` writes a public `data/metadata/catalog.json` and a private `data/metadata/inventory.json`. Source paths and probe details never enter the public snapshot.
The production scanner also understands categorized, multi-quality archives:
```text
archive/<category>/<year>/<Spring|Summer|Fall|Winter|Movie>/<title>/<quality>/*.mkv
```
For example, `anime/2026/Summer/Mushoku Tensei S3/720/...mkv` becomes Anime → Mushoku Tensei → Season 3. Files for the same episode under `480`, `720`, `1080`, or codec-suffixed quality folders become selectable source variants rather than duplicate episodes. A `thumbnail.jpg`, `.jpeg`, `.png`, or `.webp` beside the quality folders is copied to the generated artwork store; the archive itself remains private and read-only. The older `Title S3/*.mkv` layout remains supported.
To package one scanned media item with the locally installed FFmpeg, copy its UUID from `inventory.json` and run:
```sh
node apps/worker/dist/cli.js package \
--root ./movies \
--root ./archive \
--cache ./data/cache \
--inventory ./data/metadata/inventory.json \
--registry ./data/metadata/package-registry.json \
@@ -66,7 +76,13 @@ bash scripts/setup-ubuntu.sh
The script installs Docker Engine and the Compose plugin from Docker's official apt repository, asks which host address may expose port 8080 (loopback by default), creates the writable host directories for UID/GID 1000, backs up an existing `.env`, writes the replacement with mode `0600`, validates the rendered Compose configuration, and asks before building or starting containers. Use `--no-start` to configure without launching, or `--skip-docker-install` when a supported Docker installation already exists.
It does not configure DNS, TLS certificates, CDN edge authorization, origin firewall rules, archive mounts, or backups. Complete those production gates separately.
If you decline the offered Caddy step, the main bootstrap leaves DNS, TLS termination, and inbound firewall configuration untouched. CDN edge authorization, archive mounts, and backups remain separate production gates in either case.
To publish an already-running installation, use the separate domain bootstrap. It installs Caddy, configures automatic HTTPS, and proxies the public hostname to the loopback-only gateway:
```sh
bash scripts/setup-domain.sh
```
### Manual alternative
@@ -97,7 +113,7 @@ docker compose exec worker node apps/worker/dist/cli.js prepare \
## Important v1 boundaries
- There is one representation, not an adaptive-bitrate ladder. A slow connection cannot switch to a lower quality.
- There is no adaptive-bitrate ladder. Viewers may manually select an available source quality; each selection is packaged independently on demand and never switches automatically.
- Compatible media still occupies temporary HLS cache space; “no duplication” means no permanent HLS copy for every title.
- Durable compatibility encoding is intentionally operator-controlled and CPU-limited to one job at a time.
- TMDB stays disabled until both an API token and explicit commercial-license confirmation are configured.
+14
View File
@@ -10,6 +10,8 @@ import {
CacheStatusSchema,
CatalogQuerySchema,
CatalogResponseSchema,
CatalogSectionsQuerySchema,
CatalogSectionsResponseSchema,
CreatePlaybackSessionSchema,
DateTimeSchema,
ErrorResponseSchema,
@@ -31,6 +33,7 @@ import {
UuidSchema,
type AdminLogin,
type CatalogQuery,
type CatalogSectionsQuery,
type CreatePlaybackSession,
type MetadataMatchBody,
type MetadataSearchQuery,
@@ -233,6 +236,17 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
async (request) => repository.listCatalog(request.query),
);
app.get<{ Querystring: CatalogSectionsQuery }>(
'/api/v1/catalog/sections',
{
schema: {
querystring: CatalogSectionsQuerySchema,
response: { 200: CatalogSectionsResponseSchema },
},
},
async (request) => ({ sections: await repository.listCatalogSections(request.query.limitPerSection ?? 12) }),
);
app.get<{ Params: Static<typeof SlugParamsSchema> }>(
'/api/v1/titles/:slug',
{
+12
View File
@@ -3,6 +3,7 @@ import type {
AudioTrack,
CacheStatus,
CatalogCard,
CatalogSection,
CatalogQuery,
ClientCapabilities,
Job,
@@ -20,6 +21,14 @@ export interface MediaItemForPlayback {
durationSeconds: number;
compatibility: 'COPY' | 'AUDIO_TRANSCODE' | 'VIDEO_TRANSCODE' | 'HOLD_HDR' | 'INVALID';
published: boolean;
variants: Array<{
id: string;
label: string;
height?: number;
compatibility: 'COPY' | 'AUDIO_TRANSCODE' | 'VIDEO_TRANSCODE' | 'HOLD_HDR' | 'INVALID';
available: boolean;
isDefault: boolean;
}>;
}
export interface CatalogPage {
@@ -29,6 +38,7 @@ export interface CatalogPage {
export interface CatalogRepository {
listCatalog(query: CatalogQuery): Promise<CatalogPage>;
listCatalogSections(limitPerSection: number): Promise<CatalogSection[]>;
searchTitles(query: SearchQuery): Promise<CatalogCard[]>;
getTitleBySlug(slug: string): Promise<TitleDetail | undefined>;
getMediaItem(id: string): Promise<MediaItemForPlayback | undefined>;
@@ -95,12 +105,14 @@ export interface MediaPreparationService {
prepare(input: {
sessionId: string;
mediaItem: MediaItemForPlayback;
variantId?: string;
capabilities: ClientCapabilities;
protectUntil?: string;
}): Promise<MediaPreparation>;
getStatus(input: {
sessionId: string;
mediaItem: MediaItemForPlayback;
variantId?: string;
protectUntil?: string;
}): Promise<MediaPreparation>;
}
+28
View File
@@ -52,6 +52,9 @@ export class InMemoryRepository implements AppRepository {
const published = [...this.titles.values()]
.filter((title) => title.mediaItems.some((item) => item.published))
.filter((title) => !query.kind || title.kind === query.kind)
.filter((title) => !query.category || (title.categorySlug ?? 'other') === query.category)
.filter((title) => !query.year || title.year === query.year)
.filter((title) => !query.releaseWindow || title.releaseWindow === query.releaseWindow)
.sort((left, right) => left.slug.localeCompare(right.slug));
const cursorId = decodeCursor(query.cursor);
const start = cursorId ? Math.max(0, published.findIndex((title) => title.id === cursorId) + 1) : 0;
@@ -63,6 +66,23 @@ export class InMemoryRepository implements AppRepository {
};
}
async listCatalogSections(limitPerSection: number) {
const groups = new Map<string, TitleDetail[]>();
for (const title of this.titles.values()) {
if (!title.mediaItems.some((item) => item.published)) continue;
const categorySlug = title.categorySlug ?? 'other';
const group = groups.get(categorySlug) ?? [];
group.push(title);
groups.set(categorySlug, group);
}
return [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([slug, titles]) => ({
slug,
name: titles[0]?.category ?? 'Other',
items: titles.slice(0, limitPerSection).map(toCard),
hasMore: titles.length > limitPerSection,
}));
}
async searchTitles(query: SearchQuery) {
const needle = normalizeSearch(query.q);
const limit = query.limit ?? 20;
@@ -94,6 +114,14 @@ export class InMemoryRepository implements AppRepository {
durationSeconds: item.durationSeconds,
compatibility: item.compatibility,
published: item.published,
variants: (item.variants ?? []).map((variant) => ({
id: variant.id,
label: variant.label,
...(variant.height ? { height: variant.height } : {}),
compatibility: variant.compatibility,
available: variant.available,
isDefault: variant.isDefault,
})),
};
}
}
+52 -2
View File
@@ -1,6 +1,7 @@
import type {
CacheStatus,
CatalogCard,
CatalogSection,
CatalogQuery,
Job,
MetadataCandidate,
@@ -17,7 +18,7 @@ import {
titles,
type Database,
} from '@easy-stream/database';
import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
import type {
AdminRecord,
AppRepository,
@@ -44,7 +45,13 @@ export class PostgresRepository implements AppRepository {
const rows = await this.db
.select()
.from(titles)
.where(and(eq(titles.published, true), query.kind ? eq(titles.kind, query.kind) : undefined))
.where(and(
eq(titles.published, true),
query.kind ? eq(titles.kind, query.kind) : undefined,
query.category ? (query.category === 'other' ? isNull(titles.categorySlug) : eq(titles.categorySlug, query.category)) : undefined,
query.year ? eq(titles.releaseYear, query.year) : undefined,
query.releaseWindow ? eq(titles.releaseWindow, query.releaseWindow) : undefined,
))
.orderBy(asc(titles.slug), asc(titles.id))
.limit(limit + 1)
.offset(offset);
@@ -56,6 +63,30 @@ export class PostgresRepository implements AppRepository {
};
}
async listCatalogSections(limitPerSection: number): Promise<CatalogSection[]> {
const rows = await this.db.select().from(titles)
.where(eq(titles.published, true))
.orderBy(asc(titles.categorySlug), desc(titles.releaseYear), asc(titles.slug));
const groups = new Map<string, typeof rows>();
for (const row of rows) {
const categorySlug = row.categorySlug ?? 'other';
const group = groups.get(categorySlug) ?? [];
group.push(row);
groups.set(categorySlug, group);
}
const result: CatalogSection[] = [];
for (const [slug, group] of groups) {
const visible = group.slice(0, limitPerSection);
result.push({
slug,
name: group[0]?.category ?? 'Other',
items: await this.cardsForRows(visible),
hasMore: group.length > visible.length,
});
}
return result;
}
async searchTitles(query: SearchQuery): Promise<CatalogCard[]> {
const needle = `%${query.q.trim().replaceAll('%', '\\%').replaceAll('_', '\\_')}%`;
const rows = await this.db
@@ -101,6 +132,14 @@ export class PostgresRepository implements AppRepository {
durationSeconds: row.media.durationSeconds ?? 0,
compatibility: row.media.compatibility,
published: row.media.published && row.titlePublished,
variants: (row.media.variants ?? []).map((variant) => ({
id: variant.id,
label: variant.label,
...(variant.height ? { height: variant.height } : {}),
compatibility: variant.compatibility as MediaItemForPlayback['compatibility'],
available: variant.available,
isDefault: variant.isDefault,
})),
};
}
@@ -156,6 +195,7 @@ export class PostgresRepository implements AppRepository {
await this.db.insert(playbackSessions).values({
id: session.id,
mediaItemId: session.mediaItemId,
...(session.variantId ? { variantId: session.variantId } : {}),
...(session.generationId ? { generationId: session.generationId } : {}),
state: session.state,
capabilities: session.capabilities,
@@ -177,6 +217,7 @@ export class PostgresRepository implements AppRepository {
return {
id: row.id,
mediaItemId: row.mediaItemId,
...(row.variantId ? { variantId: row.variantId } : {}),
state: row.state,
capabilities: row.capabilities as StoredPlaybackSession['capabilities'],
expiresAt: row.expiresAt.toISOString(),
@@ -185,6 +226,7 @@ export class PostgresRepository implements AppRepository {
...(row.pollAfterMs ? { pollAfterMs: row.pollAfterMs } : {}),
...(details.manifestUrl ? { manifestUrl: details.manifestUrl } : {}),
...(details.durationSeconds !== undefined ? { durationSeconds: details.durationSeconds } : {}),
...(details.qualityLabel ? { qualityLabel: details.qualityLabel } : {}),
...(details.audioTracks ? { audioTracks: details.audioTracks } : {}),
...(details.subtitleTracks ? { subtitleTracks: details.subtitleTracks } : {}),
};
@@ -196,6 +238,7 @@ export class PostgresRepository implements AppRepository {
.set({
state: session.state,
generationId: session.generationId ?? null,
variantId: session.variantId ?? null,
reasonCode: session.reasonCode ?? null,
pollAfterMs: session.pollAfterMs ?? null,
responseJson: publicSessionDetails(session),
@@ -344,7 +387,11 @@ function toCatalogCard(
...(title.posterUrl ? { posterUrl: title.posterUrl } : {}),
...(title.backdropUrl ? { backdropUrl: title.backdropUrl } : {}),
...(title.releaseYear !== null ? { year: title.releaseYear } : {}),
...(title.category ? { category: title.category } : {}),
...(title.categorySlug ? { categorySlug: title.categorySlug } : {}),
...(title.releaseWindow ? { releaseWindow: title.releaseWindow } : {}),
...(first ? { resumeMediaItemId: first.id } : {}),
...(first && first.variants.length ? { variants: first.variants as NonNullable<CatalogCard['variants']> } : {}),
};
}
@@ -387,6 +434,7 @@ function toTitleDetail(
durationSeconds: item.durationSeconds ?? 0,
compatibility: item.compatibility,
published: item.published,
variants: item.variants as NonNullable<TitleDetail['mediaItems'][number]['variants']>,
})),
updatedAt: title.updatedAt.toISOString(),
};
@@ -420,6 +468,8 @@ function toJob(job: typeof jobs.$inferSelect): Job {
function publicSessionDetails(session: StoredPlaybackSession): Record<string, unknown> {
return {
...(session.variantId ? { variantId: session.variantId } : {}),
...(session.qualityLabel ? { qualityLabel: session.qualityLabel } : {}),
...(session.manifestUrl ? { manifestUrl: session.manifestUrl } : {}),
...(session.durationSeconds !== undefined ? { durationSeconds: session.durationSeconds } : {}),
...(session.audioTracks ? { audioTracks: session.audioTracks } : {}),
+3
View File
@@ -167,6 +167,9 @@ export class AdminService {
const preparation = await this.media.getStatus({
sessionId: randomUUID(),
mediaItem: item,
variantId: item.variants.find((variant) => variant.available && variant.isDefault)?.id
?? item.variants.find((variant) => variant.available)?.id
?? item.id,
});
if (preparation.state !== 'READY' && !preparation.playable) {
throw new AppError(
+14 -10
View File
@@ -43,24 +43,26 @@ export class FileMediaPreparationService implements MediaPreparationService {
) {}
async prepare(input: Parameters<MediaPreparationService['prepare']>[0]) {
const status = await this.find(input.mediaItem.id);
const status = await this.find(input.mediaItem.id, input.variantId);
const requestKey = `${input.mediaItem.id}:${input.variantId ?? 'legacy'}`;
if (status) {
if (status.playable || status.state === 'READY' || status.state === 'FAILED') {
this.requested.delete(input.mediaItem.id);
this.requested.delete(requestKey);
}
await this.recordCacheAccess(input, status);
return status;
}
if (!this.requested.has(input.mediaItem.id)) {
this.requested.add(input.mediaItem.id);
if (!this.requested.has(requestKey)) {
this.requested.add(requestKey);
try {
await this.publisher.publish({
type: 'media.playback.requested',
sessionId: input.sessionId,
mediaItemId: input.mediaItem.id,
...(input.variantId ? { variantId: input.variantId } : {}),
});
} catch (error) {
this.requested.delete(input.mediaItem.id);
this.requested.delete(requestKey);
throw error;
}
}
@@ -73,9 +75,10 @@ export class FileMediaPreparationService implements MediaPreparationService {
}
async getStatus(input: Parameters<MediaPreparationService['getStatus']>[0]) {
const status = await this.find(input.mediaItem.id);
const status = await this.find(input.mediaItem.id, input.variantId);
const requestKey = `${input.mediaItem.id}:${input.variantId ?? 'legacy'}`;
if (status?.playable || status?.state === 'READY' || status?.state === 'FAILED') {
this.requested.delete(input.mediaItem.id);
this.requested.delete(requestKey);
}
const result = status ?? {
state: 'PREPARING' as const,
@@ -102,9 +105,10 @@ export class FileMediaPreparationService implements MediaPreparationService {
});
}
private async find(mediaItemId: string): Promise<MediaPreparation | undefined> {
private async find(mediaItemId: string, variantId?: string): Promise<MediaPreparation | undefined> {
const registry = await readPackageRegistry(this.registryPath);
const entry = registry?.packages.find((candidate) => candidate.mediaItemId === mediaItemId);
const entry = registry?.packages.find((candidate) => candidate.mediaItemId === mediaItemId
&& (candidate.variantId ?? candidate.mediaItemId) === (variantId ?? mediaItemId));
if (!entry) return undefined;
return {
state: entry.state,
@@ -226,7 +230,7 @@ function redisConnection(redisUrl: string): ConnectionOptions {
function commandJobId(command: MediaCommand, profile: string): string {
switch (command.type) {
case 'media.playback.requested':
return `playback-${command.mediaItemId}-${profile}`;
return `playback-${command.mediaItemId}-${command.variantId ?? 'legacy'}-${profile}`;
case 'archive.scan.requested':
return `scan-${command.jobId}`;
case 'media.publication.changed':
+35 -4
View File
@@ -23,10 +23,15 @@ export class PlaybackService {
async create(input: CreatePlaybackSession): Promise<StoredPlaybackSession> {
const item = await this.requirePlayableMedia(input.mediaItemId);
const variant = selectVariant(item, input.variantId);
if (!variant) throw new AppError(404, 'NOT_FOUND', 'Requested quality is unavailable');
const selectedItem = { ...item, compatibility: variant.compatibility };
const now = Date.now();
const base: StoredPlaybackSession = {
id: randomUUID(),
mediaItemId: item.id,
variantId: variant.id,
qualityLabel: variant.label,
state: 'PREPARING',
capabilities: input.clientCapabilities,
expiresAt: new Date(now + this.config.playbackTtlSeconds * 1000).toISOString(),
@@ -41,7 +46,7 @@ export class PlaybackService {
await this.repository.createPlaybackSession(unsupported);
return unsupported;
}
if (item.compatibility === 'HOLD_HDR') {
if (selectedItem.compatibility === 'HOLD_HDR') {
const unsupported: StoredPlaybackSession = {
...base,
state: 'UNSUPPORTED_CLIENT',
@@ -50,7 +55,7 @@ export class PlaybackService {
await this.repository.createPlaybackSession(unsupported);
return unsupported;
}
if (item.compatibility === 'INVALID') {
if (selectedItem.compatibility === 'INVALID') {
const failed: StoredPlaybackSession = {
...base,
state: 'FAILED',
@@ -63,7 +68,8 @@ export class PlaybackService {
await this.repository.createPlaybackSession(base);
const preparation = await this.media.prepare({
sessionId: base.id,
mediaItem: item,
mediaItem: selectedItem,
variantId: variant.id,
capabilities: input.clientCapabilities,
protectUntil: base.expiresAt,
});
@@ -79,9 +85,12 @@ export class PlaybackService {
}
if (session.state !== 'PREPARING') return session;
const item = await this.requirePlayableMedia(session.mediaItemId);
const variant = selectVariant(item, session.variantId);
if (!variant) throw new AppError(404, 'NOT_FOUND', 'Playback quality is no longer available');
const preparation = await this.media.getStatus({
sessionId: id,
mediaItem: item,
mediaItem: { ...item, compatibility: variant.compatibility },
variantId: variant.id,
protectUntil: session.expiresAt,
});
const updated = this.mergePreparation(session, preparation);
@@ -135,6 +144,28 @@ export class PlaybackService {
}
}
function selectVariant(item: MediaItemForPlayback, requestedId?: string) {
const available = item.variants.filter((variant) => variant.available);
if (requestedId) return available.find((variant) => variant.id === requestedId);
if (available.length === 0) {
return item.published ? {
id: item.id,
label: 'Source',
compatibility: item.compatibility,
available: true,
isDefault: true,
} : undefined;
}
return available.find((variant) => variant.isDefault)
?? [...available].sort((left, right) => {
const leftHeight = left.height ?? 0;
const rightHeight = right.height ?? 0;
const distance = Math.abs(leftHeight - 720) - Math.abs(rightHeight - 720);
if (distance !== 0) return distance;
return leftHeight <= 720 && rightHeight > 720 ? -1 : 1;
})[0];
}
function supportsHls(capabilities: ClientCapabilities): boolean {
return capabilities.nativeHls || (capabilities.mse && capabilities.hlsJs);
}
+6
View File
@@ -61,6 +61,10 @@ describe('viewer API', () => {
expect.objectContaining({ id: ids.title, playable: true }),
]);
const sections = await app.inject({ method: 'GET', url: '/api/v1/catalog/sections?limitPerSection=12' });
expect(sections.statusCode).toBe(200);
expect(sections.json().sections[0]).toEqual(expect.objectContaining({ slug: 'anime', name: 'Anime' }));
const search = await app.inject({ method: 'GET', url: '/api/v1/search?q=Sample' });
expect(search.statusCode).toBe(200);
expect(search.json().items[0].slug).toBe('sample-series');
@@ -89,6 +93,7 @@ describe('viewer API', () => {
url: '/api/v1/playback-sessions',
payload: {
mediaItemId: ids.media,
variantId: ids.variant,
clientCapabilities: capabilities(),
},
});
@@ -96,6 +101,7 @@ describe('viewer API', () => {
expect(response.json()).toEqual(
expect.objectContaining({
state: 'READY',
variantId: ids.variant,
manifestUrl: `http://localhost:8080/media/generations/${ids.generation}/master.m3u8`,
}),
);
+7
View File
@@ -7,6 +7,7 @@ export const ids = {
generation: '30000000-0000-4000-8000-000000000001',
audio: '40000000-0000-4000-8000-000000000001',
subtitle: '50000000-0000-4000-8000-000000000001',
variant: '60000000-0000-4000-8000-000000000001',
};
export const titleFixture: TitleDetail = {
@@ -16,6 +17,11 @@ export const titleFixture: TitleDetail = {
name: { fa: 'سریال نمونه', en: 'Sample Series' },
synopsis: { fa: 'خلاصه نمونه', en: 'Sample synopsis' },
playable: true,
category: 'Anime',
categorySlug: 'anime',
releaseWindow: 'SUMMER',
year: 2026,
variants: [{ id: ids.variant, label: '720p', width: 1280, height: 720, videoCodec: 'h264', compatibility: 'COPY', available: true, isDefault: true }],
resumeMediaItemId: ids.media,
seasons: [{ number: 1, episodeCount: 1 }],
mediaItems: [
@@ -28,6 +34,7 @@ export const titleFixture: TitleDetail = {
durationSeconds: 1420,
compatibility: 'COPY',
published: true,
variants: [{ id: ids.variant, label: '720p', width: 1280, height: 720, videoCodec: 'h264', compatibility: 'COPY', available: true, isDefault: true }],
},
],
updatedAt: '2026-07-14T00:00:00.000Z',
+1
View File
@@ -68,6 +68,7 @@ function mediaItem() {
durationSeconds: 100,
compatibility: 'COPY' as const,
published: true,
variants: [],
};
}
+25
View File
@@ -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"
}
}
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env node
import { mkdir } from 'node:fs/promises';
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);
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
pnpm showcase export-static [--output <directory>]
pnpm showcase preview-static [--output <directory>] [--port <number>]
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();
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 {
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 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();
}
}
main().catch((error) => {
console.error(`Error: ${(error as Error).message}`);
process.exitCode = 1;
});
+62
View File
@@ -0,0 +1,62 @@
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;
exportRoot: string;
}
export 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',
exportRoot: path.resolve(projectRoot, process.env.SHOWCASE_EXPORT_ROOT ?? './dist/showcase-static'),
};
}
export async function assertArchive(config: ShowcaseConfig): Promise<void> {
await access(config.archiveRoot);
}
+57
View File
@@ -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[];
}
+129
View File
@@ -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;
}
+107
View File
@@ -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),
};
}
+38
View File
@@ -0,0 +1,38 @@
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',
exportRoot: path.join(root, 'export'),
};
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();
});
});
+65
View File
@@ -0,0 +1,65 @@
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 { 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.'); });
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 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), 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 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 = 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 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', ...playback, 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}`);
}
+160
View File
@@ -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,
};
}
+89
View File
@@ -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');
});
});
+255
View File
@@ -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}`);
}
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2024"],
"types": ["node"],
"noEmit": true
},
"include": ["src/**/*.ts"]
}
+3
View File
@@ -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>
<template v-if="!showcase">
<span class="footer-dot" aria-hidden="true">•</span>
<RouterLink to="/admin">Admin</RouterLink>
</template>
</footer>
<PlayerShell />
</div>
+43
View File
@@ -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)
})
});
+141 -33
View File
@@ -3,6 +3,7 @@ import type {
AdminJob,
CatalogItem,
CatalogPage,
CatalogSection,
ClientCapabilities,
EpisodeItem,
LocalizedText,
@@ -10,11 +11,15 @@ import type {
PlaybackSession,
PlaybackState,
PlaybackSubtitleTrack,
QualityVariant,
SeasonItem,
TitleDetail,
} 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'
@@ -32,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)
@@ -67,6 +75,36 @@ 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 {
id: text(item.id) ?? '',
label: text(item.label) ?? `${number(item.height) ?? 0}p`,
...(number(item.width) ? { width: number(item.width) } : {}),
...(number(item.height) ? { height: number(item.height) } : {}),
...(text(item.videoCodec) ? { videoCodec: text(item.videoCodec) } : {}),
compatibility: text(item.compatibility) ?? 'INVALID',
available: boolean(item.available),
isDefault: boolean(item.isDefault),
}
}
function normalizeCatalogItem(input: unknown): CatalogItem {
const item = record(input)
const metadata = record(item.metadata)
@@ -95,6 +133,10 @@ function normalizeCatalogItem(input: unknown): CatalogItem {
...(posterUrl ? { posterUrl } : {}),
...(backdropUrl ? { backdropUrl } : {}),
...(number(item.year ?? metadata.year) !== undefined ? { year: number(item.year ?? metadata.year) } : {}),
...(text(item.category) ? { category: text(item.category) } : {}),
...(text(item.categorySlug) ? { categorySlug: text(item.categorySlug) } : {}),
...(text(item.releaseWindow) ? { releaseWindow: text(item.releaseWindow) } : {}),
variants: array(item.variants).map(normalizeVariant).filter((variant) => variant.id),
...(number(item.runtimeSeconds ?? item.durationSeconds) !== undefined
? { runtimeSeconds: number(item.runtimeSeconds ?? item.durationSeconds) }
: {}),
@@ -121,6 +163,7 @@ function normalizeEpisode(input: unknown, seasonNumber: number): EpisodeItem {
? { durationSeconds: number(item.durationSeconds ?? item.runtimeSeconds) }
: {}),
published: item.published === undefined ? true : boolean(item.published),
variants: array(item.variants).map(normalizeVariant).filter((variant) => variant.id),
}
}
@@ -134,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)
@@ -207,6 +283,8 @@ export function normalizePlaybackSession(input: unknown): PlaybackSession {
id,
state: normalizeState(payload.state ?? payload.status),
mediaItemId: text(payload.mediaItemId) ?? '',
...(text(payload.variantId) ? { variantId: text(payload.variantId) } : {}),
...(text(payload.qualityLabel) ? { qualityLabel: text(payload.qualityLabel) } : {}),
...(manifestUrl ? { manifestUrl } : {}),
...(number(payload.durationSeconds ?? payload.duration) !== undefined
? { durationSeconds: number(payload.durationSeconds ?? payload.duration) }
@@ -270,7 +348,17 @@ function withSignal(signal: AbortSignal | undefined, init: RequestInit = {}): Re
}
export const api = {
async catalog(options: { cursor?: string; limit?: number; kind?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
async catalog(options: { cursor?: string; limit?: number; kind?: string; category?: string; year?: number; releaseWindow?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
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
@@ -284,6 +372,27 @@ 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)
return {
slug: text(section.slug) ?? '',
name: text(section.name) ?? text(section.slug) ?? '',
items: array(section.items).map(normalizeCatalogItem).filter((item) => item.id),
hasMore: boolean(section.hasMore),
}
}).filter((section) => section.slug && section.items.length)
},
async search(term: string, signal?: AbortSignal): Promise<CatalogPage> {
const body = await request(`/search${queryString({ q: term, limit: 40 })}`, withSignal(signal))
const source = record(body)
@@ -296,59 +405,58 @@ 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(
mediaItemId: string,
clientCapabilities: ClientCapabilities,
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, clientCapabilities }),
body: JSON.stringify({ mediaItemId, ...(variantId ? { variantId } : {}), clientCapabilities }),
}))
const session = normalizePlaybackSession(body)
return { ...session, mediaItemId: session.mediaItemId || mediaItemId }
},
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 })
},
@@ -436,7 +544,7 @@ export const api = {
const body = record(await request('/admin/scans', {
method: 'POST',
headers: { 'x-csrf-token': csrfToken },
body: JSON.stringify({ full: false }),
body: JSON.stringify({ full: true }),
}))
const jobId = text(body.id ?? body.jobId ?? record(body.data).jobId)
return { ...(jobId ? { jobId } : {}) }
+3 -2
View File
@@ -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"
@@ -14,6 +14,7 @@ const item: CatalogItem = {
title: { fa: 'فیلم نمونه', en: 'Sample movie' },
overview: {},
playable: true,
variants: [],
year: 2026,
}
+1
View File
@@ -19,6 +19,7 @@ function play() {
if (!props.item.playable || !props.item.mediaItemId) return
player.play({
mediaItemId: props.item.mediaItemId,
...(props.item.variants.length ? { variants: props.item.variants } : {}),
title: title.value,
...(props.item.posterUrl ? { posterUrl: props.item.posterUrl } : {}),
})
+40 -4
View File
@@ -36,7 +36,7 @@ const currentTime = ref(0)
const duration = ref(0)
const buffered = ref(0)
const controlsVisible = ref(true)
const menu = ref<'subtitles' | 'audio' | null>(null)
const menu = ref<'subtitles' | 'audio' | 'quality' | null>(null)
const session = ref<PlaybackSession | null>(null)
const selectedSubtitle = ref('off')
const selectedAudio = ref('')
@@ -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())
@@ -442,7 +442,17 @@ async function start(request: PlayRequest) {
}
try {
const initial = await api.createPlaybackSession(request.mediaItemId, capabilities, requestController.signal)
const variants = (request.variants ?? []).filter((variant) => variant.available)
const selectedVariant = request.variantId
? variants.find((variant) => variant.id === request.variantId)
: variants.find((variant) => variant.height === ui.preferences.preferredQualityHeight)
?? variants.find((variant) => variant.isDefault)
const initial = await api.createPlaybackSession(
request.mediaItemId,
capabilities,
selectedVariant?.id,
requestController.signal,
)
await resolveSession(initial, sequence, requestController.signal)
} catch (error) {
if ((error as { name?: string }).name === 'AbortError' || sequence !== requestSequence) return
@@ -503,11 +513,23 @@ function toggleMute() {
void ui.setVolume(element.volume, element.muted)
}
function toggleMenu(target: 'subtitles' | 'audio') {
function toggleMenu(target: 'subtitles' | 'audio' | 'quality') {
menu.value = menu.value === target ? null : target
showControls()
}
async function chooseQuality(variant: NonNullable<PlayRequest['variants']>[number]) {
const request = currentRequest.value
if (!request || session.value?.variantId === variant.id) {
menu.value = null
return
}
await saveProgress(true)
if (variant.height) await ui.setPreferredQuality(variant.height)
menu.value = null
await start({ ...request, variantId: variant.id })
}
function formatTime(seconds: number): string {
if (!Number.isFinite(seconds) || seconds < 0) return '00:00'
const hours = Math.floor(seconds / 3600)
@@ -671,6 +693,20 @@ onBeforeUnmount(() => {
<span class="control-spacer" />
<div v-if="currentRequest?.variants?.some((variant) => variant.available)" class="control-menu-wrap">
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('quality')">{{ t('quality') }}</button>
<div v-if="menu === 'quality'" class="track-menu">
<button
v-for="variant in currentRequest.variants.filter((candidate) => candidate.available)"
:key="variant.id"
type="button"
data-tv-focus
:class="{ selected: variant.id === session?.variantId }"
@click="chooseQuality(variant)"
>{{ variant.label }}</button>
</div>
</div>
<div v-if="session?.audioTracks.length" class="control-menu-wrap">
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('audio')">{{ t('audio') }}</button>
<div v-if="menu === 'audio'" class="track-menu">
+3
View File
@@ -1,7 +1,10 @@
/// <reference types="vite/client" />
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 {
+12
View File
@@ -61,6 +61,12 @@ const fa = {
unavailable: 'ناموجود',
unsupported: 'پشتیبانی‌نشده',
year: 'سال',
quality: 'کیفیت',
browse: 'مرور',
browseAll: 'مشاهده همه',
allYears: 'همه سال‌ها',
releaseWindow: 'بازه انتشار',
allSeasons: 'همه فصل‌ها',
} as const
const en: Record<keyof typeof fa, string> = {
@@ -122,6 +128,12 @@ const en: Record<keyof typeof fa, string> = {
unavailable: 'Unavailable',
unsupported: 'Unsupported',
year: 'Year',
quality: 'Quality',
browse: 'Browse',
browseAll: 'Browse all',
allYears: 'All years',
releaseWindow: 'Release season',
allSeasons: 'All seasons',
}
export type TranslationKey = keyof typeof fa
+10 -6
View File
@@ -1,18 +1,22 @@
import { createRouter, createWebHistory } from 'vue-router'
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import AdminView from '@/views/AdminView.vue'
import CatalogView from '@/views/CatalogView.vue'
import SearchView from '@/views/SearchView.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 },
{ path: '/search', name: 'search', component: SearchView },
...(!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: '/' },
],
})
+1
View File
@@ -18,6 +18,7 @@ describe('viewer storage', () => {
audioLanguage: 'ja',
volume: 0.7,
muted: false,
preferredQualityHeight: 1080,
})
await expect(readPreferences()).resolves.toMatchObject({ uiLanguage: 'en', subtitleLanguage: 'en', volume: 0.7 })
+1
View File
@@ -11,6 +11,7 @@ export const defaultPreferences: ViewerPreferences = {
audioLanguage: 'ja',
volume: 1,
muted: false,
preferredQualityHeight: 720,
}
let databasePromise: Promise<IDBDatabase | null> | undefined
+2
View File
@@ -3,6 +3,8 @@ import { markRaw } from 'vue'
export interface PlayRequest {
mediaItemId: string
variantId?: string
variants?: import('@/types').QualityVariant[]
title: string
posterUrl?: string
}
+5
View File
@@ -43,5 +43,10 @@ export const useUiStore = defineStore('ui', {
this.preferences.muted = muted
await writePreferences({ ...this.preferences })
},
async setPreferredQuality(height: number) {
this.preferences.preferredQualityHeight = Math.max(1, Math.round(height))
await writePreferences({ ...this.preferences })
},
},
})
+53 -4
View File
@@ -39,7 +39,8 @@ body {
}
button,
input {
input,
select {
font: inherit;
}
@@ -968,15 +969,18 @@ button:disabled,
.player-status {
position: absolute;
z-index: 8;
box-sizing: border-box;
display: flex;
width: min(42rem, calc(100% - 2rem));
min-height: 18rem;
min-height: min(18rem, calc(100% - 2rem));
max-height: calc(100% - 2rem);
overflow-y: auto;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.9rem;
inset-block-start: 50%;
inset-inline-start: 50%;
top: 50%;
left: 50%;
padding: 2rem;
color: white;
text-align: center;
@@ -1002,6 +1006,7 @@ button:disabled,
.player-status p,
.player-status small {
color: #c7ccda;
overflow-wrap: anywhere;
}
.status-symbol {
@@ -1356,3 +1361,47 @@ button:disabled,
animation-iteration-count: 1 !important;
}
}
.section-heading,
.browse-header,
.browse-filters {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.category-rail {
display: flex;
overflow-x: auto;
overflow-y: hidden;
scroll-snap-type: x proximity;
padding-block: .5rem 1rem;
}
.category-rail > * {
flex: 0 0 clamp(10rem, 17vw, 15rem);
scroll-snap-align: start;
}
.browse-view {
padding: 7rem clamp(1rem, 4vw, 4rem) 4rem;
min-height: 100vh;
}
.browse-header { margin-bottom: 2rem; align-items: end; }
.browse-header h1 { margin: .25rem 0 0; font-size: clamp(2rem, 5vw, 4rem); }
.browse-filters select {
min-width: 10rem;
padding: .75rem 1rem;
color: var(--text);
background: var(--panel-raised);
border: 1px solid var(--line);
border-radius: .8rem;
}
@media (max-width: 700px) {
.browse-header { align-items: stretch; flex-direction: column; }
.browse-filters { align-items: stretch; }
.browse-filters select { min-width: 0; flex: 1; }
}
+26
View File
@@ -6,6 +6,17 @@ export interface LocalizedText {
en?: string | undefined
}
export interface QualityVariant {
id: string
label: string
width?: number | undefined
height?: number | undefined
videoCodec?: string | undefined
compatibility: string
available: boolean
isDefault: boolean
}
export interface CatalogItem {
id: string
mediaItemId: string
@@ -16,6 +27,10 @@ export interface CatalogItem {
posterUrl?: string | undefined
backdropUrl?: string | undefined
year?: number | undefined
category?: string | undefined
categorySlug?: string | undefined
releaseWindow?: string | undefined
variants: QualityVariant[]
runtimeSeconds?: number | undefined
seasonCount?: number | undefined
episodeCount?: number | undefined
@@ -34,6 +49,7 @@ export interface EpisodeItem {
posterUrl?: string | undefined
durationSeconds?: number | undefined
published: boolean
variants: QualityVariant[]
}
export interface SeasonItem {
@@ -54,6 +70,13 @@ export interface CatalogPage {
total?: number | undefined
}
export interface CatalogSection {
slug: string
name: string
items: CatalogItem[]
hasMore: boolean
}
export type PlaybackState = 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED'
export type SubtitleDelivery = 'ASS_JASSUB' | 'WEBVTT' | 'OFF'
@@ -79,6 +102,8 @@ export interface PlaybackSession {
id: string
state: PlaybackState
mediaItemId: string
variantId?: string | undefined
qualityLabel?: string | undefined
manifestUrl?: string | undefined
durationSeconds?: number | undefined
pollAfterMs: number
@@ -115,6 +140,7 @@ export interface ViewerPreferences {
audioLanguage: string
volume: number
muted: boolean
preferredQualityHeight: number
}
export interface AdminJob {
+74
View File
@@ -0,0 +1,74 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { api } from '@/api/client'
import LoadingState from '@/components/LoadingState.vue'
import MediaCard from '@/components/MediaCard.vue'
import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import type { CatalogItem } from '@/types'
const route = useRoute()
const root = ref<HTMLElement | null>(null)
const items = ref<CatalogItem[]>([])
const sourceItems = ref<CatalogItem[]>([])
const year = ref('')
const releaseWindow = ref('')
const loading = ref(true)
const error = ref('')
let controller: AbortController | undefined
const { t } = useI18n()
useSpatialNavigation(root, { restoreKey: 'browse-focus' })
const category = computed(() => String(route.params.category ?? ''))
const categoryName = computed(() => sourceItems.value[0]?.category ?? category.value)
const years = computed(() => [...new Set(sourceItems.value.map((item) => item.year).filter((value): value is number => value !== undefined))].sort((a, b) => b - a))
const windows = computed(() => [...new Set(sourceItems.value.map((item) => item.releaseWindow).filter((value): value is string => Boolean(value)))])
async function load() {
controller?.abort()
controller = new AbortController()
loading.value = true
error.value = ''
try {
const page = await api.catalog({
category: category.value,
limit: 100,
...(year.value ? { year: Number(year.value) } : {}),
...(releaseWindow.value ? { releaseWindow: releaseWindow.value } : {}),
}, controller.signal)
items.value = page.items
if (!year.value && !releaseWindow.value) sourceItems.value = page.items
} catch (reason) {
if ((reason as { name?: string }).name !== 'AbortError') error.value = reason instanceof Error ? reason.message : t('networkError')
} finally {
loading.value = false
}
}
watch([category, year, releaseWindow], () => void load(), { immediate: true })
onBeforeUnmount(() => controller?.abort())
</script>
<template>
<main ref="root" class="browse-view">
<header class="browse-header">
<div><p class="eyebrow">{{ t('browse') }}</p><h1>{{ categoryName }}</h1></div>
<div class="browse-filters">
<select v-model="year" data-tv-focus class="focus-ring" :aria-label="t('year')">
<option value="">{{ t('allYears') }}</option>
<option v-for="value in years" :key="value" :value="String(value)">{{ value }}</option>
</select>
<select v-model="releaseWindow" data-tv-focus class="focus-ring" :aria-label="t('releaseWindow')">
<option value="">{{ t('allSeasons') }}</option>
<option v-for="value in windows" :key="value" :value="value">{{ value }}</option>
</select>
</div>
</header>
<LoadingState v-if="loading" :label="t('loadingCatalog')" />
<section v-else-if="error" class="center-state error-state"><p>{{ error }}</p></section>
<section v-else-if="items.length" class="media-grid">
<MediaCard v-for="item in items" :key="item.id" :item="item" />
</section>
<section v-else class="center-state"><h2>{{ t('emptyCatalog') }}</h2></section>
</main>
</template>
+16 -8
View File
@@ -8,15 +8,17 @@ import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import { listProgress } from '@/storage/viewer-db'
import { usePlayerStore } from '@/stores/player'
import type { CatalogItem } from '@/types'
import type { CatalogItem, CatalogSection } from '@/types'
const root = ref<HTMLElement | null>(null)
const items = ref<CatalogItem[]>([])
const sections = ref<CatalogSection[]>([])
const progress = ref<Record<string, number>>({})
const loading = ref(true)
const error = ref('')
const { localize, t } = useI18n()
const player = usePlayerStore()
const 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' })
@@ -25,6 +27,7 @@ function playFeatured() {
if (!item?.playable || !item.mediaItemId) return
player.play({
mediaItemId: item.mediaItemId,
...(item.variants.length ? { variants: item.variants } : {}),
title: localize(item.title, item.slug),
...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
})
@@ -34,8 +37,8 @@ async function load() {
loading.value = true
error.value = ''
try {
const [catalog, storedProgress] = await Promise.all([api.catalog({ limit: 60 }), listProgress()])
items.value = catalog.items
const [catalogSections, storedProgress] = await Promise.all([api.catalogSections(12), listProgress()])
sections.value = catalogSections
progress.value = Object.fromEntries(storedProgress.map((entry) => [
entry.mediaItemId,
entry.durationSeconds > 0 ? (entry.positionSeconds / entry.durationSeconds) * 100 : 0,
@@ -96,11 +99,16 @@ onMounted(() => void load())
</div>
</section>
<section class="catalog-section" aria-labelledby="catalog-heading">
<h2 id="catalog-heading">{{ t('allTitles') }}</h2>
<div class="media-grid">
<section v-for="section in sections" :key="section.slug" class="catalog-section">
<div class="section-heading">
<h2>{{ section.name }}</h2>
<RouterLink v-if="!showcase" class="secondary-button focus-ring" data-tv-focus :to="{ name: 'browse', params: { category: section.slug } }">
{{ t('browseAll') }}
</RouterLink>
</div>
<div class="media-grid category-rail">
<MediaCard
v-for="item in items"
v-for="item in section.items"
:key="item.id"
:item="item"
:progress="progress[item.mediaItemId]"
+2
View File
@@ -31,6 +31,7 @@ function playTitle() {
if (!detail.value || !mediaItemId) return
player.play({
mediaItemId,
...(detail.value.variants.length ? { variants: detail.value.variants } : {}),
title: title.value,
...(detail.value.posterUrl ? { posterUrl: detail.value.posterUrl } : {}),
})
@@ -39,6 +40,7 @@ function playTitle() {
function playEpisode(episode: EpisodeItem) {
player.play({
mediaItemId: episode.mediaItemId,
...(episode.variants.length ? { variants: episode.variants } : {}),
title: `${title.value} · ${t('episode')} ${episode.number}`,
...(episode.posterUrl ? { posterUrl: episode.posterUrl } : {}),
})
+1
View File
@@ -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: {
+191 -29
View File
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto';
import { access, copyFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
import {
assDialogueText,
@@ -23,6 +24,11 @@ export interface ParsedMediaIdentity {
seasonNumber?: number;
episodeNumber?: number;
episodeTitle?: string;
category?: string;
categorySlug?: string;
year?: number;
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
titleDirectory?: string;
}
export interface SnapshotSubtitle {
@@ -38,16 +44,15 @@ export interface SnapshotSubtitle {
forced: false;
}
export interface SnapshotMediaItem {
export interface SnapshotMediaVariant {
id: string;
titleId: string;
kind: 'MOVIE' | 'EPISODE';
sourcePath: string;
durationSeconds: number;
seasonNumber?: number;
episodeNumber?: number;
title: { en: string; fa?: string };
published: boolean;
qualityLabel: string;
width?: number;
height?: number;
videoCodec?: string;
available: boolean;
compatibility: Classification['class'];
compatibilityReasons: string[];
fingerprint: SourceFingerprint;
@@ -55,6 +60,16 @@ export interface SnapshotMediaItem {
subtitles: SnapshotSubtitle[];
}
export interface SnapshotMediaItem extends SnapshotMediaVariant {
titleId: string;
kind: 'MOVIE' | 'EPISODE';
seasonNumber?: number;
episodeNumber?: number;
title: { en: string; fa?: string };
published: boolean;
variants?: SnapshotMediaVariant[];
}
export interface SnapshotSeason {
number: number;
title: { en: string };
@@ -66,6 +81,11 @@ export interface SnapshotTitle {
slug: string;
kind: CatalogKind;
title: { en: string; fa?: string };
category?: string;
categorySlug?: string;
year?: number;
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
posterUrl?: string;
published: boolean;
playable: boolean;
mediaItemId: string;
@@ -93,6 +113,16 @@ export interface PublicMediaItem {
durationSeconds: number;
compatibility: Classification['class'];
published: boolean;
variants?: Array<{
id: string;
label: string;
width?: number;
height?: number;
videoCodec?: string;
compatibility: Classification['class'];
available: boolean;
isDefault: boolean;
}>;
}
export interface PublicTitleDetail {
@@ -100,8 +130,14 @@ export interface PublicTitleDetail {
slug: string;
kind: CatalogKind;
name: { fa: string; en?: string };
posterUrl?: string;
category?: string;
categorySlug?: string;
year?: number;
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
playable: boolean;
resumeMediaItemId?: string;
variants?: PublicMediaItem['variants'];
synopsis: { fa?: string; en?: string };
seasons?: Array<{ number: number; episodeCount: number }>;
mediaItems: PublicMediaItem[];
@@ -146,16 +182,33 @@ export function slugify(value: string): string {
export function parseMediaIdentity(relativePath: string): ParsedMediaIdentity {
const extension = path.extname(relativePath);
const filename = path.basename(relativePath, extension);
const parent = path.basename(path.dirname(relativePath));
const segments = relativePath.split('/').filter(Boolean);
const immediateParent = segments.at(-2) ?? '';
const qualityDirectory = /^(?:\d{3,4}p?)(?:[\s._-]+(?:x26[45]|hevc|av1))?$|^(?:x26[45]|hevc|av1)$/iu.test(immediateParent);
const titleDirectory = segments.at(qualityDirectory ? -3 : -2) ?? immediateParent;
const titleIndex = Math.max(0, segments.length - (qualityDirectory ? 3 : 2));
const hierarchy = segments.slice(0, titleIndex);
const categorySource = hierarchy[0];
const yearSource = hierarchy.find((segment) => /^(?:18|19|20|21|22)\d{2}$/u.test(segment));
const releaseSource = hierarchy.find((segment) => /^(?:spring|summer|fall|winter|movie)$/iu.test(segment));
const releaseWindow = releaseSource?.toLocaleUpperCase('en-US') as ParsedMediaIdentity['releaseWindow'];
const category = categorySource ? cleanName(categorySource).replace(/^./u, (value) => value.toLocaleUpperCase('en-US')) : undefined;
const combined = filename.match(/\bS(?:eason)?\s*(\d{1,3})\s*E(?:p(?:isode)?)?\s*(\d{1,4})\b/iu);
const parentSeason = parent.match(/^(.*?)(?:[\s._-]+S(?:eason)?\s*(\d{1,3}))$/iu);
const parentSeason = titleDirectory.match(/^(.*?)(?:[\s._-]+S(?:eason)?\s*(\d{1,3}))$/iu);
const episode = combined?.[2]
?? filename.match(/(?:-|–)\s*(\d{1,4})(?=(?:[.\s_\[]|$))/u)?.[1]
?? filename.match(/\bE(?:p(?:isode)?)?\s*(\d{1,4})\b/iu)?.[1];
if (episode !== undefined) {
const common = {
...(category ? { category, categorySlug: slugify(category) } : {}),
...(yearSource ? { year: Number(yearSource) } : {}),
...(releaseWindow ? { releaseWindow } : {}),
...(titleDirectory ? { titleDirectory: segments.slice(0, titleIndex + 1).join('/') } : {}),
};
if (episode !== undefined && releaseWindow !== 'MOVIE') {
const season = Number(combined?.[1] ?? parentSeason?.[2] ?? 1);
const title = cleanName(parentSeason?.[1] ?? parent);
const title = cleanName(parentSeason?.[1] ?? titleDirectory);
return {
...common,
kind: 'SERIES',
title: title || cleanName(filename),
seasonNumber: season,
@@ -163,7 +216,7 @@ export function parseMediaIdentity(relativePath: string): ParsedMediaIdentity {
episodeTitle: `Episode ${Number(episode)}`,
};
}
return { kind: 'MOVIE', title: cleanName(filename) };
return { ...common, kind: 'MOVIE', title: cleanName(titleDirectory || filename) };
}
export interface ScanArchiveOptions {
@@ -171,6 +224,7 @@ export interface ScanArchiveOptions {
ffmpegPath?: string;
ffprobePath?: string;
onFile?: (relativePath: string, current: number) => void;
artworkRoot?: string;
}
const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']);
@@ -185,7 +239,7 @@ async function inspectFile(
sourcePath: string,
archiveRoot: string,
options: ScanArchiveOptions,
): Promise<{ identity: ParsedMediaIdentity; media: SnapshotMediaItem }> {
): Promise<{ identity: ParsedMediaIdentity; variant: SnapshotMediaVariant }> {
const relativePath = path.relative(archiveRoot, sourcePath).split(path.sep).join('/');
const identity = parseMediaIdentity(relativePath);
const [probe, fingerprint] = await Promise.all([
@@ -193,8 +247,7 @@ async function inspectFile(
fingerprintSource(archiveRoot, sourcePath),
]);
const compatibility = classifyMedia(probe);
const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`);
const mediaId = deterministicUuid(`media:${relativePath}`);
const variantId = deterministicUuid(`variant:${relativePath}`);
const tracks = normalizeTracks(probe);
const subtitles: SnapshotSubtitle[] = [];
for (const stream of probe.streams.filter((candidate) => candidate.codec_type === 'subtitle')) {
@@ -234,19 +287,20 @@ async function inspectFile(
});
}
const duration = Number(probe.format.duration);
const published = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class);
const video = probe.streams.find((stream) => stream.codec_type === 'video');
const available = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class);
const qualityLabel = video?.height ? `${video.height}p` : cleanName(path.basename(path.dirname(relativePath))) || 'Source';
return {
identity,
media: {
id: mediaId,
titleId,
kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE',
variant: {
id: variantId,
sourcePath: relativePath,
durationSeconds: Number.isFinite(duration) ? duration : 0,
...(identity.seasonNumber === undefined ? {} : { seasonNumber: identity.seasonNumber }),
...(identity.episodeNumber === undefined ? {} : { episodeNumber: identity.episodeNumber }),
title: { en: identity.episodeTitle ?? identity.title },
published,
qualityLabel,
...(video?.width ? { width: video.width } : {}),
...(video?.height ? { height: video.height } : {}),
...(video?.codec_name ? { videoCodec: video.codec_name } : {}),
available,
compatibility: compatibility.class,
compatibilityReasons: compatibility.reasons,
fingerprint,
@@ -258,19 +312,48 @@ async function inspectFile(
export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArchiveResult> {
const root = path.resolve(options.archiveRoot);
const grouped = new Map<string, { identity: ParsedMediaIdentity; media: SnapshotMediaItem[] }>();
const grouped = new Map<string, { identity: ParsedMediaIdentity; variants: SnapshotMediaVariant[] }>();
let current = 0;
for await (const sourcePath of walkArchive(root)) {
current += 1;
const relative = path.relative(root, sourcePath).split(path.sep).join('/');
options.onFile?.(relative, current);
const inspected = await inspectFile(sourcePath, root, options);
const key = `${inspected.identity.kind}:${inspected.identity.title.toLocaleLowerCase('en-US')}`;
const group = grouped.get(key) ?? { identity: inspected.identity, media: [] };
group.media.push(inspected.media);
const logical = inspected.identity.kind === 'MOVIE'
? 'movie'
: `s${inspected.identity.seasonNumber ?? 1}e${inspected.identity.episodeNumber ?? 0}`;
const key = `${inspected.identity.kind}:${inspected.identity.title.toLocaleLowerCase('en-US')}:${logical}`;
const group = grouped.get(key) ?? { identity: inspected.identity, variants: [] };
group.variants.push(inspected.variant);
grouped.set(key, group);
}
const items: SnapshotTitle[] = [...grouped.values()].map(({ identity, media }) => {
const logicalItems = [...grouped.values()].map(({ identity, variants }) => {
variants.sort(compareVariants);
const selected = variants[0];
if (!selected) throw new Error('Internal media group has no source variants');
const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`);
const logicalKey = identity.kind === 'MOVIE' ? 'movie' : `s${identity.seasonNumber ?? 1}e${identity.episodeNumber ?? 0}`;
const media: SnapshotMediaItem = {
...selected,
id: deterministicUuid(`media:${titleId}:${logicalKey}`),
titleId,
kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE',
...(identity.seasonNumber === undefined ? {} : { seasonNumber: identity.seasonNumber }),
...(identity.episodeNumber === undefined ? {} : { episodeNumber: identity.episodeNumber }),
title: { en: identity.episodeTitle ?? identity.title },
published: variants.some((variant) => variant.available),
variants,
};
return { identity, media };
});
const byTitle = new Map<string, { identity: ParsedMediaIdentity; media: SnapshotMediaItem[] }>();
for (const entry of logicalItems) {
const key = `${entry.identity.kind}:${entry.identity.title.toLocaleLowerCase('en-US')}`;
const title = byTitle.get(key) ?? { identity: entry.identity, media: [] };
title.media.push(entry.media);
byTitle.set(key, title);
}
const items: SnapshotTitle[] = [...byTitle.values()].map(({ identity, media }) => {
media.sort((left, right) => (left.seasonNumber ?? 0) - (right.seasonNumber ?? 0)
|| (left.episodeNumber ?? 0) - (right.episodeNumber ?? 0));
const first = media[0];
@@ -291,6 +374,10 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
slug: slugify(identity.title),
kind: identity.kind,
title: { en: identity.title },
...(identity.category ? { category: identity.category } : {}),
...(identity.categorySlug ? { categorySlug: identity.categorySlug } : {}),
...(identity.year ? { year: identity.year } : {}),
...(identity.releaseWindow ? { releaseWindow: identity.releaseWindow } : {}),
published,
playable: published,
mediaItemId: first.id,
@@ -301,6 +388,18 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
mediaItems: media,
};
});
for (const item of items) {
const identity = byTitle.get(`${item.kind}:${item.title.en.toLocaleLowerCase('en-US')}`)?.identity;
if (!identity?.titleDirectory) continue;
const source = await findThumbnail(path.join(root, identity.titleDirectory));
if (!source) continue;
const extension = path.extname(source).toLocaleLowerCase('en-US').replace('.jpeg', '.jpg');
item.posterUrl = `/images/archive/${item.id}${extension}`;
if (options.artworkRoot) {
await mkdir(options.artworkRoot, { recursive: true, mode: 0o750 });
await copyFile(source, path.join(options.artworkRoot, `${item.id}${extension}`));
}
}
items.sort((left, right) => left.title.en.localeCompare(right.title.en));
const generatedAt = new Date().toISOString();
const titles: PublicTitleDetail[] = items.map((item) => ({
@@ -309,8 +408,25 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
kind: item.kind,
// Filename-derived text is a safe temporary fallback until metadata matching supplies Persian.
name: { fa: item.title.fa ?? item.title.en, en: item.title.en },
...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
...(item.category ? { category: item.category } : {}),
...(item.categorySlug ? { categorySlug: item.categorySlug } : {}),
...(item.year ? { year: item.year } : {}),
...(item.releaseWindow ? { releaseWindow: item.releaseWindow } : {}),
playable: item.playable,
...(item.playable ? { resumeMediaItemId: item.resumeMediaItemId } : {}),
...(item.mediaItems[0]?.variants ? {
variants: item.mediaItems[0].variants.map((variant, index) => ({
id: variant.id,
label: variant.qualityLabel,
...(variant.width ? { width: variant.width } : {}),
...(variant.height ? { height: variant.height } : {}),
...(variant.videoCodec ? { videoCodec: variant.videoCodec } : {}),
compatibility: variant.compatibility,
available: variant.available,
isDefault: index === 0,
})),
} : {}),
synopsis: {},
...(item.kind === 'SERIES'
? { seasons: item.seasons.map((season) => ({ number: season.number, episodeCount: season.episodes.length })) }
@@ -324,6 +440,16 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
durationSeconds: media.durationSeconds,
compatibility: media.compatibility,
published: media.published,
variants: (media.variants ?? [media]).map((variant, index) => ({
id: variant.id,
label: variant.qualityLabel,
...(variant.width ? { width: variant.width } : {}),
...(variant.height ? { height: variant.height } : {}),
...(variant.videoCodec ? { videoCodec: variant.videoCodec } : {}),
compatibility: variant.compatibility,
available: variant.available,
isDefault: index === 0,
})),
})),
updatedAt: generatedAt,
}));
@@ -337,3 +463,39 @@ export function findMediaItem(snapshot: InventorySnapshot, idOrPath: string): Sn
return snapshot.items.flatMap((item) => item.mediaItems)
.find((media) => media.id === idOrPath || media.sourcePath === idOrPath);
}
export function findMediaVariant(
snapshot: InventorySnapshot,
mediaItemId: string,
variantId?: string,
): SnapshotMediaItem | undefined {
const media = findMediaItem(snapshot, mediaItemId);
if (!media || variantId === undefined) return media;
const variant = media.variants?.find((candidate) => candidate.id === variantId);
return variant ? { ...media, ...variant, id: media.id, ...(media.variants ? { variants: media.variants } : {}) } : undefined;
}
function compareVariants(left: SnapshotMediaVariant, right: SnapshotMediaVariant): number {
if (left.available !== right.available) return left.available ? -1 : 1;
const leftHeight = left.height ?? 0;
const rightHeight = right.height ?? 0;
const leftDistance = Math.abs(leftHeight - 720);
const rightDistance = Math.abs(rightHeight - 720);
if (leftDistance !== rightDistance) return leftDistance - rightDistance;
if ((leftHeight <= 720) !== (rightHeight <= 720)) return leftHeight <= 720 ? -1 : 1;
if (left.compatibility !== right.compatibility) return left.compatibility === 'COPY' ? -1 : 1;
return left.sourcePath.localeCompare(right.sourcePath);
}
async function findThumbnail(directory: string): Promise<string | undefined> {
for (const filename of ['thumbnail.jpg', 'thumbnail.jpeg', 'thumbnail.png', 'thumbnail.webp']) {
const candidate = path.join(directory, filename);
try {
await access(candidate);
return candidate;
} catch {
// Continue to the next supported local artwork extension.
}
}
return undefined;
}
+48 -11
View File
@@ -29,6 +29,7 @@ import {
import {
deterministicUuid,
findMediaItem,
findMediaVariant,
scanArchive,
type InventorySnapshot,
type SnapshotMediaItem,
@@ -111,12 +112,21 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
}
const result = await scanArchive({
archiveRoot,
...(output === undefined ? {} : { artworkRoot: path.join(path.dirname(output), 'artwork') }),
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
...(flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
onFile(relativePath, current) {
process.stderr.write(`[scan ${current}] ${relativePath}\n`);
},
});
// Direct scans stay portable; the long-running worker passes DATABASE_URL explicitly.
const databaseUrl = flag(arguments_, 'database');
const databaseSync = databaseUrl === undefined
? undefined
: await withDatabase(databaseUrl, (database) => syncCatalogSnapshot(database, result.catalog, {
authoritative: arguments_.flags.has('full'),
}));
if (databaseSync) applyMediaIdMap(result, databaseSync.mediaIdMap);
if (output !== undefined) {
await Promise.all([
writeJsonAtomic(output, result.catalog),
@@ -124,12 +134,6 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
]);
}
// Direct scans stay portable; the long-running worker passes DATABASE_URL explicitly.
const databaseUrl = flag(arguments_, 'database');
const databaseSync = databaseUrl === undefined
? undefined
: await withDatabase(databaseUrl, (database) => syncCatalogSnapshot(database, result.catalog));
if (output === undefined) process.stdout.write(`${JSON.stringify(result.catalog, null, 2)}\n`);
else {
process.stdout.write(`${JSON.stringify({
@@ -137,11 +141,26 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
...(inventoryOutput === undefined ? {} : { inventoryOutput: path.resolve(inventoryOutput) }),
titles: result.catalog.titles.length,
mediaItems: result.catalog.titles.reduce((sum, item) => sum + item.mediaItems.length, 0),
...(databaseSync === undefined ? {} : { databaseSync }),
...(databaseSync === undefined ? {} : { databaseSync: { titlesSeen: databaseSync.titlesSeen, mediaItemsSeen: databaseSync.mediaItemsSeen } }),
})}\n`);
}
}
function applyMediaIdMap(result: Awaited<ReturnType<typeof scanArchive>>, mediaIdMap: Record<string, string>): void {
for (const title of result.inventory.items) {
for (const media of title.mediaItems) media.id = mediaIdMap[media.id] ?? media.id;
title.mediaItemId = mediaIdMap[title.mediaItemId] ?? title.mediaItemId;
title.resumeMediaItemId = mediaIdMap[title.resumeMediaItemId] ?? title.resumeMediaItemId;
for (const season of title.seasons) {
for (const media of season.episodes) media.id = mediaIdMap[media.id] ?? media.id;
}
}
for (const title of result.catalog.titles) {
if (title.resumeMediaItemId) title.resumeMediaItemId = mediaIdMap[title.resumeMediaItemId] ?? title.resumeMediaItemId;
for (const media of title.mediaItems) media.id = mediaIdMap[media.id] ?? media.id;
}
}
async function withDatabase<T>(
connectionString: string,
action: (database: Database) => Promise<T>,
@@ -163,8 +182,9 @@ async function loadInventory(snapshotPath: string): Promise<InventorySnapshot> {
async function sourceSelection(
arguments_: Arguments,
archiveRoot: string,
): Promise<{ media: SnapshotMediaItem; sourcePath: string }> {
): Promise<{ media: SnapshotMediaItem; sourcePath: string; variantId: string }> {
const mediaItem = flag(arguments_, 'media-item');
const variantId = flag(arguments_, 'variant-id');
const requestedSource = flag(arguments_, 'source');
const inventoryPath = flag(arguments_, 'inventory', './data/inventory.json') ?? './data/inventory.json';
let inventory: InventorySnapshot | undefined;
@@ -175,9 +195,14 @@ async function sourceSelection(
}
const selected = mediaItem === undefined
? (requestedSource === undefined ? undefined : inventory === undefined ? undefined : findMediaItem(inventory, requestedSource))
: inventory === undefined ? undefined : findMediaItem(inventory, mediaItem);
: inventory === undefined ? undefined : findMediaVariant(inventory, mediaItem, variantId);
if (selected !== undefined) {
return { media: selected, sourcePath: await resolveInside(archiveRoot, path.join(archiveRoot, selected.sourcePath)) };
const selectedVariantId = selected.variants?.find((variant) => variant.sourcePath === selected.sourcePath)?.id ?? selected.id;
return {
media: selected,
variantId: selectedVariantId,
sourcePath: await resolveInside(archiveRoot, path.join(archiveRoot, selected.sourcePath)),
};
}
if (mediaItem !== undefined) throw new Error(`Media item was not found in ${inventoryPath}: ${mediaItem}`);
if (requestedSource === undefined) throw new Error('package requires --media-item ID or --source PATH');
@@ -192,12 +217,17 @@ async function sourceSelection(
const classification = classifyMedia(probe);
return {
sourcePath,
variantId: deterministicUuid(`variant:${relative}`),
media: {
id: deterministicUuid(`media:${relative}`),
titleId: deterministicUuid(`title:${relative}`),
kind: 'MOVIE',
sourcePath: relative,
durationSeconds: Number(probe.format.duration) || 0,
qualityLabel: probe.streams.find((stream) => stream.codec_type === 'video')?.height
? `${probe.streams.find((stream) => stream.codec_type === 'video')?.height}p`
: 'Source',
available: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class),
title: { en: path.basename(relative, path.extname(relative)) },
published: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class),
compatibility: classification.class,
@@ -232,6 +262,7 @@ async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): P
const preparing = async (error?: string): Promise<void> => {
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: error === undefined ? 'PREPARING' : 'FAILED',
playable: false,
@@ -304,6 +335,7 @@ async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): P
const fontUrls = fonts.map((font) => `/media/${generationPath}/fonts/${font.sha256}.${font.format}`);
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: 'READY',
playable: true,
@@ -378,6 +410,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
const generationId = deterministicUuid(`generation:compat-h264-v1:${fingerprint.digest}`);
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: 'PREPARING',
playable: false,
@@ -416,6 +449,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio');
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: 'READY',
playable: true,
@@ -442,6 +476,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
} catch (error) {
await updateRegistry(registryPath, selected.media.id, {
mediaItemId: selected.media.id,
variantId: selected.variantId,
generationId,
state: 'FAILED',
playable: false,
@@ -482,7 +517,8 @@ async function workCommand(arguments_: Arguments): Promise<void> {
if (command.type === 'media.playback.requested') {
await main([
'package', '--root', archiveRoot, '--cache', cacheRoot, '--inventory', inventory,
'--registry', registry, '--media-item', command.mediaItemId, ...mediaTools,
'--registry', registry, '--media-item', command.mediaItemId,
...(command.variantId ? ['--variant-id', command.variantId] : []), ...mediaTools,
], { protectedCacheKeys: () => running.protectedCacheGenerations() });
} else if (command.type === 'archive.scan.requested') {
if (databaseUrl !== undefined) {
@@ -491,6 +527,7 @@ async function workCommand(arguments_: Arguments): Promise<void> {
}
await main([
'scan', '--root', archiveRoot, '--output', catalog, '--inventory-output', inventory,
...(command.full ? ['--full'] : []),
...(databaseUrl === undefined ? [] : ['--database', databaseUrl]),
...mediaTools,
]);
+3 -1
View File
@@ -45,6 +45,7 @@ export interface RegistrySubtitleTrack {
export interface RegistryGeneration {
mediaItemId: string;
variantId?: string;
state: 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED';
generationId?: string;
manifestPath?: string;
@@ -104,7 +105,8 @@ export async function updateRegistry(
const current = previous.catch(() => undefined).then(async () => {
const registry = await readRegistry(key);
registry.updatedAt = new Date().toISOString();
const index = registry.packages.findIndex((entry) => entry.mediaItemId === mediaItemId);
const index = registry.packages.findIndex((entry) => entry.mediaItemId === mediaItemId
&& (entry.variantId ?? entry.mediaItemId) === (generation.variantId ?? generation.mediaItemId));
if (index < 0) registry.packages.push(generation);
else {
const current = registry.packages[index];
+9 -1
View File
@@ -4,7 +4,15 @@ import { deterministicUuid, parseMediaIdentity, shouldInspectSubtitleContent, sl
describe('catalog filename parsing', () => {
it('groups the supplied season folder and episode filename', () => {
expect(parseMediaIdentity('Mushoku Tensei S3/Mushoku Tensei S3 - 01.[SS][720p][MixFlixTop].mkv'))
.toEqual({ kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 1, episodeTitle: 'Episode 1' });
.toEqual({ kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 1, episodeTitle: 'Episode 1', titleDirectory: 'Mushoku Tensei S3' });
});
it('uses the title above a nested quality folder and derives archive taxonomy', () => {
expect(parseMediaIdentity('anime/2026/Summer/Mushoku Tensei S3/720/Mushoku Tensei S3 - 02.mkv'))
.toMatchObject({
kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 2,
category: 'Anime', categorySlug: 'anime', year: 2026, releaseWindow: 'SUMMER',
});
});
it('creates stable UUIDs and Unicode-safe slugs', () => {
+16
View File
@@ -12,6 +12,22 @@ import {
} from '../src/registry.js';
describe('local generation registry', () => {
it('keeps independent generations for quality variants of one episode', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-variants-'));
const registryPath = path.join(directory, 'package-registry.json');
const mediaItemId = '11111111-1111-4111-8111-111111111111';
for (const [variantId, generationId] of [
['22222222-2222-4222-8222-222222222222', '33333333-3333-4333-8333-333333333333'],
['44444444-4444-4444-8444-444444444444', '55555555-5555-4555-8555-555555555555'],
] as const) {
await updateRegistry(registryPath, mediaItemId, {
mediaItemId, variantId, generationId, state: 'READY', playable: true,
manifestPath: `/media/generations/${generationId}/master.m3u8`,
});
}
expect((await readRegistry(registryPath)).packages).toHaveLength(2);
});
it('atomically records API-loadable per-media status', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-'));
const registryPath = path.join(directory, 'package-registry.json');
+2 -1
View File
@@ -140,7 +140,7 @@ services:
CACHE_LOW_WATERMARK: ${CACHE_LOW_WATERMARK:-0.75}
MEDIA_WORKER_CONCURRENCY: ${JIT_REMUX_CONCURRENCY:-2}
volumes:
- ${ARCHIVE_ROOT:-./movies}:/archive:ro
- ${ARCHIVE_ROOT:-./archive}:/archive:ro
- ${CACHE_ROOT:-./data/cache}:/data/cache
- ${DERIVED_ROOT:-./data/derived}:/data/derived
- ${METADATA_ROOT:-./data/metadata}:/data/metadata
@@ -174,6 +174,7 @@ services:
volumes:
- ${CACHE_ROOT:-./data/cache}:/srv/easy-stream/cache:ro
- ${DERIVED_ROOT:-./data/derived}:/srv/easy-stream/derived:ro
- ${METADATA_ROOT:-./data/metadata}:/srv/easy-stream/metadata:ro
depends_on:
api:
condition: service_healthy
+3 -3
View File
@@ -29,15 +29,15 @@ The archive is never exposed over HTTP and is never writable by an application c
## Media lifecycle
1. The worker walks regular `.mkv` files under `ARCHIVE_ROOT`, rejects escaping symlinks, fingerprints the file, and records ffprobe stream metadata.
1. The worker walks regular `.mkv` files under `ARCHIVE_ROOT`, rejects escaping symlinks, derives category/year/release-window/title identity from the archive hierarchy, fingerprints each source variant, and records ffprobe stream metadata.
2. Sources are classified as `COPY`, `AUDIO_TRANSCODE`, `VIDEO_TRANSCODE`, `HOLD_HDR`, or `INVALID`.
3. Publication is allowed immediately for `COPY`; incompatible SDR media must finish its single H.264/AAC compatibility representation first. HDR is held in v1.
4. A cold playback request creates one packaging job per source/profile fingerprint. FFmpeg copies supported elementary streams to separate fragmented-MP4 HLS playlists.
4. A movie or episode may have several source-quality variants. Auto prefers 720p and viewers may change quality explicitly; a cold playback request creates one packaging job per selected source/profile fingerprint. FFmpeg copies supported elementary streams to separate fragmented-MP4 HLS playlists.
5. EVENT manifests may grow privately, but the registry remains `PREPARING` until HLS, subtitles, and generation-scoped fonts are all ready. The worker then publishes one complete `READY` record and finalizes immutable VOD playlists.
6. Compatible generations live in the 2 TB LRU cache. A playback session records a Redis lease and persistent access timestamp through the signed-cookie expiry; high/low-watermark sweeps skip leased, building, pinned, and recently touched entries. Encoded compatibility components live on separately sized durable storage and are never swept.
7. Eviction removes the matching package-registry entry so the next request regenerates it. Aged global font objects with no generation hardlinks are pruned during packaging sweeps.
There is deliberately no adaptive bitrate ladder. Slow connections or devices that reject the original resolution receive a clear compatibility/connection error rather than an undisclosed quality reduction.
There is deliberately no adaptive bitrate ladder. Quality changes are explicit, preserve the logical-media resume position, and create independent cache generations. Devices that reject every available representation receive a clear compatibility error.
## Trust boundaries
+13 -1
View File
@@ -24,12 +24,22 @@ The Docker build pins pnpm and gives npm downloads bounded retries and a five-mi
When outbound access requires a proxy, enter its URL during setup. A proxy listening on host loopback, such as `http://127.0.0.1:8118`, automatically selects host networking for Dockerfile `RUN` steps so that loopback resolves to the server. Proxy values are passed through Docker's predefined build arguments and are not persisted in the resulting images. This setting affects build downloads only; image pulls still use the Docker daemon's own proxy configuration.
## Public domain and HTTPS
The Compose gateway intentionally listens only on `127.0.0.1:8080`. Publish an existing installation with:
```sh
bash scripts/setup-domain.sh
```
The interactive script installs Caddy from its official Ubuntu repository, verifies the local gateway, preserves the previous Caddyfile, validates the replacement, configures automatic HTTPS, and offers to open TCP 80/443 when UFW is active. If the host needs an outbound proxy for ACME requests, the script adds a Caddy-specific systemd override while keeping `127.0.0.1` in `NO_PROXY` for the local upstream. DNS and any cloud-provider firewall still need to point/allow traffic to the server.
## Host layout
- `/srv/easy-stream/archive`: read-only archive mount
- `/srv/easy-stream/cache`: 2 TB NVMe hot package cache
- `/srv/easy-stream/derived`: persistent compatibility components
- `/srv/easy-stream/metadata`: extracted subtitles, approved fonts, and cached metadata
- `/srv/easy-stream/metadata`: snapshots, copied archive artwork, extracted subtitles, approved fonts, and cached metadata
- Docker named volume `postgres-data`: PostgreSQL data (PostgreSQL 18 layout)
Use a dedicated unprivileged service account. Confirm the archive mount is read-only with `findmnt -no OPTIONS /srv/easy-stream/archive` before starting workers.
@@ -43,6 +53,8 @@ sudo install -d -o 1000 -g 1000 -m 0750 \
/srv/easy-stream/metadata
```
An administrator-initiated scan is authoritative: files no longer present in the mounted archive are removed from the public catalog without deleting historical database rows. After reorganizing archive paths, run a full scan before testing playback. Generated posters are served only from `/srv/easy-stream/metadata/artwork`; the gateway never receives an archive mount.
Use one public HTTPS origin for the SPA, API, and media routes. The v1 playback grant is a host-only, generation-path cookie, so a second media hostname will not receive it. A split hostname requires CDN-native edge authorization instead.
The API and media worker run as UID 1000, and the gateway's Nginx workers are configured to the same UID for read-only media access. Keep the bind mounts owned by that account rather than making generated media world-readable.
+123
View File
@@ -0,0 +1,123 @@
# Showcase edition
The Showcase edition is the small-server path for a few demo anime. It is a single Fastify process, a local SQLite file, the existing Vue catalog/player, and one operator CLI. It has no accounts or playback cookies: every prepared title is openly playable from the server's HTTP address.
## Requirements
- Ubuntu 24.04 or another current Linux distribution
- Node.js 24 and Corepack
- FFmpeg and ffprobe 8.x
Install dependencies and create the local configuration:
```sh
corepack enable
corepack pnpm install --frozen-lockfile
cp .env.showcase.example .env.showcase
```
For direct LAN/public-IP testing, set these values in `.env.showcase`:
```dotenv
SHOWCASE_ARCHIVE_ROOT=./archive
SHOWCASE_DATA_ROOT=./data/showcase
SHOWCASE_HOST=0.0.0.0
SHOWCASE_PORT=8080
```
`SHOWCASE_ARCHIVE_ROOT` and `SHOWCASE_DATA_ROOT` may be absolute paths. Relative paths are always resolved from the repository root, so commands behave the same when pnpm changes the package working directory.
## Archive layout
Use the same categorized layout as the full edition:
```text
archive/<category>/<year>/<season>/<title>/<quality>/*.mkv
archive/anime/2026/Summer/Mushoku Tensei S3/720/*.mkv
```
Put `thumbnail.jpg`, `.jpeg`, `.png`, or `.webp` in the title directory. Multiple quality directories for the same episode become selectable quality variants.
An optional `metadata.json` in the title directory can override filename-derived text:
```json
{
"titleEn": "Mushoku Tensei",
"titleFa": "موشوکو تنسی",
"synopsisFa": "خلاصه کوتاه",
"synopsisEn": "A short synopsis",
"category": "Anime",
"year": 2026,
"releaseWindow": "SUMMER"
}
```
## Operator workflow
Build the guest-only viewer and the standalone CLI, scan the archive, then explicitly prepare media before serving it:
```sh
corepack pnpm showcase:build
corepack pnpm showcase scan
corepack pnpm showcase status
corepack pnpm showcase prepare --all
corepack pnpm showcase serve
```
Open `http://SERVER_IP:8080`. Only successfully prepared variants appear in the public catalog.
For a smaller update:
```sh
corepack pnpm showcase prepare --title mushoku-tensei
corepack pnpm showcase prepare --title mushoku-tensei --quality 720p
```
Preparation is sequential and operator-controlled. Compatible H.264/AAC is remuxed without video encoding; incompatible audio is converted to AAC; incompatible SDR video is converted once to H.264/AAC. HDR, Dolby Vision, and invalid media remain unpublished. Subtitles and embedded fonts are extracted into the generated media directory. Original MKV files are never modified.
After archive changes, run `scan` again. A changed source fingerprint resets that variant to `UNPREPARED`. Inspect failures with `status`, retry deliberately with `--force`, and preview or apply stale-generation cleanup with:
```sh
corepack pnpm showcase prune
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.
+2 -4
View File
@@ -10,8 +10,7 @@ WORKDIR /workspace
# Corepack's downloader has a fixed, short connection timeout and no retry,
# which makes first builds fragile on distant or temporarily congested npm
# routes. npm honors the retry/timeout settings above; keep the version pinned.
RUN --mount=type=cache,id=easy-stream-npm,target=/root/.npm \
npm install --global "pnpm@${PNPM_VERSION}" \
RUN npm install --global "pnpm@${PNPM_VERSION}" \
&& test "$(pnpm --version)" = "${PNPM_VERSION}"
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml tsconfig.base.json ./
@@ -21,8 +20,7 @@ COPY apps/worker/package.json ./apps/worker/package.json
COPY packages/contracts/package.json ./packages/contracts/package.json
COPY packages/database/package.json ./packages/database/package.json
COPY packages/media/package.json ./packages/media/package.json
RUN --mount=type=cache,id=easy-stream-pnpm,target=/root/.local/share/pnpm/store \
pnpm install --frozen-lockfile
RUN pnpm install --frozen-lockfile
COPY apps ./apps
COPY packages ./packages
+13
View File
@@ -99,6 +99,19 @@ server {
include /etc/nginx/security-headers.conf;
}
location /images/archive/ {
limit_except GET HEAD { deny all; }
alias /srv/easy-stream/metadata/artwork/;
disable_symlinks on;
types {
image/jpeg jpg jpeg;
image/png png;
image/webp webp;
}
add_header Cache-Control "public, max-age=86400, stale-while-revalidate=604800" always;
include /etc/nginx/security-headers.conf;
}
location /healthz {
access_log off;
return 200 "ok\n";
+3 -1
View File
@@ -12,7 +12,9 @@
"dev": "corepack pnpm --parallel --filter @easy-stream/api --filter @easy-stream/worker --filter @easy-stream/web dev",
"test": "corepack pnpm -r --if-present test",
"typecheck": "corepack pnpm -r --if-present typecheck",
"scan:samples": "corepack pnpm --filter @easy-stream/worker scan -- --root ./movies --output ./data/metadata/catalog.json --inventory-output ./data/metadata/inventory.json",
"scan:samples": "corepack pnpm --filter @easy-stream/worker scan -- --root ./archive --output ./data/metadata/catalog.json --inventory-output ./data/metadata/inventory.json",
"showcase": "corepack pnpm --filter @easy-stream/showcase cli --",
"showcase:build": "VITE_APP_EDITION=showcase corepack pnpm --filter @easy-stream/web build && corepack pnpm --filter @easy-stream/showcase build",
"migrate": "corepack pnpm --filter @easy-stream/database migrate",
"clean": "corepack pnpm -r --if-present clean"
},
+68 -7
View File
@@ -20,6 +20,36 @@ export const OptionalLocalizedTextSchema = Type.Object(
{ additionalProperties: false },
);
export const ReleaseWindowSchema = Type.Union([
Type.Literal('SPRING'),
Type.Literal('SUMMER'),
Type.Literal('FALL'),
Type.Literal('WINTER'),
Type.Literal('MOVIE'),
]);
const CatalogCompatibilityClassSchema = Type.Union([
Type.Literal('COPY'),
Type.Literal('AUDIO_TRANSCODE'),
Type.Literal('VIDEO_TRANSCODE'),
Type.Literal('HOLD_HDR'),
Type.Literal('INVALID'),
]);
export const MediaVariantSchema = Type.Object(
{
id: UuidSchema,
label: Type.String({ minLength: 1, maxLength: 64 }),
width: Type.Optional(Type.Integer({ minimum: 1 })),
height: Type.Optional(Type.Integer({ minimum: 1 })),
videoCodec: Type.Optional(Type.String({ maxLength: 64 })),
compatibility: CatalogCompatibilityClassSchema,
available: Type.Boolean(),
isDefault: Type.Boolean(),
},
{ additionalProperties: false },
);
export const CatalogCardSchema = Type.Object(
{
id: UuidSchema,
@@ -29,8 +59,12 @@ export const CatalogCardSchema = Type.Object(
posterUrl: Type.Optional(Type.String()),
backdropUrl: Type.Optional(Type.String()),
year: Type.Optional(Type.Integer()),
category: Type.Optional(Type.String({ maxLength: 100 })),
categorySlug: Type.Optional(Type.String({ maxLength: 100 })),
releaseWindow: Type.Optional(ReleaseWindowSchema),
playable: Type.Boolean(),
resumeMediaItemId: Type.Optional(UuidSchema),
variants: Type.Optional(Type.Array(MediaVariantSchema)),
},
{ additionalProperties: false },
);
@@ -43,14 +77,9 @@ export const MediaItemSummarySchema = Type.Object(
episodeNumber: Type.Optional(Type.Integer({ minimum: 0 })),
name: Type.Optional(OptionalLocalizedTextSchema),
durationSeconds: Type.Number({ minimum: 0 }),
compatibility: Type.Union([
Type.Literal('COPY'),
Type.Literal('AUDIO_TRANSCODE'),
Type.Literal('VIDEO_TRANSCODE'),
Type.Literal('HOLD_HDR'),
Type.Literal('INVALID'),
]),
compatibility: CatalogCompatibilityClassSchema,
published: Type.Boolean(),
variants: Type.Optional(Type.Array(MediaVariantSchema)),
},
{ additionalProperties: false },
);
@@ -72,8 +101,12 @@ export const TitleDetailSchema = Type.Object(
posterUrl: Type.Optional(Type.String()),
backdropUrl: Type.Optional(Type.String()),
year: Type.Optional(Type.Integer()),
category: Type.Optional(Type.String({ maxLength: 100 })),
categorySlug: Type.Optional(Type.String({ maxLength: 100 })),
releaseWindow: Type.Optional(ReleaseWindowSchema),
playable: Type.Boolean(),
resumeMediaItemId: Type.Optional(UuidSchema),
variants: Type.Optional(Type.Array(MediaVariantSchema)),
synopsis: OptionalLocalizedTextSchema,
seasons: Type.Optional(Type.Array(SeasonSummarySchema)),
mediaItems: Type.Array(MediaItemSummarySchema),
@@ -87,6 +120,9 @@ export const CatalogQuerySchema = Type.Object(
cursor: Type.Optional(Type.String({ maxLength: 512 })),
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, default: 24 })),
kind: Type.Optional(TitleKindSchema),
category: Type.Optional(Type.String({ maxLength: 100 })),
year: Type.Optional(Type.Integer({ minimum: 1888, maximum: 2200 })),
releaseWindow: Type.Optional(ReleaseWindowSchema),
},
{ additionalProperties: false },
);
@@ -107,6 +143,26 @@ export const CatalogResponseSchema = Type.Object(
{ additionalProperties: false },
);
export const CatalogSectionsQuerySchema = Type.Object(
{ limitPerSection: Type.Optional(Type.Integer({ minimum: 1, maximum: 40, default: 12 })) },
{ additionalProperties: false },
);
export const CatalogSectionSchema = Type.Object(
{
slug: Type.String(),
name: Type.String(),
items: Type.Array(CatalogCardSchema),
hasMore: Type.Boolean(),
},
{ additionalProperties: false },
);
export const CatalogSectionsResponseSchema = Type.Object(
{ sections: Type.Array(CatalogSectionSchema) },
{ additionalProperties: false },
);
export const SearchResponseSchema = Type.Object(
{ items: Type.Array(CatalogCardSchema) },
{ additionalProperties: false },
@@ -125,10 +181,15 @@ export type TitleKind = Static<typeof TitleKindSchema>;
export type MediaKind = Static<typeof MediaKindSchema>;
export type LocalizedText = Static<typeof LocalizedTextSchema>;
export type OptionalLocalizedText = Static<typeof OptionalLocalizedTextSchema>;
export type ReleaseWindow = Static<typeof ReleaseWindowSchema>;
export type MediaVariant = Static<typeof MediaVariantSchema>;
export type CatalogCard = Static<typeof CatalogCardSchema>;
export type MediaItemSummary = Static<typeof MediaItemSummarySchema>;
export type TitleDetail = Static<typeof TitleDetailSchema>;
export type CatalogQuery = Static<typeof CatalogQuerySchema>;
export type SearchQuery = Static<typeof SearchQuerySchema>;
export type CatalogResponse = Static<typeof CatalogResponseSchema>;
export type CatalogSectionsQuery = Static<typeof CatalogSectionsQuerySchema>;
export type CatalogSection = Static<typeof CatalogSectionSchema>;
export type CatalogSectionsResponse = Static<typeof CatalogSectionsResponseSchema>;
export type CatalogSnapshot = Static<typeof CatalogSnapshotSchema>;
+2
View File
@@ -8,6 +8,7 @@ export const MediaCommandSchema = Type.Union([
type: Type.Literal('media.playback.requested'),
sessionId: UuidSchema,
mediaItemId: UuidSchema,
variantId: Type.Optional(UuidSchema),
},
{ additionalProperties: false },
),
@@ -63,6 +64,7 @@ export const MediaPreparationResultSchema = Type.Object(
export const PackageRegistryEntrySchema = Type.Object(
{
mediaItemId: UuidSchema,
variantId: Type.Optional(UuidSchema),
state: Type.Union([
Type.Literal('PREPARING'),
Type.Literal('READY'),
+3
View File
@@ -61,6 +61,7 @@ export const SubtitleTrackSchema = Type.Object(
export const CreatePlaybackSessionSchema = Type.Object(
{
mediaItemId: UuidSchema,
variantId: Type.Optional(UuidSchema),
clientCapabilities: ClientCapabilitiesSchema,
},
{ additionalProperties: false },
@@ -70,6 +71,8 @@ export const PlaybackSessionSchema = Type.Object(
{
id: UuidSchema,
mediaItemId: UuidSchema,
variantId: Type.Optional(UuidSchema),
qualityLabel: Type.Optional(Type.String({ maxLength: 64 })),
state: PlaybackStateSchema,
manifestUrl: Type.Optional(Type.String()),
generationId: Type.Optional(UuidSchema),
@@ -7,6 +7,7 @@ describe('public contracts', () => {
expect(
Value.Check(CreatePlaybackSessionSchema, {
mediaItemId: '00000000-0000-4000-8000-000000000001',
variantId: '00000000-0000-4000-8000-000000000003',
clientCapabilities: {
mse: true,
nativeHls: false,
@@ -0,0 +1,25 @@
CREATE TYPE "release_window" AS ENUM ('SPRING', 'SUMMER', 'FALL', 'WINTER', 'MOVIE');
--> statement-breakpoint
ALTER TABLE "titles" ADD COLUMN "category" varchar(100);
ALTER TABLE "titles" ADD COLUMN "category_slug" varchar(100);
ALTER TABLE "titles" ADD COLUMN "release_window" "release_window";
ALTER TABLE "media_items" ADD COLUMN "logical_key" varchar(80);
ALTER TABLE "media_items" ADD COLUMN "variants" jsonb DEFAULT '[]'::jsonb NOT NULL;
ALTER TABLE "source_files" ADD COLUMN "quality_label" varchar(64);
ALTER TABLE "source_files" ADD COLUMN "width" integer;
ALTER TABLE "source_files" ADD COLUMN "height" integer;
ALTER TABLE "source_files" ADD COLUMN "video_codec" varchar(64);
ALTER TABLE "source_files" ADD COLUMN "duration_seconds" double precision;
ALTER TABLE "source_files" ADD COLUMN "compatibility" "compatibility_class" DEFAULT 'INVALID' NOT NULL;
ALTER TABLE "source_files" ADD COLUMN "compatibility_reason" text;
ALTER TABLE "media_packages" ADD COLUMN "variant_id" uuid;
ALTER TABLE "playback_sessions" ADD COLUMN "variant_id" uuid;
--> statement-breakpoint
UPDATE "media_items"
SET "logical_key" = CASE
WHEN "kind" = 'MOVIE' THEN 'movie'
ELSE 's' || COALESCE("season_number", 1)::text || 'e' || COALESCE("episode_number", 0)::text
END;
--> statement-breakpoint
CREATE UNIQUE INDEX "media_items_logical_uidx" ON "media_items" ("title_id", "logical_key");
CREATE INDEX "titles_category_idx" ON "titles" ("category_slug", "release_year", "release_window");
@@ -15,6 +15,13 @@
"when": 1784016000000,
"tag": "0001_playback_generation_external",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1784073600000,
"tag": "0002_archive_variants",
"breakpoints": true
}
]
}
+56 -2
View File
@@ -1,6 +1,6 @@
import { CatalogSnapshotSchema, type CatalogSnapshot } from '@easy-stream/contracts';
import { Value } from '@sinclair/typebox/value';
import { sql } from 'drizzle-orm';
import { inArray, notInArray, sql } from 'drizzle-orm';
import type { Database } from './client.js';
import { mediaItems, titles } from './schema.js';
@@ -15,6 +15,7 @@ export interface PreparedCatalogSync {
export interface CatalogSyncResult {
titlesSeen: number;
mediaItemsSeen: number;
mediaIdMap: Record<string, string>;
}
/**
@@ -53,6 +54,9 @@ export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
posterUrl: title.posterUrl ?? null,
backdropUrl: title.backdropUrl ?? null,
releaseYear: title.year ?? null,
category: title.category ?? null,
categorySlug: title.categorySlug ?? null,
releaseWindow: title.releaseWindow ?? null,
published,
publishedAt: published ? scannedAt : null,
createdAt: scannedAt,
@@ -68,12 +72,14 @@ export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
id: item.id,
titleId: title.id,
kind: item.kind,
logicalKey: item.kind === 'MOVIE' ? 'movie' : `s${item.seasonNumber ?? 1}e${item.episodeNumber ?? 0}`,
seasonNumber: item.seasonNumber ?? null,
episodeNumber: item.episodeNumber ?? null,
nameFa: item.name?.fa ?? null,
nameEn: item.name?.en ?? null,
durationSeconds: item.durationSeconds,
compatibility: item.compatibility,
variants: item.variants ?? [],
published: item.published,
publishedAt: item.published ? scannedAt : null,
createdAt: scannedAt,
@@ -93,8 +99,10 @@ export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
export async function syncCatalogSnapshot(
db: Database,
snapshot: unknown,
options: { authoritative?: boolean } = {},
): Promise<CatalogSyncResult> {
const prepared = prepareCatalogSync(snapshot);
const mediaIdMap: Record<string, string> = {};
await db.transaction(async (transaction) => {
// Prevent two worker processes from interleaving catalog snapshots.
await transaction.execute(sql`select pg_advisory_xact_lock(hashtext('easy-stream.catalog-sync'))`);
@@ -108,12 +116,44 @@ export async function syncCatalogSnapshot(
set: {
slug: sql`excluded.slug`,
kind: sql`excluded.kind`,
category: sql`excluded.category`,
categorySlug: sql`excluded.category_slug`,
releaseWindow: sql`excluded.release_window`,
releaseYear: sql`coalesce(${titles.releaseYear}, excluded.release_year)`,
posterUrl: sql`case when ${titles.posterUrl} is null or ${titles.posterUrl} like '/images/archive/%' then excluded.poster_url else ${titles.posterUrl} end`,
updatedAt: prepared.scannedAt,
},
setWhere: sql`${titles.slug} is distinct from excluded.slug or ${titles.kind} is distinct from excluded.kind`,
setWhere: sql`${titles.slug} is distinct from excluded.slug
or ${titles.kind} is distinct from excluded.kind
or ${titles.category} is distinct from excluded.category
or ${titles.categorySlug} is distinct from excluded.category_slug
or ${titles.releaseWindow} is distinct from excluded.release_window
or (${titles.releaseYear} is null and excluded.release_year is not null)
or ((${titles.posterUrl} is null or ${titles.posterUrl} like '/images/archive/%') and ${titles.posterUrl} is distinct from excluded.poster_url)`,
});
}
if (prepared.titleRows.length > 0) {
const existing = await transaction.select({
id: mediaItems.id,
titleId: mediaItems.titleId,
logicalKey: mediaItems.logicalKey,
seasonNumber: mediaItems.seasonNumber,
episodeNumber: mediaItems.episodeNumber,
kind: mediaItems.kind,
}).from(mediaItems).where(inArray(mediaItems.titleId, prepared.titleRows.map((row) => row.id as string)));
const byLogicalKey = new Map(existing.map((row) => [
`${row.titleId}:${row.logicalKey ?? (row.kind === 'MOVIE' ? 'movie' : `s${row.seasonNumber ?? 1}e${row.episodeNumber ?? 0}`)}`,
row.id,
]));
for (const row of prepared.mediaItemRows) {
const current = byLogicalKey.get(`${row.titleId}:${row.logicalKey}`);
if (!current || current === row.id) continue;
mediaIdMap[String(row.id)] = current;
row.id = current;
}
}
for (const batch of batches(prepared.mediaItemRows, UPSERT_BATCH_SIZE)) {
await transaction
.insert(mediaItems)
@@ -123,26 +163,40 @@ export async function syncCatalogSnapshot(
set: {
titleId: sql`excluded.title_id`,
kind: sql`excluded.kind`,
logicalKey: sql`excluded.logical_key`,
seasonNumber: sql`excluded.season_number`,
episodeNumber: sql`excluded.episode_number`,
durationSeconds: sql`excluded.duration_seconds`,
compatibility: sql`excluded.compatibility`,
variants: sql`excluded.variants`,
updatedAt: prepared.scannedAt,
},
setWhere: sql`
${mediaItems.titleId} is distinct from excluded.title_id
or ${mediaItems.kind} is distinct from excluded.kind
or ${mediaItems.logicalKey} is distinct from excluded.logical_key
or ${mediaItems.seasonNumber} is distinct from excluded.season_number
or ${mediaItems.episodeNumber} is distinct from excluded.episode_number
or ${mediaItems.durationSeconds} is distinct from excluded.duration_seconds
or ${mediaItems.compatibility} is distinct from excluded.compatibility
or ${mediaItems.variants} is distinct from excluded.variants
`,
});
}
if (options.authoritative) {
const seenMediaIds = prepared.mediaItemRows.map((row) => row.id as string);
const seenTitleIds = prepared.titleRows.map((row) => row.id as string);
await transaction.update(mediaItems).set({ published: false, publishedAt: null, updatedAt: prepared.scannedAt })
.where(seenMediaIds.length ? notInArray(mediaItems.id, seenMediaIds) : sql`true`);
await transaction.update(titles).set({ published: false, publishedAt: null, updatedAt: prepared.scannedAt })
.where(seenTitleIds.length ? notInArray(titles.id, seenTitleIds) : sql`true`);
}
});
return {
titlesSeen: prepared.titleRows.length,
mediaItemsSeen: prepared.mediaItemRows.length,
mediaIdMap,
};
}
+26
View File
@@ -16,6 +16,7 @@ import {
} from 'drizzle-orm/pg-core';
export const titleKind = pgEnum('title_kind', ['MOVIE', 'SERIES']);
export const releaseWindow = pgEnum('release_window', ['SPRING', 'SUMMER', 'FALL', 'WINTER', 'MOVIE']);
export const mediaKind = pgEnum('media_kind', ['MOVIE', 'EPISODE']);
export const streamKind = pgEnum('stream_kind', ['VIDEO', 'AUDIO']);
export const compatibilityClass = pgEnum('compatibility_class', [
@@ -64,6 +65,9 @@ export const titles = pgTable(
posterUrl: text('poster_url'),
backdropUrl: text('backdrop_url'),
releaseYear: integer('release_year'),
category: varchar('category', { length: 100 }),
categorySlug: varchar('category_slug', { length: 100 }),
releaseWindow: releaseWindow('release_window'),
tmdbId: integer('tmdb_id'),
published: boolean('published').notNull().default(false),
publishedAt: timestamp('published_at', { withTimezone: true }),
@@ -84,6 +88,7 @@ export const mediaItems = pgTable(
.notNull()
.references(() => titles.id, { onDelete: 'cascade' }),
kind: mediaKind('kind').notNull(),
logicalKey: varchar('logical_key', { length: 80 }),
seasonNumber: integer('season_number'),
episodeNumber: integer('episode_number'),
nameFa: text('name_fa'),
@@ -91,12 +96,23 @@ export const mediaItems = pgTable(
durationSeconds: doublePrecision('duration_seconds'),
compatibility: compatibilityClass('compatibility').notNull().default('INVALID'),
compatibilityReason: text('compatibility_reason'),
variants: jsonb('variants').$type<Array<{
id: string;
label: string;
width?: number;
height?: number;
videoCodec?: string;
compatibility: string;
available: boolean;
isDefault: boolean;
}>>().notNull().default([]),
published: boolean('published').notNull().default(false),
publishedAt: timestamp('published_at', { withTimezone: true }),
...timestamps,
},
(table) => [
index('media_items_title_idx').on(table.titleId),
uniqueIndex('media_items_logical_uidx').on(table.titleId, table.logicalKey),
uniqueIndex('media_items_episode_uidx').on(
table.titleId,
table.seasonNumber,
@@ -120,6 +136,13 @@ export const sourceFiles = pgTable(
headHash: varchar('head_hash', { length: 128 }).notNull(),
tailHash: varchar('tail_hash', { length: 128 }).notNull(),
fingerprint: varchar('fingerprint', { length: 128 }).notNull(),
qualityLabel: varchar('quality_label', { length: 64 }),
width: integer('width'),
height: integer('height'),
videoCodec: varchar('video_codec', { length: 64 }),
durationSeconds: doublePrecision('duration_seconds'),
compatibility: compatibilityClass('compatibility').notNull().default('INVALID'),
compatibilityReason: text('compatibility_reason'),
probeJson: jsonb('probe_json').$type<Record<string, unknown>>(),
present: boolean('present').notNull().default(true),
lastSeenAt: timestamp('last_seen_at', { withTimezone: true }).notNull().defaultNow(),
@@ -217,6 +240,8 @@ export const mediaPackages = pgTable(
mediaItemId: uuid('media_item_id')
.notNull()
.references(() => mediaItems.id, { onDelete: 'cascade' }),
// Scanner variant IDs are deterministic external identifiers, like generation IDs.
variantId: uuid('variant_id'),
sourceFingerprint: varchar('source_fingerprint', { length: 128 }).notNull(),
profileVersion: varchar('profile_version', { length: 64 }).notNull(),
state: packageState('state').notNull().default('QUEUED'),
@@ -296,6 +321,7 @@ export const playbackSessions = pgTable(
mediaItemId: uuid('media_item_id')
.notNull()
.references(() => mediaItems.id, { onDelete: 'cascade' }),
variantId: uuid('variant_id'),
// Packaging generation IDs are deterministic UUIDs owned by the media worker. They are
// deliberately not media_packages.id, so this column must not reference that primary key.
generationId: uuid('generation_id'),
+6 -1
View File
@@ -57,6 +57,9 @@ describe('catalog snapshot synchronization', () => {
const conflicts: Array<{ table: unknown; set: Record<string, unknown> }> = [];
const transaction = {
async execute() {},
select() {
return { from() { return { async where() { return []; } }; } };
},
insert(table: unknown) {
return {
values() {
@@ -78,16 +81,18 @@ describe('catalog snapshot synchronization', () => {
await syncCatalogSnapshot(database, snapshot);
expect(Object.keys(conflicts.find((entry) => entry.table === titles)!.set).sort())
.toEqual(['kind', 'slug', 'updatedAt']);
.toEqual(['category', 'categorySlug', 'kind', 'posterUrl', 'releaseWindow', 'releaseYear', 'slug', 'updatedAt']);
expect(Object.keys(conflicts.find((entry) => entry.table === mediaItems)!.set).sort())
.toEqual([
'compatibility',
'durationSeconds',
'episodeNumber',
'kind',
'logicalKey',
'seasonNumber',
'titleId',
'updatedAt',
'variants',
]);
});
+187
View File
@@ -64,6 +64,34 @@ importers:
specifier: ^3.2.4
version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1)
apps/showcase:
dependencies:
'@easy-stream/media':
specifier: workspace:*
version: link:../../packages/media
'@fastify/static':
specifier: ^8.3.0
version: 8.3.0
fastify:
specifier: ^5.6.2
version: 5.10.0
devDependencies:
'@types/node':
specifier: ^24.10.1
version: 24.13.3
esbuild:
specifier: ^0.25.12
version: 0.25.12
tsx:
specifier: ^4.20.6
version: 4.23.1
typescript:
specifier: ^5.9.3
version: 5.9.3
vitest:
specifier: ^3.2.4
version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1)
apps/web:
dependencies:
'@fontsource/vazirmatn':
@@ -696,6 +724,9 @@ packages:
cpu: [x64]
os: [win32]
'@fastify/accept-negotiator@2.0.1':
resolution: {integrity: sha512-/c/TW2bO/v9JeEgoD/g1G5GxGeCF1Hafdf79WPmUlgYiBXummY0oX3VVq4yFkKKVBKDNlaDUYoab7g38RpPqCQ==}
'@fastify/ajv-compiler@4.0.5':
resolution: {integrity: sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==}
@@ -726,6 +757,12 @@ packages:
'@fastify/rate-limit@10.3.0':
resolution: {integrity: sha512-eIGkG9XKQs0nyynatApA3EVrojHOuq4l6fhB4eeCk4PIOeadvOJz9/4w3vGI44Go17uaXOWEcPkaD8kuKm7g6Q==}
'@fastify/send@4.1.0':
resolution: {integrity: sha512-TMYeQLCBSy2TOFmV95hQWkiTYgC/SEx7vMdV+wnZVX4tt8VBLKzmH8vV9OzJehV0+XBfg+WxPMt5wp+JBUKsVw==}
'@fastify/static@8.3.0':
resolution: {integrity: sha512-yKxviR5PH1OKNnisIzZKmgZSus0r2OZb8qCSbqmw34aolT4g3UlzYfeBRym+HJ1J471CR8e2ldNub4PubD1coA==}
'@fontsource/vazirmatn@5.2.8':
resolution: {integrity: sha512-WoDgv8R/y1gwgTS8Q2uL8d2ayeSGNv2IrYQ4wHmJkVwYPb8KVODrqbbvEjBqLOo5WP5kLJIrO06FRDMnSFuCaA==}
@@ -736,6 +773,10 @@ packages:
resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
engines: {node: '>=12'}
'@isaacs/cliui@9.0.0':
resolution: {integrity: sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==}
engines: {node: '>=18'}
'@jridgewell/sourcemap-codec@1.5.5':
resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
@@ -1104,12 +1145,20 @@ packages:
balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
balanced-match@4.0.4:
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
engines: {node: 18 || 20 || >=22}
birpc@2.9.0:
resolution: {integrity: sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==}
brace-expansion@2.1.2:
resolution: {integrity: sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==}
brace-expansion@5.0.7:
resolution: {integrity: sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==}
engines: {node: 18 || 20 || >=22}
buffer-from@1.1.2:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
@@ -1152,6 +1201,10 @@ packages:
config-chain@1.1.13:
resolution: {integrity: sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==}
content-disposition@0.5.4:
resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==}
engines: {node: '>= 0.6'}
cookie@1.1.1:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
@@ -1208,6 +1261,10 @@ packages:
resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==}
engines: {node: '>=0.10'}
depd@2.0.0:
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
dequal@2.0.3:
resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
engines: {node: '>=6'}
@@ -1352,6 +1409,9 @@ packages:
engines: {node: '>=18'}
hasBin: true
escape-html@1.0.3:
resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}
estree-walker@2.0.2:
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
@@ -1422,6 +1482,12 @@ packages:
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
hasBin: true
glob@11.1.0:
resolution: {integrity: sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==}
engines: {node: 20 || >=22}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
hasBin: true
helmet@8.3.0:
resolution: {integrity: sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==}
engines: {node: '>=18.0.0'}
@@ -1436,6 +1502,10 @@ packages:
resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}
engines: {node: '>=18'}
http-errors@2.0.1:
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
engines: {node: '>= 0.8'}
http-proxy-agent@7.0.2:
resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}
engines: {node: '>= 14'}
@@ -1448,6 +1518,9 @@ packages:
resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
engines: {node: '>=0.10.0'}
inherits@2.0.4:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
ini@1.3.8:
resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==}
@@ -1476,6 +1549,10 @@ packages:
jackspeak@3.4.3:
resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}
jackspeak@4.2.3:
resolution: {integrity: sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==}
engines: {node: 20 || >=22}
jassub@2.5.7:
resolution: {integrity: sha512-ynn0D65lsQwkBhnTi7WqJ7upy7jHMq+ePP637rI2x7cQYVJlsG8zrAacP5DCq9nO+W3lY0IXRT2VzjBwSpHzWA==}
@@ -1523,6 +1600,10 @@ packages:
lru-cache@10.4.3:
resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}
lru-cache@11.5.2:
resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==}
engines: {node: 20 || >=22}
luxon@3.7.2:
resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==}
engines: {node: '>=12'}
@@ -1530,6 +1611,15 @@ packages:
magic-string@0.30.21:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
mime@3.0.0:
resolution: {integrity: sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==}
engines: {node: '>=10.0.0'}
hasBin: true
minimatch@10.2.5:
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
minimatch@9.0.9:
resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==}
engines: {node: '>=16 || 14 >=14.17'}
@@ -1603,6 +1693,10 @@ packages:
resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}
engines: {node: '>=16 || 14 >=14.18'}
path-scurry@2.0.2:
resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}
engines: {node: 18 || 20 || >=22}
pathe@2.0.3:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
@@ -1707,6 +1801,9 @@ packages:
rvfc-polyfill@1.0.8:
resolution: {integrity: sha512-uA+0wwTkZ4OT8v45pfDfH+7Yq8mY6MvNngiF5Sq6VBgjJsvsfgt7Q18cyZqZjfAhW9rhkgXPX0cW0R9uw7yElA==}
safe-buffer@5.2.1:
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
safe-regex2@5.1.1:
resolution: {integrity: sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==}
hasBin: true
@@ -1733,6 +1830,9 @@ packages:
set-cookie-parser@2.7.2:
resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==}
setprototypeof@1.2.0:
resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}
shebang-command@2.0.0:
resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}
engines: {node: '>=8'}
@@ -1776,6 +1876,10 @@ packages:
standard-as-callback@2.1.0:
resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
statuses@2.0.2:
resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}
engines: {node: '>= 0.8'}
std-env@3.10.0:
resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
@@ -1845,6 +1949,10 @@ packages:
resolution: {integrity: sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==}
engines: {node: '>=20'}
toidentifier@1.0.1:
resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}
engines: {node: '>=0.6'}
tough-cookie@5.1.2:
resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==}
engines: {node: '>=16'}
@@ -2304,6 +2412,8 @@ snapshots:
'@esbuild/win32-x64@0.28.1':
optional: true
'@fastify/accept-negotiator@2.0.1': {}
'@fastify/ajv-compiler@4.0.5':
dependencies:
ajv: 8.20.0
@@ -2348,6 +2458,23 @@ snapshots:
fastify-plugin: 5.1.0
toad-cache: 3.7.4
'@fastify/send@4.1.0':
dependencies:
'@lukeed/ms': 2.0.2
escape-html: 1.0.3
fast-decode-uri-component: 1.0.1
http-errors: 2.0.1
mime: 3.0.0
'@fastify/static@8.3.0':
dependencies:
'@fastify/accept-negotiator': 2.0.1
'@fastify/send': 4.1.0
content-disposition: 0.5.4
fastify-plugin: 5.1.0
fastq: 1.20.1
glob: 11.1.0
'@fontsource/vazirmatn@5.2.8': {}
'@ioredis/commands@1.5.1': {}
@@ -2361,6 +2488,8 @@ snapshots:
wrap-ansi: 8.1.0
wrap-ansi-cjs: wrap-ansi@7.0.0
'@isaacs/cliui@9.0.0': {}
'@jridgewell/sourcemap-codec@1.5.5': {}
'@lukeed/ms@2.0.2': {}
@@ -2686,12 +2815,18 @@ snapshots:
balanced-match@1.0.2: {}
balanced-match@4.0.4: {}
birpc@2.9.0: {}
brace-expansion@2.1.2:
dependencies:
balanced-match: 1.0.2
brace-expansion@5.0.7:
dependencies:
balanced-match: 4.0.4
buffer-from@1.1.2: {}
bullmq@5.80.2:
@@ -2732,6 +2867,10 @@ snapshots:
ini: 1.3.8
proto-list: 1.2.4
content-disposition@0.5.4:
dependencies:
safe-buffer: 5.2.1
cookie@1.1.1: {}
cookie@2.0.1: {}
@@ -2777,6 +2916,8 @@ snapshots:
denque@2.1.0: {}
depd@2.0.0: {}
dequal@2.0.3: {}
detect-libc@2.1.2:
@@ -2895,6 +3036,8 @@ snapshots:
'@esbuild/win32-ia32': 0.28.1
'@esbuild/win32-x64': 0.28.1
escape-html@1.0.3: {}
estree-walker@2.0.2: {}
estree-walker@3.0.3:
@@ -2981,6 +3124,15 @@ snapshots:
package-json-from-dist: 1.0.1
path-scurry: 1.11.1
glob@11.1.0:
dependencies:
foreground-child: 3.3.1
jackspeak: 4.2.3
minimatch: 10.2.5
minipass: 7.1.3
package-json-from-dist: 1.0.1
path-scurry: 2.0.2
helmet@8.3.0: {}
hls.js@1.6.16: {}
@@ -2991,6 +3143,14 @@ snapshots:
dependencies:
whatwg-encoding: 3.1.1
http-errors@2.0.1:
dependencies:
depd: 2.0.0
inherits: 2.0.4
setprototypeof: 1.2.0
statuses: 2.0.2
toidentifier: 1.0.1
http-proxy-agent@7.0.2:
dependencies:
agent-base: 7.1.4
@@ -3009,6 +3169,8 @@ snapshots:
dependencies:
safer-buffer: 2.1.2
inherits@2.0.4: {}
ini@1.3.8: {}
ioredis@5.10.1:
@@ -3041,6 +3203,10 @@ snapshots:
optionalDependencies:
'@pkgjs/parseargs': 0.11.0
jackspeak@4.2.3:
dependencies:
'@isaacs/cliui': 9.0.0
jassub@2.5.7:
dependencies:
abslink: 1.2.2
@@ -3109,12 +3275,20 @@ snapshots:
lru-cache@10.4.3: {}
lru-cache@11.5.2: {}
luxon@3.7.2: {}
magic-string@0.30.21:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
mime@3.0.0: {}
minimatch@10.2.5:
dependencies:
brace-expansion: 5.0.7
minimatch@9.0.9:
dependencies:
brace-expansion: 2.1.2
@@ -3179,6 +3353,11 @@ snapshots:
lru-cache: 10.4.3
minipass: 7.1.3
path-scurry@2.0.2:
dependencies:
lru-cache: 11.5.2
minipass: 7.1.3
pathe@2.0.3: {}
pathval@2.0.1: {}
@@ -3289,6 +3468,8 @@ snapshots:
rvfc-polyfill@1.0.8: {}
safe-buffer@5.2.1: {}
safe-regex2@5.1.1:
dependencies:
ret: 0.5.0
@@ -3307,6 +3488,8 @@ snapshots:
set-cookie-parser@2.7.2: {}
setprototypeof@1.2.0: {}
shebang-command@2.0.0:
dependencies:
shebang-regex: 3.0.0
@@ -3338,6 +3521,8 @@ snapshots:
standard-as-callback@2.1.0: {}
statuses@2.0.2: {}
std-env@3.10.0: {}
string-width@4.2.3:
@@ -3399,6 +3584,8 @@ snapshots:
toad-cache@3.7.4: {}
toidentifier@1.0.1: {}
tough-cookie@5.1.2:
dependencies:
tldts: 6.1.86
+359
View File
@@ -0,0 +1,359 @@
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
umask 077
readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
readonly PROJECT_ROOT="${EASY_STREAM_PROJECT_ROOT:-$(cd -- "${SCRIPT_DIR}/.." && pwd -P)}"
readonly ENV_FILE="${PROJECT_ROOT}/.env"
VALIDATION_ERROR=''
DOMAIN=''
ADMIN_EMAIL=''
OUTBOUND_PROXY=''
CONFIG_BACKUP=''
declare -a ROOT_COMMAND=()
declare -a CLEANUP_FILES=()
cleanup() {
local file
for file in "${CLEANUP_FILES[@]:-}"; do
[[ -n "${file}" ]] && rm -f -- "${file}"
done
return 0
}
trap cleanup EXIT
info() { printf '\n\033[1;34m==>\033[0m %s\n' "$*"; }
success() { printf '\033[1;32mOK:\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33mWARNING:\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31mERROR:\033[0m %s\n' "$*" >&2; exit 1; }
usage() {
cat <<'EOF'
Usage: bash scripts/setup-domain.sh
Installs Caddy and publishes Easy Stream through automatic HTTPS. The script
reads defaults from .env, preserves an existing Caddyfile, and requires an
interactive confirmation before changing the server.
EOF
}
validation_failure() { VALIDATION_ERROR="$1"; return 1; }
validate_domain() {
local value="$1"
if [[ ! "${value}" =~ ^([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$ ]]; then
validation_failure 'Enter a hostname such as stream.example.com, without a scheme, path, or port.'
return 1
fi
}
validate_email() {
local value="$1"
if [[ ! "${value}" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]]; then
validation_failure 'Enter a valid email address for certificate notices.'
return 1
fi
}
validate_optional_proxy() {
local value="$1"
local proxy_pattern='^https?://[^[:space:]"\\]+$'
[[ -n "${value}" ]] || return 0
if [[ ! "${value}" =~ ${proxy_pattern} ]]; then
validation_failure 'Use an http:// or https:// proxy URL, or leave it blank.'
return 1
fi
}
prompt_value() {
local destination="$1" label="$2" default_value="$3" validator="$4" value
while true; do
VALIDATION_ERROR=''
if [[ -n "${default_value}" ]]; then
read -r -p "${label} [${default_value}]: " value
value="${value:-${default_value}}"
else
read -r -p "${label}: " value
fi
if "${validator}" "${value}"; then
printf -v "${destination}" '%s' "${value}"
return 0
fi
warn "${VALIDATION_ERROR:-Invalid value.}"
done
}
confirm() {
local prompt="$1" default_answer="${2:-no}" hint answer
[[ "${default_answer}" == yes ]] && hint='Y/n' || hint='y/N'
while true; do
read -r -p "${prompt} [${hint}]: " answer
answer="${answer:-${default_answer}}"
case "${answer,,}" in
y|yes) return 0 ;;
n|no) return 1 ;;
*) warn 'Answer yes or no.' ;;
esac
done
}
read_env_value() {
local key="$1" line value
[[ -f "${ENV_FILE}" ]] || return 1
line="$(grep -m1 -E "^${key}=" "${ENV_FILE}" || true)"
[[ -n "${line}" ]] || return 1
value="${line#*=}"
if [[ "${value}" == "'"*"'" && ${#value} -ge 2 ]]; then
value="${value:1:${#value}-2}"
elif [[ "${value}" == '"'*'"' && ${#value} -ge 2 ]]; then
value="${value:1:${#value}-2}"
fi
printf '%s\n' "${value}"
}
domain_from_origin() {
local origin="$1" authority
[[ "${origin}" == https://* ]] || return 1
authority="${origin#https://}"
[[ "${authority}" != *'/'* && "${authority}" != *':'* ]] || return 1
validate_domain "${authority}" || return 1
printf '%s\n' "${authority}"
}
proxy_from_systemd_environment() {
local environment="$1"
if [[ " ${environment} " =~ [[:space:]]HTTPS_PROXY=([^[:space:]]+) ]]; then
printf '%s\n' "${BASH_REMATCH[1]}"
elif [[ " ${environment} " =~ [[:space:]]HTTP_PROXY=([^[:space:]]+) ]]; then
printf '%s\n' "${BASH_REMATCH[1]}"
else
return 1
fi
}
detect_docker_proxy() {
command -v systemctl >/dev/null 2>&1 || return 1
local environment
environment="$(systemctl show docker.service --property=Environment --value 2>/dev/null || true)"
proxy_from_systemd_environment "${environment}"
}
initialize_privilege() {
if ((EUID == 0)); then
ROOT_COMMAND=()
else
command -v sudo >/dev/null || die 'sudo is required when not running as root.'
sudo -v
ROOT_COMMAND=(sudo)
fi
}
run_root() {
if ((${#ROOT_COMMAND[@]} == 0)); then "$@"; else "${ROOT_COMMAND[@]}" "$@"; fi
}
run_root_network() {
if [[ -n "${OUTBOUND_PROXY}" ]]; then
run_root env \
HTTP_PROXY="${OUTBOUND_PROXY}" HTTPS_PROXY="${OUTBOUND_PROXY}" \
http_proxy="${OUTBOUND_PROXY}" https_proxy="${OUTBOUND_PROXY}" \
NO_PROXY='localhost,127.0.0.1' no_proxy='localhost,127.0.0.1' "$@"
else
run_root "$@"
fi
}
download() {
local url="$1" destination="$2"
if [[ -n "${OUTBOUND_PROXY}" ]]; then
curl --fail --location --silent --show-error --retry 4 --retry-all-errors \
--connect-timeout 30 --max-time 300 --proxy "${OUTBOUND_PROXY}" \
--output "${destination}" "${url}"
else
curl --fail --location --silent --show-error --retry 4 --retry-all-errors \
--connect-timeout 30 --max-time 300 --output "${destination}" "${url}"
fi
}
install_caddy() {
if command -v caddy >/dev/null 2>&1; then
success "Caddy is already installed ($(caddy version | head -n1))."
return 0
fi
info "Installing Caddy from Caddy's official Ubuntu repository"
local repository_file='/etc/apt/sources.list.d/caddy-stable.list'
local disabled_repository_file='/etc/apt/sources.list.d/caddy-stable.list.disabled-by-easy-stream'
local keyring_file='/usr/share/keyrings/caddy-stable-archive-keyring.gpg'
# A previous interrupted attempt may have enabled the repository without a
# readable keyring. Disable it before the prerequisite apt update so reruns
# can repair themselves instead of failing at the first command.
if [[ -f "${repository_file}" ]]; then
run_root mv -f "${repository_file}" "${disabled_repository_file}"
fi
run_root_network env DEBIAN_FRONTEND=noninteractive apt-get update
run_root_network env DEBIAN_FRONTEND=noninteractive apt-get install -y \
apt-transport-https ca-certificates curl debian-archive-keyring debian-keyring gpg
local key_tmp keyring_tmp repository_tmp
key_tmp="$(mktemp)"
keyring_tmp="$(mktemp)"
repository_tmp="$(mktemp)"
CLEANUP_FILES+=("${key_tmp}" "${keyring_tmp}" "${repository_tmp}")
download 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' "${key_tmp}"
download 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' "${repository_tmp}"
gpg --batch --show-keys "${key_tmp}" >/dev/null \
|| die 'The downloaded Caddy repository key is not a valid OpenPGP key.'
gpg --batch --yes --dearmor --output "${keyring_tmp}" "${key_tmp}"
# The script-wide umask is intentionally 077, but APT drops privileges to
# _apt for repository access and must be able to read this public keyring.
run_root install -m 0644 "${keyring_tmp}" "${keyring_file}"
run_root install -m 0644 "${repository_tmp}" "${repository_file}"
run_root rm -f -- "${disabled_repository_file}"
run_root_network env DEBIAN_FRONTEND=noninteractive apt-get update
run_root_network env DEBIAN_FRONTEND=noninteractive apt-get install -y caddy
success "Installed $(caddy version | head -n1)."
}
write_proxy_override() {
local override_dir='/etc/systemd/system/caddy.service.d'
local override_file="${override_dir}/easy-stream-proxy.conf"
if [[ -n "${OUTBOUND_PROXY}" ]]; then
local temporary
temporary="$(mktemp)"
CLEANUP_FILES+=("${temporary}")
cat > "${temporary}" <<EOF
[Service]
Environment="HTTP_PROXY=${OUTBOUND_PROXY}"
Environment="HTTPS_PROXY=${OUTBOUND_PROXY}"
Environment="NO_PROXY=localhost,127.0.0.1"
EOF
run_root install -d -m 0755 "${override_dir}"
run_root install -m 0600 "${temporary}" "${override_file}"
elif [[ -f "${override_file}" ]]; then
run_root rm -f -- "${override_file}"
fi
run_root systemctl daemon-reload
}
write_caddy_config() {
local destination="$1"
cat > "${destination}" <<EOF
{
email ${ADMIN_EMAIL}
}
${DOMAIN} {
encode zstd gzip
reverse_proxy 127.0.0.1:8080
header -Server
}
EOF
}
install_configuration() {
info "Configuring automatic HTTPS for ${DOMAIN}"
local temporary='/etc/caddy/Caddyfile.easy-stream.tmp'
local candidate
candidate="$(mktemp)"
CLEANUP_FILES+=("${candidate}")
write_caddy_config "${candidate}"
run_root install -m 0644 "${candidate}" "${temporary}"
run_root caddy validate --config "${temporary}" --adapter caddyfile >/dev/null \
|| die 'Caddy rejected the generated configuration; the active configuration was not changed.'
if [[ -f /etc/caddy/Caddyfile ]]; then
CONFIG_BACKUP="/etc/caddy/Caddyfile.backup.$(date -u +%Y%m%dT%H%M%SZ).$$"
run_root cp -p /etc/caddy/Caddyfile "${CONFIG_BACKUP}"
fi
run_root mv -f "${temporary}" /etc/caddy/Caddyfile
if ! run_root caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null; then
[[ -n "${CONFIG_BACKUP}" ]] && run_root cp -p "${CONFIG_BACKUP}" /etc/caddy/Caddyfile
die 'Caddy validation failed after installation; the previous configuration was restored.'
fi
[[ -z "${CONFIG_BACKUP}" ]] || success "Preserved the previous Caddyfile at ${CONFIG_BACKUP}."
}
configure_firewall() {
command -v ufw >/dev/null 2>&1 || return 0
local status
status="$(run_root ufw status | head -n1)"
[[ "${status}" == *active* && "${status}" != *inactive* ]] || return 0
if confirm 'UFW is active. Allow public HTTP and HTTPS traffic?' yes; then
run_root ufw allow 80/tcp
run_root ufw allow 443/tcp
else
warn 'Ports 80 and 443 were not opened; automatic certificate issuance may fail.'
fi
}
check_gateway() {
command -v curl >/dev/null || die 'curl is required.'
curl --noproxy '*' --fail --silent --show-error --max-time 10 http://127.0.0.1:8080/ >/dev/null \
|| die 'Easy Stream is not responding at http://127.0.0.1:8080. Start the Compose stack first.'
success 'Easy Stream gateway is responding on 127.0.0.1:8080.'
}
check_public_ports() {
command -v ss >/dev/null 2>&1 || return 0
local listeners
listeners="$(run_root ss -H -ltnp 2>/dev/null | awk '$4 ~ /:80$|:443$/ { print }')"
[[ -z "${listeners}" ]] && return 0
if command -v caddy >/dev/null 2>&1 && grep -qi caddy <<< "${listeners}"; then
return 0
fi
warn 'Another process already listens on public HTTP/HTTPS ports:'
printf '%s\n' "${listeners}" >&2
die 'Stop or reconfigure that reverse proxy before installing Caddy; the existing service was not changed.'
}
main() {
if (($# > 0)); then
case "$1" in -h|--help) usage; return 0 ;; *) die "Unknown option: $1" ;; esac
fi
[[ -t 0 && -t 1 ]] || die 'Run this script from an interactive terminal.'
[[ -r /etc/os-release ]] || die 'Cannot identify this operating system.'
# shellcheck disable=SC1091
source /etc/os-release
[[ "${ID:-}" == ubuntu ]] || die 'This domain setup supports Ubuntu only.'
local origin default_domain default_email default_proxy
origin="${EASY_STREAM_DOMAIN_ORIGIN:-$(read_env_value PUBLIC_ORIGIN || true)}"
default_domain="$(domain_from_origin "${origin}" 2>/dev/null || true)"
default_email="${EASY_STREAM_ADMIN_EMAIL:-$(read_env_value ADMIN_BOOTSTRAP_EMAIL || true)}"
default_proxy="${EASY_STREAM_OUTBOUND_PROXY:-$(read_env_value BUILD_HTTP_PROXY || true)}"
if [[ -z "${default_proxy}" ]]; then
default_proxy="$(detect_docker_proxy || true)"
fi
info 'Public domain and automatic HTTPS'
prompt_value DOMAIN 'Public domain' "${default_domain}" validate_domain
prompt_value ADMIN_EMAIL 'Certificate notification email' "${default_email}" validate_email
prompt_value OUTBOUND_PROXY 'Host outbound HTTP(S) proxy (optional)' "${default_proxy}" validate_optional_proxy
printf '\nDomain: %s\nUpstream: http://127.0.0.1:8080\nHTTPS: automatic (Caddy)\nOutbound proxy: %s\n' \
"${DOMAIN}" "$([[ -n "${OUTBOUND_PROXY}" ]] && printf enabled || printf disabled)"
warn 'DNS must point to this server, and provider/network firewalls must allow inbound TCP 80 and 443.'
confirm 'Install and activate this public HTTPS endpoint?' no || die 'Domain setup cancelled without changes.'
initialize_privilege
check_gateway
check_public_ports
install_caddy
write_proxy_override
install_configuration
configure_firewall
run_root systemctl enable caddy.service
# A reload applies the Caddyfile but retains the running process environment.
# Restart so a newly installed systemd proxy override is actually inherited.
run_root systemctl restart caddy.service
success "Caddy is active. Open https://${DOMAIN}/ and https://${DOMAIN}/admin."
printf 'Certificate status: journalctl -u caddy --since "10 minutes ago" --no-pager\n'
}
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
main "$@"
fi
+7 -1
View File
@@ -718,7 +718,13 @@ main() {
if [[ "${should_start}" == true ]]; then
start_stack
success "Easy Stream is running. Route ${PUBLIC_ORIGIN} through TLS/CDN to this server's port 8080, then open ${PUBLIC_ORIGIN}/admin."
success "Easy Stream's loopback gateway is running on port 8080."
if confirm 'Configure the public domain and automatic HTTPS with Caddy now?' yes; then
EASY_STREAM_DOMAIN_ORIGIN="${PUBLIC_ORIGIN}" \
EASY_STREAM_ADMIN_EMAIL="${ADMIN_BOOTSTRAP_EMAIL}" \
EASY_STREAM_OUTBOUND_PROXY="${BUILD_HTTP_PROXY}" \
bash "${PROJECT_ROOT}/scripts/setup-domain.sh"
fi
else
info 'Configuration is complete; the stack was not started'
local docker_prefix=''
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
set -Eeuo pipefail
readonly TEST_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
# shellcheck source=setup-domain.sh
source "${TEST_DIR}/setup-domain.sh"
fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; }
expect_valid() { VALIDATION_ERROR=''; "$1" "$2" || fail "Expected $1 to accept $2: ${VALIDATION_ERROR}"; }
expect_invalid() { VALIDATION_ERROR=''; if "$1" "$2"; then fail "Expected $1 to reject $2"; fi; }
expect_valid validate_domain 'es.mvphub.ir'
expect_valid validate_domain 'stream.example.com'
expect_invalid validate_domain 'https://stream.example.com'
expect_invalid validate_domain 'stream.example.com:443'
expect_invalid validate_domain 'localhost'
expect_valid validate_email 'admin@mvphub.ir'
expect_invalid validate_email 'admin'
expect_valid validate_optional_proxy ''
expect_valid validate_optional_proxy 'http://127.0.0.1:8118'
expect_invalid validate_optional_proxy 'socks5://127.0.0.1:1080'
[[ "$(domain_from_origin 'https://es.mvphub.ir')" == 'es.mvphub.ir' ]] || fail 'Origin parsing failed'
if domain_from_origin 'https://es.mvphub.ir:8443' >/dev/null 2>&1; then fail 'Custom origin port was accepted'; fi
[[ "$(proxy_from_systemd_environment 'HTTP_PROXY=http://127.0.0.1:8118 HTTPS_PROXY=http://127.0.0.1:8118 NO_PROXY=localhost')" == 'http://127.0.0.1:8118' ]] \
|| fail 'Docker systemd proxy detection failed'
if proxy_from_systemd_environment 'NO_PROXY=localhost,127.0.0.1' >/dev/null 2>&1; then
fail 'A missing Docker proxy was accepted'
fi
fixture="$(mktemp -d)"
trap 'rm -rf -- "${fixture}"' EXIT
DOMAIN='es.mvphub.ir'
ADMIN_EMAIL='admin@mvphub.ir'
write_caddy_config "${fixture}/Caddyfile"
grep -q '^es\.mvphub\.ir {$' "${fixture}/Caddyfile" || fail 'Domain missing from Caddyfile'
grep -q $'^\treverse_proxy 127\.0\.0\.1:8080$' "${fixture}/Caddyfile" || fail 'Upstream missing from Caddyfile'
grep -q $'^\temail admin@mvphub\.ir$' "${fixture}/Caddyfile" || fail 'Email missing from Caddyfile'
grep -q 'install -m 0644 "${keyring_tmp}" "${keyring_file}"' "${TEST_DIR}/setup-domain.sh" \
|| fail 'APT keyring readability protection is missing'
grep -q 'systemctl restart caddy.service' "${TEST_DIR}/setup-domain.sh" \
|| fail 'Caddy restart required for proxy inheritance is missing'
printf 'setup-domain helper tests: ok\n'