This commit is contained in:
Meghdad committed 2026-07-14 12:51:36 +03:30
commit f035fcef4f
134 files changed
+18678

No files matched your search

+558
View File
@@ -0,0 +1,558 @@
import { randomUUID } from 'node:crypto';
import cookie from '@fastify/cookie';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';
import {
AdminLoginSchema,
AdminSessionResponseSchema,
CacheParamsSchema,
CacheStatusSchema,
CatalogQuerySchema,
CatalogResponseSchema,
CreatePlaybackSessionSchema,
DateTimeSchema,
ErrorResponseSchema,
JobParamsSchema,
JobSchema,
MetadataCandidateSchema,
MetadataMatchBodySchema,
MetadataMatchParamsSchema,
MetadataSearchQuerySchema,
MetadataSearchResponseSchema,
PlaybackSessionParamsSchema,
PlaybackSessionSchema,
PublicationBodySchema,
PublicationParamsSchema,
SearchQuerySchema,
SearchResponseSchema,
StartScanSchema,
TitleDetailSchema,
UuidSchema,
type AdminLogin,
type CatalogQuery,
type CreatePlaybackSession,
type MetadataMatchBody,
type MetadataSearchQuery,
type SearchQuery,
type StartScan,
} from '@easy-stream/contracts';
import { createDatabase } from '@easy-stream/database';
import { Type, type Static } from '@sinclair/typebox';
import Fastify, {
type FastifyInstance,
type FastifyReply,
type FastifyRequest,
} from 'fastify';
import { loadConfig, type ApiConfig } from './config.js';
import { PlaybackGrantSigner, playbackCookieName } from './crypto.js';
import type {
AppRepository,
MediaCommandPublisher,
MediaPreparationService,
MetadataProvider,
PasswordHasher,
StoredPlaybackSession,
TotpVerifier,
} from './domain.js';
import { AppError } from './errors.js';
import { InMemoryRepository, loadCatalogSnapshot } from './repositories/in-memory.js';
import { PostgresRepository } from './repositories/postgres.js';
import { AdminService, Argon2PasswordHasher, DenyEncryptedTotpVerifier } from './services/admin.js';
import {
FileMediaPreparationService,
BullMqMediaBridge,
JsonlMediaCommandPublisher,
} from './services/media-preparation.js';
import { PlaybackService } from './services/playback.js';
import {
FilesystemCacheStatusService,
type CacheStatusService,
} from './services/cache-status.js';
import { createMetadataProvider } from './services/tmdb.js';
interface BuildAppOptions {
config?: ApiConfig;
repository?: AppRepository;
mediaPreparation?: MediaPreparationService;
commandPublisher?: MediaCommandPublisher;
metadataProvider?: MetadataProvider;
passwordHasher?: PasswordHasher;
totpVerifier?: TotpVerifier;
cacheStatus?: CacheStatusService;
fetch?: typeof globalThis.fetch;
logger?: boolean;
}
const SlugParamsSchema = Type.Object(
{ slug: Type.String({ minLength: 1, maxLength: 240 }) },
{ additionalProperties: false },
);
const OkSchema = Type.Object({ ok: Type.Literal(true) }, { additionalProperties: false });
const HealthSchema = Type.Object(
{
status: Type.Literal('ok'),
time: Type.String(),
repository: Type.Union([Type.Literal('memory'), Type.Literal('postgres')]),
},
{ additionalProperties: false },
);
const JobsResponseSchema = Type.Object(
{ items: Type.Array(JobSchema) },
{ additionalProperties: false },
);
const ClientEventSchema = Type.Object(
{
name: Type.String({ minLength: 1, maxLength: 64, pattern: '^[a-z0-9._-]+$' }),
mediaItemId: Type.Optional(UuidSchema),
sessionId: Type.Optional(UuidSchema),
occurredAt: DateTimeSchema,
details: Type.Optional(
Type.Record(
Type.String({ minLength: 1, maxLength: 64 }),
Type.Union([
Type.String({ maxLength: 2048 }),
Type.Number(),
Type.Boolean(),
Type.Null(),
]),
),
),
},
{ additionalProperties: false },
);
type PublicationBody = Static<typeof PublicationBodySchema>;
export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyInstance> {
const config = options.config ?? loadConfig();
const app = Fastify({
logger: options.logger ?? config.nodeEnv !== 'test',
genReqId: (request) =>
typeof request.headers['x-request-id'] === 'string'
? request.headers['x-request-id'].slice(0, 128)
: randomUUID(),
bodyLimit: 64 * 1024,
trustProxy: config.nodeEnv === 'production' ? 1 : false,
});
await app.register(cookie);
await app.register(cors, {
origin: config.webOrigin,
credentials: true,
methods: ['GET', 'HEAD', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['content-type', 'x-csrf-token', 'x-request-id'],
});
await app.register(helmet, {
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
});
await app.register(rateLimit, {
global: true,
max: 300,
timeWindow: '1 minute',
});
const runtime = await createRepository(app, config, options.repository);
const repository = runtime.repository;
const cacheStatus = options.cacheStatus ?? new FilesystemCacheStatusService({
cacheRoot: config.cacheRoot,
maxBytes: config.cacheMaxBytes,
highWatermark: config.cacheHighWatermark,
lowWatermark: config.cacheLowWatermark,
});
const redisBridge =
config.redisUrl && (!options.commandPublisher || !options.mediaPreparation)
? new BullMqMediaBridge(config.redisUrl, config.packageRegistryPath, config.playbackProfile)
: undefined;
if (redisBridge) app.addHook('onClose', async () => redisBridge.close());
const commands =
options.commandPublisher ??
redisBridge ??
new JsonlMediaCommandPublisher(config.mediaCommandsPath);
const media =
options.mediaPreparation ??
redisBridge ??
new FileMediaPreparationService(config.packageRegistryPath, commands);
const metadata =
options.metadataProvider ?? createMetadataProvider(config, options.fetch ?? globalThis.fetch);
const playback = new PlaybackService(repository, media, config);
const admin = new AdminService(
repository,
commands,
media,
metadata,
options.passwordHasher ?? new Argon2PasswordHasher(),
options.totpVerifier ?? new DenyEncryptedTotpVerifier(),
config,
);
await admin.initialize();
const grantSigner = new PlaybackGrantSigner(config.playbackSigningSecret);
app.setErrorHandler((error, request, reply) => {
if (error instanceof AppError) {
return reply.code(error.statusCode).send({
error: {
code: error.code,
message: error.message,
requestId: request.id,
...(error.details !== undefined ? { details: error.details } : {}),
},
});
}
if (typeof error === 'object' && error && 'validation' in error && error.validation) {
return reply.code(400).send({
error: {
code: 'VALIDATION_ERROR',
message: 'Request validation failed',
requestId: request.id,
details: error.validation,
},
});
}
request.log.error({ err: error }, 'unhandled request error');
return reply.code(500).send({
error: { code: 'INTERNAL_ERROR', message: 'Internal server error', requestId: request.id },
});
});
app.get('/health', { schema: { response: { 200: HealthSchema } } }, async () => ({
status: 'ok' as const,
time: new Date().toISOString(),
repository: config.repositoryDriver,
}));
app.get<{ Querystring: CatalogQuery }>(
'/api/v1/catalog',
{
schema: {
querystring: CatalogQuerySchema,
response: { 200: CatalogResponseSchema, 400: ErrorResponseSchema },
},
},
async (request) => repository.listCatalog(request.query),
);
app.get<{ Params: Static<typeof SlugParamsSchema> }>(
'/api/v1/titles/:slug',
{
schema: {
params: SlugParamsSchema,
response: { 200: TitleDetailSchema, 404: ErrorResponseSchema },
},
},
async (request) => {
const title = await repository.getTitleBySlug(request.params.slug);
if (!title) throw new AppError(404, 'NOT_FOUND', 'Title not found');
return title;
},
);
app.get<{ Querystring: SearchQuery }>(
'/api/v1/search',
{
schema: {
querystring: SearchQuerySchema,
response: { 200: SearchResponseSchema, 400: ErrorResponseSchema },
},
},
async (request) => ({ items: await repository.searchTitles(request.query) }),
);
app.post<{ Body: Static<typeof ClientEventSchema> }>(
'/api/v1/client-events',
{
config: { rateLimit: { max: 120, timeWindow: '1 minute' } },
schema: {
body: ClientEventSchema,
response: { 202: OkSchema, 400: ErrorResponseSchema },
},
},
async (request, reply) => {
request.log.info({ clientEvent: request.body }, 'client playback event');
return reply.code(202).send({ ok: true as const });
},
);
app.post<{ Body: CreatePlaybackSession }>(
'/api/v1/playback-sessions',
{
config: { rateLimit: { max: 60, timeWindow: '1 minute' } },
schema: {
body: CreatePlaybackSessionSchema,
response: {
200: PlaybackSessionSchema,
202: PlaybackSessionSchema,
400: ErrorResponseSchema,
404: ErrorResponseSchema,
},
},
},
async (request, reply) => {
const session = await playback.create(request.body);
if (session.state === 'READY') issuePlaybackCookie(reply, session, grantSigner, config);
return reply.code(session.state === 'PREPARING' ? 202 : 200).send(playback.toPublic(session));
},
);
app.get<{ Params: Static<typeof PlaybackSessionParamsSchema> }>(
'/api/v1/playback-sessions/:id',
{
schema: {
params: PlaybackSessionParamsSchema,
response: { 200: PlaybackSessionSchema, 202: PlaybackSessionSchema, 404: ErrorResponseSchema },
},
},
async (request, reply) => {
const session = await playback.get(request.params.id);
if (session.state === 'READY') issuePlaybackCookie(reply, session, grantSigner, config);
return reply.code(session.state === 'PREPARING' ? 202 : 200).send(playback.toPublic(session));
},
);
app.get(
'/internal/media-auth',
{ config: { rateLimit: false } },
async (request, reply) => {
if (header(request, 'x-media-auth-secret') !== config.mediaAuthSharedSecret) {
throw new AppError(401, 'UNAUTHORIZED', 'Invalid media authorization secret');
}
const originalUri = header(request, 'x-original-uri');
if (!originalUri || /%2f|%5c|%2e/i.test(originalUri)) {
throw new AppError(401, 'UNAUTHORIZED', 'Invalid media request path');
}
const pathname = new URL(originalUri, config.publicOrigin).pathname;
const match = pathname.match(
/^\/media\/(?:derived\/)?generations\/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\//i,
);
const generationId = match?.[1];
if (!generationId) throw new AppError(401, 'UNAUTHORIZED', 'Invalid media request path');
const token = request.cookies[playbackCookieName(generationId)];
const grant = token ? grantSigner.verify(token) : undefined;
if (
!grant ||
grant.generationId !== generationId ||
grant.expiresAtEpochSeconds <= Math.floor(Date.now() / 1000) ||
!pathname.startsWith(grant.path)
) {
throw new AppError(401, 'UNAUTHORIZED', 'Media authorization expired or invalid');
}
const session = await repository.getPlaybackSession(grant.sessionId);
if (
!session ||
session.state !== 'READY' ||
session.generationId !== generationId ||
Date.parse(session.expiresAt) <= Date.now()
) {
throw new AppError(401, 'UNAUTHORIZED', 'Playback session expired or invalid');
}
return reply.code(204).send();
},
);
app.post<{ Body: AdminLogin }>(
'/api/v1/admin/login',
{
config: { rateLimit: { max: 5, timeWindow: '1 minute' } },
schema: {
body: AdminLoginSchema,
response: { 200: AdminSessionResponseSchema, 401: ErrorResponseSchema },
},
},
async (request, reply) => {
const result = await admin.login(request.body);
reply.setCookie('es_admin_session', result.rawToken, adminCookie(config));
return result.response;
},
);
const adminRead = async (request: FastifyRequest) => {
await admin.authenticate(request.cookies.es_admin_session);
};
const adminWrite = async (request: FastifyRequest) => {
const csrf = header(request, 'x-csrf-token');
if (!csrf) throw new AppError(403, 'FORBIDDEN', 'CSRF token is required');
await admin.authenticate(request.cookies.es_admin_session, csrf);
};
app.post(
'/api/v1/admin/logout',
{ preHandler: adminWrite, schema: { response: { 200: OkSchema } } },
async (request, reply) => {
await admin.logout(request.cookies.es_admin_session, header(request, 'x-csrf-token'));
reply.clearCookie('es_admin_session', { path: '/' });
return { ok: true as const };
},
);
app.post<{ Body: StartScan }>(
'/api/v1/admin/scans',
{
preHandler: adminWrite,
schema: { body: StartScanSchema, response: { 202: JobSchema } },
},
async (request, reply) => reply.code(202).send(await admin.startScan(request.body.full ?? false)),
);
app.patch<{
Params: Static<typeof PublicationParamsSchema>;
Body: PublicationBody;
}>(
'/api/v1/admin/media/:mediaItemId/publication',
{
preHandler: adminWrite,
schema: {
params: PublicationParamsSchema,
body: PublicationBodySchema,
response: { 200: OkSchema },
},
},
async (request) => {
await admin.setPublished(request.params.mediaItemId, request.body.published);
return { ok: true as const };
},
);
app.get(
'/api/v1/admin/jobs',
{ preHandler: adminRead, schema: { response: { 200: JobsResponseSchema } } },
async () => ({ items: await repository.listJobs() }),
);
app.post<{ Params: Static<typeof JobParamsSchema> }>(
'/api/v1/admin/jobs/:jobId/retry',
{
preHandler: adminWrite,
schema: { params: JobParamsSchema, response: { 202: JobSchema } },
},
async (request, reply) => reply.code(202).send(await admin.retryJob(request.params.jobId)),
);
app.get(
'/api/v1/admin/cache',
{ preHandler: adminRead, schema: { response: { 200: CacheStatusSchema } } },
async () => cacheStatus.getStatus(),
);
app.post<{ Params: Static<typeof CacheParamsSchema> }>(
'/api/v1/admin/cache/:generationId/evict',
{
preHandler: adminWrite,
schema: { params: CacheParamsSchema, response: { 202: OkSchema } },
},
async (request, reply) => {
await admin.evict(request.params.generationId);
return reply.code(202).send({ ok: true as const });
},
);
app.get<{ Querystring: MetadataSearchQuery }>(
'/api/v1/admin/metadata/tmdb/search',
{
preHandler: adminRead,
schema: {
querystring: MetadataSearchQuerySchema,
response: { 200: MetadataSearchResponseSchema },
},
},
async (request) => ({ items: await admin.searchMetadata(request.query) }),
);
app.post<{
Params: Static<typeof MetadataMatchParamsSchema>;
Body: MetadataMatchBody;
}>(
'/api/v1/admin/titles/:titleId/metadata-match',
{
preHandler: adminWrite,
schema: {
params: MetadataMatchParamsSchema,
body: MetadataMatchBodySchema,
response: { 200: MetadataCandidateSchema },
},
},
async (request) => admin.matchMetadata(request.params.titleId, request.body),
);
await app.ready();
return app;
}
async function createRepository(
app: FastifyInstance,
config: ApiConfig,
injected: AppRepository | undefined,
): Promise<{ repository: AppRepository }> {
if (injected) return { repository: injected };
if (config.repositoryDriver === 'memory') {
const snapshot = await loadCatalogSnapshot(config.catalogSnapshotPath);
const repository = new InMemoryRepository({
...(snapshot ? { titles: snapshot.titles } : {}),
cache: {
maxBytes: config.cacheMaxBytes,
highWatermark: config.cacheHighWatermark,
lowWatermark: config.cacheLowWatermark,
},
});
if (snapshot) app.log.info({ path: config.catalogSnapshotPath }, 'loaded catalog snapshot');
else app.log.warn({ path: config.catalogSnapshotPath }, 'catalog snapshot not found; catalog is empty');
return { repository };
}
const connection = createDatabase(config.databaseUrl!);
app.addHook('onClose', async () => connection.close());
return {
repository: new PostgresRepository(connection.db, {
cacheMaxBytes: config.cacheMaxBytes,
cacheHighWatermark: config.cacheHighWatermark,
cacheLowWatermark: config.cacheLowWatermark,
}),
};
}
function issuePlaybackCookie(
reply: FastifyReply,
session: StoredPlaybackSession,
signer: PlaybackGrantSigner,
config: ApiConfig,
): void {
if (!session.generationId || !session.manifestUrl) return;
const manifestPath = new URL(session.manifestUrl).pathname;
const match = manifestPath.match(
/^\/media\/(?:derived\/)?generations\/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\//i,
);
if (!match || match[1]?.toLowerCase() !== session.generationId.toLowerCase()) return;
const path = match[0];
const expiresAtEpochSeconds = Math.floor(Date.parse(session.expiresAt) / 1000);
reply.setCookie(
playbackCookieName(session.generationId),
signer.sign({
version: 1,
sessionId: session.id,
generationId: session.generationId,
path,
expiresAtEpochSeconds,
}),
{
httpOnly: true,
secure: config.nodeEnv === 'production',
sameSite: 'lax',
path,
expires: new Date(session.expiresAt),
},
);
}
function adminCookie(config: ApiConfig) {
return {
httpOnly: true,
secure: config.nodeEnv === 'production',
sameSite: 'strict' as const,
path: '/',
maxAge: config.adminSessionTtlSeconds,
};
}
function header(request: FastifyRequest, name: string): string | undefined {
const value = request.headers[name];
return Array.isArray(value) ? value[0] : value;
}
+199
View File
@@ -0,0 +1,199 @@
import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
const ConfigSchema = Type.Object(
{
nodeEnv: Type.Union([
Type.Literal('development'),
Type.Literal('test'),
Type.Literal('production'),
]),
host: Type.String({ minLength: 1 }),
port: Type.Integer({ minimum: 1, maximum: 65535 }),
webOrigin: Type.String({ pattern: '^https?://[^\\s]+$' }),
publicOrigin: Type.String({ pattern: '^https?://[^\\s]+$' }),
mediaPublicBaseUrl: Type.String({ pattern: '^https?://[^\\s]+$' }),
repositoryDriver: Type.Union([Type.Literal('memory'), Type.Literal('postgres')]),
databaseUrl: Type.Optional(Type.String({ minLength: 1 })),
redisUrl: Type.Optional(Type.String({ pattern: '^rediss?://[^\\s]+$' })),
catalogSnapshotPath: Type.String({ minLength: 1 }),
packageRegistryPath: Type.String({ minLength: 1 }),
mediaCommandsPath: Type.String({ minLength: 1 }),
cacheRoot: Type.String({ minLength: 1 }),
playbackProfile: Type.String({
minLength: 1,
maxLength: 64,
pattern: '^[a-zA-Z0-9._-]+$',
}),
playbackSigningSecret: Type.String({ minLength: 32 }),
// This value is substituted into an Nginx quoted string, so keep it to a
// portable base64url/hex alphabet rather than accepting config syntax.
mediaAuthSharedSecret: Type.String({
minLength: 32,
maxLength: 256,
pattern: '^[A-Za-z0-9_-]+$',
}),
playbackTtlSeconds: Type.Integer({ minimum: 300, maximum: 86400 }),
adminSessionTtlSeconds: Type.Integer({ minimum: 300, maximum: 86400 }),
adminBootstrapEmail: Type.Optional(
Type.String({ maxLength: 320, pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$' }),
),
adminBootstrapPassword: Type.Optional(Type.String({ minLength: 12 })),
tmdbApiToken: Type.Optional(Type.String({ minLength: 1 })),
tmdbCommercialLicenseConfirmed: Type.Boolean(),
tmdbBaseUrl: Type.String({ pattern: '^https?://[^\\s]+$' }),
tmdbTimeoutMs: Type.Integer({ minimum: 250, maximum: 30000 }),
tmdbMaxRetries: Type.Integer({ minimum: 0, maximum: 5 }),
cacheMaxBytes: Type.Integer({ minimum: 1 }),
cacheHighWatermark: Type.Number({ exclusiveMinimum: 0, maximum: 1 }),
cacheLowWatermark: Type.Number({ minimum: 0, exclusiveMaximum: 1 }),
},
{ additionalProperties: false },
);
export interface ApiConfig {
nodeEnv: 'development' | 'test' | 'production';
host: string;
port: number;
webOrigin: string;
publicOrigin: string;
mediaPublicBaseUrl: string;
repositoryDriver: 'memory' | 'postgres';
databaseUrl?: string;
redisUrl?: string;
catalogSnapshotPath: string;
packageRegistryPath: string;
mediaCommandsPath: string;
cacheRoot: string;
playbackProfile: string;
playbackSigningSecret: string;
mediaAuthSharedSecret: string;
playbackTtlSeconds: number;
adminSessionTtlSeconds: number;
adminBootstrapEmail?: string;
adminBootstrapPassword?: string;
tmdbApiToken?: string;
tmdbCommercialLicenseConfirmed: boolean;
tmdbBaseUrl: string;
tmdbTimeoutMs: number;
tmdbMaxRetries: number;
cacheMaxBytes: number;
cacheHighWatermark: number;
cacheLowWatermark: number;
}
function integer(value: string | undefined, fallback: number): number {
if (value === undefined || value === '') return fallback;
if (!/^-?[0-9]+$/.test(value)) return Number.NaN;
return Number(value);
}
function decimal(value: string | undefined, fallback: number): number {
if (value === undefined || value === '') return fallback;
return Number(value);
}
function bool(value: string | undefined, fallback: boolean): boolean {
if (value === undefined || value === '') return fallback;
if (value === 'true') return true;
if (value === 'false') return false;
throw new Error(`Expected a boolean, received ${JSON.stringify(value)}`);
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): ApiConfig {
const nodeEnv = env.NODE_ENV ?? 'development';
const signingSecret = env.PLAYBACK_SIGNING_SECRET ?? '';
const config: ApiConfig = {
nodeEnv: nodeEnv as ApiConfig['nodeEnv'],
host: env.HOST ?? '0.0.0.0',
port: integer(env.PORT, 3000),
webOrigin: env.WEB_ORIGIN ?? 'http://localhost:5173',
publicOrigin: env.PUBLIC_ORIGIN ?? 'http://localhost:8080',
mediaPublicBaseUrl: env.MEDIA_PUBLIC_BASE_URL ?? 'http://localhost:8080/media',
repositoryDriver:
(env.REPOSITORY_DRIVER as ApiConfig['repositoryDriver'] | undefined) ??
(nodeEnv === 'production' ? 'postgres' : 'memory'),
...(env.DATABASE_URL ? { databaseUrl: env.DATABASE_URL } : {}),
...(env.REDIS_URL ? { redisUrl: env.REDIS_URL } : {}),
catalogSnapshotPath: env.CATALOG_SNAPSHOT_PATH ?? './data/catalog.json',
packageRegistryPath: env.PACKAGE_REGISTRY_PATH ?? './data/package-registry.json',
mediaCommandsPath: env.MEDIA_COMMANDS_PATH ?? './data/media-commands.jsonl',
cacheRoot: env.CACHE_ROOT ?? './data/cache',
playbackProfile: env.PLAYBACK_PROFILE ?? 'cmaf-v1',
playbackSigningSecret: signingSecret,
mediaAuthSharedSecret: env.MEDIA_AUTH_SHARED_SECRET ?? signingSecret,
playbackTtlSeconds: integer(env.PLAYBACK_TTL_SECONDS, 4 * 60 * 60),
adminSessionTtlSeconds: integer(env.ADMIN_SESSION_TTL_SECONDS, 8 * 60 * 60),
...(env.ADMIN_BOOTSTRAP_EMAIL ? { adminBootstrapEmail: env.ADMIN_BOOTSTRAP_EMAIL } : {}),
...(env.ADMIN_BOOTSTRAP_PASSWORD
? { adminBootstrapPassword: env.ADMIN_BOOTSTRAP_PASSWORD }
: {}),
...(env.TMDB_API_TOKEN ? { tmdbApiToken: env.TMDB_API_TOKEN } : {}),
tmdbCommercialLicenseConfirmed: bool(env.TMDB_COMMERCIAL_LICENSE_CONFIRMED, false),
tmdbBaseUrl: env.TMDB_BASE_URL ?? 'https://api.themoviedb.org/3',
tmdbTimeoutMs: integer(env.TMDB_TIMEOUT_MS, 4000),
tmdbMaxRetries: integer(env.TMDB_MAX_RETRIES, 2),
cacheMaxBytes: integer(env.CACHE_MAX_BYTES, 2_147_483_648_000),
cacheHighWatermark: decimal(env.CACHE_HIGH_WATERMARK, 0.85),
cacheLowWatermark: decimal(env.CACHE_LOW_WATERMARK, 0.75),
};
if (!Value.Check(ConfigSchema, config)) {
const errors = [...Value.Errors(ConfigSchema, config)]
.map((error) => `${error.path || '/'} ${error.message}`)
.join('; ');
throw new Error(`Invalid API configuration: ${errors}`);
}
if (config.repositoryDriver === 'postgres' && !config.databaseUrl) {
throw new Error('DATABASE_URL is required when REPOSITORY_DRIVER=postgres');
}
if (config.cacheLowWatermark >= config.cacheHighWatermark) {
throw new Error('CACHE_LOW_WATERMARK must be lower than CACHE_HIGH_WATERMARK');
}
const mediaBase = new URL(config.mediaPublicBaseUrl);
if (mediaBase.pathname.replace(/\/+$/u, '') !== '/media' || mediaBase.search || mediaBase.hash) {
throw new Error('MEDIA_PUBLIC_BASE_URL must use the /media path without query or fragment');
}
if (
config.nodeEnv === 'production' &&
config.adminBootstrapPassword === 'change-me-before-production'
) {
throw new Error('The example administrator password is forbidden in production');
}
if (
config.nodeEnv === 'production' &&
[
'replace-with-at-least-32-random-characters',
'replace-with-another-32-random-character-secret',
].includes(config.playbackSigningSecret)
) {
throw new Error('The example playback signing secret is forbidden in production');
}
if (
config.nodeEnv === 'production' &&
[
'replace-with-at-least-32-random-characters',
'replace-with-another-32-random-character-secret',
].includes(config.mediaAuthSharedSecret)
) {
throw new Error('The example media auth secret is forbidden in production');
}
if (
config.nodeEnv === 'production' &&
config.mediaAuthSharedSecret === config.playbackSigningSecret
) {
throw new Error('MEDIA_AUTH_SHARED_SECRET must differ from PLAYBACK_SIGNING_SECRET in production');
}
if (config.nodeEnv === 'production') {
const publicOrigin = new URL(config.publicOrigin).origin;
if (
new URL(config.webOrigin).origin !== publicOrigin ||
mediaBase.origin !== publicOrigin
) {
throw new Error(
'WEB_ORIGIN, PUBLIC_ORIGIN, and MEDIA_PUBLIC_BASE_URL must use one origin in production',
);
}
}
return config;
}
+59
View File
@@ -0,0 +1,59 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
export function randomToken(bytes = 32): string {
return randomBytes(bytes).toString('base64url');
}
export function sha256(value: string): string {
return createHash('sha256').update(value).digest('hex');
}
function safeEqual(left: string, right: string): boolean {
const a = Buffer.from(left);
const b = Buffer.from(right);
return a.length === b.length && timingSafeEqual(a, b);
}
export interface PlaybackGrant {
version: 1;
sessionId: string;
generationId: string;
path: string;
expiresAtEpochSeconds: number;
}
export class PlaybackGrantSigner {
constructor(private readonly secret: string) {}
sign(grant: PlaybackGrant): string {
const payload = Buffer.from(JSON.stringify(grant)).toString('base64url');
const signature = createHmac('sha256', this.secret).update(payload).digest('base64url');
return `${payload}.${signature}`;
}
verify(token: string): PlaybackGrant | undefined {
const [payload, signature, extra] = token.split('.');
if (!payload || !signature || extra) return undefined;
const expected = createHmac('sha256', this.secret).update(payload).digest('base64url');
if (!safeEqual(signature, expected)) return undefined;
try {
const value = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as PlaybackGrant;
if (
value.version !== 1 ||
!value.sessionId ||
!value.generationId ||
!value.path.startsWith('/media/') ||
!Number.isInteger(value.expiresAtEpochSeconds)
) {
return undefined;
}
return value;
} catch {
return undefined;
}
}
}
export function playbackCookieName(generationId: string): string {
return `es_playback_${generationId.replaceAll('-', '')}`;
}
+136
View File
@@ -0,0 +1,136 @@
import type {
AdminSessionResponse,
AudioTrack,
CacheStatus,
CatalogCard,
CatalogQuery,
ClientCapabilities,
Job,
MetadataCandidate,
MediaCommand,
PlaybackSession,
SearchQuery,
SubtitleTrack,
TitleDetail,
} from '@easy-stream/contracts';
export interface MediaItemForPlayback {
id: string;
titleId: string;
durationSeconds: number;
compatibility: 'COPY' | 'AUDIO_TRANSCODE' | 'VIDEO_TRANSCODE' | 'HOLD_HDR' | 'INVALID';
published: boolean;
}
export interface CatalogPage {
items: CatalogCard[];
nextCursor?: string;
}
export interface CatalogRepository {
listCatalog(query: CatalogQuery): Promise<CatalogPage>;
searchTitles(query: SearchQuery): Promise<CatalogCard[]>;
getTitleBySlug(slug: string): Promise<TitleDetail | undefined>;
getMediaItem(id: string): Promise<MediaItemForPlayback | undefined>;
setMediaPublished(mediaItemId: string, published: boolean): Promise<boolean>;
applyTitleMetadata(titleId: string, metadata: MetadataCandidate): Promise<boolean>;
}
export interface StoredPlaybackSession extends PlaybackSession {
capabilities: ClientCapabilities;
}
export interface PlaybackRepository {
createPlaybackSession(session: StoredPlaybackSession): Promise<void>;
getPlaybackSession(id: string): Promise<StoredPlaybackSession | undefined>;
updatePlaybackSession(session: StoredPlaybackSession): Promise<void>;
}
export interface AdminRecord {
id: string;
email: string;
passwordHash: string;
totpSecretEncrypted?: string;
disabled: boolean;
}
export interface StoredAdminSession {
id: string;
adminId: string;
tokenHash: string;
csrfTokenHash: string;
expiresAt: string;
revokedAt?: string;
}
export interface AdminRepository {
findAdminByEmail(email: string): Promise<AdminRecord | undefined>;
findAdminById(id: string): Promise<AdminRecord | undefined>;
createAdmin(admin: AdminRecord): Promise<void>;
createAdminSession(session: StoredAdminSession): Promise<void>;
findAdminSessionByTokenHash(tokenHash: string): Promise<StoredAdminSession | undefined>;
revokeAdminSession(id: string): Promise<void>;
createJob(job: Job, payload: Record<string, unknown>): Promise<void>;
listJobs(): Promise<Job[]>;
findJob(id: string): Promise<Job | undefined>;
retryJob(id: string): Promise<Job | undefined>;
getCacheStatus(): Promise<CacheStatus>;
}
export type AppRepository = CatalogRepository & PlaybackRepository & AdminRepository;
export interface MediaPreparation {
state: PlaybackSession['state'];
playable: boolean;
generationId?: string;
manifestPath?: string;
reasonCode?: string;
pollAfterMs?: number;
durationSeconds?: number;
audioTracks?: AudioTrack[];
subtitleTracks?: SubtitleTrack[];
}
export interface MediaPreparationService {
prepare(input: {
sessionId: string;
mediaItem: MediaItemForPlayback;
capabilities: ClientCapabilities;
protectUntil?: string;
}): Promise<MediaPreparation>;
getStatus(input: {
sessionId: string;
mediaItem: MediaItemForPlayback;
protectUntil?: string;
}): Promise<MediaPreparation>;
}
export interface MediaCommandPublisher {
publish(command: MediaCommand): Promise<void>;
}
export interface PasswordHasher {
hash(password: string): Promise<string>;
verify(hash: string, password: string): Promise<boolean>;
}
export interface TotpVerifier {
verify(encryptedSecret: string, code: string): Promise<boolean>;
}
export interface MetadataProvider {
search(input: {
query: string;
kind: 'MOVIE' | 'SERIES';
year?: number;
}): Promise<MetadataCandidate[]>;
getDetails(input: {
externalId: number;
kind: 'MOVIE' | 'SERIES';
}): Promise<MetadataCandidate>;
}
export interface AuthenticatedAdmin extends AdminSessionResponse {
sessionId: string;
rawToken: string;
}
+13
View File
@@ -0,0 +1,13 @@
import type { ErrorCode } from '@easy-stream/contracts';
export class AppError extends Error {
constructor(
public readonly statusCode: number,
public readonly code: ErrorCode,
message: string,
public readonly details?: unknown,
) {
super(message);
this.name = 'AppError';
}
}
+23
View File
@@ -0,0 +1,23 @@
export { buildApp } from './app.js';
export { loadConfig, type ApiConfig } from './config.js';
export type {
AppRepository,
MediaCommandPublisher,
MediaPreparation,
MediaPreparationService,
MetadataProvider,
} from './domain.js';
export { InMemoryRepository, loadCatalogSnapshot } from './repositories/in-memory.js';
export { PostgresRepository } from './repositories/postgres.js';
export {
FilesystemCacheStatusService,
type CacheStatusService,
type FilesystemCacheStatusOptions,
} from './services/cache-status.js';
export {
FileMediaPreparationService,
BullMqMediaBridge,
InMemoryMediaCommandPublisher,
JsonlMediaCommandPublisher,
} from './services/media-preparation.js';
export { DisabledMetadataProvider, TmdbMetadataProvider } from './services/tmdb.js';
+280
View File
@@ -0,0 +1,280 @@
import { readFile } from 'node:fs/promises';
import {
CatalogSnapshotSchema,
type CacheStatus,
type CatalogQuery,
type CatalogSnapshot,
type Job,
type MetadataCandidate,
type SearchQuery,
type TitleDetail,
} from '@easy-stream/contracts';
import { Value } from '@sinclair/typebox/value';
import type {
AdminRecord,
AppRepository,
MediaItemForPlayback,
StoredAdminSession,
StoredPlaybackSession,
} from '../domain.js';
interface InMemoryRepositoryOptions {
titles?: TitleDetail[];
cache?: Partial<CacheStatus>;
}
export class InMemoryRepository implements AppRepository {
private readonly titles = new Map<string, TitleDetail>();
private readonly playbackSessions = new Map<string, StoredPlaybackSession>();
private readonly admins = new Map<string, AdminRecord>();
private readonly adminSessions = new Map<string, StoredAdminSession>();
private readonly jobs = new Map<string, { job: Job; payload: Record<string, unknown> }>();
private readonly cache: CacheStatus;
constructor(options: InMemoryRepositoryOptions = {}) {
for (const title of options.titles ?? []) this.titles.set(title.id, structuredClone(title));
this.cache = {
usedBytes: options.cache?.usedBytes ?? 0,
maxBytes: options.cache?.maxBytes ?? 2_147_483_648_000,
highWatermark: options.cache?.highWatermark ?? 0.85,
lowWatermark: options.cache?.lowWatermark ?? 0.75,
activePackages: options.cache?.activePackages ?? 0,
};
}
replaceCatalog(titles: TitleDetail[]): void {
this.titles.clear();
for (const title of titles) this.titles.set(title.id, structuredClone(title));
}
async listCatalog(query: CatalogQuery) {
const limit = query.limit ?? 24;
const published = [...this.titles.values()]
.filter((title) => title.mediaItems.some((item) => item.published))
.filter((title) => !query.kind || title.kind === query.kind)
.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;
const page = published.slice(start, start + limit);
const next = published[start + limit];
return {
items: page.map(toCard),
...(next && page.at(-1) ? { nextCursor: encodeCursor(page.at(-1)!.id) } : {}),
};
}
async searchTitles(query: SearchQuery) {
const needle = normalizeSearch(query.q);
const limit = query.limit ?? 20;
return [...this.titles.values()]
.filter((title) => title.mediaItems.some((item) => item.published))
.filter((title) =>
[title.name.fa, title.name.en]
.filter((value): value is string => Boolean(value))
.some((value) => normalizeSearch(value).includes(needle)),
)
.slice(0, limit)
.map(toCard);
}
async getTitleBySlug(slug: string): Promise<TitleDetail | undefined> {
const title = [...this.titles.values()].find(
(candidate) => candidate.slug === slug && candidate.mediaItems.some((item) => item.published),
);
return title ? publicTitle(title) : undefined;
}
async getMediaItem(id: string): Promise<MediaItemForPlayback | undefined> {
for (const title of this.titles.values()) {
const item = title.mediaItems.find((candidate) => candidate.id === id);
if (item) {
return {
id: item.id,
titleId: title.id,
durationSeconds: item.durationSeconds,
compatibility: item.compatibility,
published: item.published,
};
}
}
return undefined;
}
async setMediaPublished(mediaItemId: string, published: boolean): Promise<boolean> {
for (const [titleId, title] of this.titles) {
const index = title.mediaItems.findIndex((item) => item.id === mediaItemId);
if (index < 0) continue;
const existing = title.mediaItems[index];
if (!existing) return false;
const mediaItems = [...title.mediaItems];
mediaItems[index] = { ...existing, published };
this.titles.set(titleId, {
...title,
playable: mediaItems.some((item) => item.published),
mediaItems,
updatedAt: new Date().toISOString(),
});
return true;
}
return false;
}
async applyTitleMetadata(titleId: string, metadata: MetadataCandidate): Promise<boolean> {
const title = this.titles.get(titleId);
if (!title || title.kind !== metadata.kind) return false;
const {
posterUrl: _posterUrl,
backdropUrl: _backdropUrl,
year: _year,
name: _name,
synopsis: _synopsis,
...unchanged
} = title;
this.titles.set(titleId, {
...unchanged,
name: structuredClone(metadata.name),
synopsis: structuredClone(metadata.synopsis),
...(metadata.posterUrl ? { posterUrl: metadata.posterUrl } : {}),
...(metadata.backdropUrl ? { backdropUrl: metadata.backdropUrl } : {}),
...(metadata.year !== undefined ? { year: metadata.year } : {}),
updatedAt: new Date().toISOString(),
});
return true;
}
async createPlaybackSession(session: StoredPlaybackSession): Promise<void> {
this.playbackSessions.set(session.id, structuredClone(session));
}
async getPlaybackSession(id: string): Promise<StoredPlaybackSession | undefined> {
const session = this.playbackSessions.get(id);
return session ? structuredClone(session) : undefined;
}
async updatePlaybackSession(session: StoredPlaybackSession): Promise<void> {
this.playbackSessions.set(session.id, structuredClone(session));
}
async findAdminByEmail(email: string): Promise<AdminRecord | undefined> {
const normalized = email.trim().toLowerCase();
const record = [...this.admins.values()].find((admin) => admin.email === normalized);
return record ? structuredClone(record) : undefined;
}
async findAdminById(id: string): Promise<AdminRecord | undefined> {
const record = this.admins.get(id);
return record ? structuredClone(record) : undefined;
}
async createAdmin(admin: AdminRecord): Promise<void> {
const normalized = admin.email.trim().toLowerCase();
if ([...this.admins.values()].some((entry) => entry.email === normalized)) return;
this.admins.set(admin.id, { ...structuredClone(admin), email: normalized });
}
async createAdminSession(session: StoredAdminSession): Promise<void> {
this.adminSessions.set(session.id, structuredClone(session));
}
async findAdminSessionByTokenHash(tokenHash: string): Promise<StoredAdminSession | undefined> {
const session = [...this.adminSessions.values()].find((entry) => entry.tokenHash === tokenHash);
return session ? structuredClone(session) : undefined;
}
async revokeAdminSession(id: string): Promise<void> {
const session = this.adminSessions.get(id);
if (session) this.adminSessions.set(id, { ...session, revokedAt: new Date().toISOString() });
}
async createJob(job: Job, payload: Record<string, unknown>): Promise<void> {
this.jobs.set(job.id, { job: structuredClone(job), payload: structuredClone(payload) });
}
async listJobs(): Promise<Job[]> {
return [...this.jobs.values()]
.map(({ job }) => structuredClone(job))
.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
}
async findJob(id: string): Promise<Job | undefined> {
const entry = this.jobs.get(id);
return entry ? structuredClone(entry.job) : undefined;
}
async retryJob(id: string): Promise<Job | undefined> {
const entry = this.jobs.get(id);
if (!entry || (entry.job.state !== 'FAILED' && entry.job.state !== 'CANCELLED')) return undefined;
const now = new Date().toISOString();
const job: Job = { ...entry.job, state: 'QUEUED', progress: 0, error: null, updatedAt: now };
this.jobs.set(id, { ...entry, job });
return structuredClone(job);
}
async getCacheStatus(): Promise<CacheStatus> {
return structuredClone(this.cache);
}
}
export async function loadCatalogSnapshot(path: string): Promise<CatalogSnapshot | undefined> {
let source: string;
try {
source = await readFile(path, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
throw error;
}
const parsed: unknown = JSON.parse(source);
if (!Value.Check(CatalogSnapshotSchema, parsed)) {
const errors = [...Value.Errors(CatalogSnapshotSchema, parsed)]
.map((error) => `${error.path || '/'} ${error.message}`)
.join('; ');
throw new Error(`Invalid catalog snapshot at ${path}: ${errors}`);
}
return parsed;
}
function toCard(title: TitleDetail) {
const { synopsis: _synopsis, seasons: _seasons, mediaItems: _mediaItems, updatedAt: _updatedAt, ...card } =
title;
return card;
}
function normalizeSearch(value: string): string {
return value.normalize('NFKC').trim().toLocaleLowerCase('fa-IR');
}
function publicTitle(title: TitleDetail): TitleDetail {
const mediaItems = title.mediaItems.filter((item) => item.published);
const { seasons: _seasons, resumeMediaItemId: _resumeMediaItemId, ...base } = title;
const seasonNumbers = [...new Set(mediaItems.map((item) => item.seasonNumber))].filter(
(value): value is number => value !== undefined,
);
return structuredClone({
...base,
playable: mediaItems.length > 0,
...(mediaItems[0] ? { resumeMediaItemId: mediaItems[0].id } : {}),
...(seasonNumbers.length
? {
seasons: seasonNumbers.map((number) => ({
number,
episodeCount: mediaItems.filter((item) => item.seasonNumber === number).length,
})),
}
: {}),
mediaItems,
});
}
function encodeCursor(id: string): string {
return Buffer.from(JSON.stringify({ id })).toString('base64url');
}
function decodeCursor(cursor: string | undefined): string | undefined {
if (!cursor) return undefined;
try {
const value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as { id?: unknown };
return typeof value.id === 'string' ? value.id : undefined;
} catch {
return undefined;
}
}
+450
View File
@@ -0,0 +1,450 @@
import type {
CacheStatus,
CatalogCard,
CatalogQuery,
Job,
MetadataCandidate,
SearchQuery,
TitleDetail,
} from '@easy-stream/contracts';
import {
adminSessions,
admins,
jobs,
mediaItems,
mediaPackages,
playbackSessions,
titles,
type Database,
} from '@easy-stream/database';
import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';
import type {
AdminRecord,
AppRepository,
MediaItemForPlayback,
StoredAdminSession,
StoredPlaybackSession,
} from '../domain.js';
interface PostgresRepositoryOptions {
cacheMaxBytes: number;
cacheHighWatermark: number;
cacheLowWatermark: number;
}
export class PostgresRepository implements AppRepository {
constructor(
private readonly db: Database,
private readonly options: PostgresRepositoryOptions,
) {}
async listCatalog(query: CatalogQuery) {
const limit = query.limit ?? 24;
const offset = decodeOffset(query.cursor);
const rows = await this.db
.select()
.from(titles)
.where(and(eq(titles.published, true), query.kind ? eq(titles.kind, query.kind) : undefined))
.orderBy(asc(titles.slug), asc(titles.id))
.limit(limit + 1)
.offset(offset);
const visible = rows.slice(0, limit);
const cards = await this.cardsForRows(visible);
return {
items: cards,
...(rows.length > limit ? { nextCursor: encodeOffset(offset + limit) } : {}),
};
}
async searchTitles(query: SearchQuery): Promise<CatalogCard[]> {
const needle = `%${query.q.trim().replaceAll('%', '\\%').replaceAll('_', '\\_')}%`;
const rows = await this.db
.select()
.from(titles)
.where(
and(
eq(titles.published, true),
or(ilike(titles.nameFa, needle), ilike(titles.nameEn, needle)),
),
)
.orderBy(asc(titles.slug))
.limit(query.limit ?? 20);
return this.cardsForRows(rows);
}
async getTitleBySlug(slug: string): Promise<TitleDetail | undefined> {
const [title] = await this.db
.select()
.from(titles)
.where(and(eq(titles.slug, slug), eq(titles.published, true)))
.limit(1);
if (!title) return undefined;
const media = await this.db
.select()
.from(mediaItems)
.where(and(eq(mediaItems.titleId, title.id), eq(mediaItems.published, true)))
.orderBy(asc(mediaItems.seasonNumber), asc(mediaItems.episodeNumber), asc(mediaItems.id));
return toTitleDetail(title, media);
}
async getMediaItem(id: string): Promise<MediaItemForPlayback | undefined> {
const [row] = await this.db
.select({ media: mediaItems, titlePublished: titles.published })
.from(mediaItems)
.innerJoin(titles, eq(mediaItems.titleId, titles.id))
.where(eq(mediaItems.id, id))
.limit(1);
if (!row) return undefined;
return {
id: row.media.id,
titleId: row.media.titleId,
durationSeconds: row.media.durationSeconds ?? 0,
compatibility: row.media.compatibility,
published: row.media.published && row.titlePublished,
};
}
async setMediaPublished(mediaItemId: string, published: boolean): Promise<boolean> {
return this.db.transaction(async (transaction) => {
const [media] = await transaction
.update(mediaItems)
.set({
published,
publishedAt: published ? new Date() : null,
updatedAt: new Date(),
})
.where(eq(mediaItems.id, mediaItemId))
.returning({ titleId: mediaItems.titleId });
if (!media) return false;
const [countRow] = await transaction
.select({ count: sql<number>`count(*)::int` })
.from(mediaItems)
.where(and(eq(mediaItems.titleId, media.titleId), eq(mediaItems.published, true)));
const titlePublished = (countRow?.count ?? 0) > 0;
await transaction
.update(titles)
.set({
published: titlePublished,
publishedAt: titlePublished ? new Date() : null,
updatedAt: new Date(),
})
.where(eq(titles.id, media.titleId));
return true;
});
}
async applyTitleMetadata(titleId: string, metadata: MetadataCandidate): Promise<boolean> {
const [title] = await this.db
.update(titles)
.set({
tmdbId: metadata.externalId,
nameFa: metadata.name.fa,
nameEn: metadata.name.en ?? null,
synopsisFa: metadata.synopsis.fa ?? null,
synopsisEn: metadata.synopsis.en ?? null,
posterUrl: metadata.posterUrl ?? null,
backdropUrl: metadata.backdropUrl ?? null,
releaseYear: metadata.year ?? null,
updatedAt: new Date(),
})
.where(and(eq(titles.id, titleId), eq(titles.kind, metadata.kind)))
.returning({ id: titles.id });
return Boolean(title);
}
async createPlaybackSession(session: StoredPlaybackSession): Promise<void> {
await this.db.insert(playbackSessions).values({
id: session.id,
mediaItemId: session.mediaItemId,
...(session.generationId ? { generationId: session.generationId } : {}),
state: session.state,
capabilities: session.capabilities,
...(session.reasonCode ? { reasonCode: session.reasonCode } : {}),
...(session.pollAfterMs ? { pollAfterMs: session.pollAfterMs } : {}),
responseJson: publicSessionDetails(session),
expiresAt: new Date(session.expiresAt),
});
}
async getPlaybackSession(id: string): Promise<StoredPlaybackSession | undefined> {
const [row] = await this.db
.select()
.from(playbackSessions)
.where(eq(playbackSessions.id, id))
.limit(1);
if (!row) return undefined;
const details = row.responseJson as Partial<StoredPlaybackSession>;
return {
id: row.id,
mediaItemId: row.mediaItemId,
state: row.state,
capabilities: row.capabilities as StoredPlaybackSession['capabilities'],
expiresAt: row.expiresAt.toISOString(),
...(row.generationId ? { generationId: row.generationId } : {}),
...(row.reasonCode ? { reasonCode: row.reasonCode } : {}),
...(row.pollAfterMs ? { pollAfterMs: row.pollAfterMs } : {}),
...(details.manifestUrl ? { manifestUrl: details.manifestUrl } : {}),
...(details.durationSeconds !== undefined ? { durationSeconds: details.durationSeconds } : {}),
...(details.audioTracks ? { audioTracks: details.audioTracks } : {}),
...(details.subtitleTracks ? { subtitleTracks: details.subtitleTracks } : {}),
};
}
async updatePlaybackSession(session: StoredPlaybackSession): Promise<void> {
await this.db
.update(playbackSessions)
.set({
state: session.state,
generationId: session.generationId ?? null,
reasonCode: session.reasonCode ?? null,
pollAfterMs: session.pollAfterMs ?? null,
responseJson: publicSessionDetails(session),
updatedAt: new Date(),
})
.where(eq(playbackSessions.id, session.id));
}
async findAdminByEmail(email: string): Promise<AdminRecord | undefined> {
const [admin] = await this.db
.select()
.from(admins)
.where(eq(admins.email, email.trim().toLowerCase()))
.limit(1);
return admin ? toAdmin(admin) : undefined;
}
async findAdminById(id: string): Promise<AdminRecord | undefined> {
const [admin] = await this.db.select().from(admins).where(eq(admins.id, id)).limit(1);
return admin ? toAdmin(admin) : undefined;
}
async createAdmin(admin: AdminRecord): Promise<void> {
await this.db
.insert(admins)
.values({
id: admin.id,
email: admin.email.trim().toLowerCase(),
passwordHash: admin.passwordHash,
...(admin.totpSecretEncrypted
? { totpSecretEncrypted: admin.totpSecretEncrypted }
: {}),
disabled: admin.disabled,
})
.onConflictDoNothing({ target: admins.email });
}
async createAdminSession(session: StoredAdminSession): Promise<void> {
await this.db.insert(adminSessions).values({
id: session.id,
adminId: session.adminId,
tokenHash: session.tokenHash,
csrfTokenHash: session.csrfTokenHash,
expiresAt: new Date(session.expiresAt),
});
}
async findAdminSessionByTokenHash(tokenHash: string): Promise<StoredAdminSession | undefined> {
const [session] = await this.db
.select()
.from(adminSessions)
.where(eq(adminSessions.tokenHash, tokenHash))
.limit(1);
return session
? {
id: session.id,
adminId: session.adminId,
tokenHash: session.tokenHash,
csrfTokenHash: session.csrfTokenHash,
expiresAt: session.expiresAt.toISOString(),
...(session.revokedAt ? { revokedAt: session.revokedAt.toISOString() } : {}),
}
: undefined;
}
async revokeAdminSession(id: string): Promise<void> {
await this.db
.update(adminSessions)
.set({ revokedAt: new Date() })
.where(eq(adminSessions.id, id));
}
async createJob(job: Job, payload: Record<string, unknown>): Promise<void> {
await this.db.insert(jobs).values({
id: job.id,
type: job.type,
state: job.state,
progress: job.progress,
payload,
...(job.error ? { error: job.error } : {}),
});
}
async listJobs(): Promise<Job[]> {
const rows = await this.db.select().from(jobs).orderBy(desc(jobs.createdAt)).limit(200);
return rows.map(toJob);
}
async findJob(id: string): Promise<Job | undefined> {
const [job] = await this.db.select().from(jobs).where(eq(jobs.id, id)).limit(1);
return job ? toJob(job) : undefined;
}
async retryJob(id: string): Promise<Job | undefined> {
const [job] = await this.db
.update(jobs)
.set({ state: 'QUEUED', progress: 0, error: null, updatedAt: new Date() })
.where(and(eq(jobs.id, id), inArray(jobs.state, ['FAILED', 'CANCELLED'])))
.returning();
return job ? toJob(job) : undefined;
}
async getCacheStatus(): Promise<CacheStatus> {
const [summary] = await this.db
.select({
usedBytes: sql<number>`coalesce(sum(case when ${mediaPackages.cacheResident} then ${mediaPackages.sizeBytes} else 0 end), 0)::bigint`,
activePackages: sql<number>`count(*) filter (where ${mediaPackages.state} = 'BUILDING')::int`,
})
.from(mediaPackages);
return {
usedBytes: Number(summary?.usedBytes ?? 0),
maxBytes: this.options.cacheMaxBytes,
highWatermark: this.options.cacheHighWatermark,
lowWatermark: this.options.cacheLowWatermark,
activePackages: summary?.activePackages ?? 0,
};
}
private async cardsForRows(rows: (typeof titles.$inferSelect)[]): Promise<CatalogCard[]> {
if (rows.length === 0) return [];
const media = await this.db
.select()
.from(mediaItems)
.where(and(inArray(mediaItems.titleId, rows.map((row) => row.id)), eq(mediaItems.published, true)))
.orderBy(asc(mediaItems.seasonNumber), asc(mediaItems.episodeNumber), asc(mediaItems.id));
return rows.map((title) =>
toCatalogCard(
title,
media.filter((item) => item.titleId === title.id),
),
);
}
}
function toCatalogCard(
title: typeof titles.$inferSelect,
media: (typeof mediaItems.$inferSelect)[],
): CatalogCard {
const first = media[0];
return {
id: title.id,
slug: title.slug,
kind: title.kind,
name: localizedRequired(title.nameFa, title.nameEn),
playable: media.length > 0,
...(title.posterUrl ? { posterUrl: title.posterUrl } : {}),
...(title.backdropUrl ? { backdropUrl: title.backdropUrl } : {}),
...(title.releaseYear !== null ? { year: title.releaseYear } : {}),
...(first ? { resumeMediaItemId: first.id } : {}),
};
}
function toTitleDetail(
title: typeof titles.$inferSelect,
media: (typeof mediaItems.$inferSelect)[],
): TitleDetail {
const card = toCatalogCard(
title,
media.filter((item) => item.published),
);
const seasonNumbers = [...new Set(media.map((item) => item.seasonNumber).filter(isNumber))];
return {
...card,
synopsis: {
...(title.synopsisFa ? { fa: title.synopsisFa } : {}),
...(title.synopsisEn ? { en: title.synopsisEn } : {}),
},
...(seasonNumbers.length > 0
? {
seasons: seasonNumbers.map((number) => ({
number,
episodeCount: media.filter((item) => item.seasonNumber === number).length,
})),
}
: {}),
mediaItems: media.map((item) => ({
id: item.id,
kind: item.kind,
...(item.seasonNumber !== null ? { seasonNumber: item.seasonNumber } : {}),
...(item.episodeNumber !== null ? { episodeNumber: item.episodeNumber } : {}),
...(item.nameFa || item.nameEn
? {
name: {
...(item.nameFa ? { fa: item.nameFa } : {}),
...(item.nameEn ? { en: item.nameEn } : {}),
},
}
: {}),
durationSeconds: item.durationSeconds ?? 0,
compatibility: item.compatibility,
published: item.published,
})),
updatedAt: title.updatedAt.toISOString(),
};
}
function localizedRequired(fa: string | null, en: string | null) {
return { fa: fa ?? en ?? 'بدون عنوان', ...(en ? { en } : {}) };
}
function toAdmin(admin: typeof admins.$inferSelect): AdminRecord {
return {
id: admin.id,
email: admin.email,
passwordHash: admin.passwordHash,
disabled: admin.disabled,
...(admin.totpSecretEncrypted ? { totpSecretEncrypted: admin.totpSecretEncrypted } : {}),
};
}
function toJob(job: typeof jobs.$inferSelect): Job {
return {
id: job.id,
type: job.type,
state: job.state,
progress: job.progress,
error: job.error,
createdAt: job.createdAt.toISOString(),
updatedAt: job.updatedAt.toISOString(),
};
}
function publicSessionDetails(session: StoredPlaybackSession): Record<string, unknown> {
return {
...(session.manifestUrl ? { manifestUrl: session.manifestUrl } : {}),
...(session.durationSeconds !== undefined ? { durationSeconds: session.durationSeconds } : {}),
...(session.audioTracks ? { audioTracks: session.audioTracks } : {}),
...(session.subtitleTracks ? { subtitleTracks: session.subtitleTracks } : {}),
};
}
function isNumber(value: number | null): value is number {
return value !== null;
}
function encodeOffset(offset: number): string {
return Buffer.from(JSON.stringify({ offset })).toString('base64url');
}
function decodeOffset(cursor: string | undefined): number {
if (!cursor) return 0;
try {
const value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as {
offset?: unknown;
};
return typeof value.offset === 'number' && Number.isSafeInteger(value.offset) && value.offset >= 0
? value.offset
: 0;
} catch {
return 0;
}
}
+31
View File
@@ -0,0 +1,31 @@
import { buildApp } from './app.js';
import { loadConfig } from './config.js';
for (const candidate of [process.env.ENV_FILE, '.env', '../../.env']) {
if (!candidate) continue;
try {
process.loadEnvFile?.(candidate);
break;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
}
const config = loadConfig();
const app = await buildApp({ config });
const shutdown = async (signal: string) => {
app.log.info({ signal }, 'shutting down');
await app.close();
process.exitCode = 0;
};
process.once('SIGINT', () => void shutdown('SIGINT'));
process.once('SIGTERM', () => void shutdown('SIGTERM'));
try {
await app.listen({ host: config.host, port: config.port });
} catch (error) {
app.log.fatal({ err: error }, 'API startup failed');
process.exitCode = 1;
}
+228
View File
@@ -0,0 +1,228 @@
import { randomUUID } from 'node:crypto';
import { argon2id, hash, verify } from 'argon2';
import type {
AdminLogin,
AdminSessionResponse,
Job,
MetadataMatchBody,
MetadataSearchQuery,
} from '@easy-stream/contracts';
import type { ApiConfig } from '../config.js';
import { randomToken, sha256 } from '../crypto.js';
import type {
AdminRecord,
AppRepository,
MediaCommandPublisher,
MediaPreparationService,
MetadataProvider,
PasswordHasher,
TotpVerifier,
} from '../domain.js';
import { AppError } from '../errors.js';
export class Argon2PasswordHasher implements PasswordHasher {
async hash(password: string): Promise<string> {
return hash(password, {
type: argon2id,
memoryCost: 65_536,
timeCost: 3,
parallelism: 1,
});
}
async verify(passwordHash: string, password: string): Promise<boolean> {
try {
return await verify(passwordHash, password);
} catch {
return false;
}
}
}
export class DenyEncryptedTotpVerifier implements TotpVerifier {
async verify(): Promise<boolean> {
return false;
}
}
interface AdminPrincipal {
admin: AdminRecord;
sessionId: string;
}
export class AdminService {
private dummyPasswordHash?: string;
constructor(
private readonly repository: AppRepository,
private readonly commands: MediaCommandPublisher,
private readonly media: MediaPreparationService,
private readonly metadata: MetadataProvider,
private readonly passwordHasher: PasswordHasher,
private readonly totpVerifier: TotpVerifier,
private readonly config: ApiConfig,
) {}
async initialize(): Promise<void> {
this.dummyPasswordHash = await this.passwordHasher.hash(randomToken());
if (!this.config.adminBootstrapEmail || !this.config.adminBootstrapPassword) return;
const existing = await this.repository.findAdminByEmail(this.config.adminBootstrapEmail);
if (existing) return;
await this.repository.createAdmin({
id: randomUUID(),
email: this.config.adminBootstrapEmail,
passwordHash: await this.passwordHasher.hash(this.config.adminBootstrapPassword),
disabled: false,
});
}
async login(input: AdminLogin): Promise<{
response: AdminSessionResponse;
rawToken: string;
}> {
const admin = await this.repository.findAdminByEmail(input.email);
const validPassword = await this.passwordHasher.verify(
admin?.passwordHash ?? this.dummyPasswordHash ?? '$argon2id$invalid',
input.password,
);
if (!admin || !validPassword || admin.disabled) throw invalidCredentials();
if (
admin.totpSecretEncrypted &&
(!input.totp || !(await this.totpVerifier.verify(admin.totpSecretEncrypted, input.totp)))
) {
throw invalidCredentials();
}
const rawToken = randomToken();
const csrfToken = randomToken();
const expiresAt = new Date(
Date.now() + this.config.adminSessionTtlSeconds * 1000,
).toISOString();
await this.repository.createAdminSession({
id: randomUUID(),
adminId: admin.id,
tokenHash: sha256(rawToken),
csrfTokenHash: sha256(csrfToken),
expiresAt,
});
return {
rawToken,
response: {
admin: { id: admin.id, email: admin.email },
csrfToken,
expiresAt,
},
};
}
async authenticate(rawToken: string | undefined, csrfToken?: string): Promise<AdminPrincipal> {
if (!rawToken) throw new AppError(401, 'UNAUTHORIZED', 'Administrator authentication required');
const session = await this.repository.findAdminSessionByTokenHash(sha256(rawToken));
if (
!session ||
session.revokedAt ||
Date.parse(session.expiresAt) <= Date.now() ||
(csrfToken !== undefined && sha256(csrfToken) !== session.csrfTokenHash)
) {
throw new AppError(401, 'UNAUTHORIZED', 'Administrator session is invalid or expired');
}
const admin = await this.repository.findAdminById(session.adminId);
if (!admin || admin.disabled) {
throw new AppError(401, 'UNAUTHORIZED', 'Administrator session is invalid or expired');
}
return { admin, sessionId: session.id };
}
async logout(rawToken: string | undefined, csrfToken: string | undefined): Promise<void> {
const principal = await this.authenticate(rawToken, csrfToken);
await this.repository.revokeAdminSession(principal.sessionId);
}
async startScan(full: boolean): Promise<Job> {
const now = new Date().toISOString();
const job: Job = {
id: randomUUID(),
type: 'ARCHIVE_SCAN',
state: 'QUEUED',
progress: 0,
error: null,
createdAt: now,
updatedAt: now,
};
await this.repository.createJob(job, { full });
await this.commands.publish({ type: 'archive.scan.requested', jobId: job.id, full });
return job;
}
async setPublished(mediaItemId: string, published: boolean): Promise<void> {
const item = await this.repository.getMediaItem(mediaItemId);
if (!item) throw new AppError(404, 'NOT_FOUND', 'Media item not found');
if (published && (item.compatibility === 'INVALID' || item.compatibility === 'HOLD_HDR')) {
throw new AppError(409, 'CONFLICT', 'This media item is not eligible for publication');
}
if (
published &&
(item.compatibility === 'AUDIO_TRANSCODE' || item.compatibility === 'VIDEO_TRANSCODE')
) {
const preparation = await this.media.getStatus({
sessionId: randomUUID(),
mediaItem: item,
});
if (preparation.state !== 'READY' && !preparation.playable) {
throw new AppError(
409,
'CONFLICT',
'The browser-compatible representation must be ready before publication',
);
}
}
if (!(await this.repository.setMediaPublished(mediaItemId, published))) {
throw new AppError(404, 'NOT_FOUND', 'Media item not found');
}
await this.commands.publish({
type: 'media.publication.changed',
mediaItemId,
published,
});
}
async retryJob(jobId: string): Promise<Job> {
const existing = await this.repository.findJob(jobId);
if (existing !== undefined && existing.type !== 'ARCHIVE_SCAN') {
throw new AppError(409, 'CONFLICT', `Retry is not implemented for job type ${existing.type}`);
}
const job = await this.repository.retryJob(jobId);
if (!job) throw new AppError(409, 'CONFLICT', 'Only failed or cancelled jobs can be retried');
// A full scan is the conservative retry when the public Job contract does not expose
// the original private payload.
await this.commands.publish({ type: 'archive.scan.requested', jobId: job.id, full: true });
return job;
}
async evict(generationId: string): Promise<void> {
await this.commands.publish({ type: 'package.eviction.requested', generationId });
}
async searchMetadata(query: MetadataSearchQuery) {
return this.metadata.search({
query: query.q,
kind: query.kind,
...(query.year !== undefined ? { year: query.year } : {}),
});
}
async matchMetadata(titleId: string, body: MetadataMatchBody) {
const candidate = await this.metadata.getDetails({
externalId: body.externalId,
kind: body.kind,
});
if (!(await this.repository.applyTitleMetadata(titleId, candidate))) {
throw new AppError(404, 'NOT_FOUND', 'Title not found or title kind does not match');
}
return candidate;
}
}
function invalidCredentials(): AppError {
return new AppError(401, 'UNAUTHORIZED', 'Invalid email, password, or verification code');
}
+226
View File
@@ -0,0 +1,226 @@
import { constants } from 'node:fs';
import { lstat, open, opendir } from 'node:fs/promises';
import path from 'node:path';
import type { CacheStatus } from '@easy-stream/contracts';
import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
const CACHE_METADATA = '.cache-entry.json';
const MAX_METADATA_BYTES = 64 * 1024;
const CacheEntryMetadataSchema = Type.Object(
{
version: Type.Literal(1),
key: Type.String({ minLength: 8, maxLength: 128, pattern: '^[a-z0-9][a-z0-9._-]+$' }),
bytes: Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),
lastAccessedAt: Type.String({ minLength: 1, maxLength: 64 }),
protectedUntil: Type.Optional(Type.String({ minLength: 1, maxLength: 64 })),
active: Type.Boolean(),
building: Type.Boolean(),
pinned: Type.Boolean(),
},
{ additionalProperties: false },
);
interface CacheEntryMetadata {
version: 1;
key: string;
bytes: number;
lastAccessedAt: string;
protectedUntil?: string;
active: boolean;
building: boolean;
pinned: boolean;
}
export interface CacheStatusService {
getStatus(): Promise<CacheStatus>;
}
export interface FilesystemCacheStatusOptions {
cacheRoot: string;
maxBytes: number;
highWatermark: number;
lowWatermark: number;
}
/** Reads the worker-owned cache projection without mutating or walking media payloads. */
export class FilesystemCacheStatusService implements CacheStatusService {
private readonly root: string;
constructor(private readonly options: FilesystemCacheStatusOptions) {
this.root = path.resolve(options.cacheRoot);
}
async getStatus(): Promise<CacheStatus> {
if (!(await managedDirectoryExists(this.root, 'cache root'))) return this.result(0, 0);
const generations = await readGenerations(path.join(this.root, 'generations'));
const fontStore = path.join(this.root, 'assets', 'fonts', 'sha256');
const fontBytes = await managedSubdirectoryExists(
this.root,
['assets', 'fonts', 'sha256'],
'global font store',
) ? await readFontStoreBytes(fontStore) : 0;
return this.result(
safeAdd(generations.bytes, fontBytes, 'cache usage'),
generations.building,
);
}
private result(usedBytes: number, activePackages: number): CacheStatus {
return {
usedBytes,
maxBytes: this.options.maxBytes,
highWatermark: this.options.highWatermark,
lowWatermark: this.options.lowWatermark,
activePackages,
};
}
}
async function readGenerations(
directory: string,
): Promise<{ bytes: number; building: number }> {
if (!(await managedDirectoryExists(directory, 'cache generations root'))) {
return { bytes: 0, building: 0 };
}
let bytes = 0;
let building = 0;
const handle = await opendir(directory);
for await (const entry of handle) {
const candidate = path.join(directory, entry.name);
if (entry.isSymbolicLink()) throw new Error(`Symlink found in cache generations: ${candidate}`);
if (!entry.isDirectory()) continue;
let metadata: CacheEntryMetadata | undefined;
try {
metadata = await readCacheMetadata(path.join(candidate, CACHE_METADATA), entry.name);
} catch (error) {
if (isMissing(error)) continue;
throw error;
}
if (metadata === undefined) continue;
bytes = safeAdd(bytes, metadata.bytes, 'generation cache usage');
if (metadata.building) building += 1;
}
return { bytes, building };
}
async function readCacheMetadata(
metadataPath: string,
expectedKey: string,
): Promise<CacheEntryMetadata | undefined> {
let handle: Awaited<ReturnType<typeof open>>;
try {
handle = await open(metadataPath, constants.O_RDONLY | constants.O_NOFOLLOW);
} catch (error) {
if (isMissing(error)) return undefined;
if ((error as NodeJS.ErrnoException).code === 'ELOOP') {
throw new Error(`Symlink found at cache metadata: ${metadataPath}`);
}
throw error;
}
try {
const details = await handle.stat();
if (!details.isFile() || details.size > MAX_METADATA_BYTES) {
throw new Error(`Cache metadata is not a bounded regular file: ${metadataPath}`);
}
let parsed: unknown;
try {
parsed = JSON.parse(await handle.readFile('utf8'));
} catch (error) {
throw new Error(`Invalid cache metadata JSON: ${metadataPath}`, { cause: error });
}
if (!Value.Check(CacheEntryMetadataSchema, parsed)) {
throw new Error(`Invalid cache metadata shape: ${metadataPath}`);
}
const metadata = parsed as CacheEntryMetadata;
const archivedGeneration = expectedKey.match(
/^failed-[0-9]{10,16}-([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/u,
)?.[1];
if (
(metadata.key !== expectedKey && metadata.key !== archivedGeneration)
|| !Number.isFinite(Date.parse(metadata.lastAccessedAt))
) {
throw new Error(`Cache metadata does not match its generation: ${metadataPath}`);
}
if (
metadata.protectedUntil !== undefined
&& !Number.isFinite(Date.parse(metadata.protectedUntil))
) {
throw new Error(`Cache metadata has an invalid protection timestamp: ${metadataPath}`);
}
// If packaging could not rewrite metadata after archiving a failed build, its original
// UUID key/building flag can remain. The exact archive name relationship makes this safe
// to count as diagnostic disk usage without reporting a live build forever.
return archivedGeneration === undefined ? metadata : { ...metadata, building: false };
} finally {
await handle.close();
}
}
async function readFontStoreBytes(directory: string): Promise<number> {
let bytes = 0;
const handle = await opendir(directory);
for await (const entry of handle) {
const candidate = path.join(directory, entry.name);
if (entry.isSymbolicLink()) throw new Error(`Symlink found in global font store: ${candidate}`);
if (!entry.isFile()) {
throw new Error(`Non-regular entry found in global font store: ${candidate}`);
}
let file: Awaited<ReturnType<typeof open>>;
try {
file = await open(candidate, constants.O_RDONLY | constants.O_NOFOLLOW);
} catch (error) {
// Font pruning can remove an entry after opendir returned it.
if (isMissing(error)) continue;
if ((error as NodeJS.ErrnoException).code === 'ELOOP') {
throw new Error(`Symlink found in global font store: ${candidate}`);
}
throw error;
}
try {
const details = await file.stat();
if (!details.isFile()) throw new Error(`Non-regular entry found in global font store: ${candidate}`);
bytes = safeAdd(bytes, details.size, 'global font cache usage');
} finally {
await file.close();
}
}
return bytes;
}
async function managedSubdirectoryExists(
root: string,
components: readonly string[],
label: string,
): Promise<boolean> {
let current = root;
for (const component of components) {
current = path.join(current, component);
if (!(await managedDirectoryExists(current, label))) return false;
}
return true;
}
async function managedDirectoryExists(directory: string, label: string): Promise<boolean> {
let details: Awaited<ReturnType<typeof lstat>>;
try {
details = await lstat(directory);
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
if (details.isSymbolicLink() || !details.isDirectory()) {
throw new Error(`Managed ${label} is not a regular directory: ${directory}`);
}
return true;
}
function safeAdd(left: number, right: number, label: string): number {
const result = left + right;
if (!Number.isSafeInteger(result) || result < 0) throw new Error(`${label} exceeds safe limits`);
return result;
}
function isMissing(error: unknown): boolean {
return (error as NodeJS.ErrnoException).code === 'ENOENT';
}
+239
View File
@@ -0,0 +1,239 @@
import { appendFile, mkdir, readFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import {
CACHE_GENERATION_LEASES_KEY,
PackageRegistrySchema,
type MediaCommand,
type PackageRegistry,
} from '@easy-stream/contracts';
import { Value } from '@sinclair/typebox/value';
import { Queue, type ConnectionOptions } from 'bullmq';
import type {
MediaCommandPublisher,
MediaPreparation,
MediaPreparationService,
} from '../domain.js';
export class JsonlMediaCommandPublisher implements MediaCommandPublisher {
constructor(private readonly path: string) {}
async publish(command: MediaCommand): Promise<void> {
await mkdir(dirname(this.path), { recursive: true });
await appendFile(this.path, `${JSON.stringify(command)}\n`, {
encoding: 'utf8',
mode: 0o600,
});
}
}
export class InMemoryMediaCommandPublisher implements MediaCommandPublisher {
readonly commands: MediaCommand[] = [];
async publish(command: MediaCommand): Promise<void> {
this.commands.push(structuredClone(command));
}
}
export class FileMediaPreparationService implements MediaPreparationService {
private readonly requested = new Set<string>();
constructor(
private readonly registryPath: string,
private readonly publisher: MediaCommandPublisher,
) {}
async prepare(input: Parameters<MediaPreparationService['prepare']>[0]) {
const status = await this.find(input.mediaItem.id);
if (status) {
if (status.playable || status.state === 'READY' || status.state === 'FAILED') {
this.requested.delete(input.mediaItem.id);
}
await this.recordCacheAccess(input, status);
return status;
}
if (!this.requested.has(input.mediaItem.id)) {
this.requested.add(input.mediaItem.id);
try {
await this.publisher.publish({
type: 'media.playback.requested',
sessionId: input.sessionId,
mediaItemId: input.mediaItem.id,
});
} catch (error) {
this.requested.delete(input.mediaItem.id);
throw error;
}
}
return {
state: 'PREPARING' as const,
playable: false,
pollAfterMs: 1500,
reasonCode: 'PACKAGE_REQUESTED',
};
}
async getStatus(input: Parameters<MediaPreparationService['getStatus']>[0]) {
const status = await this.find(input.mediaItem.id);
if (status?.playable || status?.state === 'READY' || status?.state === 'FAILED') {
this.requested.delete(input.mediaItem.id);
}
const result = status ?? {
state: 'PREPARING' as const,
playable: false,
pollAfterMs: 1500,
reasonCode: 'PACKAGE_REQUESTED',
};
await this.recordCacheAccess(input, result);
return result;
}
private async recordCacheAccess(
input: { sessionId: string; protectUntil?: string },
status: MediaPreparation,
): Promise<void> {
if (input.protectUntil === undefined || !status.playable || !status.generationId
|| !status.manifestPath?.startsWith('/media/generations/')) return;
await this.publisher.publish({
type: 'cache.generation.accessed',
sessionId: input.sessionId,
generationId: status.generationId,
accessedAt: new Date().toISOString(),
protectedUntil: input.protectUntil,
});
}
private async find(mediaItemId: string): Promise<MediaPreparation | undefined> {
const registry = await readPackageRegistry(this.registryPath);
const entry = registry?.packages.find((candidate) => candidate.mediaItemId === mediaItemId);
if (!entry) return undefined;
return {
state: entry.state,
playable: entry.playable,
...(entry.generationId ? { generationId: entry.generationId } : {}),
...(entry.manifestPath ? { manifestPath: entry.manifestPath } : {}),
...(entry.reasonCode ? { reasonCode: entry.reasonCode } : {}),
...(entry.pollAfterMs ? { pollAfterMs: entry.pollAfterMs } : {}),
...(entry.durationSeconds !== undefined ? { durationSeconds: entry.durationSeconds } : {}),
...(entry.audioTracks ? { audioTracks: entry.audioTracks } : {}),
...(entry.subtitleTracks ? { subtitleTracks: entry.subtitleTracks } : {}),
};
}
}
export async function readPackageRegistry(path: string): Promise<PackageRegistry | undefined> {
let source: string;
try {
source = await readFile(path, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
throw error;
}
const parsed: unknown = JSON.parse(source);
if (!Value.Check(PackageRegistrySchema, parsed)) {
const errors = [...Value.Errors(PackageRegistrySchema, parsed)]
.map((error) => `${error.path || '/'} ${error.message}`)
.join('; ');
throw new Error(`Invalid package registry at ${path}: ${errors}`);
}
return parsed;
}
export class BullMqMediaBridge implements MediaPreparationService, MediaCommandPublisher {
private readonly fileStatus: FileMediaPreparationService;
private readonly queue: Queue<MediaCommand>;
private leaseCommandReady?: Promise<void>;
constructor(
redisUrl: string,
registryPath: string,
private readonly profile: string,
) {
this.queue = new Queue<MediaCommand>('easy-stream-media', {
connection: redisConnection(redisUrl),
defaultJobOptions: {
attempts: 2,
backoff: { type: 'exponential', delay: 1000 },
removeOnComplete: { age: 3600, count: 2000 },
removeOnFail: { age: 86_400, count: 2000 },
},
});
this.fileStatus = new FileMediaPreparationService(registryPath, this);
}
async prepare(input: Parameters<MediaPreparationService['prepare']>[0]) {
return this.fileStatus.prepare(input);
}
async getStatus(input: Parameters<MediaPreparationService['getStatus']>[0]) {
return this.fileStatus.getStatus(input);
}
async publish(command: MediaCommand): Promise<void> {
if (command.type === 'cache.generation.accessed') {
const protectedUntil = Date.parse(command.protectedUntil);
if (!Number.isFinite(protectedUntil)) throw new Error('Invalid cache lease expiration');
const client = await this.queue.client;
this.leaseCommandReady ??= Promise.resolve(client.defineCommand(
'easyStreamExtendCacheLease',
{
numberOfKeys: 1,
lua: "return redis.call('ZADD', KEYS[1], 'GT', ARGV[1], ARGV[2])",
},
));
await this.leaseCommandReady;
await client.runCommand('easyStreamExtendCacheLease', [
CACHE_GENERATION_LEASES_KEY,
protectedUntil,
command.generationId,
]);
}
const jobId = commandJobId(command, this.profile);
if (command.type === 'archive.scan.requested') {
const existing = await this.queue.getJob(jobId);
if (existing !== undefined && await existing.getState() === 'failed') {
await existing.retry('failed');
return;
}
}
await this.queue.add(command.type, command, {
jobId,
...(['media.playback.requested', 'cache.generation.accessed'].includes(command.type)
? { removeOnComplete: true }
: {}),
});
}
async close(): Promise<void> {
await this.queue.close();
}
}
function redisConnection(redisUrl: string): ConnectionOptions {
const url = new URL(redisUrl);
const database = url.pathname.length > 1 ? Number(url.pathname.slice(1)) : 0;
if (!Number.isInteger(database) || database < 0) throw new Error('REDIS_URL has an invalid database');
return {
host: url.hostname,
port: url.port ? Number(url.port) : 6379,
...(url.username ? { username: decodeURIComponent(url.username) } : {}),
...(url.password ? { password: decodeURIComponent(url.password) } : {}),
db: database,
...(url.protocol === 'rediss:' ? { tls: {} } : {}),
maxRetriesPerRequest: null,
};
}
function commandJobId(command: MediaCommand, profile: string): string {
switch (command.type) {
case 'media.playback.requested':
return `playback-${command.mediaItemId}-${profile}`;
case 'archive.scan.requested':
return `scan-${command.jobId}`;
case 'media.publication.changed':
return `publication-${command.mediaItemId}-${command.published ? 'on' : 'off'}-${Date.now()}`;
case 'package.eviction.requested':
return `eviction-${command.generationId}`;
case 'cache.generation.accessed':
return `cache-access-${command.sessionId}-${command.generationId}`;
}
}
+152
View File
@@ -0,0 +1,152 @@
import { randomUUID } from 'node:crypto';
import type {
ClientCapabilities,
CreatePlaybackSession,
PlaybackSession,
} from '@easy-stream/contracts';
import type { ApiConfig } from '../config.js';
import type {
AppRepository,
MediaItemForPlayback,
MediaPreparation,
MediaPreparationService,
StoredPlaybackSession,
} from '../domain.js';
import { AppError } from '../errors.js';
export class PlaybackService {
constructor(
private readonly repository: AppRepository,
private readonly media: MediaPreparationService,
private readonly config: ApiConfig,
) {}
async create(input: CreatePlaybackSession): Promise<StoredPlaybackSession> {
const item = await this.requirePlayableMedia(input.mediaItemId);
const now = Date.now();
const base: StoredPlaybackSession = {
id: randomUUID(),
mediaItemId: item.id,
state: 'PREPARING',
capabilities: input.clientCapabilities,
expiresAt: new Date(now + this.config.playbackTtlSeconds * 1000).toISOString(),
};
if (!supportsHls(input.clientCapabilities)) {
const unsupported: StoredPlaybackSession = {
...base,
state: 'UNSUPPORTED_CLIENT',
reasonCode: 'HLS_MSE_UNAVAILABLE',
};
await this.repository.createPlaybackSession(unsupported);
return unsupported;
}
if (item.compatibility === 'HOLD_HDR') {
const unsupported: StoredPlaybackSession = {
...base,
state: 'UNSUPPORTED_CLIENT',
reasonCode: 'HDR_UNSUPPORTED_V1',
};
await this.repository.createPlaybackSession(unsupported);
return unsupported;
}
if (item.compatibility === 'INVALID') {
const failed: StoredPlaybackSession = {
...base,
state: 'FAILED',
reasonCode: 'MEDIA_NOT_VALIDATED',
};
await this.repository.createPlaybackSession(failed);
return failed;
}
await this.repository.createPlaybackSession(base);
const preparation = await this.media.prepare({
sessionId: base.id,
mediaItem: item,
capabilities: input.clientCapabilities,
protectUntil: base.expiresAt,
});
const session = this.mergePreparation(base, preparation);
await this.repository.updatePlaybackSession(session);
return session;
}
async get(id: string): Promise<StoredPlaybackSession> {
const session = await this.repository.getPlaybackSession(id);
if (!session || Date.parse(session.expiresAt) <= Date.now()) {
throw new AppError(404, 'NOT_FOUND', 'Playback session not found');
}
if (session.state !== 'PREPARING') return session;
const item = await this.requirePlayableMedia(session.mediaItemId);
const preparation = await this.media.getStatus({
sessionId: id,
mediaItem: item,
protectUntil: session.expiresAt,
});
const updated = this.mergePreparation(session, preparation);
await this.repository.updatePlaybackSession(updated);
return updated;
}
toPublic(session: StoredPlaybackSession): PlaybackSession {
const { capabilities: _capabilities, ...publicSession } = session;
return publicSession;
}
private async requirePlayableMedia(id: string): Promise<MediaItemForPlayback> {
const item = await this.repository.getMediaItem(id);
if (!item || !item.published) {
throw new AppError(404, 'NOT_FOUND', 'Media item not found');
}
return item;
}
private mergePreparation(
session: StoredPlaybackSession,
preparation: MediaPreparation,
): StoredPlaybackSession {
if (preparation.state === 'READY' || (preparation.state === 'PREPARING' && preparation.playable)) {
if (!preparation.generationId || !preparation.manifestPath) {
throw new AppError(500, 'INTERNAL_ERROR', 'Ready media preparation is incomplete');
}
const expectedPrefix = new RegExp(
`^/media/(?:derived/)?generations/${preparation.generationId}/`,
);
if (!expectedPrefix.test(preparation.manifestPath)) {
throw new AppError(500, 'INTERNAL_ERROR', 'Media preparation returned an unsafe path');
}
return {
...session,
state: 'READY',
generationId: preparation.generationId,
manifestUrl: publicMediaUrl(this.config.mediaPublicBaseUrl, preparation.manifestPath),
durationSeconds: preparation.durationSeconds ?? 0,
audioTracks: preparation.audioTracks ?? [],
subtitleTracks: preparation.subtitleTracks ?? [],
};
}
return {
...session,
state: preparation.state,
...(preparation.pollAfterMs ? { pollAfterMs: preparation.pollAfterMs } : {}),
...(preparation.reasonCode ? { reasonCode: preparation.reasonCode } : {}),
};
}
}
function supportsHls(capabilities: ClientCapabilities): boolean {
return capabilities.nativeHls || (capabilities.mse && capabilities.hlsJs);
}
function publicMediaUrl(baseUrl: string, manifestPath: string): string {
const base = new URL(baseUrl);
const mediaBasePath = base.pathname.replace(/\/$/, '');
if (!manifestPath.startsWith(`${mediaBasePath}/`) && mediaBasePath !== '/media') {
throw new AppError(500, 'INTERNAL_ERROR', 'Manifest path does not match media base URL');
}
base.pathname = manifestPath;
base.search = '';
base.hash = '';
return base.toString();
}
+216
View File
@@ -0,0 +1,216 @@
import type { MetadataCandidate } from '@easy-stream/contracts';
import type { ApiConfig } from '../config.js';
import type { MetadataProvider } from '../domain.js';
import { AppError } from '../errors.js';
type Fetch = typeof globalThis.fetch;
interface TmdbListResponse {
results?: unknown[];
}
export class DisabledMetadataProvider implements MetadataProvider {
async search(): Promise<MetadataCandidate[]> {
throw disabledError();
}
async getDetails(): Promise<MetadataCandidate> {
throw disabledError();
}
}
export class TmdbMetadataProvider implements MetadataProvider {
constructor(
private readonly token: string,
private readonly options: {
baseUrl: string;
timeoutMs: number;
maxRetries: number;
},
private readonly fetchImpl: Fetch = globalThis.fetch,
) {}
async search(input: {
query: string;
kind: 'MOVIE' | 'SERIES';
year?: number;
}): Promise<MetadataCandidate[]> {
const mediaPath = input.kind === 'MOVIE' ? 'movie' : 'tv';
const query: Record<string, string> = {
query: input.query,
include_adult: 'false',
language: 'fa-IR',
};
if (input.year !== undefined) {
query[input.kind === 'MOVIE' ? 'year' : 'first_air_date_year'] = String(input.year);
}
let result = await this.request<TmdbListResponse>(`/search/${mediaPath}`, query);
if (!Array.isArray(result.results) || result.results.length === 0) {
result = await this.request<TmdbListResponse>(`/search/${mediaPath}`, {
...query,
language: 'en-US',
});
}
return (result.results ?? [])
.map((entry) => toCandidate(entry, input.kind))
.filter((entry): entry is MetadataCandidate => Boolean(entry))
.slice(0, 20);
}
async getDetails(input: {
externalId: number;
kind: 'MOVIE' | 'SERIES';
}): Promise<MetadataCandidate> {
const mediaPath = input.kind === 'MOVIE' ? 'movie' : 'tv';
const fa = await this.request<unknown>(`/${mediaPath}/${input.externalId}`, {
language: 'fa-IR',
});
const en = await this.request<unknown>(`/${mediaPath}/${input.externalId}`, {
language: 'en-US',
});
const faCandidate = toCandidate(fa, input.kind);
const enCandidate = toCandidate(en, input.kind);
if (!faCandidate && !enCandidate) {
throw new AppError(502, 'MEDIA_UNAVAILABLE', 'TMDB returned invalid title metadata');
}
const primary = faCandidate ?? enCandidate!;
const posterUrl = faCandidate?.posterUrl ?? enCandidate?.posterUrl;
const backdropUrl = faCandidate?.backdropUrl ?? enCandidate?.backdropUrl;
return {
...primary,
name: {
fa: faCandidate?.name.fa || enCandidate?.name.fa || 'بدون عنوان',
...(enCandidate?.name.fa ? { en: enCandidate.name.fa } : {}),
},
synopsis: {
...(faCandidate?.synopsis.fa
? { fa: faCandidate.synopsis.fa }
: enCandidate?.synopsis.fa
? { fa: enCandidate.synopsis.fa }
: {}),
...(enCandidate?.synopsis.fa ? { en: enCandidate.synopsis.fa } : {}),
},
...(posterUrl ? { posterUrl } : {}),
...(backdropUrl ? { backdropUrl } : {}),
...((faCandidate?.year ?? enCandidate?.year) !== undefined
? { year: (faCandidate?.year ?? enCandidate?.year)! }
: {}),
};
}
private async request<T>(path: string, query: Record<string, string>): Promise<T> {
const url = new URL(`${this.options.baseUrl.replace(/\/$/, '')}${path}`);
for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
let lastError: unknown;
for (let attempt = 0; attempt <= this.options.maxRetries; attempt += 1) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs);
try {
const response = await this.fetchImpl(url, {
method: 'GET',
headers: {
accept: 'application/json',
authorization: `Bearer ${this.token}`,
},
signal: controller.signal,
});
if (response.ok) return (await response.json()) as T;
if ((response.status === 429 || response.status >= 500) && attempt < this.options.maxRetries) {
await delay(retryDelay(response.headers.get('retry-after'), attempt));
continue;
}
if (response.status === 404) {
throw new AppError(404, 'NOT_FOUND', 'TMDB title not found');
}
throw new AppError(502, 'MEDIA_UNAVAILABLE', `TMDB request failed (${response.status})`);
} catch (error) {
lastError = error;
if (error instanceof AppError) throw error;
if (attempt >= this.options.maxRetries) break;
await delay(100 * 2 ** attempt);
} finally {
clearTimeout(timeout);
}
}
throw new AppError(502, 'MEDIA_UNAVAILABLE', 'TMDB request timed out or was unavailable', {
cause: lastError instanceof Error ? lastError.message : 'unknown',
});
}
}
export function createMetadataProvider(
config: ApiConfig,
fetchImpl: Fetch = globalThis.fetch,
): MetadataProvider {
if (!config.tmdbApiToken || !config.tmdbCommercialLicenseConfirmed) {
return new DisabledMetadataProvider();
}
return new TmdbMetadataProvider(
config.tmdbApiToken,
{
baseUrl: config.tmdbBaseUrl,
timeoutMs: config.tmdbTimeoutMs,
maxRetries: config.tmdbMaxRetries,
},
fetchImpl,
);
}
function toCandidate(value: unknown, kind: 'MOVIE' | 'SERIES'): MetadataCandidate | undefined {
if (!isObject(value) || typeof value.id !== 'number') return undefined;
const name = string(value[kind === 'MOVIE' ? 'title' : 'name']);
const originalName = string(value[kind === 'MOVIE' ? 'original_title' : 'original_name']);
if (!name && !originalName) return undefined;
const date = string(value[kind === 'MOVIE' ? 'release_date' : 'first_air_date']);
const year = date && /^[0-9]{4}/.test(date) ? Number(date.slice(0, 4)) : undefined;
const posterPath = imagePath(value.poster_path);
const backdropPath = imagePath(value.backdrop_path);
const overview = string(value.overview);
return {
provider: 'TMDB',
externalId: value.id,
kind,
name: {
fa: name ?? originalName!,
...(originalName && originalName !== name ? { en: originalName } : {}),
},
synopsis: { ...(overview ? { fa: overview } : {}) },
...(posterPath ? { posterUrl: `/images/tmdb/w500${posterPath}` } : {}),
...(backdropPath
? { backdropUrl: `/images/tmdb/w1280${backdropPath}` }
: {}),
...(year !== undefined ? { year } : {}),
};
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function string(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}
function imagePath(value: unknown): string | undefined {
const path = string(value);
return path?.startsWith('/') ? path : undefined;
}
function retryDelay(retryAfter: string | null, attempt: number): number {
if (retryAfter && /^[0-9]+$/.test(retryAfter)) {
return Math.min(Number(retryAfter) * 1000, 2000);
}
return 100 * 2 ** attempt;
}
function delay(milliseconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
function disabledError(): AppError {
return new AppError(
409,
'CONFLICT',
'TMDB is disabled until TMDB_API_TOKEN and TMDB_COMMERCIAL_LICENSE_CONFIRMED=true are configured',
);
}