init
This commit is contained in:
134 files changed
+18678
No files matched your search
@@ -0,0 +1,14 @@
|
||||
.git
|
||||
.github
|
||||
.DS_Store
|
||||
.env
|
||||
movies
|
||||
data
|
||||
cache
|
||||
derived
|
||||
node_modules
|
||||
**/node_modules
|
||||
**/dist
|
||||
coverage
|
||||
playwright-report
|
||||
test-results
|
||||
@@ -0,0 +1,37 @@
|
||||
NODE_ENV=development
|
||||
HOST=0.0.0.0
|
||||
PORT=3000
|
||||
POSTGRES_PASSWORD=replace-with-a-long-alphanumeric-password
|
||||
REPOSITORY_DRIVER=memory
|
||||
# Production requires one HTTPS origin for the SPA, API, and media cookie path.
|
||||
WEB_ORIGIN=http://localhost:5173
|
||||
PUBLIC_ORIGIN=http://localhost:8080
|
||||
GATEWAY_BIND_ADDRESS=0.0.0.0
|
||||
DATABASE_URL=
|
||||
REDIS_URL=redis://localhost:6379
|
||||
ARCHIVE_ROOT=./movies
|
||||
CACHE_ROOT=./data/cache
|
||||
DERIVED_ROOT=./data/derived
|
||||
METADATA_ROOT=./data/metadata
|
||||
CATALOG_SNAPSHOT_PATH=./data/metadata/catalog.json
|
||||
INVENTORY_SNAPSHOT_PATH=./data/metadata/inventory.json
|
||||
PACKAGE_REGISTRY_PATH=./data/metadata/package-registry.json
|
||||
MEDIA_COMMANDS_PATH=./data/metadata/media-commands.jsonl
|
||||
FFMPEG_PATH=ffmpeg
|
||||
FFPROBE_PATH=ffprobe
|
||||
PLAYBACK_PROFILE=cmaf-v1
|
||||
# Use two different random hex/base64url values (for example: openssl rand -hex 32).
|
||||
PLAYBACK_SIGNING_SECRET=replace-with-at-least-32-random-characters
|
||||
MEDIA_AUTH_SHARED_SECRET=replace-with-another-32-random-character-secret
|
||||
PLAYBACK_TTL_SECONDS=14400
|
||||
ADMIN_BOOTSTRAP_EMAIL=admin@example.com
|
||||
ADMIN_BOOTSTRAP_PASSWORD=change-me-before-production
|
||||
ADMIN_SESSION_TTL_SECONDS=28800
|
||||
TMDB_API_TOKEN=
|
||||
TMDB_COMMERCIAL_LICENSE_CONFIRMED=false
|
||||
MEDIA_PUBLIC_BASE_URL=http://localhost:8080/media
|
||||
JIT_REMUX_CONCURRENCY=2
|
||||
ENCODE_CONCURRENCY=1
|
||||
CACHE_HIGH_WATERMARK=0.85
|
||||
CACHE_LOW_WATERMARK=0.75
|
||||
CACHE_MAX_BYTES=2147483648000
|
||||
@@ -0,0 +1,20 @@
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
- run: corepack enable && corepack prepare pnpm@11.13.0 --activate
|
||||
- run: corepack pnpm install --frozen-lockfile
|
||||
- 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
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
movies/
|
||||
.DS_Store
|
||||
.idea/
|
||||
node_modules/
|
||||
.pnpm-store/
|
||||
dist/
|
||||
coverage/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
data/
|
||||
cache/
|
||||
derived/
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
playwright-report/
|
||||
test-results/
|
||||
@@ -0,0 +1,105 @@
|
||||
# Easy Stream
|
||||
|
||||
Easy Stream is a browser-first streaming layer for a read-only Matroska archive. It keeps the original MKV files untouched, remuxes compatible H.264/AAC sources to CMAF/fMP4 HLS only when requested, and bounds those generated files with a 2 TB LRU cache. Incompatible SDR sources can be prepared once as a durable, same-resolution H.264/AAC representation; HDR is held for review in v1.
|
||||
|
||||
The first version targets Chrome, Firefox, and modern MSE-capable Android TV browsers. The UI is guest-first, Persian/RTL by default, remote-control friendly, and stores viewer preferences and resume progress only in IndexedDB.
|
||||
|
||||
## Repository layout
|
||||
|
||||
- `apps/web`: Vue/Vite catalog, TV navigation, player, local progress, and admin UI.
|
||||
- `apps/api`: Fastify catalog, playback sessions, signed media authorization, admin, and TMDB metadata endpoints.
|
||||
- `apps/worker`: archive scanner, BullMQ worker, JIT packager, offline compatibility encoder, and cache maintenance.
|
||||
- `packages/contracts`: closed TypeBox API, queue, snapshot, and registry contracts.
|
||||
- `packages/media`: FFmpeg, subtitle, font, HLS validation, path-safety, and LRU primitives.
|
||||
- `packages/database`: Drizzle schema, migrations, catalog synchronization, and job lifecycle helpers.
|
||||
- `infra`: production Node/FFmpeg images and the same-origin Nginx gateway.
|
||||
|
||||
See [architecture.md](docs/architecture.md) for the media decisions and [operations.md](docs/operations.md) for deployment gates.
|
||||
|
||||
## What happens to a movie
|
||||
|
||||
| Source | v1 behavior | Storage |
|
||||
|---|---|---|
|
||||
| Browser-compatible H.264/AAC SDR | Stream-copy to progressive fMP4 HLS on first play | Bounded, disposable cache |
|
||||
| H.264 SDR with incompatible audio | Copy video and encode audio to AAC | Bounded, disposable cache |
|
||||
| Other SDR video | One offline H.264/AAC encode at the source resolution | Durable derived disk |
|
||||
| HDR, Dolby Vision, invalid, or incomplete media | Not published | Original only |
|
||||
|
||||
ASS subtitles are preserved for JASSUB/libass rendering, with WebVTT fallback. Embedded fonts are validated, content-addressed, and exposed only inside the signed generation path.
|
||||
|
||||
## Local verification
|
||||
|
||||
Requirements: Node.js 24 LTS (22 is supported for development), pnpm 11 through Corepack, and FFmpeg/ffprobe 8.x.
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
corepack pnpm install
|
||||
corepack pnpm typecheck
|
||||
corepack pnpm test
|
||||
corepack pnpm build
|
||||
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.
|
||||
|
||||
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 \
|
||||
--cache ./data/cache \
|
||||
--inventory ./data/metadata/inventory.json \
|
||||
--registry ./data/metadata/package-registry.json \
|
||||
--media-item MEDIA_ITEM_UUID
|
||||
```
|
||||
|
||||
The original file is opened read-only. Generated media is written under `data/cache/generations/<generation-id>`.
|
||||
|
||||
## Ubuntu / Docker Compose
|
||||
|
||||
On a fresh Ubuntu server, clone this repository and run the interactive bootstrap. It asks for the real HTTPS origin, storage paths, cache size, administrator account, passwords, signing secrets, concurrency, playback lifetime, and optional licensed TMDB access. Secret input is hidden; blank infrastructure secrets are generated securely.
|
||||
|
||||
```sh
|
||||
chmod +x scripts/setup-ubuntu.sh
|
||||
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.
|
||||
|
||||
### Manual alternative
|
||||
|
||||
1. Copy `.env.example` to `.env` and replace every bootstrap password and signing secret. Keep `PLAYBACK_SIGNING_SECRET` and `MEDIA_AUTH_SHARED_SECRET` different.
|
||||
2. Set absolute `ARCHIVE_ROOT`, `CACHE_ROOT`, `DERIVED_ROOT`, and `METADATA_ROOT` paths. The archive is mounted read-only.
|
||||
3. Make the three writable directories available to UID/GID `1000:1000`, used by the unprivileged worker image.
|
||||
4. Set `WEB_ORIGIN`, `PUBLIC_ORIGIN`, and `MEDIA_PUBLIC_BASE_URL` to the same public HTTPS origin. Put port 8080 behind the CDN/TLS edge and restrict direct origin access.
|
||||
5. Start the stack:
|
||||
|
||||
```sh
|
||||
docker compose build
|
||||
docker compose up -d
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
Compose waits for PostgreSQL, applies migrations once, then starts the API, worker, and gateway. On a new installation, open `/admin`, sign in with the bootstrap administrator, and start the first archive scan. The worker writes the snapshots and transactionally imports public catalog rows into PostgreSQL.
|
||||
|
||||
Cold playback is automatic. For a media item classified `VIDEO_TRANSCODE`, run the deliberate offline preparation command before publishing it:
|
||||
|
||||
```sh
|
||||
docker compose exec worker node apps/worker/dist/cli.js prepare \
|
||||
--root /archive \
|
||||
--derived /data/derived \
|
||||
--inventory /data/metadata/inventory.json \
|
||||
--registry /data/metadata/package-registry.json \
|
||||
--media-item MEDIA_ITEM_UUID
|
||||
```
|
||||
|
||||
## Important v1 boundaries
|
||||
|
||||
- There is one representation, not an adaptive-bitrate ladder. A slow connection cannot switch to a lower quality.
|
||||
- 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.
|
||||
- The gateway deliberately marks media responses `private`. Do not override that at a CDN until the CDN validates a signed playback grant **before every cache lookup**; merely forwarding the cookie on cache misses is not authorization.
|
||||
- Physical Android TV, CDN, Redis/PostgreSQL failure recovery, incompatible-SDR encoding, and the full 100 TB census remain production acceptance gates.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Security policy
|
||||
|
||||
Please report vulnerabilities privately to the project operator rather than opening a public issue. Include the affected endpoint or media workflow, reproduction steps, and expected impact.
|
||||
|
||||
The original archive is outside the web trust boundary. A report showing that a browser can obtain an archive path, bypass a generation-scoped playback token, cause a worker to write outside its configured output root, or execute a source filename through a shell is considered critical.
|
||||
|
||||
Production deployments must use patched Node.js, FFmpeg, PostgreSQL, Redis, and Nginx releases and rotate playback/admin secrets after any suspected disclosure.
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@easy-stream/api",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"dev": "tsx watch src/server.ts",
|
||||
"start": "node dist/server.js",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@easy-stream/contracts": "workspace:*",
|
||||
"@easy-stream/database": "workspace:*",
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/cors": "^11.1.0",
|
||||
"@fastify/helmet": "^13.0.2",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@sinclair/typebox": "^0.34.41",
|
||||
"argon2": "^0.44.0",
|
||||
"bullmq": "^5.61.2",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"fastify": "^5.6.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.7.2",
|
||||
"tsx": "^4.20.6",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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('-', '')}`;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
@@ -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}`;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
import type { MetadataCandidate } from '@easy-stream/contracts';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { buildApp } from '../src/app.js';
|
||||
import type {
|
||||
MediaPreparationService,
|
||||
MetadataProvider,
|
||||
PasswordHasher,
|
||||
} from '../src/domain.js';
|
||||
import type { CacheStatusService } from '../src/services/cache-status.js';
|
||||
import { InMemoryRepository } from '../src/repositories/in-memory.js';
|
||||
import { InMemoryMediaCommandPublisher } from '../src/services/media-preparation.js';
|
||||
import { ids, testConfig, titleFixture } from './fixtures.js';
|
||||
|
||||
const passwordHasher: PasswordHasher = {
|
||||
async hash(password) {
|
||||
return `test:${password}`;
|
||||
},
|
||||
async verify(hash, password) {
|
||||
return hash === `test:${password}`;
|
||||
},
|
||||
};
|
||||
|
||||
const readyMedia: MediaPreparationService = {
|
||||
async prepare() {
|
||||
return readyPreparation();
|
||||
},
|
||||
async getStatus() {
|
||||
return readyPreparation();
|
||||
},
|
||||
};
|
||||
|
||||
const metadataCandidate: MetadataCandidate = {
|
||||
provider: 'TMDB',
|
||||
externalId: 42,
|
||||
kind: 'SERIES',
|
||||
name: { fa: 'عنوان تازه', en: 'Fresh title' },
|
||||
synopsis: { fa: 'خلاصه تازه' },
|
||||
year: 2026,
|
||||
};
|
||||
|
||||
const metadataProvider: MetadataProvider = {
|
||||
async search() {
|
||||
return [metadataCandidate];
|
||||
},
|
||||
async getDetails() {
|
||||
return metadataCandidate;
|
||||
},
|
||||
};
|
||||
|
||||
const apps: Awaited<ReturnType<typeof buildApp>>[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(apps.splice(0).map((app) => app.close()));
|
||||
});
|
||||
|
||||
describe('viewer API', () => {
|
||||
it('lists and searches published catalog titles', async () => {
|
||||
const app = await makeApp();
|
||||
const catalog = await app.inject({ method: 'GET', url: '/api/v1/catalog' });
|
||||
expect(catalog.statusCode).toBe(200);
|
||||
expect(catalog.json().items).toEqual([
|
||||
expect.objectContaining({ id: ids.title, playable: true }),
|
||||
]);
|
||||
|
||||
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');
|
||||
|
||||
const detail = await app.inject({ method: 'GET', url: '/api/v1/titles/sample-series' });
|
||||
expect(detail.statusCode).toBe(200);
|
||||
expect(detail.json().mediaItems[0].id).toBe(ids.media);
|
||||
|
||||
const event = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/client-events',
|
||||
payload: {
|
||||
name: 'playback_started',
|
||||
mediaItemId: ids.media,
|
||||
occurredAt: '2026-07-14T00:00:00.000Z',
|
||||
details: { subtitleDelivery: 'ASS_JASSUB' },
|
||||
},
|
||||
});
|
||||
expect(event.statusCode).toBe(202);
|
||||
});
|
||||
|
||||
it('creates a ready session and authorizes only its generation path', async () => {
|
||||
const app = await makeApp();
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/playback-sessions',
|
||||
payload: {
|
||||
mediaItemId: ids.media,
|
||||
clientCapabilities: capabilities(),
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual(
|
||||
expect.objectContaining({
|
||||
state: 'READY',
|
||||
manifestUrl: `http://localhost:8080/media/generations/${ids.generation}/master.m3u8`,
|
||||
}),
|
||||
);
|
||||
expect(response.json().subtitleTracks[0]).toEqual(
|
||||
expect.objectContaining({ assUrl: expect.any(String), vttUrl: expect.any(String) }),
|
||||
);
|
||||
const setCookie = response.headers['set-cookie'];
|
||||
const cookie = (Array.isArray(setCookie) ? setCookie[0] : setCookie)?.split(';', 1)[0];
|
||||
expect(cookie).toBeTruthy();
|
||||
|
||||
const allowed = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/internal/media-auth',
|
||||
headers: {
|
||||
cookie: cookie!,
|
||||
'x-media-auth-secret': testConfig().mediaAuthSharedSecret,
|
||||
'x-original-uri': `/media/generations/${ids.generation}/video/segment-00001.m4s`,
|
||||
},
|
||||
});
|
||||
expect(allowed.statusCode).toBe(204);
|
||||
|
||||
const denied = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/internal/media-auth',
|
||||
headers: {
|
||||
cookie: cookie!,
|
||||
'x-media-auth-secret': testConfig().mediaAuthSharedSecret,
|
||||
'x-original-uri': '/media/generations/30000000-0000-4000-8000-000000000002/master.m3u8',
|
||||
},
|
||||
});
|
||||
expect(denied.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('promotes a playable EVENT package while it is still preparing', async () => {
|
||||
const progressive: MediaPreparationService = {
|
||||
async prepare() {
|
||||
return { ...readyPreparation(), state: 'PREPARING' };
|
||||
},
|
||||
async getStatus() {
|
||||
return { ...readyPreparation(), state: 'PREPARING' };
|
||||
},
|
||||
};
|
||||
const app = await makeApp(progressive);
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/playback-sessions',
|
||||
payload: { mediaItemId: ids.media, clientCapabilities: capabilities() },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().state).toBe('READY');
|
||||
});
|
||||
|
||||
it('scopes durable compatibility media to the derived generation path', async () => {
|
||||
const derivedMedia: MediaPreparationService = {
|
||||
async prepare() {
|
||||
return {
|
||||
...readyPreparation(),
|
||||
manifestPath: `/media/derived/generations/${ids.generation}/master.m3u8`,
|
||||
subtitleTracks: [
|
||||
{
|
||||
id: ids.subtitle,
|
||||
language: 'fa',
|
||||
label: 'فارسی',
|
||||
default: true,
|
||||
forced: false,
|
||||
assUrl: `/media/derived/generations/${ids.generation}/subtitles/fa.ass`,
|
||||
vttUrl: `/media/derived/generations/${ids.generation}/subtitles/fa.vtt`,
|
||||
fontUrls: [`/media/derived/generations/${ids.generation}/fonts/a.ttf`],
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
async getStatus() {
|
||||
throw new Error('not used');
|
||||
},
|
||||
};
|
||||
const app = await makeApp(derivedMedia);
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/playback-sessions',
|
||||
payload: { mediaItemId: ids.media, clientCapabilities: capabilities() },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().manifestUrl).toBe(
|
||||
`http://localhost:8080/media/derived/generations/${ids.generation}/master.m3u8`,
|
||||
);
|
||||
const setCookie = response.headers['set-cookie'];
|
||||
const cookieHeader = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
||||
expect(cookieHeader).toContain(`Path=/media/derived/generations/${ids.generation}/`);
|
||||
const cookie = cookieHeader?.split(';', 1)[0];
|
||||
|
||||
const allowed = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/internal/media-auth',
|
||||
headers: {
|
||||
cookie: cookie!,
|
||||
'x-media-auth-secret': testConfig().mediaAuthSharedSecret,
|
||||
'x-original-uri': `/media/derived/generations/${ids.generation}/fonts/a.ttf`,
|
||||
},
|
||||
});
|
||||
expect(allowed.statusCode).toBe(204);
|
||||
|
||||
const wrongStore = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/internal/media-auth',
|
||||
headers: {
|
||||
cookie: cookie!,
|
||||
'x-media-auth-secret': testConfig().mediaAuthSharedSecret,
|
||||
'x-original-uri': `/media/generations/${ids.generation}/master.m3u8`,
|
||||
},
|
||||
});
|
||||
expect(wrongStore.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns a stable unsupported-client session without enqueueing media', async () => {
|
||||
const app = await makeApp();
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/playback-sessions',
|
||||
payload: {
|
||||
mediaItemId: ids.media,
|
||||
clientCapabilities: { ...capabilities(), mse: false, hlsJs: false },
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual(
|
||||
expect.objectContaining({ state: 'UNSUPPORTED_CLIENT', reasonCode: 'HLS_MSE_UNAVAILABLE' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('administrator API', () => {
|
||||
it('enforces session and CSRF, enqueues scans, and applies a metadata match', async () => {
|
||||
const commands = new InMemoryMediaCommandPublisher();
|
||||
const cacheStatus: CacheStatusService = {
|
||||
async getStatus() {
|
||||
return {
|
||||
usedBytes: 321,
|
||||
maxBytes: 1_000,
|
||||
highWatermark: 0.85,
|
||||
lowWatermark: 0.75,
|
||||
activePackages: 2,
|
||||
};
|
||||
},
|
||||
};
|
||||
const app = await makeApp(readyMedia, commands, cacheStatus);
|
||||
const login = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/admin/login',
|
||||
payload: { email: 'admin@example.com', password: 'a-good-test-password' },
|
||||
});
|
||||
expect(login.statusCode).toBe(200);
|
||||
const csrf = login.json().csrfToken as string;
|
||||
const setCookie = login.headers['set-cookie'];
|
||||
const cookie = (Array.isArray(setCookie) ? setCookie[0] : setCookie)?.split(';', 1)[0];
|
||||
|
||||
const blocked = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/admin/scans',
|
||||
headers: { cookie: cookie! },
|
||||
payload: { full: false },
|
||||
});
|
||||
expect(blocked.statusCode).toBe(403);
|
||||
|
||||
const scan = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/admin/scans',
|
||||
headers: { cookie: cookie!, 'x-csrf-token': csrf },
|
||||
payload: { full: true },
|
||||
});
|
||||
expect(scan.statusCode).toBe(202);
|
||||
expect(commands.commands).toContainEqual(
|
||||
expect.objectContaining({ type: 'archive.scan.requested', full: true }),
|
||||
);
|
||||
|
||||
const match = await app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/v1/admin/titles/${ids.title}/metadata-match`,
|
||||
headers: { cookie: cookie!, 'x-csrf-token': csrf },
|
||||
payload: { provider: 'TMDB', externalId: 42, kind: 'SERIES' },
|
||||
});
|
||||
expect(match.statusCode).toBe(200);
|
||||
const detail = await app.inject({ method: 'GET', url: '/api/v1/titles/sample-series' });
|
||||
expect(detail.json().name.fa).toBe('عنوان تازه');
|
||||
|
||||
const cache = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/admin/cache',
|
||||
headers: { cookie: cookie! },
|
||||
});
|
||||
expect(cache.statusCode).toBe(200);
|
||||
expect(cache.json()).toEqual(expect.objectContaining({ usedBytes: 321, activePackages: 2 }));
|
||||
});
|
||||
});
|
||||
|
||||
async function makeApp(
|
||||
media: MediaPreparationService = readyMedia,
|
||||
commands = new InMemoryMediaCommandPublisher(),
|
||||
cacheStatus?: CacheStatusService,
|
||||
) {
|
||||
const app = await buildApp({
|
||||
config: testConfig(),
|
||||
repository: new InMemoryRepository({ titles: [titleFixture] }),
|
||||
mediaPreparation: media,
|
||||
commandPublisher: commands,
|
||||
metadataProvider,
|
||||
passwordHasher,
|
||||
...(cacheStatus === undefined ? {} : { cacheStatus }),
|
||||
logger: false,
|
||||
});
|
||||
apps.push(app);
|
||||
return app;
|
||||
}
|
||||
|
||||
function capabilities() {
|
||||
return {
|
||||
mse: true,
|
||||
nativeHls: false,
|
||||
hlsJs: true,
|
||||
assRenderer: true,
|
||||
supportedCodecs: ['avc1.64001f', 'mp4a.40.2'],
|
||||
};
|
||||
}
|
||||
|
||||
function readyPreparation() {
|
||||
return {
|
||||
state: 'READY' as const,
|
||||
playable: true,
|
||||
generationId: ids.generation,
|
||||
manifestPath: `/media/generations/${ids.generation}/master.m3u8`,
|
||||
durationSeconds: 1420,
|
||||
audioTracks: [
|
||||
{ id: ids.audio, language: 'ja', label: '日本語', default: true },
|
||||
],
|
||||
subtitleTracks: [
|
||||
{
|
||||
id: ids.subtitle,
|
||||
language: 'fa',
|
||||
label: 'فارسی',
|
||||
default: true,
|
||||
forced: false,
|
||||
assUrl: `/media/generations/${ids.generation}/subtitles/fa.ass`,
|
||||
vttUrl: `/media/generations/${ids.generation}/subtitles/fa.vtt`,
|
||||
fontUrls: [`/media/generations/${ids.generation}/fonts/a.ttf`],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { FilesystemCacheStatusService } from '../src/services/cache-status.js';
|
||||
|
||||
const temporaryRoots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
describe('filesystem cache status', () => {
|
||||
it('sums valid generation metadata and global font-store files', async () => {
|
||||
const root = await temporaryRoot();
|
||||
const generations = path.join(root, 'generations');
|
||||
await Promise.all([
|
||||
writeEntry(generations, '11111111-1111-4111-8111-111111111111', 120, false),
|
||||
writeEntry(generations, '22222222-2222-4222-8222-222222222222', 230, true),
|
||||
mkdir(path.join(generations, 'incomplete-generation'), { recursive: true }),
|
||||
]);
|
||||
const fontStore = path.join(root, 'assets', 'fonts', 'sha256');
|
||||
await mkdir(fontStore, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(path.join(fontStore, `${'a'.repeat(64)}.ttf`), Buffer.alloc(11)),
|
||||
writeFile(path.join(fontStore, `${'b'.repeat(64)}.otf`), Buffer.alloc(19)),
|
||||
]);
|
||||
|
||||
await expect(service(root).getStatus()).resolves.toEqual({
|
||||
usedBytes: 380,
|
||||
maxBytes: 1_000,
|
||||
highWatermark: 0.85,
|
||||
lowWatermark: 0.75,
|
||||
activePackages: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a missing cache root as an empty cache', async () => {
|
||||
const base = await temporaryRoot();
|
||||
await expect(service(path.join(base, 'missing')).getStatus()).resolves.toMatchObject({
|
||||
usedBytes: 0,
|
||||
activePackages: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects invalid managed generation metadata', async () => {
|
||||
const root = await temporaryRoot();
|
||||
const generations = path.join(root, 'generations');
|
||||
const generation = '11111111-1111-4111-8111-111111111111';
|
||||
const directory = path.join(generations, generation);
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(path.join(directory, '.cache-entry.json'), JSON.stringify({
|
||||
...metadata('different-generation', 10, false),
|
||||
}));
|
||||
|
||||
await expect(service(root).getStatus()).rejects.toThrow(/does not match its generation/u);
|
||||
});
|
||||
|
||||
it('counts a known archived failure without treating stale metadata as a live build', async () => {
|
||||
const root = await temporaryRoot();
|
||||
const generations = path.join(root, 'generations');
|
||||
const generation = '11111111-1111-4111-8111-111111111111';
|
||||
const archived = `failed-1784023200000-${generation}`;
|
||||
const directory = path.join(generations, archived);
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(path.join(directory, '.cache-entry.json'), JSON.stringify(
|
||||
metadata(generation, 77, true),
|
||||
));
|
||||
|
||||
await expect(service(root).getStatus()).resolves.toMatchObject({
|
||||
usedBytes: 77,
|
||||
activePackages: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('fails closed on symlinks in managed cache namespaces', async () => {
|
||||
const root = await temporaryRoot();
|
||||
const outside = await temporaryRoot();
|
||||
const generations = path.join(root, 'generations');
|
||||
await mkdir(generations, { recursive: true });
|
||||
await symlink(outside, path.join(generations, 'linked-generation'));
|
||||
await expect(service(root).getStatus()).rejects.toThrow(/Symlink found in cache generations/u);
|
||||
|
||||
await rm(generations, { recursive: true, force: true });
|
||||
await symlink(outside, path.join(root, 'assets'));
|
||||
await expect(service(root).getStatus()).rejects.toThrow(/not a regular directory/u);
|
||||
});
|
||||
});
|
||||
|
||||
function service(cacheRoot: string): FilesystemCacheStatusService {
|
||||
return new FilesystemCacheStatusService({
|
||||
cacheRoot,
|
||||
maxBytes: 1_000,
|
||||
highWatermark: 0.85,
|
||||
lowWatermark: 0.75,
|
||||
});
|
||||
}
|
||||
|
||||
async function temporaryRoot(): Promise<string> {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-api-cache-'));
|
||||
temporaryRoots.push(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
async function writeEntry(
|
||||
generations: string,
|
||||
generation: string,
|
||||
bytes: number,
|
||||
building: boolean,
|
||||
): Promise<void> {
|
||||
const directory = path.join(generations, generation);
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(path.join(directory, '.cache-entry.json'), JSON.stringify(
|
||||
metadata(generation, bytes, building),
|
||||
));
|
||||
}
|
||||
|
||||
function metadata(key: string, bytes: number, building: boolean) {
|
||||
return {
|
||||
version: 1,
|
||||
key,
|
||||
bytes,
|
||||
lastAccessedAt: '2026-07-14T10:00:00.000Z',
|
||||
active: false,
|
||||
building,
|
||||
pinned: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
|
||||
describe('loadConfig', () => {
|
||||
it('loads a secure in-memory development configuration', () => {
|
||||
const config = loadConfig({
|
||||
NODE_ENV: 'development',
|
||||
PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars',
|
||||
});
|
||||
expect(config.repositoryDriver).toBe('memory');
|
||||
expect(config.catalogSnapshotPath).toBe('./data/catalog.json');
|
||||
expect(config.cacheRoot).toBe('./data/cache');
|
||||
expect(config.cacheLowWatermark).toBeLessThan(config.cacheHighWatermark);
|
||||
});
|
||||
|
||||
it('accepts an explicit read-only cache root', () => {
|
||||
const config = loadConfig({
|
||||
NODE_ENV: 'test',
|
||||
CACHE_ROOT: '/srv/easy-stream/cache',
|
||||
PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars',
|
||||
});
|
||||
expect(config.cacheRoot).toBe('/srv/easy-stream/cache');
|
||||
});
|
||||
|
||||
it('rejects short signing secrets', () => {
|
||||
expect(() =>
|
||||
loadConfig({ NODE_ENV: 'test', PLAYBACK_SIGNING_SECRET: 'short' }),
|
||||
).toThrow(/playbackSigningSecret/);
|
||||
});
|
||||
|
||||
it('requires a database URL for PostgreSQL', () => {
|
||||
expect(() =>
|
||||
loadConfig({
|
||||
NODE_ENV: 'test',
|
||||
REPOSITORY_DRIVER: 'postgres',
|
||||
PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars',
|
||||
}),
|
||||
).toThrow(/DATABASE_URL/);
|
||||
});
|
||||
|
||||
it('accepts only a base64url-safe media auth secret', () => {
|
||||
expect(() =>
|
||||
loadConfig({
|
||||
NODE_ENV: 'test',
|
||||
PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars',
|
||||
MEDIA_AUTH_SHARED_SECRET: 'invalid-secret-with-a-quote-"-inside',
|
||||
}),
|
||||
).toThrow(/mediaAuthSharedSecret/);
|
||||
});
|
||||
|
||||
it('requires the web, API, and media URLs to remain same-origin in production', () => {
|
||||
expect(() =>
|
||||
loadConfig({
|
||||
NODE_ENV: 'production',
|
||||
DATABASE_URL: 'postgres://easy-stream:test@postgres/easy-stream',
|
||||
WEB_ORIGIN: 'https://watch.example.com',
|
||||
PUBLIC_ORIGIN: 'https://watch.example.com',
|
||||
MEDIA_PUBLIC_BASE_URL: 'https://media.example.com/media',
|
||||
PLAYBACK_SIGNING_SECRET: 'production-playback-signing-secret-000000000',
|
||||
MEDIA_AUTH_SHARED_SECRET: 'production_media_auth_secret_11111111111',
|
||||
}),
|
||||
).toThrow(/must use one origin/);
|
||||
});
|
||||
|
||||
it('requires the canonical media base path', () => {
|
||||
expect(() =>
|
||||
loadConfig({
|
||||
NODE_ENV: 'test',
|
||||
PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars',
|
||||
MEDIA_PUBLIC_BASE_URL: 'http://localhost:8080/not-media',
|
||||
}),
|
||||
).toThrow(/\/media path/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { ApiConfig } from '../src/config.js';
|
||||
import type { TitleDetail } from '@easy-stream/contracts';
|
||||
|
||||
export const ids = {
|
||||
title: '10000000-0000-4000-8000-000000000001',
|
||||
media: '20000000-0000-4000-8000-000000000001',
|
||||
generation: '30000000-0000-4000-8000-000000000001',
|
||||
audio: '40000000-0000-4000-8000-000000000001',
|
||||
subtitle: '50000000-0000-4000-8000-000000000001',
|
||||
};
|
||||
|
||||
export const titleFixture: TitleDetail = {
|
||||
id: ids.title,
|
||||
slug: 'sample-series',
|
||||
kind: 'SERIES',
|
||||
name: { fa: 'سریال نمونه', en: 'Sample Series' },
|
||||
synopsis: { fa: 'خلاصه نمونه', en: 'Sample synopsis' },
|
||||
playable: true,
|
||||
resumeMediaItemId: ids.media,
|
||||
seasons: [{ number: 1, episodeCount: 1 }],
|
||||
mediaItems: [
|
||||
{
|
||||
id: ids.media,
|
||||
kind: 'EPISODE',
|
||||
seasonNumber: 1,
|
||||
episodeNumber: 1,
|
||||
name: { fa: 'قسمت یک', en: 'Episode One' },
|
||||
durationSeconds: 1420,
|
||||
compatibility: 'COPY',
|
||||
published: true,
|
||||
},
|
||||
],
|
||||
updatedAt: '2026-07-14T00:00:00.000Z',
|
||||
};
|
||||
|
||||
export function testConfig(overrides: Partial<ApiConfig> = {}): ApiConfig {
|
||||
return {
|
||||
nodeEnv: 'test',
|
||||
host: '127.0.0.1',
|
||||
port: 3000,
|
||||
webOrigin: 'http://localhost:5173',
|
||||
publicOrigin: 'http://localhost:8080',
|
||||
mediaPublicBaseUrl: 'http://localhost:8080/media',
|
||||
repositoryDriver: 'memory',
|
||||
catalogSnapshotPath: '/tmp/easy-stream-test-catalog-does-not-exist.json',
|
||||
packageRegistryPath: '/tmp/easy-stream-test-registry-does-not-exist.json',
|
||||
mediaCommandsPath: '/tmp/easy-stream-test-commands.jsonl',
|
||||
cacheRoot: '/tmp/easy-stream-test-cache-does-not-exist',
|
||||
playbackProfile: 'cmaf-v1',
|
||||
playbackSigningSecret: 'playback-signing-secret-that-is-long-enough',
|
||||
mediaAuthSharedSecret: 'media-auth-shared-secret-that-is-long-enough',
|
||||
playbackTtlSeconds: 14_400,
|
||||
adminSessionTtlSeconds: 28_800,
|
||||
adminBootstrapEmail: 'admin@example.com',
|
||||
adminBootstrapPassword: 'a-good-test-password',
|
||||
tmdbCommercialLicenseConfirmed: false,
|
||||
tmdbBaseUrl: 'https://api.themoviedb.org/3',
|
||||
tmdbTimeoutMs: 1000,
|
||||
tmdbMaxRetries: 1,
|
||||
cacheMaxBytes: 2_000_000,
|
||||
cacheHighWatermark: 0.85,
|
||||
cacheLowWatermark: 0.75,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { mkdtemp, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
FileMediaPreparationService,
|
||||
InMemoryMediaCommandPublisher,
|
||||
} from '../src/services/media-preparation.js';
|
||||
import { ids } from './fixtures.js';
|
||||
|
||||
describe('file media preparation cache access', () => {
|
||||
it('records a cache lease through the playback session expiry', async () => {
|
||||
const registry = await readyRegistry(`/media/generations/${ids.generation}/master.m3u8`);
|
||||
const commands = new InMemoryMediaCommandPublisher();
|
||||
const service = new FileMediaPreparationService(registry, commands);
|
||||
const protectedUntil = '2026-07-14T14:00:00.000Z';
|
||||
const result = await service.prepare({
|
||||
sessionId: ids.title,
|
||||
mediaItem: mediaItem(),
|
||||
capabilities: capabilities(),
|
||||
protectUntil: protectedUntil,
|
||||
});
|
||||
expect(result.state).toBe('READY');
|
||||
expect(commands.commands).toEqual([
|
||||
expect.objectContaining({
|
||||
type: 'cache.generation.accessed',
|
||||
generationId: ids.generation,
|
||||
protectedUntil,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not put durable derived generations in the disposable cache lifecycle', async () => {
|
||||
const registry = await readyRegistry(`/media/derived/generations/${ids.generation}/master.m3u8`);
|
||||
const commands = new InMemoryMediaCommandPublisher();
|
||||
const service = new FileMediaPreparationService(registry, commands);
|
||||
await service.prepare({
|
||||
sessionId: ids.title,
|
||||
mediaItem: mediaItem(),
|
||||
capabilities: capabilities(),
|
||||
protectUntil: '2026-07-14T14:00:00.000Z',
|
||||
});
|
||||
expect(commands.commands).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
async function readyRegistry(manifestPath: string): Promise<string> {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-api-registry-'));
|
||||
const registry = path.join(directory, 'registry.json');
|
||||
await writeFile(registry, JSON.stringify({
|
||||
version: 1,
|
||||
updatedAt: '2026-07-14T10:00:00.000Z',
|
||||
packages: [{
|
||||
mediaItemId: ids.media,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
generationId: ids.generation,
|
||||
manifestPath,
|
||||
}],
|
||||
}));
|
||||
return registry;
|
||||
}
|
||||
|
||||
function mediaItem() {
|
||||
return {
|
||||
id: ids.media,
|
||||
titleId: ids.title,
|
||||
durationSeconds: 100,
|
||||
compatibility: 'COPY' as const,
|
||||
published: true,
|
||||
};
|
||||
}
|
||||
|
||||
function capabilities() {
|
||||
return {
|
||||
mse: true,
|
||||
nativeHls: false,
|
||||
hlsJs: true,
|
||||
assRenderer: true,
|
||||
supportedCodecs: ['avc1.64001f'],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { TmdbMetadataProvider } from '../src/services/tmdb.js';
|
||||
|
||||
describe('TmdbMetadataProvider', () => {
|
||||
it('falls back from Persian search to English and sends a bearer token', async () => {
|
||||
const fetch = vi
|
||||
.fn<typeof globalThis.fetch>()
|
||||
.mockResolvedValueOnce(Response.json({ results: [] }))
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({
|
||||
results: [
|
||||
{
|
||||
id: 42,
|
||||
name: 'Sample Series',
|
||||
original_name: 'Sample Series',
|
||||
overview: 'Overview',
|
||||
first_air_date: '2026-01-02',
|
||||
poster_path: '/sample-poster.jpg',
|
||||
backdrop_path: '/sample-backdrop.jpg',
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const provider = new TmdbMetadataProvider(
|
||||
'secret-token',
|
||||
{ baseUrl: 'https://api.themoviedb.org/3', timeoutMs: 1000, maxRetries: 0 },
|
||||
fetch,
|
||||
);
|
||||
|
||||
const result = await provider.search({ query: 'Sample', kind: 'SERIES' });
|
||||
expect(result[0]).toEqual(expect.objectContaining({
|
||||
externalId: 42,
|
||||
year: 2026,
|
||||
posterUrl: '/images/tmdb/w500/sample-poster.jpg',
|
||||
backdropUrl: '/images/tmdb/w1280/sample-backdrop.jpg',
|
||||
}));
|
||||
expect(new URL(String(fetch.mock.calls[0]?.[0])).searchParams.get('language')).toBe('fa-IR');
|
||||
expect(new URL(String(fetch.mock.calls[1]?.[0])).searchParams.get('language')).toBe('en-US');
|
||||
expect(fetch.mock.calls[0]?.[1]?.headers).toEqual(
|
||||
expect.objectContaining({ authorization: 'Bearer secret-token' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('merges Persian and English detail responses', async () => {
|
||||
const fetch = vi
|
||||
.fn<typeof globalThis.fetch>()
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({ id: 42, title: 'عنوان فارسی', overview: 'خلاصه', release_date: '2025-01-01' }),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({ id: 42, title: 'English title', overview: 'Synopsis', release_date: '2025-01-01' }),
|
||||
);
|
||||
const provider = new TmdbMetadataProvider(
|
||||
'token',
|
||||
{ baseUrl: 'https://api.themoviedb.org/3', timeoutMs: 1000, maxRetries: 0 },
|
||||
fetch,
|
||||
);
|
||||
const result = await provider.getDetails({ externalId: 42, kind: 'MOVIE' });
|
||||
expect(result.name).toEqual({ fa: 'عنوان فارسی', en: 'English title' });
|
||||
expect(result.synopsis).toEqual({ fa: 'خلاصه', en: 'Synopsis' });
|
||||
});
|
||||
|
||||
it('retries transient upstream failures', async () => {
|
||||
const fetch = vi
|
||||
.fn<typeof globalThis.fetch>()
|
||||
.mockResolvedValueOnce(new Response('', { status: 503 }))
|
||||
.mockResolvedValueOnce(Response.json({ results: [] }))
|
||||
.mockResolvedValueOnce(Response.json({ results: [] }));
|
||||
const provider = new TmdbMetadataProvider(
|
||||
'token',
|
||||
{ baseUrl: 'https://api.themoviedb.org/3', timeoutMs: 1000, maxRetries: 1 },
|
||||
fetch,
|
||||
);
|
||||
await expect(provider.search({ query: 'x', kind: 'MOVIE' })).resolves.toEqual([]);
|
||||
expect(fetch).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"tsBuildInfoFile": "dist/.tsbuildinfo",
|
||||
"types": ["node"],
|
||||
"paths": {
|
||||
"@easy-stream/contracts": ["packages/contracts/dist/index.d.ts"],
|
||||
"@easy-stream/database": ["packages/database/dist/index.d.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"tsBuildInfoFile": "../../node_modules/.cache/easy-stream-api-test.tsbuildinfo"
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="fa" dir="rtl">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#111722" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="description" content="Your movie archive, ready to stream." />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<title>Easy Stream</title>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main-content">رفتن به محتوای اصلی</a>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@easy-stream/web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 0.0.0.0",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/vazirmatn": "^5.2.8",
|
||||
"hls.js": "^1.6.15",
|
||||
"jassub": "^2.5.7",
|
||||
"pinia": "^3.0.3",
|
||||
"vue": "^3.5.22",
|
||||
"vue-router": "^4.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"@vue/test-utils": "^2.4.6",
|
||||
"jsdom": "^26.1.0",
|
||||
"vite": "^7.1.9",
|
||||
"vitest": "^3.2.4",
|
||||
"vue-tsc": "^3.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<linearGradient id="gold" x1="10" y1="7" x2="54" y2="58" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#FFE29A" />
|
||||
<stop offset=".46" stop-color="#F5BD43" />
|
||||
<stop offset="1" stop-color="#D98A08" />
|
||||
</linearGradient>
|
||||
<linearGradient id="shine" x1="16" y1="11" x2="43" y2="49" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#FFF5D5" stop-opacity=".82" />
|
||||
<stop offset="1" stop-color="#FFF5D5" stop-opacity="0" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="18" fill="#111722" />
|
||||
<rect x="5" y="5" width="54" height="54" rx="15" fill="url(#gold)" />
|
||||
<path d="M18 20.5c0-3.04 2.46-5.5 5.5-5.5h17.75a5.5 5.5 0 0 1 4.8 2.82l5.46 9.78a9 9 0 0 1 0 8.8l-5.46 9.78a5.5 5.5 0 0 1-4.8 2.82H23.5a5.5 5.5 0 0 1-5.5-5.5v-23Z" fill="#111722" />
|
||||
<path d="m30 24.4 12.2 7.6L30 39.6V24.4Z" fill="#FFF8E8" />
|
||||
<path d="M13.5 23.5h7M11 32h9.5M13.5 40.5h7" fill="none" stroke="#111722" stroke-width="3.5" stroke-linecap="round" />
|
||||
<path d="M17 12.5h18c8 0 13.2 4.4 16 10.5" fill="none" stroke="url(#shine)" stroke-width="2.5" stroke-linecap="round" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "Easy Stream",
|
||||
"short_name": "Easy Stream",
|
||||
"description": "Your movie archive, ready to stream.",
|
||||
"lang": "fa",
|
||||
"dir": "rtl",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#070a12",
|
||||
"theme_color": "#111722",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/favicon.svg",
|
||||
"sizes": "any",
|
||||
"type": "image/svg+xml",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
import AppHeader from '@/components/AppHeader.vue'
|
||||
import BrandMark from '@/components/BrandMark.vue'
|
||||
import PlayerShell from '@/components/PlayerShell.vue'
|
||||
import { useSpatialNavigation } from '@/composables/spatial-navigation'
|
||||
|
||||
const appRoot = ref<HTMLElement | null>(null)
|
||||
const router = useRouter()
|
||||
useSpatialNavigation(appRoot, { onBack: () => router.back() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="appRoot" class="app-shell">
|
||||
<AppHeader />
|
||||
<main id="main-content" class="main-content" tabindex="-1">
|
||||
<RouterView />
|
||||
</main>
|
||||
<footer class="app-footer">
|
||||
<span class="footer-brand">
|
||||
<BrandMark />
|
||||
<span>Easy Stream</span>
|
||||
</span>
|
||||
<span class="footer-dot" aria-hidden="true">•</span>
|
||||
<RouterLink to="/admin">Admin</RouterLink>
|
||||
</footer>
|
||||
<PlayerShell />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { normalizePlaybackSession } from '@/api/client'
|
||||
|
||||
describe('normalizePlaybackSession', () => {
|
||||
it('normalizes the canonical playback response', () => {
|
||||
const session = normalizePlaybackSession({
|
||||
id: 'session-1',
|
||||
state: 'READY',
|
||||
manifestUrl: '/media/session-1/master.m3u8',
|
||||
durationSeconds: 1420,
|
||||
audioTracks: [{ id: 'audio-ja', language: 'ja', label: 'Japanese', default: true }],
|
||||
subtitleTracks: [{
|
||||
id: 'sub-fa',
|
||||
language: 'fa',
|
||||
label: 'فارسی',
|
||||
assUrl: '/subtitles/fa.ass',
|
||||
vttUrl: '/subtitles/fa.vtt',
|
||||
fontUrls: ['/fonts/one.ttf'],
|
||||
}],
|
||||
})
|
||||
|
||||
expect(session.state).toBe('READY')
|
||||
expect(session.manifestUrl).toBe('/media/session-1/master.m3u8')
|
||||
expect(session.audioTracks[0]).toMatchObject({ language: 'ja', default: true })
|
||||
expect(session.subtitles[0]).toMatchObject({
|
||||
language: 'fa',
|
||||
assUrl: '/subtitles/fa.ass',
|
||||
vttUrl: '/subtitles/fa.vtt',
|
||||
fonts: ['/fonts/one.ttf'],
|
||||
})
|
||||
})
|
||||
|
||||
it('splits and merges a legacy mixed track array', () => {
|
||||
const session = normalizePlaybackSession({
|
||||
sessionId: 'session-2',
|
||||
status: 'building',
|
||||
tracks: [
|
||||
{ id: 'fa-ass', kind: 'SUBTITLE', language: 'fa', delivery: 'ASS', url: '/fa.ass' },
|
||||
{ id: 'fa-vtt', kind: 'SUBTITLE', language: 'fa', delivery: 'WEBVTT', url: '/fa.vtt' },
|
||||
{ id: 'ja', kind: 'AUDIO', language: 'ja', name: 'Japanese' },
|
||||
],
|
||||
})
|
||||
|
||||
expect(session.state).toBe('PREPARING')
|
||||
expect(session.subtitles).toHaveLength(1)
|
||||
expect(session.subtitles[0]).toMatchObject({ assUrl: '/fa.ass', vttUrl: '/fa.vtt' })
|
||||
expect(session.audioTracks).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,444 @@
|
||||
import type {
|
||||
AdminDashboard,
|
||||
AdminJob,
|
||||
CatalogItem,
|
||||
CatalogPage,
|
||||
ClientCapabilities,
|
||||
EpisodeItem,
|
||||
LocalizedText,
|
||||
PlaybackAudioTrack,
|
||||
PlaybackSession,
|
||||
PlaybackState,
|
||||
PlaybackSubtitleTrack,
|
||||
SeasonItem,
|
||||
TitleDetail,
|
||||
} from '@/types'
|
||||
|
||||
const API_BASE = (import.meta.env.VITE_API_BASE_URL ?? '/api/v1').replace(/\/$/, '')
|
||||
const ADMIN_CSRF_KEY = 'easy-stream-admin-csrf'
|
||||
const ADMIN_EMAIL_KEY = 'easy-stream-admin-email'
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number
|
||||
readonly code: string | undefined
|
||||
|
||||
constructor(message: string, status: number, code?: string) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
type JsonRecord = Record<string, unknown>
|
||||
|
||||
function record(value: unknown): JsonRecord {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as JsonRecord)
|
||||
: {}
|
||||
}
|
||||
|
||||
function text(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.trim() ? value : undefined
|
||||
}
|
||||
|
||||
function number(value: unknown): number | undefined {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value
|
||||
if (typeof value === 'string' && value.trim() && Number.isFinite(Number(value))) return Number(value)
|
||||
return undefined
|
||||
}
|
||||
|
||||
function boolean(value: unknown, fallback = false): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback
|
||||
}
|
||||
|
||||
function localized(value: unknown, fallback?: unknown): LocalizedText {
|
||||
if (typeof value === 'string') return { fa: value, en: value }
|
||||
const source = record(value)
|
||||
const fa = text(source.fa) ?? text(source.faIR) ?? text(source.persian)
|
||||
const en = text(source.en) ?? text(source.enUS) ?? text(source.english) ?? text(fallback)
|
||||
return {
|
||||
...(fa ? { fa } : {}),
|
||||
...(en ? { en } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function array(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : []
|
||||
}
|
||||
|
||||
function normalizeCatalogItem(input: unknown): CatalogItem {
|
||||
const item = record(input)
|
||||
const metadata = record(item.metadata)
|
||||
const titleValue = item.name ?? item.title ?? metadata.title
|
||||
const title = typeof titleValue === 'string'
|
||||
? { fa: titleValue, en: text(item.titleEn ?? metadata.titleEn) ?? titleValue }
|
||||
: localized(titleValue, item.name ?? metadata.name)
|
||||
const id = text(item.id) ?? text(item.titleId) ?? text(item.mediaItemId) ?? ''
|
||||
const mediaItemId = text(item.resumeMediaItemId) ?? text(item.mediaItemId) ?? text(item.playableMediaItemId) ?? id
|
||||
const kindValue = (text(item.kind) ?? text(item.type) ?? 'MOVIE').toUpperCase()
|
||||
const posterUrl = text(item.posterUrl) ?? text(metadata.posterUrl) ?? text(record(item.images).poster)
|
||||
const backdropUrl = text(item.backdropUrl) ?? text(metadata.backdropUrl) ?? text(record(item.images).backdrop)
|
||||
|
||||
return {
|
||||
id,
|
||||
mediaItemId,
|
||||
slug: text(item.slug) ?? id,
|
||||
kind: kindValue === 'SERIES' || kindValue === 'SHOW' ? 'SERIES' : 'MOVIE',
|
||||
title,
|
||||
overview: typeof (item.synopsis ?? item.overview ?? metadata.overview) === 'string'
|
||||
? {
|
||||
fa: text(item.synopsis ?? item.overview ?? metadata.overview),
|
||||
en: text(item.overviewEn ?? metadata.overviewEn) ?? text(item.synopsis ?? item.overview ?? metadata.overview),
|
||||
}
|
||||
: localized(item.synopsis ?? item.overview ?? metadata.overview, item.description ?? metadata.description),
|
||||
...(posterUrl ? { posterUrl } : {}),
|
||||
...(backdropUrl ? { backdropUrl } : {}),
|
||||
...(number(item.year ?? metadata.year) !== undefined ? { year: number(item.year ?? metadata.year) } : {}),
|
||||
...(number(item.runtimeSeconds ?? item.durationSeconds) !== undefined
|
||||
? { runtimeSeconds: number(item.runtimeSeconds ?? item.durationSeconds) }
|
||||
: {}),
|
||||
...(number(item.seasonCount) !== undefined ? { seasonCount: number(item.seasonCount) } : {}),
|
||||
...(number(item.episodeCount) !== undefined ? { episodeCount: number(item.episodeCount) } : {}),
|
||||
...(text(item.compatibility) ? { compatibility: text(item.compatibility) } : {}),
|
||||
playable: item.playable === undefined ? Boolean(mediaItemId) : boolean(item.playable),
|
||||
...(number(item.progress) !== undefined ? { progress: number(item.progress) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEpisode(input: unknown, seasonNumber: number): EpisodeItem {
|
||||
const item = record(input)
|
||||
const id = text(item.id) ?? text(item.mediaItemId) ?? ''
|
||||
return {
|
||||
id,
|
||||
mediaItemId: text(item.mediaItemId) ?? id,
|
||||
number: number(item.number ?? item.episodeNumber) ?? 0,
|
||||
seasonNumber: number(item.seasonNumber) ?? seasonNumber,
|
||||
title: localized(item.name ?? item.title),
|
||||
overview: localized(item.synopsis ?? item.overview, item.description),
|
||||
...(text(item.posterUrl ?? item.stillUrl) ? { posterUrl: text(item.posterUrl ?? item.stillUrl) } : {}),
|
||||
...(number(item.durationSeconds ?? item.runtimeSeconds) !== undefined
|
||||
? { durationSeconds: number(item.durationSeconds ?? item.runtimeSeconds) }
|
||||
: {}),
|
||||
published: item.published === undefined ? true : boolean(item.published),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSeason(input: unknown): SeasonItem {
|
||||
const item = record(input)
|
||||
const seasonNumber = number(item.number ?? item.seasonNumber) ?? 0
|
||||
return {
|
||||
number: seasonNumber,
|
||||
title: localized(item.title, `Season ${seasonNumber}`),
|
||||
episodes: array(item.episodes).map((episode) => normalizeEpisode(episode, seasonNumber)),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSubtitle(input: unknown, index: number): PlaybackSubtitleTrack {
|
||||
const item = record(input)
|
||||
const urls = record(item.urls)
|
||||
const language = text(item.language ?? item.lang) ?? 'und'
|
||||
const delivery = text(item.delivery ?? item.format)?.toUpperCase()
|
||||
const assUrl = text(item.assUrl) ?? text(urls.ass) ?? (delivery === 'ASS' || delivery === 'ASS_JASSUB' ? text(item.url) : undefined)
|
||||
const vttUrl = text(item.vttUrl) ?? text(urls.vtt) ?? (delivery === 'VTT' || delivery === 'WEBVTT' ? text(item.url) : undefined)
|
||||
return {
|
||||
id: text(item.id) ?? `subtitle-${index}`,
|
||||
language,
|
||||
label: text(item.label) ?? language.toUpperCase(),
|
||||
default: boolean(item.default ?? item.isDefault),
|
||||
forced: boolean(item.forced ?? item.isForced),
|
||||
...(assUrl ? { assUrl } : {}),
|
||||
...(vttUrl ? { vttUrl } : {}),
|
||||
fonts: array(item.fontUrls ?? item.fonts).flatMap((font) => (typeof font === 'string' ? [font] : [])),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeAudio(input: unknown, index: number): PlaybackAudioTrack {
|
||||
const item = record(input)
|
||||
const language = text(item.language ?? item.lang) ?? 'und'
|
||||
return {
|
||||
id: text(item.id) ?? `audio-${index}`,
|
||||
language,
|
||||
label: text(item.label ?? item.name) ?? language.toUpperCase(),
|
||||
default: boolean(item.default ?? item.isDefault),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeState(value: unknown): PlaybackState {
|
||||
const state = (text(value) ?? 'FAILED').toUpperCase()
|
||||
if (state === 'READY' || state === 'PREPARING' || state === 'UNSUPPORTED_CLIENT') return state
|
||||
if (state === 'PENDING' || state === 'BUILDING' || state === 'QUEUED') return 'PREPARING'
|
||||
return 'FAILED'
|
||||
}
|
||||
|
||||
export function normalizePlaybackSession(input: unknown): PlaybackSession {
|
||||
const source = record(input)
|
||||
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
|
||||
const trackObject = record(payload.tracks)
|
||||
const mixedTracks = array(payload.tracks)
|
||||
const id = text(payload.id) ?? text(payload.sessionId) ?? ''
|
||||
const manifestUrl = text(payload.manifestUrl) ?? text(payload.masterPlaylistUrl) ?? text(payload.url)
|
||||
const subtitleInputs = array(payload.subtitles ?? payload.subtitleTracks ?? trackObject.subtitles)
|
||||
const audioInputs = array(payload.audioTracks ?? payload.audio ?? trackObject.audio)
|
||||
if (!subtitleInputs.length) {
|
||||
subtitleInputs.push(...mixedTracks.filter((track) => {
|
||||
const kind = text(record(track).kind ?? record(track).type)?.toUpperCase()
|
||||
return kind === 'SUBTITLE' || kind === 'TEXT'
|
||||
}))
|
||||
}
|
||||
if (!audioInputs.length) {
|
||||
audioInputs.push(...mixedTracks.filter((track) => text(record(track).kind ?? record(track).type)?.toUpperCase() === 'AUDIO'))
|
||||
}
|
||||
const normalizedSubtitles = subtitleInputs.map(normalizeSubtitle)
|
||||
const mergedSubtitles = [...normalizedSubtitles.reduce((tracks, track) => {
|
||||
const key = track.id.replace(/[-_:]?(ass|webvtt|vtt)$/i, '') || track.language
|
||||
const existing = tracks.get(key) ?? [...tracks.values()].find((candidate) => candidate.language === track.language)
|
||||
if (existing) {
|
||||
if (track.assUrl) existing.assUrl = track.assUrl
|
||||
if (track.vttUrl) existing.vttUrl = track.vttUrl
|
||||
existing.fonts = [...new Set([...existing.fonts, ...track.fonts])]
|
||||
} else {
|
||||
tracks.set(key, track)
|
||||
}
|
||||
return tracks
|
||||
}, new Map<string, PlaybackSubtitleTrack>()).values()]
|
||||
|
||||
return {
|
||||
id,
|
||||
state: normalizeState(payload.state ?? payload.status),
|
||||
mediaItemId: text(payload.mediaItemId) ?? '',
|
||||
...(manifestUrl ? { manifestUrl } : {}),
|
||||
...(number(payload.durationSeconds ?? payload.duration) !== undefined
|
||||
? { durationSeconds: number(payload.durationSeconds ?? payload.duration) }
|
||||
: {}),
|
||||
pollAfterMs: Math.max(500, number(payload.pollAfterMs) ?? 1_500),
|
||||
...(number(payload.progress ?? payload.progressPercent) !== undefined
|
||||
? { progress: number(payload.progress ?? payload.progressPercent) }
|
||||
: {}),
|
||||
...(text(payload.message) ? { message: text(payload.message) } : {}),
|
||||
...(text(payload.reasonCode ?? payload.code) ? { reasonCode: text(payload.reasonCode ?? payload.code) } : {}),
|
||||
...(text(payload.expiresAt) ? { expiresAt: text(payload.expiresAt) } : {}),
|
||||
...(text(payload.videoCodec) ? { videoCodec: text(payload.videoCodec) } : {}),
|
||||
...(text(payload.audioCodec) ? { audioCodec: text(payload.audioCodec) } : {}),
|
||||
subtitles: mergedSubtitles,
|
||||
audioTracks: audioInputs.map(normalizeAudio),
|
||||
}
|
||||
}
|
||||
|
||||
async function request(path: string, init: RequestInit = {}): Promise<unknown> {
|
||||
const headers = new Headers(init.headers)
|
||||
if (init.body && !headers.has('content-type')) headers.set('content-type', 'application/json')
|
||||
headers.set('accept', 'application/json')
|
||||
|
||||
const response = await fetch(`${API_BASE}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
credentials: 'include',
|
||||
})
|
||||
|
||||
const contentType = response.headers.get('content-type') ?? ''
|
||||
const body: unknown = response.status === 204
|
||||
? undefined
|
||||
: contentType.includes('application/json')
|
||||
? await response.json()
|
||||
: await response.text()
|
||||
|
||||
if (!response.ok) {
|
||||
const outerError = record(body)
|
||||
const error = Object.keys(record(outerError.error)).length ? record(outerError.error) : outerError
|
||||
throw new ApiError(
|
||||
text(error.message) ?? text(error.error) ?? `Request failed (${response.status})`,
|
||||
response.status,
|
||||
text(error.code ?? error.reasonCode),
|
||||
)
|
||||
}
|
||||
|
||||
return body
|
||||
}
|
||||
|
||||
function queryString(params: Record<string, string | number | undefined>): string {
|
||||
const query = new URLSearchParams()
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== '') query.set(key, String(value))
|
||||
})
|
||||
const encoded = query.toString()
|
||||
return encoded ? `?${encoded}` : ''
|
||||
}
|
||||
|
||||
function withSignal(signal: AbortSignal | undefined, init: RequestInit = {}): RequestInit {
|
||||
return signal ? { ...init, signal } : init
|
||||
}
|
||||
|
||||
export const api = {
|
||||
async catalog(options: { cursor?: string; limit?: number; kind?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
|
||||
const body = await request(`/catalog${queryString({ ...options })}`, withSignal(signal))
|
||||
const source = record(body)
|
||||
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
|
||||
const rawItems = Array.isArray(body) ? body : array(payload.items ?? payload.results)
|
||||
const nextCursor = text(payload.nextCursor ?? record(payload.pagination).nextCursor)
|
||||
const total = number(payload.total ?? record(payload.pagination).total)
|
||||
return {
|
||||
items: rawItems.map(normalizeCatalogItem).filter((item) => item.id),
|
||||
...(nextCursor ? { nextCursor } : {}),
|
||||
...(total !== undefined ? { total } : {}),
|
||||
}
|
||||
},
|
||||
|
||||
async search(term: string, signal?: AbortSignal): Promise<CatalogPage> {
|
||||
const body = await request(`/search${queryString({ q: term, limit: 40 })}`, withSignal(signal))
|
||||
const source = record(body)
|
||||
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
|
||||
const rawItems = Array.isArray(body) ? body : array(payload.items ?? payload.results)
|
||||
return {
|
||||
items: rawItems.map(normalizeCatalogItem).filter((item) => item.id),
|
||||
...(number(payload.total) !== undefined ? { total: number(payload.total) } : {}),
|
||||
}
|
||||
},
|
||||
|
||||
async title(slug: string, signal?: AbortSignal): Promise<TitleDetail> {
|
||||
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 } : {}),
|
||||
}
|
||||
},
|
||||
|
||||
async createPlaybackSession(
|
||||
mediaItemId: string,
|
||||
clientCapabilities: ClientCapabilities,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PlaybackSession> {
|
||||
const body = await request('/playback-sessions', withSignal(signal, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mediaItemId, clientCapabilities }),
|
||||
}))
|
||||
const session = normalizePlaybackSession(body)
|
||||
return { ...session, mediaItemId: session.mediaItemId || mediaItemId }
|
||||
},
|
||||
|
||||
async playbackSession(id: string, signal?: AbortSignal): Promise<PlaybackSession> {
|
||||
return normalizePlaybackSession(await request(`/playback-sessions/${encodeURIComponent(id)}`, withSignal(signal)))
|
||||
},
|
||||
|
||||
async clientEvent(event: Record<string, unknown>): Promise<void> {
|
||||
await request('/client-events', { method: 'POST', body: JSON.stringify(event), keepalive: true })
|
||||
},
|
||||
|
||||
async adminSession(signal?: AbortSignal): Promise<{ authenticated: boolean; name?: string }> {
|
||||
const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY)
|
||||
if (!csrfToken) return { authenticated: false }
|
||||
try {
|
||||
await request('/admin/jobs', withSignal(signal))
|
||||
const email = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_EMAIL_KEY) ?? undefined
|
||||
return { authenticated: true, ...(email ? { name: email } : {}) }
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) return { authenticated: false }
|
||||
throw error
|
||||
}
|
||||
},
|
||||
|
||||
async adminLogin(email: string, password: string, totp?: string): Promise<void> {
|
||||
const body = record(await request('/admin/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password, ...(totp ? { totp } : {}) }),
|
||||
}))
|
||||
const csrfToken = text(body.csrfToken)
|
||||
if (!csrfToken) throw new ApiError('Administrator login did not return a CSRF token', 500, 'CSRF_TOKEN_MISSING')
|
||||
if (typeof sessionStorage !== 'undefined') {
|
||||
sessionStorage.setItem(ADMIN_CSRF_KEY, csrfToken)
|
||||
sessionStorage.setItem(ADMIN_EMAIL_KEY, text(record(body.admin).email) ?? email)
|
||||
}
|
||||
},
|
||||
|
||||
async adminLogout(): Promise<void> {
|
||||
const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY)
|
||||
try {
|
||||
await request('/admin/logout', {
|
||||
method: 'POST',
|
||||
...(csrfToken ? { headers: { 'x-csrf-token': csrfToken } } : {}),
|
||||
})
|
||||
} finally {
|
||||
if (typeof sessionStorage !== 'undefined') {
|
||||
sessionStorage.removeItem(ADMIN_CSRF_KEY)
|
||||
sessionStorage.removeItem(ADMIN_EMAIL_KEY)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async adminDashboard(signal?: AbortSignal): Promise<AdminDashboard> {
|
||||
const [jobsBody, cacheBody, catalogBody] = await Promise.all([
|
||||
request('/admin/jobs', withSignal(signal)),
|
||||
request('/admin/cache', withSignal(signal)),
|
||||
request('/catalog?limit=100', withSignal(signal)),
|
||||
])
|
||||
const jobsPayload = record(jobsBody)
|
||||
const cache = record(cacheBody)
|
||||
const catalog = record(catalogBody)
|
||||
const jobs: AdminJob[] = array(jobsPayload.items ?? jobsPayload.jobs).map((input, index) => {
|
||||
const item = record(input)
|
||||
const rawProgress = number(item.progress)
|
||||
return {
|
||||
id: text(item.id) ?? `job-${index}`,
|
||||
type: text(item.type) ?? 'UNKNOWN',
|
||||
state: text(item.state ?? item.status) ?? 'UNKNOWN',
|
||||
...(rawProgress !== undefined ? { progress: rawProgress <= 1 ? rawProgress * 100 : rawProgress } : {}),
|
||||
...(text(item.message ?? item.error) ? { message: text(item.message ?? item.error) } : {}),
|
||||
...(text(item.createdAt) ? { createdAt: text(item.createdAt) } : {}),
|
||||
}
|
||||
})
|
||||
const catalogItems = array(catalog.items)
|
||||
return {
|
||||
catalogCount: catalogItems.length,
|
||||
publishedCount: catalogItems.filter((item) => record(item).playable === true).length,
|
||||
reviewCount: 0,
|
||||
activeJobs: jobs.filter((job) => job.state === 'RUNNING' || job.state === 'QUEUED').length,
|
||||
...(number(cache.usedBytes) !== undefined
|
||||
? { cacheUsedBytes: number(cache.usedBytes) }
|
||||
: {}),
|
||||
...(number(cache.maxBytes) !== undefined
|
||||
? { cacheCapacityBytes: number(cache.maxBytes) }
|
||||
: {}),
|
||||
jobs,
|
||||
}
|
||||
},
|
||||
|
||||
async startScan(): Promise<{ jobId?: string }> {
|
||||
const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY)
|
||||
if (!csrfToken) throw new ApiError('Administrator session must be renewed', 401, 'ADMIN_SESSION_REQUIRED')
|
||||
const body = record(await request('/admin/scans', {
|
||||
method: 'POST',
|
||||
headers: { 'x-csrf-token': csrfToken },
|
||||
body: JSON.stringify({ full: false }),
|
||||
}))
|
||||
const jobId = text(body.id ?? body.jobId ?? record(body.data).jobId)
|
||||
return { ...(jobId ? { jobId } : {}) }
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
import BrandMark from '@/components/BrandMark.vue'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { useUiStore } from '@/stores/ui'
|
||||
|
||||
const ui = useUiStore()
|
||||
const router = useRouter()
|
||||
const { language, t } = useI18n()
|
||||
const searchTerm = ref('')
|
||||
|
||||
function submitSearch() {
|
||||
const query = searchTerm.value.trim()
|
||||
void router.push({ name: 'search', query: query ? { q: query } : {} })
|
||||
}
|
||||
|
||||
function toggleLanguage() {
|
||||
void ui.setLanguage(language.value === 'fa' ? 'en' : 'fa')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="app-header">
|
||||
<RouterLink class="brand focus-ring" data-tv-focus data-focus-id="nav-home" to="/" :aria-label="t('home')">
|
||||
<BrandMark />
|
||||
<span class="brand-wordmark" aria-hidden="true">
|
||||
<span class="brand-easy">Easy</span><strong>Stream</strong>
|
||||
</span>
|
||||
</RouterLink>
|
||||
|
||||
<nav class="primary-nav" :aria-label="t('home')">
|
||||
<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">
|
||||
{{ t('search') }}
|
||||
</RouterLink>
|
||||
</nav>
|
||||
|
||||
<form 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"
|
||||
data-tv-focus
|
||||
data-focus-id="header-search"
|
||||
:aria-label="t('search')"
|
||||
:placeholder="t('searchPlaceholder')"
|
||||
/>
|
||||
</form>
|
||||
|
||||
<button
|
||||
class="language-button focus-ring"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
data-focus-id="language"
|
||||
:aria-label="t('language')"
|
||||
@click="toggleLanguage"
|
||||
>
|
||||
{{ t('switchLanguage') }}
|
||||
</button>
|
||||
</header>
|
||||
</template>
|
||||
@@ -0,0 +1,17 @@
|
||||
import { mount } from '@vue/test-utils'
|
||||
|
||||
import BrandMark from './BrandMark.vue'
|
||||
|
||||
describe('BrandMark', () => {
|
||||
it('keeps SVG paint references unique across multiple instances', () => {
|
||||
const wrapper = mount({
|
||||
components: { BrandMark },
|
||||
template: '<div><BrandMark /><BrandMark /></div>',
|
||||
})
|
||||
const ids = wrapper.findAll('linearGradient').map((gradient) => gradient.attributes('id'))
|
||||
|
||||
expect(new Set(ids).size).toBe(4)
|
||||
expect(wrapper.findAll('svg')).toHaveLength(2)
|
||||
expect(wrapper.findAll('svg').every((svg) => svg.attributes('aria-hidden') === 'true')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
import { useId } from 'vue'
|
||||
|
||||
const gradientId = `brand-gold-${useId()}`
|
||||
const shineId = `brand-shine-${useId()}`
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<svg
|
||||
class="brand-symbol"
|
||||
viewBox="0 0 64 64"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<defs>
|
||||
<linearGradient :id="gradientId" x1="10" y1="7" x2="54" y2="58" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#FFE29A" />
|
||||
<stop offset="0.46" stop-color="#F5BD43" />
|
||||
<stop offset="1" stop-color="#D98A08" />
|
||||
</linearGradient>
|
||||
<linearGradient :id="shineId" x1="16" y1="11" x2="43" y2="49" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#FFF5D5" stop-opacity="0.82" />
|
||||
<stop offset="1" stop-color="#FFF5D5" stop-opacity="0" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="18" fill="#111722" />
|
||||
<rect x="5" y="5" width="54" height="54" rx="15" :fill="`url(#${gradientId})`" />
|
||||
<path d="M18 20.5c0-3.04 2.46-5.5 5.5-5.5h17.75a5.5 5.5 0 0 1 4.8 2.82l5.46 9.78a9 9 0 0 1 0 8.8l-5.46 9.78a5.5 5.5 0 0 1-4.8 2.82H23.5a5.5 5.5 0 0 1-5.5-5.5v-23Z" fill="#111722" />
|
||||
<path d="m30 24.4 12.2 7.6L30 39.6V24.4Z" fill="#FFF8E8" />
|
||||
<path d="M13.5 23.5h7M11 32h9.5M13.5 40.5h7" fill="none" stroke="#111722" stroke-width="3.5" stroke-linecap="round" />
|
||||
<path d="M17 12.5h18c8 0 13.2 4.4 16 10.5" fill="none" :stroke="`url(#${shineId})`" stroke-width="2.5" stroke-linecap="round" />
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{ label: string }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="center-state" role="status" aria-live="polite">
|
||||
<span class="spinner" aria-hidden="true" />
|
||||
<p>{{ label }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,54 @@
|
||||
import { createPinia } from 'pinia'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import MediaCard from '@/components/MediaCard.vue'
|
||||
import { usePlayerStore } from '@/stores/player'
|
||||
import type { CatalogItem } from '@/types'
|
||||
|
||||
const item: CatalogItem = {
|
||||
id: 'title-1',
|
||||
mediaItemId: 'media-1',
|
||||
slug: 'sample-title',
|
||||
kind: 'MOVIE',
|
||||
title: { fa: 'فیلم نمونه', en: 'Sample movie' },
|
||||
overview: {},
|
||||
playable: true,
|
||||
year: 2026,
|
||||
}
|
||||
|
||||
describe('MediaCard', () => {
|
||||
it('starts playback directly from the main card action', async () => {
|
||||
const pinia = createPinia()
|
||||
const start = vi.fn()
|
||||
const store = usePlayerStore(pinia)
|
||||
store.register({ start, close: vi.fn() })
|
||||
const wrapper = mount(MediaCard, {
|
||||
props: { item },
|
||||
global: {
|
||||
plugins: [pinia],
|
||||
stubs: {
|
||||
RouterLink: { template: '<a><slot /></a>' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await wrapper.get('.media-card-play').trigger('click')
|
||||
|
||||
expect(start).toHaveBeenCalledWith(expect.objectContaining({ mediaItemId: 'media-1', title: 'فیلم نمونه' }))
|
||||
expect(store.visible).toBe(true)
|
||||
})
|
||||
|
||||
it('disables direct play for unpublished media', () => {
|
||||
const pinia = createPinia()
|
||||
const wrapper = mount(MediaCard, {
|
||||
props: { item: { ...item, playable: false } },
|
||||
global: {
|
||||
plugins: [pinia],
|
||||
stubs: { RouterLink: { template: '<a><slot /></a>' } },
|
||||
},
|
||||
})
|
||||
|
||||
expect(wrapper.get('.media-card-play').attributes('disabled')).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { useI18n } from '@/i18n'
|
||||
import { usePlayerStore } from '@/stores/player'
|
||||
import type { CatalogItem } from '@/types'
|
||||
|
||||
const props = defineProps<{
|
||||
item: CatalogItem
|
||||
progress?: number | undefined
|
||||
}>()
|
||||
|
||||
const player = usePlayerStore()
|
||||
const { localize, t } = useI18n()
|
||||
const title = computed(() => localize(props.item.title, props.item.slug))
|
||||
const effectiveProgress = computed(() => props.progress ?? props.item.progress ?? 0)
|
||||
|
||||
function play() {
|
||||
if (!props.item.playable || !props.item.mediaItemId) return
|
||||
player.play({
|
||||
mediaItemId: props.item.mediaItemId,
|
||||
title: title.value,
|
||||
...(props.item.posterUrl ? { posterUrl: props.item.posterUrl } : {}),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="media-card" :class="{ 'is-unavailable': !item.playable }">
|
||||
<button
|
||||
class="media-card-play focus-ring"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
:data-focus-id="`media-${item.id}`"
|
||||
:disabled="!item.playable"
|
||||
:aria-label="`${effectiveProgress > 0 ? t('resume') : t('play')}: ${title}`"
|
||||
@click="play"
|
||||
>
|
||||
<img v-if="item.posterUrl" :src="item.posterUrl" alt="" loading="lazy" />
|
||||
<div v-else class="poster-placeholder" aria-hidden="true">
|
||||
<span>{{ title.slice(0, 1) }}</span>
|
||||
</div>
|
||||
<span class="card-gradient" aria-hidden="true" />
|
||||
<span class="card-play-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
|
||||
</span>
|
||||
<span v-if="!item.playable" class="availability-badge">{{ t('unavailable') }}</span>
|
||||
<span v-if="effectiveProgress > 0" class="progress-track" aria-hidden="true">
|
||||
<span :style="{ width: `${Math.min(100, Math.max(0, effectiveProgress))}%` }" />
|
||||
</span>
|
||||
</button>
|
||||
<div class="card-copy">
|
||||
<h3>{{ title }}</h3>
|
||||
<div class="card-meta">
|
||||
<span v-if="item.year">{{ item.year }}</span>
|
||||
<span>{{ item.kind === 'SERIES' ? t('series') : t('movies') }}</span>
|
||||
</div>
|
||||
<RouterLink
|
||||
class="card-info focus-ring"
|
||||
data-tv-focus
|
||||
:data-focus-id="`info-${item.id}`"
|
||||
:to="{ name: 'title', params: { slug: item.slug } }"
|
||||
>
|
||||
{{ t('details') }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
@@ -0,0 +1,713 @@
|
||||
<script setup lang="ts">
|
||||
import vazirmatnArabicUrl from '@fontsource/vazirmatn/files/vazirmatn-arabic-400-normal.woff2?url'
|
||||
import vazirmatnLatinUrl from '@fontsource/vazirmatn/files/vazirmatn-latin-400-normal.woff2?url'
|
||||
import Hls, { Events, type ErrorData } from 'hls.js'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
|
||||
import { api } from '@/api/client'
|
||||
import { useSpatialNavigation } from '@/composables/spatial-navigation'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { readProgress, writeProgress } from '@/storage/viewer-db'
|
||||
import { type PlayRequest, usePlayerStore } from '@/stores/player'
|
||||
import { useUiStore } from '@/stores/ui'
|
||||
import type {
|
||||
ClientCapabilities,
|
||||
PlaybackAudioTrack,
|
||||
PlaybackSession,
|
||||
PlaybackSubtitleTrack,
|
||||
SubtitleDelivery,
|
||||
} from '@/types'
|
||||
|
||||
type ViewState = 'IDLE' | 'REQUESTING' | 'PREPARING' | 'BUFFERING' | 'PLAYING' | 'UNSUPPORTED' | 'FAILED'
|
||||
type AssRenderer = { destroy: () => void; ready?: Promise<unknown> }
|
||||
|
||||
const shell = ref<HTMLElement | null>(null)
|
||||
const video = ref<HTMLVideoElement | null>(null)
|
||||
const player = usePlayerStore()
|
||||
const ui = useUiStore()
|
||||
const { t } = useI18n()
|
||||
const state = ref<ViewState>('IDLE')
|
||||
const message = ref('')
|
||||
const reasonCode = ref('')
|
||||
const preparationProgress = ref<number | undefined>()
|
||||
const paused = ref(true)
|
||||
const needsGesture = ref(false)
|
||||
const currentTime = ref(0)
|
||||
const duration = ref(0)
|
||||
const buffered = ref(0)
|
||||
const controlsVisible = ref(true)
|
||||
const menu = ref<'subtitles' | 'audio' | null>(null)
|
||||
const session = ref<PlaybackSession | null>(null)
|
||||
const selectedSubtitle = ref('off')
|
||||
const selectedAudio = ref('')
|
||||
const subtitleDelivery = ref<SubtitleDelivery>('OFF')
|
||||
const currentRequest = ref<PlayRequest | null>(null)
|
||||
const fullscreen = ref(false)
|
||||
const rootVisible = computed(() => player.visible)
|
||||
const isBusy = computed(() => state.value === 'REQUESTING' || state.value === 'PREPARING' || state.value === 'BUFFERING')
|
||||
const canSeek = computed(() => Number.isFinite(duration.value) && duration.value > 0)
|
||||
|
||||
let hls: Hls | undefined
|
||||
let assRenderer: AssRenderer | undefined
|
||||
let requestController: AbortController | undefined
|
||||
let requestSequence = 0
|
||||
let hideControlsTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let lastProgressWrite = 0
|
||||
let returnFocus: HTMLElement | null = null
|
||||
|
||||
function supportsAssRendering(): boolean {
|
||||
if (typeof window === 'undefined') return false
|
||||
const videoPrototype = typeof HTMLVideoElement === 'undefined' ? undefined : HTMLVideoElement.prototype
|
||||
return typeof WebAssembly !== 'undefined'
|
||||
&& typeof TextDecoder !== 'undefined'
|
||||
&& typeof Worker !== 'undefined'
|
||||
&& typeof OffscreenCanvas !== 'undefined'
|
||||
&& typeof fetch !== 'undefined'
|
||||
&& Boolean(videoPrototype && ('requestVideoFrameCallback' in videoPrototype || 'getVideoPlaybackQuality' in videoPrototype))
|
||||
}
|
||||
|
||||
function detectClientCapabilities(element: HTMLVideoElement): ClientCapabilities {
|
||||
const nativeHls = Boolean(
|
||||
element.canPlayType('application/vnd.apple.mpegurl')
|
||||
|| element.canPlayType('application/x-mpegURL'),
|
||||
)
|
||||
const mse = typeof MediaSource !== 'undefined'
|
||||
const codec = 'video/mp4; codecs="avc1.64001f,mp4a.40.2"'
|
||||
const h264Aac = mse && typeof MediaSource.isTypeSupported === 'function'
|
||||
? MediaSource.isTypeSupported(codec)
|
||||
: nativeHls
|
||||
return {
|
||||
nativeHls,
|
||||
mse,
|
||||
hlsJs: Hls.isSupported(),
|
||||
assRenderer: supportsAssRendering(),
|
||||
supportedCodecs: h264Aac ? ['avc1.64001f', 'mp4a.40.2'] : [],
|
||||
...(typeof navigator !== 'undefined' && navigator.userAgent ? { userAgent: navigator.userAgent.slice(0, 512) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function destroyAssRenderer() {
|
||||
try {
|
||||
assRenderer?.destroy()
|
||||
} catch {
|
||||
// Renderer teardown is best effort when a worker has already failed.
|
||||
}
|
||||
assRenderer = undefined
|
||||
}
|
||||
|
||||
function removeExternalTracks() {
|
||||
const element = video.value
|
||||
if (!element) return
|
||||
element.querySelectorAll('track[data-easy-stream]').forEach((track) => track.remove())
|
||||
}
|
||||
|
||||
function destroyMedia(clearSource = true) {
|
||||
hls?.destroy()
|
||||
hls = undefined
|
||||
destroyAssRenderer()
|
||||
removeExternalTracks()
|
||||
if (clearSource && video.value) {
|
||||
video.value.pause()
|
||||
video.value.removeAttribute('src')
|
||||
video.value.load()
|
||||
}
|
||||
}
|
||||
|
||||
function wait(milliseconds: number, signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(resolve, milliseconds)
|
||||
signal.addEventListener('abort', () => {
|
||||
clearTimeout(timer)
|
||||
reject(new DOMException('Aborted', 'AbortError'))
|
||||
}, { once: true })
|
||||
})
|
||||
}
|
||||
|
||||
function recordClientEvent(name: string, details: Record<string, unknown> = {}) {
|
||||
void api.clientEvent({
|
||||
name,
|
||||
mediaItemId: currentRequest.value?.mediaItemId,
|
||||
sessionId: session.value?.id,
|
||||
occurredAt: new Date().toISOString(),
|
||||
details,
|
||||
}).catch(() => undefined)
|
||||
}
|
||||
|
||||
async function saveProgress(force = false) {
|
||||
const element = video.value
|
||||
const request = currentRequest.value
|
||||
if (!element || !request || !Number.isFinite(element.duration) || element.duration <= 0) return
|
||||
const now = Date.now()
|
||||
if (!force && now - lastProgressWrite < 10_000) return
|
||||
lastProgressWrite = now
|
||||
const ratio = element.currentTime / element.duration
|
||||
await writeProgress({
|
||||
mediaItemId: request.mediaItemId,
|
||||
positionSeconds: Math.max(0, element.currentTime),
|
||||
durationSeconds: element.duration,
|
||||
updatedAt: now,
|
||||
completed: ratio >= 0.95,
|
||||
})
|
||||
}
|
||||
|
||||
function updateTimeline() {
|
||||
const element = video.value
|
||||
if (!element) return
|
||||
currentTime.value = Number.isFinite(element.currentTime) ? element.currentTime : 0
|
||||
duration.value = Number.isFinite(element.duration) ? element.duration : session.value?.durationSeconds ?? 0
|
||||
if (element.buffered.length && duration.value > 0) {
|
||||
buffered.value = (element.buffered.end(element.buffered.length - 1) / duration.value) * 100
|
||||
}
|
||||
void saveProgress()
|
||||
}
|
||||
|
||||
function showControls() {
|
||||
controlsVisible.value = true
|
||||
if (hideControlsTimer) clearTimeout(hideControlsTimer)
|
||||
if (!paused.value && !menu.value) {
|
||||
hideControlsTimer = setTimeout(() => {
|
||||
controlsVisible.value = false
|
||||
}, 4_000)
|
||||
}
|
||||
}
|
||||
|
||||
async function requestFullscreen() {
|
||||
const element = shell.value
|
||||
if (!element || !document.fullscreenEnabled || document.fullscreenElement) return
|
||||
try {
|
||||
await element.requestFullscreen({ navigationUI: 'hide' })
|
||||
} catch {
|
||||
// Fullscreen is opportunistic; the fixed player still fills the viewport.
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleFullscreen() {
|
||||
if (document.fullscreenElement) {
|
||||
try { await document.exitFullscreen() } catch { /* browser is already leaving fullscreen */ }
|
||||
return
|
||||
}
|
||||
await requestFullscreen()
|
||||
}
|
||||
|
||||
async function applyResumePosition() {
|
||||
const element = video.value
|
||||
const request = currentRequest.value
|
||||
if (!element || !request) return
|
||||
const progress = await readProgress(request.mediaItemId)
|
||||
if (!progress || progress.completed || progress.positionSeconds < 60) return
|
||||
const knownDuration = Number.isFinite(element.duration) ? element.duration : progress.durationSeconds
|
||||
if (knownDuration > 0 && progress.positionSeconds / knownDuration < 0.95) {
|
||||
element.currentTime = Math.min(progress.positionSeconds, Math.max(0, knownDuration - 2))
|
||||
}
|
||||
}
|
||||
|
||||
async function beginPlayback() {
|
||||
const element = video.value
|
||||
if (!element) return
|
||||
await applyResumePosition()
|
||||
try {
|
||||
await element.play()
|
||||
needsGesture.value = false
|
||||
} catch {
|
||||
needsGesture.value = true
|
||||
showControls()
|
||||
}
|
||||
}
|
||||
|
||||
function selectHlsAudio(language: string) {
|
||||
if (!hls) return
|
||||
const index = hls.audioTracks.findIndex((track) => track.lang === language || track.name === language)
|
||||
if (index >= 0) hls.audioTrack = index
|
||||
}
|
||||
|
||||
function selectNativeAudio(language: string) {
|
||||
const element = video.value as (HTMLVideoElement & { audioTracks?: { length: number; [index: number]: { language: string; enabled: boolean } } }) | null
|
||||
if (!element?.audioTracks) return
|
||||
for (let index = 0; index < element.audioTracks.length; index += 1) {
|
||||
const track = element.audioTracks[index]
|
||||
if (track) track.enabled = track.language === language
|
||||
}
|
||||
}
|
||||
|
||||
async function chooseAudio(track: PlaybackAudioTrack) {
|
||||
selectedAudio.value = track.id
|
||||
selectHlsAudio(track.language)
|
||||
selectNativeAudio(track.language)
|
||||
await ui.setAudioLanguage(track.language)
|
||||
menu.value = null
|
||||
}
|
||||
|
||||
function enableVtt(track: PlaybackSubtitleTrack): boolean {
|
||||
const element = video.value
|
||||
if (!element || !track.vttUrl) return false
|
||||
removeExternalTracks()
|
||||
const trackElement = document.createElement('track')
|
||||
trackElement.dataset.easyStream = 'true'
|
||||
trackElement.kind = 'subtitles'
|
||||
trackElement.src = track.vttUrl
|
||||
trackElement.srclang = track.language
|
||||
trackElement.label = track.label
|
||||
trackElement.default = true
|
||||
element.append(trackElement)
|
||||
trackElement.addEventListener('load', () => {
|
||||
if (trackElement.track) trackElement.track.mode = 'showing'
|
||||
}, { once: true })
|
||||
subtitleDelivery.value = 'WEBVTT'
|
||||
return true
|
||||
}
|
||||
|
||||
async function enableAss(track: PlaybackSubtitleTrack): Promise<boolean> {
|
||||
const element = video.value
|
||||
if (!element || !track.assUrl || !supportsAssRendering()) return false
|
||||
try {
|
||||
const { default: JASSUB } = await import('jassub')
|
||||
const renderer = new JASSUB({
|
||||
video: element,
|
||||
subUrl: track.assUrl,
|
||||
fonts: [...new Set([...track.fonts, vazirmatnArabicUrl, vazirmatnLatinUrl])],
|
||||
defaultFont: 'Vazirmatn',
|
||||
queryFonts: 'local',
|
||||
}) as AssRenderer
|
||||
if (renderer.ready) await renderer.ready
|
||||
assRenderer = renderer
|
||||
subtitleDelivery.value = 'ASS_JASSUB'
|
||||
return true
|
||||
} catch (error) {
|
||||
recordClientEvent('subtitle_fallback', { reason: error instanceof Error ? error.message : 'JASSUB_INIT_FAILED' })
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function chooseSubtitle(track?: PlaybackSubtitleTrack) {
|
||||
destroyAssRenderer()
|
||||
removeExternalTracks()
|
||||
if (!track) {
|
||||
selectedSubtitle.value = 'off'
|
||||
subtitleDelivery.value = 'OFF'
|
||||
menu.value = null
|
||||
return
|
||||
}
|
||||
|
||||
selectedSubtitle.value = track.id
|
||||
const renderedAss = await enableAss(track)
|
||||
if (!renderedAss && !enableVtt(track)) {
|
||||
selectedSubtitle.value = 'off'
|
||||
subtitleDelivery.value = 'OFF'
|
||||
} else {
|
||||
await ui.setSubtitleLanguage(track.language)
|
||||
}
|
||||
menu.value = null
|
||||
}
|
||||
|
||||
function preferredSubtitle(tracks: PlaybackSubtitleTrack[]): PlaybackSubtitleTrack | undefined {
|
||||
return tracks.find((track) => track.language === ui.preferences.subtitleLanguage)
|
||||
?? tracks.find((track) => track.default && !track.forced)
|
||||
?? tracks.find((track) => track.language === 'fa' || track.language.startsWith('fa-'))
|
||||
?? tracks.find((track) => track.language === 'en' || track.language.startsWith('en-'))
|
||||
}
|
||||
|
||||
function preferredAudio(tracks: PlaybackAudioTrack[]): PlaybackAudioTrack | undefined {
|
||||
return tracks.find((track) => track.language === ui.preferences.audioLanguage)
|
||||
?? tracks.find((track) => track.default)
|
||||
?? tracks[0]
|
||||
}
|
||||
|
||||
async function onManifestReady() {
|
||||
const activeSession = session.value
|
||||
if (!activeSession) return
|
||||
state.value = 'PLAYING'
|
||||
const audio = preferredAudio(activeSession.audioTracks)
|
||||
if (audio) await chooseAudio(audio)
|
||||
const subtitle = preferredSubtitle(activeSession.subtitles)
|
||||
await chooseSubtitle(subtitle)
|
||||
await beginPlayback()
|
||||
recordClientEvent('playback_started', { subtitleDelivery: subtitleDelivery.value })
|
||||
}
|
||||
|
||||
function failPlayback(error: ErrorData | string) {
|
||||
const detail = typeof error === 'string' ? error : `${error.type}:${error.details}`
|
||||
state.value = 'FAILED'
|
||||
message.value = detail
|
||||
reasonCode.value = 'PLAYER_ERROR'
|
||||
needsGesture.value = false
|
||||
recordClientEvent('fatal_player_error', { detail })
|
||||
}
|
||||
|
||||
function attachManifest(activeSession: PlaybackSession) {
|
||||
const element = video.value
|
||||
if (!element || !activeSession.manifestUrl) {
|
||||
failPlayback(activeSession.reasonCode ?? 'MANIFEST_URL_MISSING')
|
||||
return
|
||||
}
|
||||
state.value = 'BUFFERING'
|
||||
session.value = activeSession
|
||||
duration.value = activeSession.durationSeconds ?? 0
|
||||
const capabilities = detectClientCapabilities(element)
|
||||
element.volume = ui.preferences.volume
|
||||
element.muted = ui.preferences.muted
|
||||
|
||||
if (capabilities.nativeHls) {
|
||||
element.src = activeSession.manifestUrl
|
||||
element.addEventListener('loadedmetadata', () => void onManifestReady(), { once: true })
|
||||
element.addEventListener('error', () => failPlayback('NATIVE_HLS_ERROR'), { once: true })
|
||||
element.load()
|
||||
return
|
||||
}
|
||||
|
||||
if (!capabilities.hlsJs) {
|
||||
state.value = 'UNSUPPORTED'
|
||||
reasonCode.value = 'MSE_UNAVAILABLE'
|
||||
return
|
||||
}
|
||||
|
||||
hls = new Hls({
|
||||
enableWorker: true,
|
||||
lowLatencyMode: false,
|
||||
backBufferLength: 60,
|
||||
maxBufferLength: 30,
|
||||
manifestLoadingTimeOut: 20_000,
|
||||
fragLoadingTimeOut: 30_000,
|
||||
xhrSetup: (xhr) => { xhr.withCredentials = true },
|
||||
})
|
||||
hls.on(Events.MEDIA_ATTACHED, () => hls?.loadSource(activeSession.manifestUrl!))
|
||||
hls.on(Events.MANIFEST_PARSED, () => void onManifestReady())
|
||||
hls.on(Events.AUDIO_TRACKS_UPDATED, () => {
|
||||
const audio = preferredAudio(activeSession.audioTracks)
|
||||
if (audio) selectHlsAudio(audio.language)
|
||||
})
|
||||
hls.on(Events.ERROR, (_event, data) => {
|
||||
if (data.fatal) failPlayback(data)
|
||||
})
|
||||
hls.attachMedia(element)
|
||||
}
|
||||
|
||||
async function resolveSession(initial: PlaybackSession, sequence: number, signal: AbortSignal) {
|
||||
let active = initial
|
||||
while (active.state === 'PREPARING' && sequence === requestSequence) {
|
||||
session.value = active
|
||||
state.value = 'PREPARING'
|
||||
preparationProgress.value = active.progress
|
||||
message.value = active.message ?? ''
|
||||
await wait(active.pollAfterMs, signal)
|
||||
active = await api.playbackSession(active.id, signal)
|
||||
}
|
||||
if (sequence !== requestSequence) return
|
||||
session.value = active
|
||||
if (active.state === 'READY') {
|
||||
attachManifest(active)
|
||||
} else if (active.state === 'UNSUPPORTED_CLIENT') {
|
||||
state.value = 'UNSUPPORTED'
|
||||
reasonCode.value = active.reasonCode ?? 'UNSUPPORTED_CLIENT'
|
||||
message.value = active.message ?? ''
|
||||
} else {
|
||||
state.value = 'FAILED'
|
||||
reasonCode.value = active.reasonCode ?? 'PREPARATION_FAILED'
|
||||
message.value = active.message ?? ''
|
||||
}
|
||||
}
|
||||
|
||||
async function start(request: PlayRequest) {
|
||||
const element = video.value
|
||||
if (!element) return
|
||||
requestSequence += 1
|
||||
const sequence = requestSequence
|
||||
requestController?.abort()
|
||||
requestController = new AbortController()
|
||||
destroyMedia()
|
||||
currentRequest.value = request
|
||||
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
state.value = 'REQUESTING'
|
||||
message.value = ''
|
||||
reasonCode.value = ''
|
||||
preparationProgress.value = undefined
|
||||
needsGesture.value = false
|
||||
selectedSubtitle.value = 'off'
|
||||
selectedAudio.value = ''
|
||||
currentTime.value = 0
|
||||
duration.value = 0
|
||||
player.visible = true
|
||||
showControls()
|
||||
|
||||
// Both calls happen while the card activation is still the active user gesture.
|
||||
void element.play().catch(() => undefined)
|
||||
void requestFullscreen()
|
||||
await nextTick()
|
||||
shell.value?.focus({ preventScroll: true })
|
||||
|
||||
const capabilities = detectClientCapabilities(element)
|
||||
if (!capabilities.nativeHls && (!capabilities.hlsJs || capabilities.supportedCodecs.length < 2)) {
|
||||
state.value = 'UNSUPPORTED'
|
||||
reasonCode.value = 'MSE_UNAVAILABLE'
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const initial = await api.createPlaybackSession(request.mediaItemId, capabilities, requestController.signal)
|
||||
await resolveSession(initial, sequence, requestController.signal)
|
||||
} catch (error) {
|
||||
if ((error as { name?: string }).name === 'AbortError' || sequence !== requestSequence) return
|
||||
state.value = 'FAILED'
|
||||
message.value = error instanceof Error ? error.message : t('networkError')
|
||||
reasonCode.value = 'SESSION_REQUEST_FAILED'
|
||||
}
|
||||
}
|
||||
|
||||
async function close() {
|
||||
requestSequence += 1
|
||||
requestController?.abort()
|
||||
await saveProgress(true)
|
||||
destroyMedia()
|
||||
state.value = 'IDLE'
|
||||
session.value = null
|
||||
currentRequest.value = null
|
||||
player.visible = false
|
||||
menu.value = null
|
||||
if (document.fullscreenElement) {
|
||||
try { await document.exitFullscreen() } catch { /* already exiting */ }
|
||||
}
|
||||
await nextTick()
|
||||
returnFocus?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
function togglePlayback() {
|
||||
const element = video.value
|
||||
if (!element) return
|
||||
if (element.paused) {
|
||||
void element.play().then(() => { needsGesture.value = false }).catch(() => { needsGesture.value = true })
|
||||
} else {
|
||||
element.pause()
|
||||
}
|
||||
showControls()
|
||||
}
|
||||
|
||||
function seekBy(seconds: number) {
|
||||
const element = video.value
|
||||
if (!element || !canSeek.value) return
|
||||
element.currentTime = Math.min(element.duration, Math.max(0, element.currentTime + seconds))
|
||||
updateTimeline()
|
||||
showControls()
|
||||
}
|
||||
|
||||
function seekTo(event: Event) {
|
||||
const element = video.value
|
||||
const target = event.target as HTMLInputElement
|
||||
if (!element || !canSeek.value) return
|
||||
element.currentTime = Number(target.value)
|
||||
updateTimeline()
|
||||
}
|
||||
|
||||
function toggleMute() {
|
||||
const element = video.value
|
||||
if (!element) return
|
||||
element.muted = !element.muted
|
||||
void ui.setVolume(element.volume, element.muted)
|
||||
}
|
||||
|
||||
function toggleMenu(target: 'subtitles' | 'audio') {
|
||||
menu.value = menu.value === target ? null : target
|
||||
showControls()
|
||||
}
|
||||
|
||||
function formatTime(seconds: number): string {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return '00:00'
|
||||
const hours = Math.floor(seconds / 3600)
|
||||
const minutes = Math.floor((seconds % 3600) / 60)
|
||||
const remaining = Math.floor(seconds % 60)
|
||||
return hours > 0
|
||||
? `${hours}:${String(minutes).padStart(2, '0')}:${String(remaining).padStart(2, '0')}`
|
||||
: `${String(minutes).padStart(2, '0')}:${String(remaining).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function onPlayerKeydown(event: KeyboardEvent) {
|
||||
if (!rootVisible.value) return
|
||||
showControls()
|
||||
if (event.key === 'MediaPlayPause' || (event.key === ' ' && event.target === shell.value)) {
|
||||
event.preventDefault()
|
||||
togglePlayback()
|
||||
} else if (event.key === 'MediaRewind') {
|
||||
event.preventDefault()
|
||||
seekBy(-10)
|
||||
} else if (event.key === 'MediaFastForward') {
|
||||
event.preventDefault()
|
||||
seekBy(10)
|
||||
}
|
||||
}
|
||||
|
||||
const controller = { start: (request: PlayRequest) => void start(request), close: () => void close() }
|
||||
useSpatialNavigation(shell, { onBack: () => void close() })
|
||||
|
||||
onMounted(() => {
|
||||
player.register(controller)
|
||||
document.addEventListener('keydown', onPlayerKeydown)
|
||||
document.addEventListener('fullscreenchange', () => { fullscreen.value = Boolean(document.fullscreenElement) })
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
player.unregister(controller)
|
||||
document.removeEventListener('keydown', onPlayerKeydown)
|
||||
requestController?.abort()
|
||||
destroyMedia()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-show="rootVisible"
|
||||
ref="shell"
|
||||
class="player-shell"
|
||||
:class="{ 'controls-hidden': !controlsVisible }"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="currentRequest?.title ?? t('play')"
|
||||
tabindex="-1"
|
||||
@mousemove="showControls"
|
||||
@click.self="showControls"
|
||||
>
|
||||
<video
|
||||
ref="video"
|
||||
class="player-video"
|
||||
playsinline
|
||||
preload="metadata"
|
||||
crossorigin="use-credentials"
|
||||
:poster="currentRequest?.posterUrl"
|
||||
@click="togglePlayback"
|
||||
@play="paused = false; showControls()"
|
||||
@pause="paused = true; showControls(); saveProgress(true)"
|
||||
@waiting="state = 'BUFFERING'"
|
||||
@playing="state = 'PLAYING'"
|
||||
@timeupdate="updateTimeline"
|
||||
@durationchange="updateTimeline"
|
||||
@progress="updateTimeline"
|
||||
@ended="saveProgress(true)"
|
||||
@volumechange="video && ui.setVolume(video.volume, video.muted)"
|
||||
/>
|
||||
|
||||
<div v-if="isBusy" class="player-status" role="status" aria-live="polite">
|
||||
<span class="spinner large" aria-hidden="true" />
|
||||
<h2>{{ state === 'PREPARING' ? t('preparing') : t('loading') }}</h2>
|
||||
<p v-if="state === 'PREPARING'">{{ message || t('preparingHint') }}</p>
|
||||
<div v-if="preparationProgress !== undefined" class="preparing-progress">
|
||||
<span :style="{ width: `${Math.min(100, Math.max(0, preparationProgress))}%` }" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="state === 'UNSUPPORTED'" class="player-status player-error" role="alert">
|
||||
<span class="status-symbol" aria-hidden="true">!</span>
|
||||
<h2>{{ t('incompatibleTitle') }}</h2>
|
||||
<p>{{ message || t('incompatibleBody') }}</p>
|
||||
<small v-if="reasonCode">{{ reasonCode }}</small>
|
||||
<button class="primary-button large focus-ring" type="button" data-tv-focus @click="close">{{ t('close') }}</button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="state === 'FAILED'" class="player-status player-error" role="alert">
|
||||
<span class="status-symbol" aria-hidden="true">!</span>
|
||||
<h2>{{ t('playbackFailed') }}</h2>
|
||||
<p>{{ message }}</p>
|
||||
<small v-if="reasonCode">{{ reasonCode }}</small>
|
||||
<div class="hero-actions">
|
||||
<button
|
||||
v-if="currentRequest"
|
||||
class="primary-button focus-ring"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
@click="start(currentRequest)"
|
||||
>{{ t('retry') }}</button>
|
||||
<button class="secondary-button focus-ring" type="button" data-tv-focus @click="close">{{ t('close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="needsGesture && state === 'PLAYING'"
|
||||
class="gesture-play focus-ring"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
:aria-label="t('play')"
|
||||
@click="togglePlayback"
|
||||
>
|
||||
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
|
||||
<span>{{ t('pressPlay') }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="state === 'PLAYING' || state === 'BUFFERING'" class="player-topbar">
|
||||
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="t('close')" @click="close">
|
||||
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6" /></svg>
|
||||
</button>
|
||||
<strong>{{ currentRequest?.title }}</strong>
|
||||
</div>
|
||||
|
||||
<div v-if="state === 'PLAYING' || state === 'BUFFERING'" class="player-controls" @click.stop>
|
||||
<div class="timeline-wrap">
|
||||
<span>{{ formatTime(currentTime) }}</span>
|
||||
<div class="timeline">
|
||||
<span class="buffered" :style="{ width: `${buffered}%` }" aria-hidden="true" />
|
||||
<input
|
||||
type="range"
|
||||
data-tv-focus
|
||||
min="0"
|
||||
:max="duration || 0"
|
||||
step="0.25"
|
||||
:value="currentTime"
|
||||
:disabled="!canSeek"
|
||||
:aria-label="t('play')"
|
||||
@input="seekTo"
|
||||
/>
|
||||
</div>
|
||||
<span>{{ formatTime(duration) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="control-row">
|
||||
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="paused ? t('play') : t('pause')" @click="togglePlayback">
|
||||
<svg v-if="paused" aria-hidden="true" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
|
||||
<svg v-else aria-hidden="true" viewBox="0 0 24 24"><path d="M7 5h4v14H7zm6 0h4v14h-4z" /></svg>
|
||||
</button>
|
||||
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="t('seekBack')" @click="seekBy(-10)">
|
||||
<span aria-hidden="true">↶</span><small>10</small>
|
||||
</button>
|
||||
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="t('seekForward')" @click="seekBy(10)">
|
||||
<span aria-hidden="true">↷</span><small>10</small>
|
||||
</button>
|
||||
<button class="player-icon-button focus-ring" type="button" data-tv-focus aria-label="Mute" @click="toggleMute">
|
||||
<span aria-hidden="true">{{ video?.muted ? '🔇' : '🔊' }}</span>
|
||||
</button>
|
||||
|
||||
<span class="control-spacer" />
|
||||
|
||||
<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">
|
||||
<button
|
||||
v-for="track in session.audioTracks"
|
||||
:key="track.id"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
:class="{ selected: track.id === selectedAudio }"
|
||||
@click="chooseAudio(track)"
|
||||
>{{ track.label }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="session?.subtitles.length" class="control-menu-wrap">
|
||||
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('subtitles')">
|
||||
{{ t('subtitles') }}
|
||||
</button>
|
||||
<div v-if="menu === 'subtitles'" class="track-menu">
|
||||
<button type="button" data-tv-focus :class="{ selected: selectedSubtitle === 'off' }" @click="chooseSubtitle()">
|
||||
{{ t('subtitleOff') }}
|
||||
</button>
|
||||
<button
|
||||
v-for="track in session.subtitles"
|
||||
:key="track.id"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
:class="{ selected: track.id === selectedSubtitle }"
|
||||
@click="chooseSubtitle(track)"
|
||||
>{{ track.label }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="fullscreen ? t('exitFullscreen') : t('fullscreen')" @click="toggleFullscreen">
|
||||
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M4 9V4h5M4 4l6 6m10-1V4h-5m5 0-6 6M4 15v5h5m-5 0 6-6m10 1v5h-5m5 0-6-6" /></svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { moveSpatialFocus } from '@/composables/spatial-navigation'
|
||||
|
||||
function rect(left: number, top: number): DOMRect {
|
||||
return { left, top, right: left + 100, bottom: top + 60, width: 100, height: 60, x: left, y: top, toJSON: () => ({}) }
|
||||
}
|
||||
|
||||
describe('moveSpatialFocus', () => {
|
||||
it('moves to the nearest element in the requested physical direction', () => {
|
||||
const root = document.createElement('div')
|
||||
const first = document.createElement('button')
|
||||
const right = document.createElement('button')
|
||||
const below = document.createElement('button')
|
||||
for (const button of [first, right, below]) {
|
||||
button.dataset.tvFocus = ''
|
||||
root.append(button)
|
||||
}
|
||||
document.body.append(root)
|
||||
vi.spyOn(first, 'getBoundingClientRect').mockReturnValue(rect(0, 0))
|
||||
vi.spyOn(right, 'getBoundingClientRect').mockReturnValue(rect(180, 0))
|
||||
vi.spyOn(below, 'getBoundingClientRect').mockReturnValue(rect(0, 120))
|
||||
first.focus()
|
||||
|
||||
expect(moveSpatialFocus(root, 'right')).toBe(true)
|
||||
expect(document.activeElement).toBe(right)
|
||||
expect(moveSpatialFocus(root, 'down')).toBe(true)
|
||||
expect(document.activeElement).toBe(below)
|
||||
})
|
||||
|
||||
it('focuses the first TV target when focus starts outside the region', () => {
|
||||
const root = document.createElement('div')
|
||||
const button = document.createElement('button')
|
||||
button.dataset.tvFocus = ''
|
||||
root.append(button)
|
||||
document.body.append(root)
|
||||
|
||||
expect(moveSpatialFocus(root, 'down')).toBe(true)
|
||||
expect(document.activeElement).toBe(button)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import { nextTick, onBeforeUnmount, onMounted, type Ref } from 'vue'
|
||||
|
||||
type Direction = 'left' | 'right' | 'up' | 'down'
|
||||
|
||||
function isTypingTarget(target: EventTarget | null): boolean {
|
||||
return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement
|
||||
}
|
||||
|
||||
function candidates(root: HTMLElement): HTMLElement[] {
|
||||
return [...root.querySelectorAll<HTMLElement>('[data-tv-focus]:not([disabled])')]
|
||||
.filter((element) => element.offsetParent !== null && element.getAttribute('aria-hidden') !== 'true')
|
||||
}
|
||||
|
||||
function scoreCandidate(current: DOMRect, candidate: DOMRect, direction: Direction): number | undefined {
|
||||
const currentX = current.left + current.width / 2
|
||||
const currentY = current.top + current.height / 2
|
||||
const candidateX = candidate.left + candidate.width / 2
|
||||
const candidateY = candidate.top + candidate.height / 2
|
||||
const dx = candidateX - currentX
|
||||
const dy = candidateY - currentY
|
||||
|
||||
if (direction === 'left' && dx >= -1) return undefined
|
||||
if (direction === 'right' && dx <= 1) return undefined
|
||||
if (direction === 'up' && dy >= -1) return undefined
|
||||
if (direction === 'down' && dy <= 1) return undefined
|
||||
|
||||
const primary = direction === 'left' || direction === 'right' ? Math.abs(dx) : Math.abs(dy)
|
||||
const secondary = direction === 'left' || direction === 'right' ? Math.abs(dy) : Math.abs(dx)
|
||||
return primary + secondary * 2.25
|
||||
}
|
||||
|
||||
export function moveSpatialFocus(root: HTMLElement, direction: Direction): boolean {
|
||||
const focusable = candidates(root)
|
||||
if (!focusable.length) return false
|
||||
const active = document.activeElement instanceof HTMLElement && root.contains(document.activeElement)
|
||||
? document.activeElement
|
||||
: undefined
|
||||
if (!active) {
|
||||
focusable[0]?.focus()
|
||||
return true
|
||||
}
|
||||
|
||||
const currentRect = active.getBoundingClientRect()
|
||||
const ranked = focusable
|
||||
.filter((element) => element !== active)
|
||||
.map((element) => ({ element, score: scoreCandidate(currentRect, element.getBoundingClientRect(), direction) }))
|
||||
.filter((result): result is { element: HTMLElement; score: number } => result.score !== undefined)
|
||||
.sort((left, right) => left.score - right.score)
|
||||
const next = ranked[0]?.element
|
||||
if (!next) return false
|
||||
next.focus()
|
||||
next.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' })
|
||||
return true
|
||||
}
|
||||
|
||||
export function useSpatialNavigation(
|
||||
root: Ref<HTMLElement | null>,
|
||||
options: { onBack?: () => void; restoreKey?: string } = {},
|
||||
) {
|
||||
const onKeydown = (event: KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return
|
||||
const element = root.value
|
||||
if (!element || element.offsetParent === null || isTypingTarget(event.target)) return
|
||||
const directionByKey: Partial<Record<string, Direction>> = {
|
||||
ArrowLeft: 'left',
|
||||
ArrowRight: 'right',
|
||||
ArrowUp: 'up',
|
||||
ArrowDown: 'down',
|
||||
}
|
||||
const direction = directionByKey[event.key]
|
||||
if (direction && moveSpatialFocus(element, direction)) {
|
||||
event.preventDefault()
|
||||
return
|
||||
}
|
||||
if ((event.key === 'Escape' || event.key === 'BrowserBack' || event.key === 'Backspace') && options.onBack) {
|
||||
event.preventDefault()
|
||||
options.onBack()
|
||||
}
|
||||
}
|
||||
|
||||
const rememberFocus = (event: FocusEvent) => {
|
||||
const target = event.target
|
||||
if (options.restoreKey && target instanceof HTMLElement && target.dataset.focusId) {
|
||||
sessionStorage.setItem(options.restoreKey, target.dataset.focusId)
|
||||
}
|
||||
}
|
||||
|
||||
const restoreFocus = async () => {
|
||||
await nextTick()
|
||||
const element = root.value
|
||||
if (!element) return
|
||||
const id = options.restoreKey ? sessionStorage.getItem(options.restoreKey) : undefined
|
||||
const escapedId = id && typeof CSS !== 'undefined' && typeof CSS.escape === 'function' ? CSS.escape(id) : id
|
||||
const previous = escapedId ? element.querySelector<HTMLElement>(`[data-focus-id="${escapedId}"]`) : undefined
|
||||
;(previous ?? candidates(element)[0])?.focus()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('keydown', onKeydown)
|
||||
root.value?.addEventListener('focusin', rememberFocus)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('keydown', onKeydown)
|
||||
root.value?.removeEventListener('focusin', rememberFocus)
|
||||
})
|
||||
|
||||
return { restoreFocus }
|
||||
}
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_BASE_URL?: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { useUiStore } from '@/stores/ui'
|
||||
|
||||
const fa = {
|
||||
home: 'خانه',
|
||||
search: 'جستجو',
|
||||
searchPlaceholder: 'نام فیلم یا سریال…',
|
||||
admin: 'مدیریت',
|
||||
language: 'زبان',
|
||||
switchLanguage: 'English',
|
||||
featured: 'پیشنهاد برای تماشا',
|
||||
allTitles: 'همه عنوانها',
|
||||
movies: 'فیلمها',
|
||||
series: 'سریالها',
|
||||
play: 'پخش',
|
||||
resume: 'ادامه پخش',
|
||||
details: 'جزئیات',
|
||||
retry: 'تلاش دوباره',
|
||||
close: 'بستن',
|
||||
back: 'بازگشت',
|
||||
loading: 'در حال بارگذاری…',
|
||||
loadingCatalog: 'در حال آمادهکردن آرشیو…',
|
||||
emptyCatalog: 'هنوز عنوان منتشرشدهای وجود ندارد.',
|
||||
noResults: 'نتیجهای پیدا نشد.',
|
||||
networkError: 'ارتباط با سرور برقرار نشد.',
|
||||
preparing: 'فیلم برای اولین پخش آماده میشود',
|
||||
preparingHint: 'این صفحه را باز نگه دارید؛ پخش بهصورت خودکار شروع میشود.',
|
||||
incompatibleTitle: 'این مرورگر امکان پخش این ویدیو را ندارد',
|
||||
incompatibleBody: 'برای پخش از نسخه جدید Chrome یا Firefox روی دستگاهی با پشتیبانی MSE استفاده کنید.',
|
||||
playbackFailed: 'پخش ویدیو با مشکل روبهرو شد',
|
||||
pressPlay: 'برای شروع، دکمه پخش را بزنید',
|
||||
pause: 'مکث',
|
||||
seekBack: '۱۰ ثانیه عقب',
|
||||
seekForward: '۱۰ ثانیه جلو',
|
||||
fullscreen: 'تمامصفحه',
|
||||
exitFullscreen: 'خروج از تمامصفحه',
|
||||
subtitles: 'زیرنویس',
|
||||
audio: 'صدا',
|
||||
subtitleOff: 'خاموش',
|
||||
season: 'فصل',
|
||||
episode: 'قسمت',
|
||||
minutes: 'دقیقه',
|
||||
loginTitle: 'ورود مدیر',
|
||||
email: 'ایمیل',
|
||||
password: 'رمز عبور',
|
||||
totp: 'کد یکبارمصرف (اختیاری)',
|
||||
login: 'ورود',
|
||||
logout: 'خروج',
|
||||
invalidLogin: 'اطلاعات ورود پذیرفته نشد.',
|
||||
dashboard: 'وضعیت سامانه',
|
||||
catalogCount: 'کل عنوانها',
|
||||
publishedCount: 'منتشرشده',
|
||||
reviewCount: 'نیازمند بررسی',
|
||||
activeJobs: 'کارهای فعال',
|
||||
cache: 'حافظه موقت',
|
||||
recentJobs: 'کارهای اخیر',
|
||||
scanArchive: 'اسکن آرشیو',
|
||||
scanStarted: 'اسکن آرشیو در صف قرار گرفت.',
|
||||
refresh: 'بهروزرسانی',
|
||||
unavailable: 'ناموجود',
|
||||
unsupported: 'پشتیبانینشده',
|
||||
year: 'سال',
|
||||
} as const
|
||||
|
||||
const en: Record<keyof typeof fa, string> = {
|
||||
home: 'Home',
|
||||
search: 'Search',
|
||||
searchPlaceholder: 'Movie or series name…',
|
||||
admin: 'Admin',
|
||||
language: 'Language',
|
||||
switchLanguage: 'فارسی',
|
||||
featured: 'Featured',
|
||||
allTitles: 'All titles',
|
||||
movies: 'Movies',
|
||||
series: 'Series',
|
||||
play: 'Play',
|
||||
resume: 'Resume',
|
||||
details: 'Details',
|
||||
retry: 'Try again',
|
||||
close: 'Close',
|
||||
back: 'Back',
|
||||
loading: 'Loading…',
|
||||
loadingCatalog: 'Loading the archive…',
|
||||
emptyCatalog: 'No published titles yet.',
|
||||
noResults: 'No results found.',
|
||||
networkError: 'Could not reach the server.',
|
||||
preparing: 'Preparing this title for its first stream',
|
||||
preparingHint: 'Keep this screen open; playback starts automatically.',
|
||||
incompatibleTitle: 'This browser cannot play this video',
|
||||
incompatibleBody: 'Use a recent Chrome or Firefox on a device with Media Source Extensions.',
|
||||
playbackFailed: 'Playback ran into a problem',
|
||||
pressPlay: 'Press Play to begin',
|
||||
pause: 'Pause',
|
||||
seekBack: 'Back 10 seconds',
|
||||
seekForward: 'Forward 10 seconds',
|
||||
fullscreen: 'Fullscreen',
|
||||
exitFullscreen: 'Exit fullscreen',
|
||||
subtitles: 'Subtitles',
|
||||
audio: 'Audio',
|
||||
subtitleOff: 'Off',
|
||||
season: 'Season',
|
||||
episode: 'Episode',
|
||||
minutes: 'min',
|
||||
loginTitle: 'Administrator sign in',
|
||||
email: 'Email',
|
||||
password: 'Password',
|
||||
totp: 'One-time code (optional)',
|
||||
login: 'Sign in',
|
||||
logout: 'Sign out',
|
||||
invalidLogin: 'Those credentials were not accepted.',
|
||||
dashboard: 'System status',
|
||||
catalogCount: 'Catalog titles',
|
||||
publishedCount: 'Published',
|
||||
reviewCount: 'Needs review',
|
||||
activeJobs: 'Active jobs',
|
||||
cache: 'Hot cache',
|
||||
recentJobs: 'Recent jobs',
|
||||
scanArchive: 'Scan archive',
|
||||
scanStarted: 'Archive scan was queued.',
|
||||
refresh: 'Refresh',
|
||||
unavailable: 'Unavailable',
|
||||
unsupported: 'Unsupported',
|
||||
year: 'Year',
|
||||
}
|
||||
|
||||
export type TranslationKey = keyof typeof fa
|
||||
|
||||
export function useI18n() {
|
||||
const ui = useUiStore()
|
||||
const language = computed(() => ui.preferences.uiLanguage)
|
||||
const isRtl = computed(() => language.value === 'fa')
|
||||
const t = (key: TranslationKey): string => (language.value === 'fa' ? fa[key] : en[key])
|
||||
const localize = (value: { fa?: string | undefined; en?: string | undefined } | undefined, fallback = ''): string => {
|
||||
if (!value) return fallback
|
||||
return language.value === 'fa' ? value.fa ?? value.en ?? fallback : value.en ?? value.fa ?? fallback
|
||||
}
|
||||
return { language, isRtl, t, localize }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import '@fontsource/vazirmatn/400.css'
|
||||
import '@fontsource/vazirmatn/700.css'
|
||||
import { createPinia } from 'pinia'
|
||||
import { createApp } from 'vue'
|
||||
|
||||
import App from '@/App.vue'
|
||||
import { router } from '@/router'
|
||||
import { useUiStore } from '@/stores/ui'
|
||||
import '@/styles.css'
|
||||
|
||||
const app = createApp(App)
|
||||
const pinia = createPinia()
|
||||
app.use(pinia)
|
||||
app.use(router)
|
||||
app.mount('#app')
|
||||
|
||||
void useUiStore(pinia).hydrate()
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createRouter, 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'
|
||||
|
||||
export const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
scrollBehavior: (_to, _from, savedPosition) => savedPosition ?? { top: 0 },
|
||||
routes: [
|
||||
{ path: '/', name: 'catalog', component: CatalogView },
|
||||
{ path: '/search', name: 'search', component: SearchView },
|
||||
{ path: '/title/:slug', name: 'title', component: TitleView },
|
||||
{ path: '/admin', name: 'admin', component: AdminView },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
],
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
__resetMemoryStorageForTests,
|
||||
readPreferences,
|
||||
readProgress,
|
||||
writePreferences,
|
||||
writeProgress,
|
||||
} from '@/storage/viewer-db'
|
||||
|
||||
describe('viewer storage', () => {
|
||||
beforeEach(() => __resetMemoryStorageForTests())
|
||||
|
||||
it('persists viewer preferences without requiring an account', async () => {
|
||||
await writePreferences({
|
||||
uiLanguage: 'en',
|
||||
subtitleLanguage: 'en',
|
||||
audioLanguage: 'ja',
|
||||
volume: 0.7,
|
||||
muted: false,
|
||||
})
|
||||
|
||||
await expect(readPreferences()).resolves.toMatchObject({ uiLanguage: 'en', subtitleLanguage: 'en', volume: 0.7 })
|
||||
})
|
||||
|
||||
it('stores resume progress by media item', async () => {
|
||||
await writeProgress({
|
||||
mediaItemId: 'episode-1',
|
||||
positionSeconds: 640,
|
||||
durationSeconds: 1420,
|
||||
updatedAt: 10,
|
||||
completed: false,
|
||||
})
|
||||
|
||||
await expect(readProgress('episode-1')).resolves.toMatchObject({ positionSeconds: 640, completed: false })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { ProgressRecord, ViewerPreferences } from '@/types'
|
||||
|
||||
const DATABASE_NAME = 'easy-stream-viewer'
|
||||
const DATABASE_VERSION = 1
|
||||
const SETTINGS_STORE = 'settings'
|
||||
const PROGRESS_STORE = 'progress'
|
||||
|
||||
export const defaultPreferences: ViewerPreferences = {
|
||||
uiLanguage: 'fa',
|
||||
subtitleLanguage: 'fa',
|
||||
audioLanguage: 'ja',
|
||||
volume: 1,
|
||||
muted: false,
|
||||
}
|
||||
|
||||
let databasePromise: Promise<IDBDatabase | null> | undefined
|
||||
let memoryPreferences: ViewerPreferences = { ...defaultPreferences }
|
||||
const memoryProgress = new Map<string, ProgressRecord>()
|
||||
|
||||
function openDatabase(): Promise<IDBDatabase | null> {
|
||||
if (databasePromise) return databasePromise
|
||||
databasePromise = new Promise((resolve) => {
|
||||
if (typeof indexedDB === 'undefined') {
|
||||
resolve(null)
|
||||
return
|
||||
}
|
||||
|
||||
const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION)
|
||||
request.onupgradeneeded = () => {
|
||||
const database = request.result
|
||||
if (!database.objectStoreNames.contains(SETTINGS_STORE)) {
|
||||
database.createObjectStore(SETTINGS_STORE, { keyPath: 'key' })
|
||||
}
|
||||
if (!database.objectStoreNames.contains(PROGRESS_STORE)) {
|
||||
database.createObjectStore(PROGRESS_STORE, { keyPath: 'mediaItemId' })
|
||||
}
|
||||
}
|
||||
request.onsuccess = () => resolve(request.result)
|
||||
request.onerror = () => resolve(null)
|
||||
request.onblocked = () => resolve(null)
|
||||
})
|
||||
return databasePromise
|
||||
}
|
||||
|
||||
async function getRecord<T>(storeName: string, key: IDBValidKey): Promise<T | undefined> {
|
||||
const database = await openDatabase()
|
||||
if (!database) return undefined
|
||||
return new Promise((resolve) => {
|
||||
const transaction = database.transaction(storeName, 'readonly')
|
||||
const request = transaction.objectStore(storeName).get(key)
|
||||
request.onsuccess = () => resolve(request.result as T | undefined)
|
||||
request.onerror = () => resolve(undefined)
|
||||
})
|
||||
}
|
||||
|
||||
async function putRecord(storeName: string, value: unknown): Promise<void> {
|
||||
const database = await openDatabase()
|
||||
if (!database) return
|
||||
await new Promise<void>((resolve) => {
|
||||
const transaction = database.transaction(storeName, 'readwrite')
|
||||
transaction.objectStore(storeName).put(value)
|
||||
transaction.oncomplete = () => resolve()
|
||||
transaction.onerror = () => resolve()
|
||||
transaction.onabort = () => resolve()
|
||||
})
|
||||
}
|
||||
|
||||
export async function readPreferences(): Promise<ViewerPreferences> {
|
||||
const result = await getRecord<{ key: string; value: Partial<ViewerPreferences> }>(SETTINGS_STORE, 'viewer')
|
||||
if (!result) return { ...memoryPreferences }
|
||||
memoryPreferences = { ...defaultPreferences, ...result.value }
|
||||
return { ...memoryPreferences }
|
||||
}
|
||||
|
||||
export async function writePreferences(preferences: ViewerPreferences): Promise<void> {
|
||||
memoryPreferences = { ...preferences }
|
||||
await putRecord(SETTINGS_STORE, { key: 'viewer', value: preferences })
|
||||
}
|
||||
|
||||
export async function readProgress(mediaItemId: string): Promise<ProgressRecord | undefined> {
|
||||
const result = await getRecord<ProgressRecord>(PROGRESS_STORE, mediaItemId)
|
||||
return result ?? memoryProgress.get(mediaItemId)
|
||||
}
|
||||
|
||||
export async function writeProgress(progress: ProgressRecord): Promise<void> {
|
||||
memoryProgress.set(progress.mediaItemId, progress)
|
||||
await putRecord(PROGRESS_STORE, progress)
|
||||
}
|
||||
|
||||
export async function listProgress(): Promise<ProgressRecord[]> {
|
||||
const database = await openDatabase()
|
||||
if (!database) return [...memoryProgress.values()]
|
||||
return new Promise((resolve) => {
|
||||
const transaction = database.transaction(PROGRESS_STORE, 'readonly')
|
||||
const request = transaction.objectStore(PROGRESS_STORE).getAll()
|
||||
request.onsuccess = () => resolve(request.result as ProgressRecord[])
|
||||
request.onerror = () => resolve([...memoryProgress.values()])
|
||||
})
|
||||
}
|
||||
|
||||
export function __resetMemoryStorageForTests(): void {
|
||||
memoryPreferences = { ...defaultPreferences }
|
||||
memoryProgress.clear()
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { markRaw } from 'vue'
|
||||
|
||||
export interface PlayRequest {
|
||||
mediaItemId: string
|
||||
title: string
|
||||
posterUrl?: string
|
||||
}
|
||||
|
||||
export interface PlayerController {
|
||||
start(request: PlayRequest): void
|
||||
close(): void
|
||||
}
|
||||
|
||||
export const usePlayerStore = defineStore('player', {
|
||||
state: () => ({
|
||||
visible: false,
|
||||
controller: undefined as PlayerController | undefined,
|
||||
current: undefined as PlayRequest | undefined,
|
||||
}),
|
||||
|
||||
actions: {
|
||||
register(controller: PlayerController) {
|
||||
this.controller = markRaw(controller)
|
||||
},
|
||||
|
||||
unregister(controller: PlayerController) {
|
||||
if (this.controller === controller) this.controller = undefined
|
||||
},
|
||||
|
||||
play(request: PlayRequest) {
|
||||
this.current = request
|
||||
this.visible = true
|
||||
this.controller?.start(request)
|
||||
},
|
||||
|
||||
close() {
|
||||
this.controller?.close()
|
||||
this.visible = false
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
import { defaultPreferences, readPreferences, writePreferences } from '@/storage/viewer-db'
|
||||
import type { UiLanguage, ViewerPreferences } from '@/types'
|
||||
|
||||
function applyDocumentLanguage(language: UiLanguage): void {
|
||||
if (typeof document === 'undefined') return
|
||||
document.documentElement.lang = language
|
||||
document.documentElement.dir = language === 'fa' ? 'rtl' : 'ltr'
|
||||
}
|
||||
|
||||
export const useUiStore = defineStore('ui', {
|
||||
state: () => ({
|
||||
preferences: { ...defaultPreferences } as ViewerPreferences,
|
||||
hydrated: false,
|
||||
}),
|
||||
|
||||
actions: {
|
||||
async hydrate() {
|
||||
this.preferences = await readPreferences()
|
||||
this.hydrated = true
|
||||
applyDocumentLanguage(this.preferences.uiLanguage)
|
||||
},
|
||||
|
||||
async setLanguage(language: UiLanguage) {
|
||||
this.preferences.uiLanguage = language
|
||||
applyDocumentLanguage(language)
|
||||
await writePreferences({ ...this.preferences })
|
||||
},
|
||||
|
||||
async setSubtitleLanguage(language: string) {
|
||||
this.preferences.subtitleLanguage = language
|
||||
await writePreferences({ ...this.preferences })
|
||||
},
|
||||
|
||||
async setAudioLanguage(language: string) {
|
||||
this.preferences.audioLanguage = language
|
||||
await writePreferences({ ...this.preferences })
|
||||
},
|
||||
|
||||
async setVolume(volume: number, muted: boolean) {
|
||||
this.preferences.volume = Math.min(1, Math.max(0, volume))
|
||||
this.preferences.muted = muted
|
||||
await writePreferences({ ...this.preferences })
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
import { afterEach, vi } from 'vitest'
|
||||
|
||||
Object.defineProperty(HTMLElement.prototype, 'offsetParent', {
|
||||
configurable: true,
|
||||
get() {
|
||||
return this.parentElement
|
||||
},
|
||||
})
|
||||
|
||||
if (typeof CSS === 'undefined') {
|
||||
vi.stubGlobal('CSS', { escape: (value: string) => value.replace(/["\\]/g, '\\$&') })
|
||||
}
|
||||
|
||||
HTMLElement.prototype.scrollIntoView = vi.fn()
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
export type UiLanguage = 'fa' | 'en'
|
||||
export type MediaKind = 'MOVIE' | 'SERIES'
|
||||
|
||||
export interface LocalizedText {
|
||||
fa?: string | undefined
|
||||
en?: string | undefined
|
||||
}
|
||||
|
||||
export interface CatalogItem {
|
||||
id: string
|
||||
mediaItemId: string
|
||||
slug: string
|
||||
kind: MediaKind
|
||||
title: LocalizedText
|
||||
overview: LocalizedText
|
||||
posterUrl?: string | undefined
|
||||
backdropUrl?: string | undefined
|
||||
year?: number | undefined
|
||||
runtimeSeconds?: number | undefined
|
||||
seasonCount?: number | undefined
|
||||
episodeCount?: number | undefined
|
||||
compatibility?: string | undefined
|
||||
playable: boolean
|
||||
progress?: number | undefined
|
||||
}
|
||||
|
||||
export interface EpisodeItem {
|
||||
id: string
|
||||
mediaItemId: string
|
||||
number: number
|
||||
seasonNumber: number
|
||||
title: LocalizedText
|
||||
overview: LocalizedText
|
||||
posterUrl?: string | undefined
|
||||
durationSeconds?: number | undefined
|
||||
published: boolean
|
||||
}
|
||||
|
||||
export interface SeasonItem {
|
||||
number: number
|
||||
title: LocalizedText
|
||||
episodes: EpisodeItem[]
|
||||
}
|
||||
|
||||
export interface TitleDetail extends CatalogItem {
|
||||
genres: LocalizedText[]
|
||||
seasons: SeasonItem[]
|
||||
playableMediaItemId?: string | undefined
|
||||
}
|
||||
|
||||
export interface CatalogPage {
|
||||
items: CatalogItem[]
|
||||
nextCursor?: string | undefined
|
||||
total?: number | undefined
|
||||
}
|
||||
|
||||
export type PlaybackState = 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED'
|
||||
export type SubtitleDelivery = 'ASS_JASSUB' | 'WEBVTT' | 'OFF'
|
||||
|
||||
export interface PlaybackSubtitleTrack {
|
||||
id: string
|
||||
language: string
|
||||
label: string
|
||||
default: boolean
|
||||
forced: boolean
|
||||
assUrl?: string | undefined
|
||||
vttUrl?: string | undefined
|
||||
fonts: string[]
|
||||
}
|
||||
|
||||
export interface PlaybackAudioTrack {
|
||||
id: string
|
||||
language: string
|
||||
label: string
|
||||
default: boolean
|
||||
}
|
||||
|
||||
export interface PlaybackSession {
|
||||
id: string
|
||||
state: PlaybackState
|
||||
mediaItemId: string
|
||||
manifestUrl?: string | undefined
|
||||
durationSeconds?: number | undefined
|
||||
pollAfterMs: number
|
||||
progress?: number | undefined
|
||||
message?: string | undefined
|
||||
reasonCode?: string | undefined
|
||||
expiresAt?: string | undefined
|
||||
videoCodec?: string | undefined
|
||||
audioCodec?: string | undefined
|
||||
subtitles: PlaybackSubtitleTrack[]
|
||||
audioTracks: PlaybackAudioTrack[]
|
||||
}
|
||||
|
||||
export interface ClientCapabilities {
|
||||
nativeHls: boolean
|
||||
mse: boolean
|
||||
hlsJs: boolean
|
||||
assRenderer: boolean
|
||||
supportedCodecs: string[]
|
||||
userAgent?: string | undefined
|
||||
}
|
||||
|
||||
export interface ProgressRecord {
|
||||
mediaItemId: string
|
||||
positionSeconds: number
|
||||
durationSeconds: number
|
||||
updatedAt: number
|
||||
completed: boolean
|
||||
}
|
||||
|
||||
export interface ViewerPreferences {
|
||||
uiLanguage: UiLanguage
|
||||
subtitleLanguage: string
|
||||
audioLanguage: string
|
||||
volume: number
|
||||
muted: boolean
|
||||
}
|
||||
|
||||
export interface AdminJob {
|
||||
id: string
|
||||
type: string
|
||||
state: string
|
||||
progress?: number | undefined
|
||||
message?: string | undefined
|
||||
createdAt?: string | undefined
|
||||
}
|
||||
|
||||
export interface AdminDashboard {
|
||||
catalogCount: number
|
||||
publishedCount: number
|
||||
reviewCount: number
|
||||
activeJobs: number
|
||||
cacheUsedBytes?: number | undefined
|
||||
cacheCapacityBytes?: number | undefined
|
||||
jobs: AdminJob[]
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
|
||||
import { ApiError, api } from '@/api/client'
|
||||
import LoadingState from '@/components/LoadingState.vue'
|
||||
import { useSpatialNavigation } from '@/composables/spatial-navigation'
|
||||
import { useI18n } from '@/i18n'
|
||||
import type { AdminDashboard } from '@/types'
|
||||
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const checking = ref(true)
|
||||
const authenticated = ref(false)
|
||||
const name = ref('')
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const totp = ref('')
|
||||
const submitting = ref(false)
|
||||
const error = ref('')
|
||||
const notice = ref('')
|
||||
const dashboard = ref<AdminDashboard | null>(null)
|
||||
const { t } = useI18n()
|
||||
const { restoreFocus } = useSpatialNavigation(root, { restoreKey: 'admin-focus' })
|
||||
let controller: AbortController | undefined
|
||||
|
||||
function formatBytes(bytes?: number): string {
|
||||
if (bytes === undefined) return '—'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
let value = bytes
|
||||
let unit = units[0]
|
||||
for (let index = 1; index < units.length && value >= 1024; index += 1) {
|
||||
value /= 1024
|
||||
unit = units[index]
|
||||
}
|
||||
return `${value.toFixed(value >= 10 ? 1 : 2)} ${unit}`
|
||||
}
|
||||
|
||||
async function loadDashboard() {
|
||||
controller?.abort()
|
||||
controller = new AbortController()
|
||||
error.value = ''
|
||||
try {
|
||||
dashboard.value = await api.adminDashboard(controller.signal)
|
||||
void restoreFocus()
|
||||
} catch (reason) {
|
||||
if (reason instanceof ApiError && reason.status === 401) {
|
||||
authenticated.value = false
|
||||
dashboard.value = null
|
||||
return
|
||||
}
|
||||
if ((reason as { name?: string }).name !== 'AbortError') {
|
||||
error.value = reason instanceof Error ? reason.message : t('networkError')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function checkSession() {
|
||||
checking.value = true
|
||||
try {
|
||||
const session = await api.adminSession()
|
||||
authenticated.value = session.authenticated
|
||||
name.value = session.name ?? ''
|
||||
if (authenticated.value) await loadDashboard()
|
||||
} catch (reason) {
|
||||
error.value = reason instanceof Error ? reason.message : t('networkError')
|
||||
} finally {
|
||||
checking.value = false
|
||||
void restoreFocus()
|
||||
}
|
||||
}
|
||||
|
||||
async function login() {
|
||||
submitting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await api.adminLogin(email.value.trim(), password.value, totp.value.trim() || undefined)
|
||||
authenticated.value = true
|
||||
password.value = ''
|
||||
totp.value = ''
|
||||
await loadDashboard()
|
||||
} catch (reason) {
|
||||
error.value = reason instanceof ApiError && (reason.status === 401 || reason.status === 403)
|
||||
? t('invalidLogin')
|
||||
: reason instanceof Error ? reason.message : t('networkError')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await api.adminLogout()
|
||||
} finally {
|
||||
authenticated.value = false
|
||||
dashboard.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function scanArchive() {
|
||||
submitting.value = true
|
||||
notice.value = ''
|
||||
error.value = ''
|
||||
try {
|
||||
await api.startScan()
|
||||
notice.value = t('scanStarted')
|
||||
await loadDashboard()
|
||||
} catch (reason) {
|
||||
error.value = reason instanceof Error ? reason.message : t('networkError')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => void checkSession())
|
||||
onBeforeUnmount(() => controller?.abort())
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="root" class="page-view admin-view">
|
||||
<LoadingState v-if="checking" :label="t('loading')" />
|
||||
|
||||
<section v-else-if="!authenticated" class="login-panel">
|
||||
<p class="eyebrow">Easy Stream</p>
|
||||
<h1>{{ t('loginTitle') }}</h1>
|
||||
<form @submit.prevent="login">
|
||||
<label>
|
||||
<span>{{ t('email') }}</span>
|
||||
<input v-model="email" data-tv-focus data-focus-id="admin-email" type="email" autocomplete="username" required />
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t('password') }}</span>
|
||||
<input
|
||||
v-model="password"
|
||||
data-tv-focus
|
||||
data-focus-id="admin-password"
|
||||
type="password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t('totp') }}</span>
|
||||
<input
|
||||
v-model="totp"
|
||||
data-tv-focus
|
||||
data-focus-id="admin-totp"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
autocomplete="one-time-code"
|
||||
pattern="[0-9]*"
|
||||
/>
|
||||
</label>
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
<button class="primary-button large focus-ring" data-tv-focus data-focus-id="admin-login" :disabled="submitting">
|
||||
{{ submitting ? t('loading') : t('login') }}
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<template v-else>
|
||||
<section class="admin-heading">
|
||||
<div>
|
||||
<p class="eyebrow">{{ name || 'Easy Stream' }}</p>
|
||||
<h1>{{ t('dashboard') }}</h1>
|
||||
</div>
|
||||
<div class="admin-actions">
|
||||
<button class="secondary-button focus-ring" type="button" data-tv-focus @click="loadDashboard">{{ t('refresh') }}</button>
|
||||
<button
|
||||
class="primary-button focus-ring"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
:disabled="submitting"
|
||||
@click="scanArchive"
|
||||
>
|
||||
{{ t('scanArchive') }}
|
||||
</button>
|
||||
<button class="text-button focus-ring" type="button" data-tv-focus @click="logout">{{ t('logout') }}</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p v-if="notice" class="notice" role="status">{{ notice }}</p>
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<section v-if="dashboard" class="dashboard-grid">
|
||||
<article class="stat-card"><span>{{ t('catalogCount') }}</span><strong>{{ dashboard.catalogCount }}</strong></article>
|
||||
<article class="stat-card"><span>{{ t('publishedCount') }}</span><strong>{{ dashboard.publishedCount }}</strong></article>
|
||||
<article class="stat-card"><span>{{ t('reviewCount') }}</span><strong>{{ dashboard.reviewCount }}</strong></article>
|
||||
<article class="stat-card"><span>{{ t('activeJobs') }}</span><strong>{{ dashboard.activeJobs }}</strong></article>
|
||||
<article class="stat-card cache-card">
|
||||
<span>{{ t('cache') }}</span>
|
||||
<strong>{{ formatBytes(dashboard.cacheUsedBytes) }}</strong>
|
||||
<small v-if="dashboard.cacheCapacityBytes">/ {{ formatBytes(dashboard.cacheCapacityBytes) }}</small>
|
||||
<progress
|
||||
v-if="dashboard.cacheUsedBytes !== undefined && dashboard.cacheCapacityBytes"
|
||||
:value="dashboard.cacheUsedBytes"
|
||||
:max="dashboard.cacheCapacityBytes"
|
||||
/>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section v-if="dashboard?.jobs.length" class="jobs-panel">
|
||||
<h2>{{ t('recentJobs') }}</h2>
|
||||
<div class="jobs-table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Type</th><th>Status</th><th>Progress</th><th>Message</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="job in dashboard.jobs" :key="job.id">
|
||||
<td>{{ job.type }}</td>
|
||||
<td><span class="status-pill">{{ job.state }}</span></td>
|
||||
<td>{{ job.progress === undefined ? '—' : `${Math.round(job.progress)}%` }}</td>
|
||||
<td>{{ job.message ?? '—' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,116 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
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 { listProgress } from '@/storage/viewer-db'
|
||||
import { usePlayerStore } from '@/stores/player'
|
||||
import type { CatalogItem } from '@/types'
|
||||
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const items = ref<CatalogItem[]>([])
|
||||
const progress = ref<Record<string, number>>({})
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
const { localize, t } = useI18n()
|
||||
const player = usePlayerStore()
|
||||
const featured = computed(() => items.value.find((item) => item.playable) ?? items.value[0])
|
||||
const { restoreFocus } = useSpatialNavigation(root, { restoreKey: 'catalog-focus' })
|
||||
|
||||
function playFeatured() {
|
||||
const item = featured.value
|
||||
if (!item?.playable || !item.mediaItemId) return
|
||||
player.play({
|
||||
mediaItemId: item.mediaItemId,
|
||||
title: localize(item.title, item.slug),
|
||||
...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [catalog, storedProgress] = await Promise.all([api.catalog({ limit: 60 }), listProgress()])
|
||||
items.value = catalog.items
|
||||
progress.value = Object.fromEntries(storedProgress.map((entry) => [
|
||||
entry.mediaItemId,
|
||||
entry.durationSeconds > 0 ? (entry.positionSeconds / entry.durationSeconds) * 100 : 0,
|
||||
]))
|
||||
void restoreFocus()
|
||||
} catch (reason) {
|
||||
error.value = reason instanceof Error ? reason.message : t('networkError')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => void load())
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="root" class="catalog-view">
|
||||
<LoadingState v-if="loading" :label="t('loadingCatalog')" />
|
||||
|
||||
<section v-else-if="error" class="center-state error-state" role="alert">
|
||||
<h1>{{ t('networkError') }}</h1>
|
||||
<p>{{ error }}</p>
|
||||
<button class="primary-button focus-ring" type="button" data-tv-focus @click="load">{{ t('retry') }}</button>
|
||||
</section>
|
||||
|
||||
<template v-else-if="items.length">
|
||||
<section
|
||||
v-if="featured"
|
||||
class="hero"
|
||||
:style="featured.backdropUrl ? { backgroundImage: `url(${featured.backdropUrl})` } : undefined"
|
||||
>
|
||||
<div class="hero-scrim" />
|
||||
<div class="hero-content">
|
||||
<p class="eyebrow">{{ t('featured') }}</p>
|
||||
<h1>{{ localize(featured.title, featured.slug) }}</h1>
|
||||
<p v-if="localize(featured.overview)" class="hero-overview">{{ localize(featured.overview) }}</p>
|
||||
<div class="hero-actions">
|
||||
<button
|
||||
class="primary-button large focus-ring"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
data-focus-id="featured-play"
|
||||
:disabled="!featured.playable"
|
||||
@click="playFeatured"
|
||||
>
|
||||
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
|
||||
{{ t('play') }}
|
||||
</button>
|
||||
<RouterLink
|
||||
class="secondary-button large focus-ring"
|
||||
data-tv-focus
|
||||
data-focus-id="featured-info"
|
||||
:to="{ name: 'title', params: { slug: featured.slug } }"
|
||||
>
|
||||
{{ t('details') }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="catalog-section" aria-labelledby="catalog-heading">
|
||||
<h2 id="catalog-heading">{{ t('allTitles') }}</h2>
|
||||
<div class="media-grid">
|
||||
<MediaCard
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
:item="item"
|
||||
:progress="progress[item.mediaItemId]"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<section v-else class="center-state">
|
||||
<h1>{{ t('emptyCatalog') }}</h1>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,97 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } 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 router = useRouter()
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const input = ref<HTMLInputElement | null>(null)
|
||||
const term = ref(typeof route.query.q === 'string' ? route.query.q : '')
|
||||
const items = ref<CatalogItem[]>([])
|
||||
const loading = ref(false)
|
||||
const searched = ref(Boolean(term.value))
|
||||
const error = ref('')
|
||||
const { t } = useI18n()
|
||||
const { restoreFocus } = useSpatialNavigation(root, { restoreKey: 'search-focus' })
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let controller: AbortController | undefined
|
||||
|
||||
async function search() {
|
||||
controller?.abort()
|
||||
const query = term.value.trim()
|
||||
void router.replace({ name: 'search', query: query ? { q: query } : {} })
|
||||
if (!query) {
|
||||
items.value = []
|
||||
searched.value = false
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
controller = new AbortController()
|
||||
loading.value = true
|
||||
searched.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
items.value = (await api.search(query, controller.signal)).items
|
||||
void restoreFocus()
|
||||
} catch (reason) {
|
||||
if ((reason as { name?: string }).name !== 'AbortError') {
|
||||
error.value = reason instanceof Error ? reason.message : t('networkError')
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(term, () => {
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = setTimeout(() => void search(), 300)
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
if (term.value) await search()
|
||||
await nextTick()
|
||||
input.value?.focus()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
controller?.abort()
|
||||
if (timer) clearTimeout(timer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="root" class="page-view search-view">
|
||||
<section class="page-heading">
|
||||
<p class="eyebrow">Easy Stream</p>
|
||||
<h1>{{ t('search') }}</h1>
|
||||
<div class="large-search">
|
||||
<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
|
||||
ref="input"
|
||||
v-model="term"
|
||||
type="search"
|
||||
data-tv-focus
|
||||
data-focus-id="search-input"
|
||||
:placeholder="t('searchPlaceholder')"
|
||||
:aria-label="t('search')"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<LoadingState v-if="loading" :label="t('loading')" />
|
||||
<section v-else-if="error" class="center-state error-state" role="alert">
|
||||
<p>{{ error }}</p>
|
||||
<button class="primary-button focus-ring" type="button" data-tv-focus @click="search">{{ t('retry') }}</button>
|
||||
</section>
|
||||
<section v-else-if="items.length" class="catalog-section">
|
||||
<div class="media-grid"><MediaCard v-for="item in items" :key="item.id" :item="item" /></div>
|
||||
</section>
|
||||
<section v-else-if="searched" class="center-state"><h2>{{ t('noResults') }}</h2></section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,132 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import { api } from '@/api/client'
|
||||
import LoadingState from '@/components/LoadingState.vue'
|
||||
import { useSpatialNavigation } from '@/composables/spatial-navigation'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { usePlayerStore } from '@/stores/player'
|
||||
import type { EpisodeItem, TitleDetail } from '@/types'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const detail = ref<TitleDetail | null>(null)
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
const player = usePlayerStore()
|
||||
const { localize, t } = useI18n()
|
||||
const { restoreFocus } = useSpatialNavigation(root, {
|
||||
restoreKey: 'title-focus',
|
||||
onBack: () => router.back(),
|
||||
})
|
||||
let controller: AbortController | undefined
|
||||
|
||||
const title = computed(() => detail.value ? localize(detail.value.title, detail.value.slug) : '')
|
||||
const canPlayTitle = computed(() => Boolean(detail.value?.playable && (detail.value.playableMediaItemId ?? detail.value.mediaItemId)))
|
||||
|
||||
function playTitle() {
|
||||
const mediaItemId = detail.value?.playableMediaItemId ?? detail.value?.mediaItemId
|
||||
if (!detail.value || !mediaItemId) return
|
||||
player.play({
|
||||
mediaItemId,
|
||||
title: title.value,
|
||||
...(detail.value.posterUrl ? { posterUrl: detail.value.posterUrl } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
function playEpisode(episode: EpisodeItem) {
|
||||
player.play({
|
||||
mediaItemId: episode.mediaItemId,
|
||||
title: `${title.value} · ${t('episode')} ${episode.number}`,
|
||||
...(episode.posterUrl ? { posterUrl: episode.posterUrl } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
async function load() {
|
||||
controller?.abort()
|
||||
controller = new AbortController()
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
detail.value = await api.title(String(route.params.slug), controller.signal)
|
||||
void restoreFocus()
|
||||
} catch (reason) {
|
||||
if ((reason as { name?: string }).name !== 'AbortError') {
|
||||
error.value = reason instanceof Error ? reason.message : t('networkError')
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => route.params.slug, () => void load(), { immediate: true })
|
||||
onBeforeUnmount(() => controller?.abort())
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="root" class="title-view">
|
||||
<LoadingState v-if="loading" :label="t('loading')" />
|
||||
<section v-else-if="error" class="center-state error-state" role="alert">
|
||||
<p>{{ error }}</p>
|
||||
<button class="primary-button focus-ring" type="button" data-tv-focus @click="load">{{ t('retry') }}</button>
|
||||
</section>
|
||||
<template v-else-if="detail">
|
||||
<section
|
||||
class="detail-hero"
|
||||
:style="detail.backdropUrl ? { backgroundImage: `url(${detail.backdropUrl})` } : undefined"
|
||||
>
|
||||
<div class="hero-scrim" />
|
||||
<button class="back-button focus-ring" type="button" data-tv-focus data-focus-id="detail-back" @click="router.back()">
|
||||
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6" /></svg>
|
||||
{{ t('back') }}
|
||||
</button>
|
||||
<div class="detail-copy">
|
||||
<p class="eyebrow">{{ detail.kind === 'SERIES' ? t('series') : t('movies') }}</p>
|
||||
<h1>{{ title }}</h1>
|
||||
<div class="detail-meta">
|
||||
<span v-if="detail.year">{{ detail.year }}</span>
|
||||
<span v-if="detail.runtimeSeconds">{{ Math.ceil(detail.runtimeSeconds / 60) }} {{ t('minutes') }}</span>
|
||||
<span v-for="genre in detail.genres" :key="localize(genre)">{{ localize(genre) }}</span>
|
||||
</div>
|
||||
<p v-if="localize(detail.overview)" class="hero-overview">{{ localize(detail.overview) }}</p>
|
||||
<button
|
||||
v-if="canPlayTitle"
|
||||
class="primary-button large focus-ring"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
data-focus-id="detail-play"
|
||||
@click="playTitle"
|
||||
>
|
||||
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
|
||||
{{ t('play') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-for="season in detail.seasons" :key="season.number" class="episodes-section">
|
||||
<h2>{{ localize(season.title, `${t('season')} ${season.number}`) }}</h2>
|
||||
<div class="episode-list">
|
||||
<button
|
||||
v-for="episode in season.episodes"
|
||||
:key="episode.id"
|
||||
class="episode-row focus-ring"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
:data-focus-id="`episode-${episode.id}`"
|
||||
:disabled="!episode.published"
|
||||
@click="playEpisode(episode)"
|
||||
>
|
||||
<span class="episode-number">{{ episode.number }}</span>
|
||||
<span class="episode-copy">
|
||||
<strong>{{ localize(episode.title, `${t('episode')} ${episode.number}`) }}</strong>
|
||||
<small v-if="episode.durationSeconds">{{ Math.ceil(episode.durationSeconds / 60) }} {{ t('minutes') }}</small>
|
||||
</span>
|
||||
<span class="episode-play" aria-hidden="true">▶</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"noEmit": true,
|
||||
"declaration": false,
|
||||
"paths": {
|
||||
"@/*": ["src/*"],
|
||||
"@easy-stream/contracts": ["../../packages/contracts/src/index.ts"]
|
||||
},
|
||||
"types": ["vite/client", "vitest/globals"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: process.env.API_ORIGIN ?? 'http://127.0.0.1:3000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/images/tmdb': {
|
||||
target: 'https://image.tmdb.org',
|
||||
changeOrigin: true,
|
||||
rewrite: (requestPath) => requestPath.replace(/^\/images\/tmdb/, '/t/p'),
|
||||
},
|
||||
},
|
||||
},
|
||||
worker: {
|
||||
format: 'es',
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
globals: true,
|
||||
setupFiles: ['./src/test/setup.ts'],
|
||||
css: false,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@easy-stream/worker",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p ../../packages/contracts/tsconfig.json && tsc -p ../../packages/media/tsconfig.json && tsc -p ../../packages/database/tsconfig.json && tsc -p tsconfig.json --noEmit",
|
||||
"test": "tsc -p ../../packages/contracts/tsconfig.json && tsc -p ../../packages/media/tsconfig.json && tsc -p ../../packages/database/tsconfig.json && vitest run",
|
||||
"dev": "tsx watch src/cli.ts work",
|
||||
"scan": "tsx src/cli.ts scan",
|
||||
"package": "tsx src/cli.ts package",
|
||||
"prepare:media": "tsx src/cli.ts prepare",
|
||||
"work": "tsx src/cli.ts work",
|
||||
"clean": "rm -rf dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"@easy-stream/contracts": "workspace:*",
|
||||
"@easy-stream/database": "workspace:*",
|
||||
"@easy-stream/media": "workspace:*",
|
||||
"@sinclair/typebox": "^0.34.41",
|
||||
"bullmq": "^5.61.2",
|
||||
"ioredis": "^5.10.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.0",
|
||||
"tsx": "^4.20.6",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import path from 'node:path';
|
||||
import { evictCache, pruneOrphanedFonts, type EvictionResult } from '@easy-stream/media';
|
||||
import { removeGenerationsFromRegistry } from './registry.js';
|
||||
|
||||
export interface CacheSweepOptions {
|
||||
cacheRoot: string;
|
||||
registryPath: string;
|
||||
capacityBytes: number;
|
||||
highWatermark: number;
|
||||
lowWatermark: number;
|
||||
playbackTtlMs: number;
|
||||
protectedKeys?: ReadonlySet<string>;
|
||||
fontOrphanMinimumAgeMs?: number;
|
||||
now?: Date;
|
||||
}
|
||||
|
||||
export interface CacheSweepResult extends EvictionResult {
|
||||
registryEntriesRemoved: string[];
|
||||
orphanFontsRemoved: string[];
|
||||
}
|
||||
|
||||
/** Sweeps only disposable cache generations. Durable derived media is deliberately out of scope. */
|
||||
export async function sweepCache(options: CacheSweepOptions): Promise<CacheSweepResult> {
|
||||
const now = options.now ?? new Date();
|
||||
const fontOptions = {
|
||||
minimumAgeMs: options.fontOrphanMinimumAgeMs ?? 60 * 60 * 1000,
|
||||
now,
|
||||
};
|
||||
const beforeFonts = await pruneOrphanedFonts(options.cacheRoot, fontOptions);
|
||||
const eviction = await evictCache(path.join(options.cacheRoot, 'generations'), {
|
||||
capacityBytes: options.capacityBytes,
|
||||
highWatermark: options.highWatermark,
|
||||
lowWatermark: options.lowWatermark,
|
||||
...(options.protectedKeys === undefined ? {} : { protectedKeys: options.protectedKeys }),
|
||||
overheadBytes: beforeFonts.retainedBytes,
|
||||
minimumRetentionMs: options.playbackTtlMs,
|
||||
now,
|
||||
});
|
||||
const registryEntriesRemoved = await removeGenerationsFromRegistry(
|
||||
options.registryPath,
|
||||
new Set(eviction.evicted),
|
||||
);
|
||||
const afterFonts = eviction.evicted.length === 0
|
||||
? { removed: [] as string[], retainedBytes: beforeFonts.retainedBytes }
|
||||
: await pruneOrphanedFonts(options.cacheRoot, fontOptions);
|
||||
return {
|
||||
...eviction,
|
||||
afterBytes: Math.max(0, eviction.afterBytes - beforeFonts.retainedBytes + afterFonts.retainedBytes),
|
||||
registryEntriesRemoved,
|
||||
orphanFontsRemoved: [...beforeFonts.removed, ...afterFonts.removed],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
assDialogueText,
|
||||
classifyMedia,
|
||||
fingerprintSource,
|
||||
normalizeStreamLanguage,
|
||||
normalizeTracks,
|
||||
probeMedia,
|
||||
readSubtitleAsAss,
|
||||
walkArchive,
|
||||
type Classification,
|
||||
type NormalizedTrack,
|
||||
type ProbeStream,
|
||||
type SourceFingerprint,
|
||||
} from '@easy-stream/media';
|
||||
|
||||
export type CatalogKind = 'MOVIE' | 'SERIES';
|
||||
|
||||
export interface ParsedMediaIdentity {
|
||||
kind: CatalogKind;
|
||||
title: string;
|
||||
seasonNumber?: number;
|
||||
episodeNumber?: number;
|
||||
episodeTitle?: string;
|
||||
}
|
||||
|
||||
export interface SnapshotSubtitle {
|
||||
id: string;
|
||||
streamIndex: number;
|
||||
codec: string;
|
||||
sourceLanguage: string;
|
||||
language: string;
|
||||
label: string;
|
||||
sourceDefault: boolean;
|
||||
sourceForced: boolean;
|
||||
default: boolean;
|
||||
forced: false;
|
||||
}
|
||||
|
||||
export interface SnapshotMediaItem {
|
||||
id: string;
|
||||
titleId: string;
|
||||
kind: 'MOVIE' | 'EPISODE';
|
||||
sourcePath: string;
|
||||
durationSeconds: number;
|
||||
seasonNumber?: number;
|
||||
episodeNumber?: number;
|
||||
title: { en: string; fa?: string };
|
||||
published: boolean;
|
||||
compatibility: Classification['class'];
|
||||
compatibilityReasons: string[];
|
||||
fingerprint: SourceFingerprint;
|
||||
streams: NormalizedTrack[];
|
||||
subtitles: SnapshotSubtitle[];
|
||||
}
|
||||
|
||||
export interface SnapshotSeason {
|
||||
number: number;
|
||||
title: { en: string };
|
||||
episodes: SnapshotMediaItem[];
|
||||
}
|
||||
|
||||
export interface SnapshotTitle {
|
||||
id: string;
|
||||
slug: string;
|
||||
kind: CatalogKind;
|
||||
title: { en: string; fa?: string };
|
||||
published: boolean;
|
||||
playable: boolean;
|
||||
mediaItemId: string;
|
||||
resumeMediaItemId: string;
|
||||
runtimeSeconds?: number;
|
||||
seasonCount?: number;
|
||||
episodeCount?: number;
|
||||
seasons: SnapshotSeason[];
|
||||
mediaItems: SnapshotMediaItem[];
|
||||
}
|
||||
|
||||
export interface InventorySnapshot {
|
||||
version: 1;
|
||||
generatedAt: string;
|
||||
archiveRoot: string;
|
||||
items: SnapshotTitle[];
|
||||
}
|
||||
|
||||
export interface PublicMediaItem {
|
||||
id: string;
|
||||
kind: 'MOVIE' | 'EPISODE';
|
||||
seasonNumber?: number;
|
||||
episodeNumber?: number;
|
||||
name?: { fa?: string; en?: string };
|
||||
durationSeconds: number;
|
||||
compatibility: Classification['class'];
|
||||
published: boolean;
|
||||
}
|
||||
|
||||
export interface PublicTitleDetail {
|
||||
id: string;
|
||||
slug: string;
|
||||
kind: CatalogKind;
|
||||
name: { fa: string; en?: string };
|
||||
playable: boolean;
|
||||
resumeMediaItemId?: string;
|
||||
synopsis: { fa?: string; en?: string };
|
||||
seasons?: Array<{ number: number; episodeCount: number }>;
|
||||
mediaItems: PublicMediaItem[];
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CatalogSnapshot {
|
||||
version: 1;
|
||||
generatedAt: string;
|
||||
titles: PublicTitleDetail[];
|
||||
}
|
||||
|
||||
export interface ScanArchiveResult {
|
||||
catalog: CatalogSnapshot;
|
||||
inventory: InventorySnapshot;
|
||||
}
|
||||
|
||||
export function deterministicUuid(value: string): string {
|
||||
const bytes = createHash('sha256').update(value).digest().subarray(0, 16);
|
||||
bytes[6] = (bytes[6] ?? 0) & 0x0f | 0x50;
|
||||
bytes[8] = (bytes[8] ?? 0) & 0x3f | 0x80;
|
||||
const hex = bytes.toString('hex');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
function cleanName(value: string): string {
|
||||
return value
|
||||
.replace(/\[[^\]]*\]/gu, ' ')
|
||||
.replace(/[._]+/gu, ' ')
|
||||
.replace(/\s+/gu, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function slugify(value: string): string {
|
||||
return value.normalize('NFKD').toLocaleLowerCase('en-US')
|
||||
.replace(/\p{Mark}+/gu, '')
|
||||
.replace(/[^\p{Letter}\p{Number}]+/gu, '-')
|
||||
.replace(/^-+|-+$/gu, '')
|
||||
.slice(0, 180) || deterministicUuid(value);
|
||||
}
|
||||
|
||||
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 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 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 season = Number(combined?.[1] ?? parentSeason?.[2] ?? 1);
|
||||
const title = cleanName(parentSeason?.[1] ?? parent);
|
||||
return {
|
||||
kind: 'SERIES',
|
||||
title: title || cleanName(filename),
|
||||
seasonNumber: season,
|
||||
episodeNumber: Number(episode),
|
||||
episodeTitle: `Episode ${Number(episode)}`,
|
||||
};
|
||||
}
|
||||
return { kind: 'MOVIE', title: cleanName(filename) };
|
||||
}
|
||||
|
||||
export interface ScanArchiveOptions {
|
||||
archiveRoot: string;
|
||||
ffmpegPath?: string;
|
||||
ffprobePath?: string;
|
||||
onFile?: (relativePath: string, current: number) => void;
|
||||
}
|
||||
|
||||
const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']);
|
||||
|
||||
export function shouldInspectSubtitleContent(stream: ProbeStream): boolean {
|
||||
return stream.codec_type === 'subtitle'
|
||||
&& TEXT_SUBTITLE_CODECS.has(stream.codec_name ?? '')
|
||||
&& normalizeStreamLanguage(stream) === 'und';
|
||||
}
|
||||
|
||||
async function inspectFile(
|
||||
sourcePath: string,
|
||||
archiveRoot: string,
|
||||
options: ScanArchiveOptions,
|
||||
): Promise<{ identity: ParsedMediaIdentity; media: SnapshotMediaItem }> {
|
||||
const relativePath = path.relative(archiveRoot, sourcePath).split(path.sep).join('/');
|
||||
const identity = parseMediaIdentity(relativePath);
|
||||
const [probe, fingerprint] = await Promise.all([
|
||||
probeMedia(sourcePath, options.ffprobePath === undefined ? {} : { ffprobePath: options.ffprobePath }),
|
||||
fingerprintSource(archiveRoot, sourcePath),
|
||||
]);
|
||||
const compatibility = classifyMedia(probe);
|
||||
const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`);
|
||||
const mediaId = deterministicUuid(`media:${relativePath}`);
|
||||
const tracks = normalizeTracks(probe);
|
||||
const subtitles: SnapshotSubtitle[] = [];
|
||||
for (const stream of probe.streams.filter((candidate) => candidate.codec_type === 'subtitle')) {
|
||||
let content: string | undefined;
|
||||
const declaredLanguage = normalizeStreamLanguage(stream);
|
||||
if (shouldInspectSubtitleContent(stream)) {
|
||||
try {
|
||||
content = await readSubtitleAsAss(sourcePath, stream.index, {
|
||||
archiveRoot,
|
||||
maxDurationSeconds: 10 * 60,
|
||||
...(options.ffmpegPath === undefined ? {} : { ffmpegPath: options.ffmpegPath }),
|
||||
});
|
||||
} catch {
|
||||
// Preserve the track as undetermined; packaging will report extraction failures.
|
||||
}
|
||||
}
|
||||
const language = content === undefined
|
||||
? declaredLanguage
|
||||
: normalizeStreamLanguage(stream, assDialogueText(content));
|
||||
const track = tracks.find((candidate) => candidate.index === stream.index);
|
||||
if (track !== undefined) {
|
||||
track.language = language;
|
||||
track.default = language === 'fa';
|
||||
track.forced = false;
|
||||
}
|
||||
subtitles.push({
|
||||
id: deterministicUuid(`subtitle:${relativePath}:${stream.index}`),
|
||||
streamIndex: stream.index,
|
||||
codec: stream.codec_name ?? 'unknown',
|
||||
sourceLanguage: stream.tags?.language ?? 'und',
|
||||
language,
|
||||
label: stream.tags?.title ?? language,
|
||||
sourceDefault: stream.disposition?.default === 1,
|
||||
sourceForced: stream.disposition?.forced === 1,
|
||||
default: language === 'fa',
|
||||
forced: false,
|
||||
});
|
||||
}
|
||||
const duration = Number(probe.format.duration);
|
||||
const published = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class);
|
||||
return {
|
||||
identity,
|
||||
media: {
|
||||
id: mediaId,
|
||||
titleId,
|
||||
kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE',
|
||||
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,
|
||||
compatibility: compatibility.class,
|
||||
compatibilityReasons: compatibility.reasons,
|
||||
fingerprint,
|
||||
streams: tracks,
|
||||
subtitles,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArchiveResult> {
|
||||
const root = path.resolve(options.archiveRoot);
|
||||
const grouped = new Map<string, { identity: ParsedMediaIdentity; media: SnapshotMediaItem[] }>();
|
||||
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);
|
||||
grouped.set(key, group);
|
||||
}
|
||||
const items: SnapshotTitle[] = [...grouped.values()].map(({ identity, media }) => {
|
||||
media.sort((left, right) => (left.seasonNumber ?? 0) - (right.seasonNumber ?? 0)
|
||||
|| (left.episodeNumber ?? 0) - (right.episodeNumber ?? 0));
|
||||
const first = media[0];
|
||||
if (first === undefined) throw new Error('Internal catalog group is empty');
|
||||
const seasonsByNumber = new Map<number, SnapshotMediaItem[]>();
|
||||
for (const item of media) {
|
||||
if (item.kind !== 'EPISODE') continue;
|
||||
const season = item.seasonNumber ?? 1;
|
||||
const episodes = seasonsByNumber.get(season) ?? [];
|
||||
episodes.push(item);
|
||||
seasonsByNumber.set(season, episodes);
|
||||
}
|
||||
const seasons = [...seasonsByNumber.entries()].sort(([left], [right]) => left - right)
|
||||
.map(([number, episodes]) => ({ number, title: { en: `Season ${number}` }, episodes }));
|
||||
const published = media.some((item) => item.published);
|
||||
return {
|
||||
id: first.titleId,
|
||||
slug: slugify(identity.title),
|
||||
kind: identity.kind,
|
||||
title: { en: identity.title },
|
||||
published,
|
||||
playable: published,
|
||||
mediaItemId: first.id,
|
||||
resumeMediaItemId: first.id,
|
||||
...(identity.kind === 'MOVIE' ? { runtimeSeconds: first.durationSeconds } : {}),
|
||||
...(identity.kind === 'SERIES' ? { seasonCount: seasons.length, episodeCount: media.length } : {}),
|
||||
seasons,
|
||||
mediaItems: media,
|
||||
};
|
||||
});
|
||||
items.sort((left, right) => left.title.en.localeCompare(right.title.en));
|
||||
const generatedAt = new Date().toISOString();
|
||||
const titles: PublicTitleDetail[] = items.map((item) => ({
|
||||
id: item.id,
|
||||
slug: item.slug,
|
||||
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 },
|
||||
playable: item.playable,
|
||||
...(item.playable ? { resumeMediaItemId: item.resumeMediaItemId } : {}),
|
||||
synopsis: {},
|
||||
...(item.kind === 'SERIES'
|
||||
? { seasons: item.seasons.map((season) => ({ number: season.number, episodeCount: season.episodes.length })) }
|
||||
: {}),
|
||||
mediaItems: item.mediaItems.map((media): PublicMediaItem => ({
|
||||
id: media.id,
|
||||
kind: media.kind,
|
||||
...(media.seasonNumber === undefined ? {} : { seasonNumber: media.seasonNumber }),
|
||||
...(media.episodeNumber === undefined ? {} : { episodeNumber: media.episodeNumber }),
|
||||
name: { fa: media.title.fa ?? media.title.en, en: media.title.en },
|
||||
durationSeconds: media.durationSeconds,
|
||||
compatibility: media.compatibility,
|
||||
published: media.published,
|
||||
})),
|
||||
updatedAt: generatedAt,
|
||||
}));
|
||||
return {
|
||||
catalog: { version: 1, generatedAt, titles },
|
||||
inventory: { version: 1, generatedAt, archiveRoot: root, items },
|
||||
};
|
||||
}
|
||||
|
||||
export function findMediaItem(snapshot: InventorySnapshot, idOrPath: string): SnapshotMediaItem | undefined {
|
||||
return snapshot.items.flatMap((item) => item.mediaItems)
|
||||
.find((media) => media.id === idOrPath || media.sourcePath === idOrPath);
|
||||
}
|
||||
@@ -0,0 +1,567 @@
|
||||
#!/usr/bin/env node
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
createDatabase,
|
||||
markArchiveScanFailed,
|
||||
markArchiveScanRunning,
|
||||
markArchiveScanSucceeded,
|
||||
syncCatalogSnapshot,
|
||||
type Database,
|
||||
} from '@easy-stream/database';
|
||||
import {
|
||||
classifyMedia,
|
||||
extractAndStoreFonts,
|
||||
extractSubtitleVariants,
|
||||
evictCacheGeneration,
|
||||
fingerprintSource,
|
||||
isPathInside,
|
||||
normalizeStreamLanguage,
|
||||
packageProgressiveHls,
|
||||
prepareCompatibilityHls,
|
||||
probeMedia,
|
||||
publishGenerationFonts,
|
||||
pruneOrphanedFonts,
|
||||
resolveInside,
|
||||
touchCacheGeneration,
|
||||
writeCacheMetadata,
|
||||
} from '@easy-stream/media';
|
||||
import {
|
||||
deterministicUuid,
|
||||
findMediaItem,
|
||||
scanArchive,
|
||||
type InventorySnapshot,
|
||||
type SnapshotMediaItem,
|
||||
} from './catalog.js';
|
||||
import { sweepCache } from './cache-lifecycle.js';
|
||||
import {
|
||||
normalizeTrackLabel,
|
||||
removeGenerationFromRegistry,
|
||||
updateRegistry,
|
||||
} from './registry.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;
|
||||
}
|
||||
}
|
||||
|
||||
interface Arguments {
|
||||
command?: string;
|
||||
flags: Map<string, string | true>;
|
||||
}
|
||||
|
||||
interface CommandRuntime {
|
||||
protectedCacheKeys?: () => Promise<ReadonlySet<string>>;
|
||||
}
|
||||
|
||||
function parseArguments(argv: readonly string[]): Arguments {
|
||||
const flags = new Map<string, string | true>();
|
||||
let command: string | undefined;
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const value = argv[index];
|
||||
if (value === undefined || value === '--') continue;
|
||||
if (!value.startsWith('--') && command === undefined) {
|
||||
command = value;
|
||||
continue;
|
||||
}
|
||||
if (!value.startsWith('--')) throw new Error(`Unexpected positional argument: ${value}`);
|
||||
const equals = value.indexOf('=');
|
||||
if (equals >= 0) {
|
||||
flags.set(value.slice(2, equals), value.slice(equals + 1));
|
||||
continue;
|
||||
}
|
||||
const next = argv[index + 1];
|
||||
if (next !== undefined && !next.startsWith('--')) {
|
||||
flags.set(value.slice(2), next);
|
||||
index += 1;
|
||||
} else {
|
||||
flags.set(value.slice(2), true);
|
||||
}
|
||||
}
|
||||
return { ...(command === undefined ? {} : { command }), flags };
|
||||
}
|
||||
|
||||
function flag(arguments_: Arguments, name: string, fallback?: string): string | undefined {
|
||||
const value = arguments_.flags.get(name);
|
||||
if (value === true) throw new Error(`--${name} requires a value`);
|
||||
return value ?? fallback;
|
||||
}
|
||||
|
||||
async function writeJsonAtomic(destinationPath: string, value: unknown): Promise<void> {
|
||||
const destination = path.resolve(destinationPath);
|
||||
await mkdir(path.dirname(destination), { recursive: true, mode: 0o750 });
|
||||
const temporary = `${destination}.${process.pid}.tmp`;
|
||||
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o640 });
|
||||
await rename(temporary, destination);
|
||||
}
|
||||
|
||||
async function scanCommand(arguments_: Arguments): Promise<void> {
|
||||
const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies');
|
||||
const output = flag(arguments_, 'output');
|
||||
const inventoryOutput = flag(arguments_, 'inventory-output')
|
||||
?? (output === undefined ? undefined : path.join(path.dirname(output), 'inventory.json'));
|
||||
if ((output !== undefined && isPathInside(archiveRoot, path.resolve(output)))
|
||||
|| (inventoryOutput !== undefined && isPathInside(archiveRoot, path.resolve(inventoryOutput)))) {
|
||||
throw new Error('Catalog output must not be written into the read-only archive');
|
||||
}
|
||||
const result = await scanArchive({
|
||||
archiveRoot,
|
||||
...(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`);
|
||||
},
|
||||
});
|
||||
if (output !== undefined) {
|
||||
await Promise.all([
|
||||
writeJsonAtomic(output, result.catalog),
|
||||
...(inventoryOutput === undefined ? [] : [writeJsonAtomic(inventoryOutput, result.inventory)]),
|
||||
]);
|
||||
}
|
||||
|
||||
// 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({
|
||||
output: path.resolve(output),
|
||||
...(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 }),
|
||||
})}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
async function withDatabase<T>(
|
||||
connectionString: string,
|
||||
action: (database: Database) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const connection = createDatabase(connectionString, { max: 2 });
|
||||
try {
|
||||
return await action(connection.db);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadInventory(snapshotPath: string): Promise<InventorySnapshot> {
|
||||
const value = JSON.parse(await readFile(snapshotPath, 'utf8')) as InventorySnapshot;
|
||||
if (value.version !== 1 || !Array.isArray(value.items)) throw new Error('Unsupported catalog snapshot');
|
||||
return value;
|
||||
}
|
||||
|
||||
async function sourceSelection(
|
||||
arguments_: Arguments,
|
||||
archiveRoot: string,
|
||||
): Promise<{ media: SnapshotMediaItem; sourcePath: string }> {
|
||||
const mediaItem = flag(arguments_, 'media-item');
|
||||
const requestedSource = flag(arguments_, 'source');
|
||||
const inventoryPath = flag(arguments_, 'inventory', './data/inventory.json') ?? './data/inventory.json';
|
||||
let inventory: InventorySnapshot | undefined;
|
||||
try {
|
||||
inventory = await loadInventory(inventoryPath);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || mediaItem !== undefined) throw error;
|
||||
}
|
||||
const selected = mediaItem === undefined
|
||||
? (requestedSource === undefined ? undefined : inventory === undefined ? undefined : findMediaItem(inventory, requestedSource))
|
||||
: inventory === undefined ? undefined : findMediaItem(inventory, mediaItem);
|
||||
if (selected !== undefined) {
|
||||
return { media: selected, 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');
|
||||
const sourcePath = await resolveInside(
|
||||
archiveRoot,
|
||||
path.isAbsolute(requestedSource) ? requestedSource : path.join(archiveRoot, requestedSource),
|
||||
);
|
||||
const relative = path.relative(archiveRoot, sourcePath).split(path.sep).join('/');
|
||||
const ffprobePath = flag(arguments_, 'ffprobe');
|
||||
const probe = await probeMedia(sourcePath, ffprobePath === undefined ? {} : { ffprobePath });
|
||||
const fingerprint = await fingerprintSource(archiveRoot, sourcePath);
|
||||
const classification = classifyMedia(probe);
|
||||
return {
|
||||
sourcePath,
|
||||
media: {
|
||||
id: deterministicUuid(`media:${relative}`),
|
||||
titleId: deterministicUuid(`title:${relative}`),
|
||||
kind: 'MOVIE',
|
||||
sourcePath: relative,
|
||||
durationSeconds: Number(probe.format.duration) || 0,
|
||||
title: { en: path.basename(relative, path.extname(relative)) },
|
||||
published: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class),
|
||||
compatibility: classification.class,
|
||||
compatibilityReasons: classification.reasons,
|
||||
fingerprint,
|
||||
streams: [],
|
||||
subtitles: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): Promise<void> {
|
||||
const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies');
|
||||
const cacheRoot = path.resolve(flag(arguments_, 'cache', './data/media-cache') ?? './data/media-cache');
|
||||
const registryPath = path.resolve(flag(arguments_, 'registry', './data/package-registry.json') ?? './data/package-registry.json');
|
||||
if (isPathInside(archiveRoot, cacheRoot) || isPathInside(archiveRoot, registryPath)) {
|
||||
throw new Error('Cache and registry must be outside the read-only archive');
|
||||
}
|
||||
const selected = await sourceSelection(arguments_, archiveRoot);
|
||||
const [probe, fingerprint] = await Promise.all([
|
||||
probeMedia(selected.sourcePath, flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
|
||||
fingerprintSource(archiveRoot, selected.sourcePath),
|
||||
]);
|
||||
const classification = classifyMedia(probe);
|
||||
if (!['COPY', 'AUDIO_TRANSCODE'].includes(classification.class)) {
|
||||
throw new Error(`Media requires offline preparation (${classification.class}): ${classification.reasons.join(', ')}`);
|
||||
}
|
||||
const generationId = deterministicUuid(`generation:cmaf-v1:${fingerprint.digest}`);
|
||||
const generationPath = `generations/${generationId}`;
|
||||
const ffmpegPath = flag(arguments_, 'ffmpeg');
|
||||
const ffprobePath = flag(arguments_, 'ffprobe');
|
||||
const preparing = async (error?: string): Promise<void> => {
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
generationId,
|
||||
state: error === undefined ? 'PREPARING' : 'FAILED',
|
||||
playable: false,
|
||||
...(error === undefined ? { pollAfterMs: 1000 } : { reasonCode: 'PACKAGE_FAILED' }),
|
||||
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
|
||||
});
|
||||
};
|
||||
type Assets = {
|
||||
subtitles: Awaited<ReturnType<typeof extractSubtitleVariants>>;
|
||||
fonts: Awaited<ReturnType<typeof extractAndStoreFonts>>;
|
||||
};
|
||||
let assetError: unknown;
|
||||
let assetsPromise: Promise<Assets | undefined> | undefined;
|
||||
const startAssets = (): void => {
|
||||
if (assetsPromise !== undefined) return;
|
||||
assetsPromise = Promise.all([
|
||||
extractSubtitleVariants(selected.sourcePath, probe, {
|
||||
archiveRoot,
|
||||
outputRoot: cacheRoot,
|
||||
generation: generationPath,
|
||||
...(ffmpegPath === undefined ? {} : { ffmpegPath }),
|
||||
}),
|
||||
extractAndStoreFonts(selected.sourcePath, probe, {
|
||||
archiveRoot,
|
||||
fontRoot: path.join(cacheRoot, 'assets', 'fonts'),
|
||||
...(ffmpegPath === undefined ? {} : { ffmpegPath }),
|
||||
...(flag(arguments_, 'font-sanitizer') === undefined ? {} : { sanitizerPath: flag(arguments_, 'font-sanitizer') as string }),
|
||||
}),
|
||||
]).then(async ([subtitles, storedFonts]) => ({
|
||||
subtitles,
|
||||
fonts: await publishGenerationFonts(storedFonts, cacheRoot, path.join(cacheRoot, generationPath)),
|
||||
})).catch((error: unknown) => {
|
||||
assetError = error;
|
||||
return undefined;
|
||||
});
|
||||
};
|
||||
let result: Awaited<ReturnType<typeof packageProgressiveHls>>;
|
||||
try {
|
||||
result = await packageProgressiveHls({
|
||||
archiveRoot,
|
||||
cacheRoot,
|
||||
sourcePath: selected.sourcePath,
|
||||
fingerprint,
|
||||
probe,
|
||||
classification,
|
||||
generation: generationId,
|
||||
...(ffmpegPath === undefined ? {} : { ffmpegPath }),
|
||||
...(ffprobePath === undefined ? {} : { ffprobePath }),
|
||||
async onProgress(progress) {
|
||||
startAssets();
|
||||
await preparing(progress.state === 'FAILED'
|
||||
? progress.error ?? 'Unknown packaging error'
|
||||
: undefined);
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
await assetsPromise;
|
||||
await preparing(error instanceof Error ? error.message : String(error));
|
||||
throw error;
|
||||
}
|
||||
startAssets();
|
||||
const assets = await assetsPromise;
|
||||
if (assetError !== undefined || assets === undefined) {
|
||||
const error = assetError instanceof Error ? assetError : new Error(String(assetError ?? 'Asset preparation failed'));
|
||||
await preparing(error.message);
|
||||
throw error;
|
||||
}
|
||||
const { subtitles, fonts } = assets;
|
||||
const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio');
|
||||
const fontUrls = fonts.map((font) => `/media/${generationPath}/fonts/${font.sha256}.${font.format}`);
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
generationId,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
manifestPath: `/media/${generationPath}/master.m3u8`,
|
||||
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
|
||||
audioTracks: audioStreams.map((stream, index) => ({
|
||||
id: deterministicUuid(`audio:${selected.media.id}:${stream.index}`),
|
||||
language: normalizeStreamLanguage(stream),
|
||||
label: normalizeTrackLabel(stream.tags?.title, normalizeStreamLanguage(stream)),
|
||||
default: index === 0,
|
||||
})),
|
||||
subtitleTracks: subtitles.map((subtitle) => ({
|
||||
id: deterministicUuid(`subtitle:${selected.media.id}:${subtitle.streamIndex}`),
|
||||
language: subtitle.language,
|
||||
label: subtitle.language,
|
||||
default: subtitle.default,
|
||||
forced: subtitle.forced,
|
||||
assUrl: `/media/${path.relative(cacheRoot, subtitle.assPath).split(path.sep).join('/')}`,
|
||||
vttUrl: `/media/${path.relative(cacheRoot, subtitle.vttPath).split(path.sep).join('/')}`,
|
||||
fontUrls,
|
||||
})),
|
||||
});
|
||||
await writeCacheMetadata(path.join(cacheRoot, 'generations'), path.join(cacheRoot, generationPath), {
|
||||
key: generationId,
|
||||
lastAccessedAt: new Date().toISOString(),
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
});
|
||||
const protectedKeys = await runtime.protectedCacheKeys?.();
|
||||
const cacheSweep = await sweepCache({
|
||||
cacheRoot,
|
||||
registryPath,
|
||||
capacityBytes: numericFlag(arguments_, 'cache-max-bytes', process.env.CACHE_MAX_BYTES, 2_147_483_648_000),
|
||||
highWatermark: numericFlag(arguments_, 'cache-high-watermark', process.env.CACHE_HIGH_WATERMARK, 0.85),
|
||||
lowWatermark: numericFlag(arguments_, 'cache-low-watermark', process.env.CACHE_LOW_WATERMARK, 0.75),
|
||||
playbackTtlMs: numericFlag(arguments_, 'playback-ttl-seconds', process.env.PLAYBACK_TTL_SECONDS, 4 * 60 * 60) * 1000,
|
||||
...(protectedKeys === undefined ? {} : { protectedKeys }),
|
||||
});
|
||||
process.stdout.write(`${JSON.stringify({ mediaItemId: selected.media.id, generationId, manifestPath: `/media/${generationPath}/master.m3u8`, knownAacRepairs: result.knownAacRepairs, subtitles: subtitles.length, fonts: fonts.length, cacheSweep })}\n`);
|
||||
}
|
||||
|
||||
function numericFlag(
|
||||
arguments_: Arguments,
|
||||
name: string,
|
||||
environmentValue: string | undefined,
|
||||
fallback: number,
|
||||
): number {
|
||||
const value = flag(arguments_, name, environmentValue);
|
||||
const number = value === undefined ? fallback : Number(value);
|
||||
if (!Number.isFinite(number)) throw new Error(`--${name} must be a finite number`);
|
||||
return number;
|
||||
}
|
||||
|
||||
async function prepareCommand(arguments_: Arguments): Promise<void> {
|
||||
const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies');
|
||||
const derivedRoot = path.resolve(flag(arguments_, 'derived', process.env.DERIVED_ROOT ?? './data/media-derived') ?? './data/media-derived');
|
||||
const registryPath = path.resolve(flag(arguments_, 'registry', './data/package-registry.json') ?? './data/package-registry.json');
|
||||
if (isPathInside(archiveRoot, derivedRoot) || isPathInside(archiveRoot, registryPath)) {
|
||||
throw new Error('Derived output and registry must be outside the read-only archive');
|
||||
}
|
||||
const selected = await sourceSelection(arguments_, archiveRoot);
|
||||
const [probe, fingerprint] = await Promise.all([
|
||||
probeMedia(selected.sourcePath, flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
|
||||
fingerprintSource(archiveRoot, selected.sourcePath),
|
||||
]);
|
||||
const classification = classifyMedia(probe);
|
||||
if (classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1');
|
||||
if (classification.class !== 'VIDEO_TRANSCODE') {
|
||||
throw new Error(`Offline video compatibility encoding is not applicable to ${classification.class}`);
|
||||
}
|
||||
const generationId = deterministicUuid(`generation:compat-h264-v1:${fingerprint.digest}`);
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
generationId,
|
||||
state: 'PREPARING',
|
||||
playable: false,
|
||||
pollAfterMs: 5000,
|
||||
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
|
||||
});
|
||||
try {
|
||||
const result = await prepareCompatibilityHls({
|
||||
archiveRoot,
|
||||
derivedRoot,
|
||||
sourcePath: selected.sourcePath,
|
||||
fingerprint,
|
||||
probe,
|
||||
classification,
|
||||
generation: generationId,
|
||||
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
|
||||
...(flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
|
||||
});
|
||||
const generationPath = `generations/${generationId}`;
|
||||
const [subtitles, storedFonts] = await Promise.all([
|
||||
extractSubtitleVariants(selected.sourcePath, probe, {
|
||||
archiveRoot,
|
||||
outputRoot: derivedRoot,
|
||||
generation: generationPath,
|
||||
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
|
||||
}),
|
||||
extractAndStoreFonts(selected.sourcePath, probe, {
|
||||
archiveRoot,
|
||||
fontRoot: path.join(derivedRoot, 'assets', 'fonts'),
|
||||
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
|
||||
...(flag(arguments_, 'font-sanitizer') === undefined ? {} : { sanitizerPath: flag(arguments_, 'font-sanitizer') as string }),
|
||||
}),
|
||||
]);
|
||||
const fonts = await publishGenerationFonts(storedFonts, derivedRoot, path.join(derivedRoot, generationPath));
|
||||
const fontUrls = fonts.map((font) => `/media/derived/${generationPath}/fonts/${font.sha256}.${font.format}`);
|
||||
const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio');
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
generationId,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
manifestPath: `/media/derived/${generationPath}/master.m3u8`,
|
||||
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
|
||||
audioTracks: audioStreams.map((stream, index) => ({
|
||||
id: deterministicUuid(`audio:${selected.media.id}:${stream.index}`),
|
||||
language: normalizeStreamLanguage(stream),
|
||||
label: normalizeTrackLabel(stream.tags?.title, normalizeStreamLanguage(stream)),
|
||||
default: index === 0,
|
||||
})),
|
||||
subtitleTracks: subtitles.map((subtitle) => ({
|
||||
id: deterministicUuid(`subtitle:${selected.media.id}:${subtitle.streamIndex}`),
|
||||
language: subtitle.language,
|
||||
label: subtitle.language,
|
||||
default: subtitle.default,
|
||||
forced: subtitle.forced,
|
||||
assUrl: `/media/derived/${path.relative(derivedRoot, subtitle.assPath).split(path.sep).join('/')}`,
|
||||
vttUrl: `/media/derived/${path.relative(derivedRoot, subtitle.vttPath).split(path.sep).join('/')}`,
|
||||
fontUrls,
|
||||
})),
|
||||
});
|
||||
process.stdout.write(`${JSON.stringify({ mediaItemId: selected.media.id, generationId, manifestPath: `/media/derived/${generationPath}/master.m3u8`, knownAacRepairs: result.knownAacRepairs })}\n`);
|
||||
} catch (error) {
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
generationId,
|
||||
state: 'FAILED',
|
||||
playable: false,
|
||||
reasonCode: 'COMPATIBILITY_ENCODE_FAILED',
|
||||
durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function workCommand(arguments_: Arguments): Promise<void> {
|
||||
const redisUrl = flag(arguments_, 'redis', process.env.REDIS_URL);
|
||||
if (redisUrl === undefined) throw new Error('REDIS_URL or --redis is required');
|
||||
const archiveRoot = flag(arguments_, 'root', process.env.ARCHIVE_ROOT ?? './movies') ?? './movies';
|
||||
const cacheRoot = flag(arguments_, 'cache', process.env.MEDIA_CACHE_ROOT ?? process.env.CACHE_ROOT ?? './data/media-cache') ?? './data/media-cache';
|
||||
const catalog = flag(arguments_, 'catalog', process.env.CATALOG_SNAPSHOT_PATH ?? './data/catalog.json') ?? './data/catalog.json';
|
||||
const inventory = flag(arguments_, 'inventory', process.env.MEDIA_INVENTORY_PATH ?? process.env.INVENTORY_SNAPSHOT_PATH ?? './data/inventory.json') ?? './data/inventory.json';
|
||||
const registry = flag(arguments_, 'registry', process.env.PACKAGE_REGISTRY_PATH ?? './data/package-registry.json') ?? './data/package-registry.json';
|
||||
const configuredDatabaseUrl = flag(arguments_, 'database', process.env.DATABASE_URL);
|
||||
const databaseUrl = configuredDatabaseUrl?.trim() ? configuredDatabaseUrl : undefined;
|
||||
const concurrency = Number(flag(
|
||||
arguments_,
|
||||
'concurrency',
|
||||
process.env.MEDIA_WORKER_CONCURRENCY ?? process.env.JIT_REMUX_CONCURRENCY ?? '2',
|
||||
));
|
||||
const ffmpegPath = flag(arguments_, 'ffmpeg', process.env.FFMPEG_PATH);
|
||||
const ffprobePath = flag(arguments_, 'ffprobe', process.env.FFPROBE_PATH);
|
||||
const mediaTools = [
|
||||
...(ffmpegPath === undefined ? [] : ['--ffmpeg', ffmpegPath]),
|
||||
...(ffprobePath === undefined ? [] : ['--ffprobe', ffprobePath]),
|
||||
];
|
||||
const { startMediaQueueWorker } = await import('./work.js');
|
||||
let running: ReturnType<typeof startMediaQueueWorker>;
|
||||
running = startMediaQueueWorker({
|
||||
redisUrl,
|
||||
concurrency,
|
||||
async dispatch(command) {
|
||||
if (command.type === 'media.playback.requested') {
|
||||
await main([
|
||||
'package', '--root', archiveRoot, '--cache', cacheRoot, '--inventory', inventory,
|
||||
'--registry', registry, '--media-item', command.mediaItemId, ...mediaTools,
|
||||
], { protectedCacheKeys: () => running.protectedCacheGenerations() });
|
||||
} else if (command.type === 'archive.scan.requested') {
|
||||
if (databaseUrl !== undefined) {
|
||||
const updated = await withDatabase(databaseUrl, (database) => markArchiveScanRunning(database, command.jobId));
|
||||
if (!updated) throw new Error(`Archive scan job is missing or not runnable: ${command.jobId}`);
|
||||
}
|
||||
await main([
|
||||
'scan', '--root', archiveRoot, '--output', catalog, '--inventory-output', inventory,
|
||||
...(databaseUrl === undefined ? [] : ['--database', databaseUrl]),
|
||||
...mediaTools,
|
||||
]);
|
||||
} else if (command.type === 'package.eviction.requested') {
|
||||
if ((await running.protectedCacheGenerations()).has(command.generationId)) {
|
||||
throw new Error(`Cache generation has an active playback lease: ${command.generationId}`);
|
||||
}
|
||||
const evicted = await evictCacheGeneration(cacheRoot, command.generationId);
|
||||
if (evicted) {
|
||||
await removeGenerationFromRegistry(registry, command.generationId);
|
||||
await pruneOrphanedFonts(cacheRoot);
|
||||
}
|
||||
} else if (command.type === 'cache.generation.accessed') {
|
||||
await running.recordCacheLease(command.generationId, command.protectedUntil);
|
||||
await touchCacheGeneration(cacheRoot, command.generationId, {
|
||||
accessedAt: command.accessedAt,
|
||||
protectedUntil: command.protectedUntil,
|
||||
});
|
||||
} else if (command.type === 'media.publication.changed') {
|
||||
// Publication state is owned by the API/database; no media mutation is necessary.
|
||||
} else {
|
||||
const exhaustive: never = command;
|
||||
throw new Error(`Unsupported media command: ${String(exhaustive)}`);
|
||||
}
|
||||
},
|
||||
async onCompleted(command) {
|
||||
if (command.type !== 'archive.scan.requested' || databaseUrl === undefined) return;
|
||||
const updated = await withDatabase(databaseUrl, (database) => markArchiveScanSucceeded(
|
||||
database,
|
||||
command.jobId,
|
||||
{ catalogPath: path.resolve(catalog), inventoryPath: path.resolve(inventory) },
|
||||
));
|
||||
if (!updated) throw new Error(`Archive scan job did not remain RUNNING: ${command.jobId}`);
|
||||
},
|
||||
async onFailed(command, error, job) {
|
||||
if (command?.type === 'archive.scan.requested' && databaseUrl !== undefined) {
|
||||
try {
|
||||
await withDatabase(databaseUrl, (database) => markArchiveScanFailed(database, command.jobId, error.message));
|
||||
} catch (statusError) {
|
||||
process.stderr.write(`${JSON.stringify({ level: 'error', queue: 'easy-stream-media', jobId: job?.id, command: command.type, error: 'Unable to persist failed job status', detail: statusError instanceof Error ? statusError.message : String(statusError) })}\n`);
|
||||
}
|
||||
}
|
||||
process.stderr.write(`${JSON.stringify({ level: 'error', queue: 'easy-stream-media', jobId: job?.id, command: command?.type, error: error.message })}\n`);
|
||||
},
|
||||
});
|
||||
process.stdout.write(`${JSON.stringify({ state: 'WORKING', queue: 'easy-stream-media', concurrency })}\n`);
|
||||
await new Promise<void>((resolve) => {
|
||||
process.once('SIGINT', resolve);
|
||||
process.once('SIGTERM', resolve);
|
||||
});
|
||||
await running.close();
|
||||
}
|
||||
|
||||
export async function main(
|
||||
argv = process.argv.slice(2),
|
||||
runtime: CommandRuntime = {},
|
||||
): Promise<void> {
|
||||
const arguments_ = parseArguments(argv);
|
||||
if (arguments_.command === 'scan') await scanCommand(arguments_);
|
||||
else if (arguments_.command === 'package') await packageCommand(arguments_, runtime);
|
||||
else if (arguments_.command === 'prepare') await prepareCommand(arguments_);
|
||||
else if (arguments_.command === 'work') await workCommand(arguments_);
|
||||
else {
|
||||
process.stderr.write('Usage:\n worker scan --root DIR [--output FILE] [--inventory-output FILE] [--database URL]\n worker package --root DIR --cache DIR (--media-item ID | --source FILE) [--inventory FILE] [--registry FILE]\n worker prepare --root DIR --derived DIR (--media-item ID | --source FILE) [--inventory FILE]\n worker work --redis URL [--database URL] [--concurrency N]\n');
|
||||
process.exitCode = arguments_.command === undefined ? 0 : 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.url === new URL(process.argv[1] ?? '', 'file:').href) {
|
||||
main().catch((error: unknown) => {
|
||||
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { main } from './cli.js';
|
||||
|
||||
export * from './catalog.js';
|
||||
export * from './registry.js';
|
||||
export * from './cache-lifecycle.js';
|
||||
export * from './work.js';
|
||||
|
||||
export { main } from './cli.js';
|
||||
|
||||
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main().catch((error: unknown) => {
|
||||
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { PackageRegistrySchema } from '@easy-stream/contracts';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
|
||||
const MAX_TRACK_LABEL_LENGTH = 100;
|
||||
const UNSAFE_LABEL_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu;
|
||||
|
||||
/** Converts untrusted container metadata into a bounded, single-line UI label. */
|
||||
export function normalizeTrackLabel(value: string | undefined, fallback: string): string {
|
||||
const clean = (candidate: string | undefined): string => (candidate ?? '')
|
||||
.normalize('NFKC')
|
||||
.replace(UNSAFE_LABEL_CHARACTERS, ' ')
|
||||
.replace(/\s+/gu, ' ')
|
||||
.trim();
|
||||
const label = clean(value) || clean(fallback) || 'und';
|
||||
if (label.length <= MAX_TRACK_LABEL_LENGTH) return label;
|
||||
|
||||
// JSON Schema maxLength is enforced at this boundary. Avoid leaving a lone
|
||||
// high surrogate when the UTF-16 limit cuts through an astral character.
|
||||
let end = MAX_TRACK_LABEL_LENGTH;
|
||||
const finalCodeUnit = label.charCodeAt(end - 1);
|
||||
if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) end -= 1;
|
||||
return label.slice(0, end).trimEnd();
|
||||
}
|
||||
|
||||
export interface RegistryAudioTrack {
|
||||
id: string;
|
||||
language: string;
|
||||
label: string;
|
||||
default: boolean;
|
||||
}
|
||||
|
||||
export interface RegistrySubtitleTrack {
|
||||
id: string;
|
||||
language: string;
|
||||
label: string;
|
||||
default: boolean;
|
||||
forced: boolean;
|
||||
assUrl?: string;
|
||||
vttUrl?: string;
|
||||
fontUrls: string[];
|
||||
}
|
||||
|
||||
export interface RegistryGeneration {
|
||||
mediaItemId: string;
|
||||
state: 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED';
|
||||
generationId?: string;
|
||||
manifestPath?: string;
|
||||
/** True once a progressive EVENT manifest has enough validated media. */
|
||||
playable: boolean;
|
||||
reasonCode?: string;
|
||||
pollAfterMs?: number;
|
||||
durationSeconds?: number;
|
||||
audioTracks?: RegistryAudioTrack[];
|
||||
subtitleTracks?: RegistrySubtitleTrack[];
|
||||
}
|
||||
|
||||
export interface PackageRegistry {
|
||||
version: 1;
|
||||
updatedAt: string;
|
||||
packages: RegistryGeneration[];
|
||||
}
|
||||
|
||||
const writes = new Map<string, Promise<void>>();
|
||||
|
||||
export async function readRegistry(registryPath: string): Promise<PackageRegistry> {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(registryPath, 'utf8'));
|
||||
assertValidRegistry(value, `Invalid package registry at ${registryPath}`);
|
||||
return value;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
return { version: 1, updatedAt: new Date(0).toISOString(), packages: [] };
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeRegistry(registryPath: string, registry: PackageRegistry): Promise<void> {
|
||||
assertValidRegistry(registry, `Refusing to publish invalid package registry at ${registryPath}`);
|
||||
const destination = path.resolve(registryPath);
|
||||
await mkdir(path.dirname(destination), { recursive: true, mode: 0o750 });
|
||||
const temporary = `${destination}.${process.pid}.${randomUUID()}.tmp`;
|
||||
await writeFile(temporary, `${JSON.stringify(registry, null, 2)}\n`, { mode: 0o640 });
|
||||
await rename(temporary, destination);
|
||||
}
|
||||
|
||||
function assertValidRegistry(value: unknown, message: string): asserts value is PackageRegistry {
|
||||
if (Value.Check(PackageRegistrySchema, value)) return;
|
||||
const detail = [...Value.Errors(PackageRegistrySchema, value)]
|
||||
.slice(0, 8)
|
||||
.map((error) => `${error.path || '/'} ${error.message}`)
|
||||
.join('; ');
|
||||
throw new Error(`${message}: ${detail}`);
|
||||
}
|
||||
|
||||
export async function updateRegistry(
|
||||
registryPath: string,
|
||||
mediaItemId: string,
|
||||
generation: RegistryGeneration,
|
||||
): Promise<void> {
|
||||
const key = path.resolve(registryPath);
|
||||
const previous = writes.get(key) ?? Promise.resolve();
|
||||
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);
|
||||
if (index < 0) registry.packages.push(generation);
|
||||
else {
|
||||
const current = registry.packages[index];
|
||||
// An idempotent package verification must never make an already served generation
|
||||
// disappear or regress to PREPARING/FAILED.
|
||||
if (current !== undefined && current.generationId === generation.generationId
|
||||
&& current.state === 'READY' && generation.state !== 'READY') return;
|
||||
registry.packages[index] = generation;
|
||||
}
|
||||
await writeRegistry(key, registry);
|
||||
});
|
||||
writes.set(key, current);
|
||||
try {
|
||||
await current;
|
||||
} finally {
|
||||
if (writes.get(key) === current) writes.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeGenerationFromRegistry(registryPath: string, generationId: string): Promise<boolean> {
|
||||
return (await removeGenerationsFromRegistry(registryPath, new Set([generationId]))).length > 0;
|
||||
}
|
||||
|
||||
export async function removeGenerationsFromRegistry(
|
||||
registryPath: string,
|
||||
generationIds: ReadonlySet<string>,
|
||||
): Promise<string[]> {
|
||||
const key = path.resolve(registryPath);
|
||||
const previous = writes.get(key) ?? Promise.resolve();
|
||||
let removed: string[] = [];
|
||||
const current = previous.catch(() => undefined).then(async () => {
|
||||
const registry = await readRegistry(key);
|
||||
removed = registry.packages
|
||||
.flatMap((entry) => entry.generationId && generationIds.has(entry.generationId) ? [entry.generationId] : []);
|
||||
if (removed.length === 0) return;
|
||||
const packages = registry.packages.filter((entry) => entry.generationId === undefined || !generationIds.has(entry.generationId));
|
||||
registry.packages = packages;
|
||||
registry.updatedAt = new Date().toISOString();
|
||||
await writeRegistry(key, registry);
|
||||
});
|
||||
writes.set(key, current);
|
||||
try {
|
||||
await current;
|
||||
return removed;
|
||||
} finally {
|
||||
if (writes.get(key) === current) writes.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
CACHE_GENERATION_LEASES_KEY,
|
||||
MediaCommandSchema,
|
||||
type MediaCommand,
|
||||
} from '@easy-stream/contracts';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { Worker, type Job } from 'bullmq';
|
||||
import { Redis } from 'ioredis';
|
||||
|
||||
export const MEDIA_QUEUE_NAME = 'easy-stream-media';
|
||||
|
||||
export interface MediaQueueWorkerOptions {
|
||||
redisUrl: string;
|
||||
concurrency?: number;
|
||||
dispatch: (command: MediaCommand, job: Job<MediaCommand>) => Promise<void>;
|
||||
onCompleted?: (command: MediaCommand, job: Job<MediaCommand>) => Promise<void>;
|
||||
onFailed?: (command: MediaCommand | undefined, error: Error, job: Job<MediaCommand> | undefined) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface RunningMediaWorker {
|
||||
worker: Worker<MediaCommand>;
|
||||
recordCacheLease(generationId: string, protectedUntil: string): Promise<void>;
|
||||
protectedCacheGenerations(now?: Date): Promise<ReadonlySet<string>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export function startMediaQueueWorker(options: MediaQueueWorkerOptions): RunningMediaWorker {
|
||||
const concurrency = options.concurrency ?? 2;
|
||||
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 32) {
|
||||
throw new RangeError('Worker concurrency must be between 1 and 32');
|
||||
}
|
||||
const redisOptions = {
|
||||
maxRetriesPerRequest: null,
|
||||
enableReadyCheck: true,
|
||||
} as const;
|
||||
const connection = new Redis(options.redisUrl, redisOptions);
|
||||
const leases = new Redis(options.redisUrl, redisOptions);
|
||||
const worker = new Worker<MediaCommand>(
|
||||
MEDIA_QUEUE_NAME,
|
||||
async (job) => {
|
||||
if (!Value.Check(MediaCommandSchema, job.data)) throw new Error(`Invalid media command in job ${job.id ?? 'unknown'}`);
|
||||
await options.dispatch(job.data, job);
|
||||
await options.onCompleted?.(job.data, job);
|
||||
},
|
||||
{ connection, concurrency },
|
||||
);
|
||||
worker.on('failed', (job, error) => {
|
||||
void options.onFailed?.(job?.data, error, job);
|
||||
});
|
||||
worker.on('error', (error) => {
|
||||
void options.onFailed?.(undefined, error, undefined);
|
||||
});
|
||||
return {
|
||||
worker,
|
||||
async recordCacheLease(generationId, protectedUntil) {
|
||||
const expiration = Date.parse(protectedUntil);
|
||||
if (!Number.isFinite(expiration)) throw new Error('Invalid cache lease expiration');
|
||||
await leases.zadd(CACHE_GENERATION_LEASES_KEY, 'GT', expiration, generationId);
|
||||
},
|
||||
async protectedCacheGenerations(now = new Date()) {
|
||||
const timestamp = now.getTime();
|
||||
await leases.zremrangebyscore(CACHE_GENERATION_LEASES_KEY, '-inf', timestamp);
|
||||
return new Set(await leases.zrangebyscore(CACHE_GENERATION_LEASES_KEY, timestamp + 1, '+inf'));
|
||||
},
|
||||
async close() {
|
||||
await worker.close();
|
||||
await Promise.all([connection.quit(), leases.quit()]);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { mkdtemp, mkdir, stat, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { writeCacheMetadata } from '@easy-stream/media';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sweepCache } from '../src/cache-lifecycle.js';
|
||||
import { readRegistry, updateRegistry } from '../src/registry.js';
|
||||
|
||||
describe('worker cache lifecycle', () => {
|
||||
it('evicts to the low watermark, removes registry rows, and prunes font orphans', async () => {
|
||||
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-sweep-'));
|
||||
const cacheRoot = path.join(base, 'cache');
|
||||
const generations = path.join(cacheRoot, 'generations');
|
||||
const registryPath = path.join(base, 'registry.json');
|
||||
const oldGeneration = '11111111-1111-4111-8111-111111111111';
|
||||
const protectedGeneration = '22222222-2222-4222-8222-222222222222';
|
||||
for (const generation of [oldGeneration, protectedGeneration]) {
|
||||
const directory = path.join(generations, generation);
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(path.join(directory, 'segment.m4s'), Buffer.alloc(60));
|
||||
await writeCacheMetadata(generations, directory, {
|
||||
key: generation,
|
||||
bytes: 60,
|
||||
lastAccessedAt: '2020-01-01T00:00:00.000Z',
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
});
|
||||
await updateRegistry(registryPath, generation, {
|
||||
mediaItemId: generation,
|
||||
generationId: generation,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
manifestPath: `/media/generations/${generation}/master.m3u8`,
|
||||
});
|
||||
}
|
||||
const fontStore = path.join(cacheRoot, 'assets', 'fonts', 'sha256');
|
||||
const orphanFont = path.join(fontStore, `${'a'.repeat(64)}.ttf`);
|
||||
await mkdir(fontStore, { recursive: true });
|
||||
await writeFile(orphanFont, Buffer.alloc(10));
|
||||
|
||||
const result = await sweepCache({
|
||||
cacheRoot,
|
||||
registryPath,
|
||||
capacityBytes: 100,
|
||||
highWatermark: 0.85,
|
||||
lowWatermark: 0.75,
|
||||
playbackTtlMs: 0,
|
||||
protectedKeys: new Set([protectedGeneration]),
|
||||
fontOrphanMinimumAgeMs: 0,
|
||||
now: new Date('2999-01-01T00:00:00.000Z'),
|
||||
});
|
||||
|
||||
expect(result.evicted).toEqual([oldGeneration]);
|
||||
expect(result.registryEntriesRemoved).toEqual([oldGeneration]);
|
||||
expect(result.orphanFontsRemoved).toEqual([path.basename(orphanFont)]);
|
||||
expect((await readRegistry(registryPath)).packages).toEqual([
|
||||
expect.objectContaining({ generationId: protectedGeneration }),
|
||||
]);
|
||||
await expect(stat(path.join(generations, oldGeneration))).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
await expect(stat(path.join(generations, protectedGeneration))).resolves.toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { deterministicUuid, parseMediaIdentity, shouldInspectSubtitleContent, slugify } from '../src/catalog.js';
|
||||
|
||||
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' });
|
||||
});
|
||||
|
||||
it('creates stable UUIDs and Unicode-safe slugs', () => {
|
||||
expect(deterministicUuid('same')).toBe(deterministicUuid('same'));
|
||||
expect(deterministicUuid('same')).toMatch(/^[0-9a-f-]{36}$/u);
|
||||
expect(slugify('فیلم نمونه')).toBe('فیلم-نمونه');
|
||||
});
|
||||
|
||||
it('samples only unknown textual subtitle languages during archive scans', () => {
|
||||
expect(shouldInspectSubtitleContent({ index: 2, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'qad' } })).toBe(true);
|
||||
expect(shouldInspectSubtitleContent({ index: 3, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'und' } })).toBe(true);
|
||||
expect(shouldInspectSubtitleContent({ index: 4, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'per' } })).toBe(false);
|
||||
expect(shouldInspectSubtitleContent({ index: 5, codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' } })).toBe(false);
|
||||
expect(shouldInspectSubtitleContent({ index: 6, codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle' })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { mkdtemp, readFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { PackageRegistrySchema } from '@easy-stream/contracts';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import {
|
||||
normalizeTrackLabel,
|
||||
readRegistry,
|
||||
removeGenerationFromRegistry,
|
||||
updateRegistry,
|
||||
} from '../src/registry.js';
|
||||
|
||||
describe('local generation registry', () => {
|
||||
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');
|
||||
const mediaItemId = '11111111-1111-4111-8111-111111111111';
|
||||
const generationId = '22222222-2222-4222-8222-222222222222';
|
||||
await updateRegistry(registryPath, mediaItemId, {
|
||||
mediaItemId, generationId, state: 'READY', playable: true,
|
||||
manifestPath: `/media/generations/${generationId}/master.m3u8`,
|
||||
});
|
||||
const registry = await readRegistry(registryPath);
|
||||
expect(registry.packages[0]).toMatchObject({ state: 'READY', playable: true });
|
||||
expect(Value.Check(PackageRegistrySchema, registry)).toBe(true);
|
||||
expect(JSON.parse(await readFile(registryPath, 'utf8'))).toMatchObject({ version: 1 });
|
||||
await updateRegistry(registryPath, mediaItemId, {
|
||||
mediaItemId, generationId, state: 'PREPARING', playable: false,
|
||||
});
|
||||
expect((await readRegistry(registryPath)).packages[0]).toMatchObject({
|
||||
state: 'READY', playable: true, manifestPath: `/media/generations/${generationId}/master.m3u8`,
|
||||
});
|
||||
expect(await removeGenerationFromRegistry(registryPath, generationId)).toBe(true);
|
||||
expect((await readRegistry(registryPath)).packages).toEqual([]);
|
||||
});
|
||||
|
||||
it('normalizes oversized and control-character container labels for the API contract', async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-label-'));
|
||||
const registryPath = path.join(directory, 'package-registry.json');
|
||||
const mediaItemId = '11111111-1111-4111-8111-111111111111';
|
||||
const generationId = '22222222-2222-4222-8222-222222222222';
|
||||
const rawMkvTitle = ` Persian\u0000\n\tAudio\u202e ${'x'.repeat(180)} `;
|
||||
const label = normalizeTrackLabel(rawMkvTitle, 'fa');
|
||||
|
||||
expect(label.length).toBeLessThanOrEqual(100);
|
||||
expect(label).toBe(`Persian Audio ${'x'.repeat(86)}`);
|
||||
expect(label).not.toMatch(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u);
|
||||
|
||||
await updateRegistry(registryPath, mediaItemId, {
|
||||
mediaItemId,
|
||||
generationId,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
manifestPath: `/media/generations/${generationId}/master.m3u8`,
|
||||
audioTracks: [{
|
||||
id: '33333333-3333-4333-8333-333333333333',
|
||||
language: 'fa',
|
||||
label,
|
||||
default: true,
|
||||
}],
|
||||
});
|
||||
|
||||
const registry = await readRegistry(registryPath);
|
||||
expect(Value.Check(PackageRegistrySchema, registry)).toBe(true);
|
||||
expect(registry.packages[0]?.audioTracks?.[0]?.label).toBe(label);
|
||||
});
|
||||
|
||||
it('rejects an invalid update before replacing a valid registry file', async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-invalid-'));
|
||||
const registryPath = path.join(directory, 'package-registry.json');
|
||||
const mediaItemId = '11111111-1111-4111-8111-111111111111';
|
||||
const generationId = '22222222-2222-4222-8222-222222222222';
|
||||
await updateRegistry(registryPath, mediaItemId, {
|
||||
mediaItemId,
|
||||
generationId,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
manifestPath: `/media/generations/${generationId}/master.m3u8`,
|
||||
});
|
||||
const before = await readFile(registryPath, 'utf8');
|
||||
|
||||
await expect(updateRegistry(registryPath, mediaItemId, {
|
||||
mediaItemId,
|
||||
generationId,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
manifestPath: `/media/generations/${generationId}/master.m3u8`,
|
||||
audioTracks: [{
|
||||
id: '33333333-3333-4333-8333-333333333333',
|
||||
language: 'en',
|
||||
label: 'x'.repeat(101),
|
||||
default: true,
|
||||
}],
|
||||
})).rejects.toThrow(/Refusing to publish invalid package registry/u);
|
||||
|
||||
expect(await readFile(registryPath, 'utf8')).toBe(before);
|
||||
expect(Value.Check(PackageRegistrySchema, await readRegistry(registryPath))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { MEDIA_QUEUE_NAME, startMediaQueueWorker } from '../src/work.js';
|
||||
|
||||
describe('BullMQ media worker', () => {
|
||||
it('uses the API queue name and rejects unsafe concurrency before connecting', () => {
|
||||
expect(MEDIA_QUEUE_NAME).toBe('easy-stream-media');
|
||||
expect(() => startMediaQueueWorker({
|
||||
redisUrl: 'redis://127.0.0.1:1',
|
||||
concurrency: 0,
|
||||
async dispatch() {},
|
||||
})).toThrow('concurrency');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"types": ["node"],
|
||||
"paths": {
|
||||
"@easy-stream/contracts": ["packages/contracts/dist/index.d.ts"],
|
||||
"@easy-stream/database": ["packages/database/dist/index.d.ts"],
|
||||
"@easy-stream/media": ["packages/media/dist/index.d.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
name: easy-stream
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: easy_stream
|
||||
POSTGRES_USER: easy_stream
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U easy_stream -d easy_stream"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
networks:
|
||||
- backend
|
||||
|
||||
redis:
|
||||
image: redis:8-alpine
|
||||
restart: unless-stopped
|
||||
command: ["redis-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
networks:
|
||||
- backend
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/docker/node.Dockerfile
|
||||
target: api
|
||||
command: ["./node_modules/.bin/drizzle-kit", "migrate", "--config", "drizzle.config.ts"]
|
||||
working_dir: /app/packages/database
|
||||
environment:
|
||||
DATABASE_URL: postgres://easy_stream:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/easy_stream
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- backend
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/docker/node.Dockerfile
|
||||
target: api
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
env_file: .env
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
REPOSITORY_DRIVER: postgres
|
||||
DATABASE_URL: postgres://easy_stream:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/easy_stream
|
||||
REDIS_URL: redis://redis:6379
|
||||
METADATA_ROOT: /data/metadata
|
||||
CATALOG_SNAPSHOT_PATH: /data/metadata/catalog.json
|
||||
PACKAGE_REGISTRY_PATH: /data/metadata/package-registry.json
|
||||
CACHE_ROOT: /data/cache
|
||||
# Use the same Compose interpolation source as the gateway. Values from
|
||||
# env_file alone can diverge when operators use --env-file or shell
|
||||
# overrides, which would make every media authorization request fail.
|
||||
MEDIA_AUTH_SHARED_SECRET: ${MEDIA_AUTH_SHARED_SECRET:?set MEDIA_AUTH_SHARED_SECRET in .env}
|
||||
volumes:
|
||||
- ${METADATA_ROOT:-./data/metadata}:/data/metadata:ro
|
||||
- ${CACHE_ROOT:-./data/cache}:/data/cache:ro
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- backend
|
||||
- edge
|
||||
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/docker/node.Dockerfile
|
||||
target: worker
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
DATABASE_URL: postgres://easy_stream:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/easy_stream
|
||||
REDIS_URL: redis://redis:6379
|
||||
ARCHIVE_ROOT: /archive
|
||||
CACHE_ROOT: /data/cache
|
||||
DERIVED_ROOT: /data/derived
|
||||
METADATA_ROOT: /data/metadata
|
||||
CATALOG_SNAPSHOT_PATH: /data/metadata/catalog.json
|
||||
INVENTORY_SNAPSHOT_PATH: /data/metadata/inventory.json
|
||||
PACKAGE_REGISTRY_PATH: /data/metadata/package-registry.json
|
||||
FFMPEG_PATH: /opt/ffmpeg/bin/ffmpeg
|
||||
FFPROBE_PATH: /opt/ffmpeg/bin/ffprobe
|
||||
PLAYBACK_PROFILE: ${PLAYBACK_PROFILE:-cmaf-v1}
|
||||
PLAYBACK_TTL_SECONDS: ${PLAYBACK_TTL_SECONDS:-14400}
|
||||
CACHE_MAX_BYTES: ${CACHE_MAX_BYTES:-2147483648000}
|
||||
CACHE_HIGH_WATERMARK: ${CACHE_HIGH_WATERMARK:-0.85}
|
||||
CACHE_LOW_WATERMARK: ${CACHE_LOW_WATERMARK:-0.75}
|
||||
MEDIA_WORKER_CONCURRENCY: ${JIT_REMUX_CONCURRENCY:-2}
|
||||
volumes:
|
||||
- ${ARCHIVE_ROOT:-./movies}:/archive:ro
|
||||
- ${CACHE_ROOT:-./data/cache}:/data/cache
|
||||
- ${DERIVED_ROOT:-./data/derived}:/data/derived
|
||||
- ${METADATA_ROOT:-./data/metadata}:/data/metadata
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- backend
|
||||
|
||||
gateway:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/docker/node.Dockerfile
|
||||
target: gateway
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${GATEWAY_BIND_ADDRESS:-0.0.0.0}:8080:8080"
|
||||
environment:
|
||||
MEDIA_AUTH_SHARED_SECRET: ${MEDIA_AUTH_SHARED_SECRET:?set MEDIA_AUTH_SHARED_SECRET in .env}
|
||||
volumes:
|
||||
- ${CACHE_ROOT:-./data/cache}:/srv/easy-stream/cache:ro
|
||||
- ${DERIVED_ROOT:-./data/derived}:/srv/easy-stream/derived:ro
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
networks:
|
||||
- backend
|
||||
- edge
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
redis-data:
|
||||
|
||||
networks:
|
||||
backend:
|
||||
internal: true
|
||||
edge:
|
||||
@@ -0,0 +1,56 @@
|
||||
# Easy Stream architecture
|
||||
|
||||
## Runtime topology
|
||||
|
||||
```text
|
||||
Browser / TV browser
|
||||
|
|
||||
v
|
||||
CDN (production, provider managed externally)
|
||||
|
|
||||
v
|
||||
Nginx gateway ───────> Vue SPA
|
||||
| |
|
||||
| └─────────> versioned CMAF/HLS cache
|
||||
v
|
||||
Fastify API ─────────> PostgreSQL
|
||||
| |
|
||||
└───────────────> Redis/BullMQ
|
||||
|
|
||||
v
|
||||
FFmpeg media worker
|
||||
| |
|
||||
v v
|
||||
read-only MKV cache/derived volumes
|
||||
archive
|
||||
```
|
||||
|
||||
The archive is never exposed over HTTP and is never writable by an application container. Nginx serves only generated, versioned media after a signed playback-cookie check. Media is private-cache by default. A production CDN may turn on shared caching only when its edge validates an equivalent grant before checking its cache; forwarding a cookie only on an origin miss is insufficient.
|
||||
|
||||
## Media lifecycle
|
||||
|
||||
1. The worker walks regular `.mkv` files under `ARCHIVE_ROOT`, rejects escaping symlinks, fingerprints the file, 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.
|
||||
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.
|
||||
|
||||
## Trust boundaries
|
||||
|
||||
- Archive filenames, Matroska flags, subtitle text, fonts, and metadata are untrusted input.
|
||||
- FFmpeg and ffprobe are spawned with argument arrays and no shell.
|
||||
- Worker processes run unprivileged with a read-only archive and receive only their database, Redis, path, and media settings—not playback, administrator, media-auth, or TMDB secrets. FFmpeg/ffprobe children receive a further allowlisted environment without database or Redis credentials.
|
||||
- Generated paths use server identifiers rather than source filenames.
|
||||
- The gateway applies CSP, COOP, COEP, nosniff, frame, and referrer protections.
|
||||
- Playback cookies are scoped to one media generation and expire after four hours.
|
||||
- Viewer state stays in IndexedDB; there is no viewer identity database in v1.
|
||||
|
||||
## Scale boundaries
|
||||
|
||||
The first deployment targets 1,000 peak concurrent viewers behind a CDN. JIT packaging defaults to two concurrent jobs and compatibility encoding to one CPU-limited job. PostgreSQL, Redis, the API, workers, cache, and gateway have explicit boundaries so they can be moved to separate hosts without changing public API contracts.
|
||||
|
||||
The implemented scanner produces codec/HDR compatibility, duration, stream, subtitle, and fingerprint inventory. Before production disk capacity is purchased, extend the archive census with measured GOP distribution, corruption sampling, aggregate bitrate, and projected derived-storage reports; those expensive archive-wide reports are an acceptance gate, not part of the request-time path.
|
||||
@@ -0,0 +1,74 @@
|
||||
# Operations
|
||||
|
||||
## Interactive Ubuntu bootstrap
|
||||
|
||||
After cloning the repository on an Ubuntu server, run:
|
||||
|
||||
```sh
|
||||
bash scripts/setup-ubuntu.sh
|
||||
```
|
||||
|
||||
The bootstrap uses Docker's signed Ubuntu apt repository, prompts for production values without echoing secrets, optionally generates 256-bit secrets, creates a mode-`0600` `.env`, and validates Compose before it offers to start the stack. It refuses overlapping archive/cache/derived/metadata paths and warns when the host archive mount is writable or the configured cache exceeds available disk space. Its gateway bind address defaults to `127.0.0.1`; select `0.0.0.0` or a specific interface only when network-level origin restrictions are ready.
|
||||
|
||||
The script intentionally does not add the operator to the `docker` group because that group grants root-equivalent privileges. It uses `sudo` for Docker when needed. It also leaves DNS, HTTPS termination, CDN authorization, firewall policy, storage mounting, and backup automation to the operator.
|
||||
|
||||
## 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
|
||||
- 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.
|
||||
|
||||
Create bind-mount destinations before the first Compose start; otherwise Docker may create root-owned directories that UID/GID 1000 cannot write:
|
||||
|
||||
```sh
|
||||
sudo install -d -o 1000 -g 1000 -m 0750 \
|
||||
/srv/easy-stream/cache \
|
||||
/srv/easy-stream/derived \
|
||||
/srv/easy-stream/metadata
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
## Required production gates
|
||||
|
||||
1. Complete the archive census and size the durable derived volume to 125% of the projected output.
|
||||
2. Validate current and previous-two Chrome/Firefox releases plus the named physical TV test devices.
|
||||
3. Load test 1,000 concurrent playback patterns through the selected CDN.
|
||||
4. Restrict origin ingress to the CDN and administration network.
|
||||
5. Replace all bootstrap credentials and signing secrets.
|
||||
6. Confirm movie, audio, subtitle, font, poster, and territorial distribution rights.
|
||||
7. Confirm a written TMDB commercial agreement before using TMDB in a commercial production service.
|
||||
8. Run migrations against an empty PostgreSQL database and verify API/worker startup before importing the archive.
|
||||
|
||||
## CDN authorization
|
||||
|
||||
The origin sends `Cache-Control: private` for immutable media and `no-store` for manifests. Keep that behavior for initial deployment. Forwarding the playback cookie to the origin secures only cache misses; it does not protect a shared cache hit.
|
||||
|
||||
Enable shared media caching only after the chosen CDN validates a signed cookie or URL before cache lookup and rejects expired grants. Keep manifests uncacheable, cache generation assets by their canonical path after authorization, restrict direct origin ingress to the CDN, and test unauthorized warm-cache requests as part of acceptance.
|
||||
|
||||
Before relying on per-client rate limits or logs, configure Nginx `real_ip_from` only for the selected CDN's published address ranges and map its authenticated client-IP header. The safe default discards client-supplied forwarding chains, which means an unconfigured CDN will otherwise group viewers by edge address.
|
||||
|
||||
## Cache lifecycle
|
||||
|
||||
Playback creation writes a Redis lease through the session expiry and queues a metadata touch. After a successful JIT package, the worker sweeps from the configured high watermark down to the low watermark. It skips active, building, pinned, recently built, or leased generations, removes evicted registry entries atomically, and prunes aged unreferenced global fonts. Durable files under `DERIVED_ROOT` are outside this lifecycle.
|
||||
|
||||
Manual eviction is intentionally refused while a generation has an active lease. If cache pressure cannot fall below the target because every candidate is protected, add capacity or wait for sessions to expire; never remove generation directories by hand while viewers are active.
|
||||
|
||||
## Backups and recovery
|
||||
|
||||
- Back up PostgreSQL and deployment configuration every night and test restoration monthly.
|
||||
- Cache media is disposable and must not be backed up.
|
||||
- Metadata and subtitles are reproducible, but snapshots reduce archive rereads.
|
||||
- Derived compatibility media is reproducible but expensive; snapshot it according to recovery-time requirements.
|
||||
- On source replacement, retain an active old generation until its playback cookies expire, then evict it.
|
||||
- Keep Redis persistence enabled: cache leases are written synchronously before a READY session is returned, then mirrored into generation metadata by the worker. The four-hour recency grace also protects a newly completed cold package before its first poll.
|
||||
|
||||
## Alerts
|
||||
|
||||
Alert on API 5xx rate, playback-session failures, FFmpeg failures, job age, cache pressure, derived disk pressure, archive I/O latency, cold-start p95, origin throughput, invalid signed-cookie spikes, and client fatal-player events.
|
||||
@@ -0,0 +1,77 @@
|
||||
FROM node:24-bookworm-slim AS build
|
||||
|
||||
ENV PNPM_HOME=/pnpm
|
||||
ENV PATH=$PNPM_HOME:$PATH
|
||||
WORKDIR /workspace
|
||||
RUN corepack enable
|
||||
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml tsconfig.base.json ./
|
||||
COPY apps ./apps
|
||||
COPY packages ./packages
|
||||
RUN corepack pnpm install --frozen-lockfile
|
||||
RUN corepack pnpm build
|
||||
|
||||
FROM node:24-bookworm-slim AS ffmpeg-build
|
||||
ARG FFMPEG_VERSION=8.1.2
|
||||
ARG FFMPEG_SHA256=464beb5e7bf0c311e68b45ae2f04e9cc2af88851abb4082231742a74d97b524c
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
build-essential ca-certificates curl libass-dev libfontconfig1-dev \
|
||||
libfreetype6-dev libfribidi-dev libharfbuzz-dev libssl-dev libx264-dev \
|
||||
nasm pkg-config xz-utils yasm zlib1g-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /tmp/ffmpeg
|
||||
RUN curl --fail --location --silent --show-error \
|
||||
"https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \
|
||||
--output ffmpeg.tar.xz \
|
||||
&& echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum --check --strict \
|
||||
&& tar --extract --file ffmpeg.tar.xz --strip-components=1 \
|
||||
&& ./configure \
|
||||
--prefix=/opt/ffmpeg \
|
||||
--disable-debug \
|
||||
--disable-doc \
|
||||
--disable-ffplay \
|
||||
--disable-static \
|
||||
--enable-shared \
|
||||
--enable-gpl \
|
||||
--enable-version3 \
|
||||
--enable-libass \
|
||||
--enable-libfontconfig \
|
||||
--enable-libfreetype \
|
||||
--enable-libx264 \
|
||||
--enable-openssl \
|
||||
&& make -j"$(nproc)" \
|
||||
&& make install
|
||||
|
||||
FROM node:24-bookworm-slim AS api
|
||||
ENV NODE_ENV=production
|
||||
WORKDIR /app
|
||||
COPY --from=build /workspace /app
|
||||
USER node
|
||||
CMD ["node", "apps/api/dist/server.js"]
|
||||
|
||||
FROM node:24-bookworm-slim AS worker
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
ca-certificates libass9 libfontconfig1 libfreetype6 libfribidi0 \
|
||||
libharfbuzz0b libssl3 libx264-164 zlib1g \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=ffmpeg-build /opt/ffmpeg /opt/ffmpeg
|
||||
ENV NODE_ENV=production
|
||||
ENV PATH=/opt/ffmpeg/bin:$PATH
|
||||
ENV LD_LIBRARY_PATH=/opt/ffmpeg/lib
|
||||
WORKDIR /app
|
||||
COPY --from=build /workspace /app
|
||||
USER node
|
||||
CMD ["node", "apps/worker/dist/index.js", "work"]
|
||||
|
||||
FROM nginx:1.28-alpine AS gateway
|
||||
RUN apk add --no-cache ca-certificates \
|
||||
&& addgroup -g 1000 easy-stream \
|
||||
&& adduser -D -H -u 1000 -G easy-stream easy-stream \
|
||||
&& sed -i 's/^user[[:space:]][[:space:]]*nginx;/user easy-stream;/' /etc/nginx/nginx.conf \
|
||||
&& chown -R easy-stream:easy-stream /var/cache/nginx
|
||||
COPY infra/nginx/default.conf.template /etc/nginx/templates/default.conf.template
|
||||
COPY infra/nginx/security-headers.conf /etc/nginx/security-headers.conf
|
||||
COPY --from=build /workspace/apps/web/dist /usr/share/nginx/html
|
||||
@@ -0,0 +1,118 @@
|
||||
map $uri $media_cache_control {
|
||||
default "no-store";
|
||||
~*\.m3u8$ "private, no-cache, no-store, must-revalidate";
|
||||
# Safe origin default: browsers may retain immutable generation assets, but a
|
||||
# shared CDN must not cache them until it enforces playback authorization at
|
||||
# the edge before cache lookup.
|
||||
~*\.(m4s|mp4|vtt|ass|ttf|otf)$ "private, max-age=31536000, immutable";
|
||||
}
|
||||
|
||||
upstream easy_stream_api {
|
||||
server api:3000;
|
||||
keepalive 64;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
server_tokens off;
|
||||
root /usr/share/nginx/html;
|
||||
|
||||
include /etc/nginx/security-headers.conf;
|
||||
|
||||
# Cache bookkeeping is mounted beside public generations but is never media.
|
||||
location ~ (^|/)\. {
|
||||
deny all;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
# Never trust a client-supplied forwarding chain. Configure real_ip_from
|
||||
# for the selected CDN at deployment time if end-user IPs are required.
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_pass http://easy_stream_api;
|
||||
add_header Cache-Control "no-store" always;
|
||||
include /etc/nginx/security-headers.conf;
|
||||
}
|
||||
|
||||
location = /_media_auth {
|
||||
internal;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header X-Original-URI $request_uri;
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
proxy_set_header X-Media-Auth-Secret "${MEDIA_AUTH_SHARED_SECRET}";
|
||||
proxy_pass http://easy_stream_api/internal/media-auth;
|
||||
}
|
||||
|
||||
# Offline compatibility encodes are durable and live on a separate disk.
|
||||
# Keep the more-specific prefix ahead of the bounded JIT cache route.
|
||||
location /media/derived/ {
|
||||
auth_request /_media_auth;
|
||||
alias /srv/easy-stream/derived/;
|
||||
disable_symlinks on;
|
||||
types {
|
||||
application/vnd.apple.mpegurl m3u8;
|
||||
video/iso.segment m4s;
|
||||
video/mp4 mp4;
|
||||
text/vtt vtt;
|
||||
text/x-ssa ass;
|
||||
font/ttf ttf;
|
||||
font/otf otf;
|
||||
}
|
||||
add_header Cache-Control $media_cache_control always;
|
||||
include /etc/nginx/security-headers.conf;
|
||||
}
|
||||
|
||||
location /media/ {
|
||||
auth_request /_media_auth;
|
||||
alias /srv/easy-stream/cache/;
|
||||
disable_symlinks on;
|
||||
types {
|
||||
application/vnd.apple.mpegurl m3u8;
|
||||
video/iso.segment m4s;
|
||||
video/mp4 mp4;
|
||||
text/vtt vtt;
|
||||
text/x-ssa ass;
|
||||
font/ttf ttf;
|
||||
font/otf otf;
|
||||
}
|
||||
add_header Cache-Control $media_cache_control always;
|
||||
include /etc/nginx/security-headers.conf;
|
||||
}
|
||||
|
||||
# TMDB artwork stays same-origin for CSP/COEP and can be cached by the outer CDN.
|
||||
location /images/tmdb/ {
|
||||
limit_except GET HEAD { deny all; }
|
||||
rewrite ^/images/tmdb/(w500|w1280)(/.*)$ /t/p/$1$2 break;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
|
||||
proxy_ssl_verify_depth 3;
|
||||
proxy_set_header Host image.tmdb.org;
|
||||
proxy_hide_header Set-Cookie;
|
||||
proxy_hide_header Cache-Control;
|
||||
proxy_pass https://image.tmdb.org;
|
||||
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";
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
try_files $uri =404;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
include /etc/nginx/security-headers.conf;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
add_header Cache-Control "no-cache";
|
||||
include /etc/nginx/security-headers.conf;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
add_header Cross-Origin-Opener-Policy same-origin always;
|
||||
add_header Cross-Origin-Embedder-Policy require-corp always;
|
||||
add_header Cross-Origin-Resource-Policy same-origin always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; worker-src 'self' blob:; font-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always;
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "easy-stream",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@11.13.0",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "corepack pnpm -r --if-present build",
|
||||
"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",
|
||||
"migrate": "corepack pnpm --filter @easy-stream/database migrate",
|
||||
"clean": "corepack pnpm -r --if-present clean"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@easy-stream/contracts",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": ["dist"],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "^0.34.41"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
import { DateTimeSchema, EmailSchema, UuidSchema } from './common.js';
|
||||
|
||||
export const AdminLoginSchema = Type.Object(
|
||||
{
|
||||
email: EmailSchema,
|
||||
password: Type.String({ minLength: 12, maxLength: 1024 }),
|
||||
totp: Type.Optional(Type.String({ pattern: '^[0-9]{6}$' })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const AdminSessionResponseSchema = Type.Object(
|
||||
{
|
||||
admin: Type.Object(
|
||||
{ id: UuidSchema, email: EmailSchema },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
csrfToken: Type.String(),
|
||||
expiresAt: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const StartScanSchema = Type.Object(
|
||||
{ full: Type.Optional(Type.Boolean({ default: false })) },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PublicationParamsSchema = Type.Object(
|
||||
{ mediaItemId: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PublicationBodySchema = Type.Object(
|
||||
{ published: Type.Boolean() },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const JobStateSchema = Type.Union([
|
||||
Type.Literal('QUEUED'),
|
||||
Type.Literal('RUNNING'),
|
||||
Type.Literal('SUCCEEDED'),
|
||||
Type.Literal('FAILED'),
|
||||
Type.Literal('CANCELLED'),
|
||||
]);
|
||||
|
||||
export const JobSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
type: Type.String(),
|
||||
state: JobStateSchema,
|
||||
progress: Type.Number({ minimum: 0, maximum: 1 }),
|
||||
error: Type.Union([Type.String(), Type.Null()]),
|
||||
createdAt: DateTimeSchema,
|
||||
updatedAt: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const JobParamsSchema = Type.Object({ jobId: UuidSchema }, { additionalProperties: false });
|
||||
export const CacheParamsSchema = Type.Object(
|
||||
{ generationId: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CacheStatusSchema = Type.Object(
|
||||
{
|
||||
usedBytes: Type.Integer({ minimum: 0 }),
|
||||
maxBytes: Type.Integer({ minimum: 1 }),
|
||||
highWatermark: Type.Number({ minimum: 0, maximum: 1 }),
|
||||
lowWatermark: Type.Number({ minimum: 0, maximum: 1 }),
|
||||
activePackages: Type.Integer({ minimum: 0 }),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataSearchQuerySchema = Type.Object(
|
||||
{
|
||||
q: Type.String({ minLength: 1, maxLength: 200 }),
|
||||
kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]),
|
||||
year: Type.Optional(Type.Integer({ minimum: 1888, maximum: 2200 })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataCandidateSchema = Type.Object(
|
||||
{
|
||||
provider: Type.Literal('TMDB'),
|
||||
externalId: Type.Integer({ minimum: 1 }),
|
||||
kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]),
|
||||
name: Type.Object(
|
||||
{ fa: Type.String(), en: Type.Optional(Type.String()) },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
synopsis: Type.Object(
|
||||
{ fa: Type.Optional(Type.String()), en: Type.Optional(Type.String()) },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
posterUrl: Type.Optional(Type.String()),
|
||||
backdropUrl: Type.Optional(Type.String()),
|
||||
year: Type.Optional(Type.Integer()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataSearchResponseSchema = Type.Object(
|
||||
{ items: Type.Array(MetadataCandidateSchema) },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataMatchParamsSchema = Type.Object(
|
||||
{ titleId: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataMatchBodySchema = Type.Object(
|
||||
{
|
||||
provider: Type.Literal('TMDB'),
|
||||
externalId: Type.Integer({ minimum: 1 }),
|
||||
kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type AdminLogin = Static<typeof AdminLoginSchema>;
|
||||
export type AdminSessionResponse = Static<typeof AdminSessionResponseSchema>;
|
||||
export type StartScan = Static<typeof StartScanSchema>;
|
||||
export type Job = Static<typeof JobSchema>;
|
||||
export type JobState = Static<typeof JobStateSchema>;
|
||||
export type CacheStatus = Static<typeof CacheStatusSchema>;
|
||||
export type MetadataSearchQuery = Static<typeof MetadataSearchQuerySchema>;
|
||||
export type MetadataCandidate = Static<typeof MetadataCandidateSchema>;
|
||||
export type MetadataMatchBody = Static<typeof MetadataMatchBodySchema>;
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
import { DateTimeSchema, UuidSchema } from './common.js';
|
||||
|
||||
export const TitleKindSchema = Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]);
|
||||
export const MediaKindSchema = Type.Union([Type.Literal('MOVIE'), Type.Literal('EPISODE')]);
|
||||
|
||||
export const LocalizedTextSchema = Type.Object(
|
||||
{
|
||||
fa: Type.String(),
|
||||
en: Type.Optional(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const OptionalLocalizedTextSchema = Type.Object(
|
||||
{
|
||||
fa: Type.Optional(Type.String()),
|
||||
en: Type.Optional(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CatalogCardSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
slug: Type.String(),
|
||||
kind: TitleKindSchema,
|
||||
name: LocalizedTextSchema,
|
||||
posterUrl: Type.Optional(Type.String()),
|
||||
backdropUrl: Type.Optional(Type.String()),
|
||||
year: Type.Optional(Type.Integer()),
|
||||
playable: Type.Boolean(),
|
||||
resumeMediaItemId: Type.Optional(UuidSchema),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MediaItemSummarySchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
kind: MediaKindSchema,
|
||||
seasonNumber: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
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'),
|
||||
]),
|
||||
published: Type.Boolean(),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const SeasonSummarySchema = Type.Object(
|
||||
{
|
||||
number: Type.Integer({ minimum: 0 }),
|
||||
episodeCount: Type.Integer({ minimum: 0 }),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const TitleDetailSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
slug: Type.String(),
|
||||
kind: TitleKindSchema,
|
||||
name: LocalizedTextSchema,
|
||||
posterUrl: Type.Optional(Type.String()),
|
||||
backdropUrl: Type.Optional(Type.String()),
|
||||
year: Type.Optional(Type.Integer()),
|
||||
playable: Type.Boolean(),
|
||||
resumeMediaItemId: Type.Optional(UuidSchema),
|
||||
synopsis: OptionalLocalizedTextSchema,
|
||||
seasons: Type.Optional(Type.Array(SeasonSummarySchema)),
|
||||
mediaItems: Type.Array(MediaItemSummarySchema),
|
||||
updatedAt: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
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),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const SearchQuerySchema = Type.Object(
|
||||
{
|
||||
q: Type.String({ minLength: 1, maxLength: 200 }),
|
||||
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 50, default: 20 })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CatalogResponseSchema = Type.Object(
|
||||
{
|
||||
items: Type.Array(CatalogCardSchema),
|
||||
nextCursor: Type.Optional(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const SearchResponseSchema = Type.Object(
|
||||
{ items: Type.Array(CatalogCardSchema) },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CatalogSnapshotSchema = Type.Object(
|
||||
{
|
||||
version: Type.Literal(1),
|
||||
generatedAt: DateTimeSchema,
|
||||
titles: Type.Array(TitleDetailSchema),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
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 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 CatalogSnapshot = Static<typeof CatalogSnapshotSchema>;
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
|
||||
export const UuidSchema = Type.String({
|
||||
pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$',
|
||||
});
|
||||
export const DateTimeSchema = Type.String({
|
||||
pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$',
|
||||
});
|
||||
export const EmailSchema = Type.String({
|
||||
maxLength: 320,
|
||||
pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$',
|
||||
});
|
||||
|
||||
export const ErrorCodeSchema = Type.Union([
|
||||
Type.Literal('BAD_REQUEST'),
|
||||
Type.Literal('NOT_FOUND'),
|
||||
Type.Literal('UNAUTHORIZED'),
|
||||
Type.Literal('FORBIDDEN'),
|
||||
Type.Literal('CONFLICT'),
|
||||
Type.Literal('VALIDATION_ERROR'),
|
||||
Type.Literal('UNSUPPORTED_CLIENT'),
|
||||
Type.Literal('MEDIA_UNAVAILABLE'),
|
||||
Type.Literal('INTERNAL_ERROR'),
|
||||
]);
|
||||
|
||||
export const ErrorResponseSchema = Type.Object(
|
||||
{
|
||||
error: Type.Object(
|
||||
{
|
||||
code: ErrorCodeSchema,
|
||||
message: Type.String(),
|
||||
requestId: Type.String(),
|
||||
details: Type.Optional(Type.Unknown()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type ErrorCode = Static<typeof ErrorCodeSchema>;
|
||||
export type ErrorResponse = Static<typeof ErrorResponseSchema>;
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
import { DateTimeSchema, UuidSchema } from './common.js';
|
||||
import { AudioTrackSchema, SubtitleTrackSchema } from './playback.js';
|
||||
|
||||
export const MediaCommandSchema = Type.Union([
|
||||
Type.Object(
|
||||
{
|
||||
type: Type.Literal('media.playback.requested'),
|
||||
sessionId: UuidSchema,
|
||||
mediaItemId: UuidSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Object(
|
||||
{ type: Type.Literal('archive.scan.requested'), jobId: UuidSchema, full: Type.Boolean() },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Object(
|
||||
{
|
||||
type: Type.Literal('media.publication.changed'),
|
||||
mediaItemId: UuidSchema,
|
||||
published: Type.Boolean(),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Object(
|
||||
{ type: Type.Literal('package.eviction.requested'), generationId: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Object(
|
||||
{
|
||||
type: Type.Literal('cache.generation.accessed'),
|
||||
sessionId: UuidSchema,
|
||||
generationId: UuidSchema,
|
||||
accessedAt: DateTimeSchema,
|
||||
protectedUntil: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
]);
|
||||
|
||||
/** Shared by the API lease writer and worker eviction reader. */
|
||||
export const CACHE_GENERATION_LEASES_KEY = 'easy-stream:cache-generation-leases:v1';
|
||||
|
||||
export const MediaPreparationResultSchema = Type.Object(
|
||||
{
|
||||
sessionId: UuidSchema,
|
||||
state: Type.Union([
|
||||
Type.Literal('PREPARING'),
|
||||
Type.Literal('READY'),
|
||||
Type.Literal('UNSUPPORTED_CLIENT'),
|
||||
Type.Literal('FAILED'),
|
||||
]),
|
||||
playable: Type.Boolean(),
|
||||
generationId: Type.Optional(UuidSchema),
|
||||
manifestPath: Type.Optional(Type.String({ pattern: '^/media/' })),
|
||||
reasonCode: Type.Optional(Type.String()),
|
||||
pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PackageRegistryEntrySchema = Type.Object(
|
||||
{
|
||||
mediaItemId: UuidSchema,
|
||||
state: Type.Union([
|
||||
Type.Literal('PREPARING'),
|
||||
Type.Literal('READY'),
|
||||
Type.Literal('UNSUPPORTED_CLIENT'),
|
||||
Type.Literal('FAILED'),
|
||||
]),
|
||||
playable: Type.Boolean(),
|
||||
generationId: Type.Optional(UuidSchema),
|
||||
manifestPath: Type.Optional(Type.String({ pattern: '^/media/' })),
|
||||
reasonCode: Type.Optional(Type.String()),
|
||||
pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })),
|
||||
durationSeconds: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
audioTracks: Type.Optional(Type.Array(AudioTrackSchema)),
|
||||
subtitleTracks: Type.Optional(Type.Array(SubtitleTrackSchema)),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PackageRegistrySchema = Type.Object(
|
||||
{
|
||||
version: Type.Literal(1),
|
||||
updatedAt: Type.String({
|
||||
pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$',
|
||||
}),
|
||||
packages: Type.Array(PackageRegistryEntrySchema),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type MediaCommand = Static<typeof MediaCommandSchema>;
|
||||
export type MediaPreparationResult = Static<typeof MediaPreparationResultSchema>;
|
||||
export type PackageRegistryEntry = Static<typeof PackageRegistryEntrySchema>;
|
||||
export type PackageRegistry = Static<typeof PackageRegistrySchema>;
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './admin.js';
|
||||
export * from './catalog.js';
|
||||
export * from './common.js';
|
||||
export * from './events.js';
|
||||
export * from './playback.js';
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
import { DateTimeSchema, UuidSchema } from './common.js';
|
||||
|
||||
export const CompatibilityClassSchema = Type.Union([
|
||||
Type.Literal('COPY'),
|
||||
Type.Literal('AUDIO_TRANSCODE'),
|
||||
Type.Literal('VIDEO_TRANSCODE'),
|
||||
Type.Literal('HOLD_HDR'),
|
||||
Type.Literal('INVALID'),
|
||||
]);
|
||||
|
||||
export const PlaybackStateSchema = Type.Union([
|
||||
Type.Literal('PREPARING'),
|
||||
Type.Literal('READY'),
|
||||
Type.Literal('UNSUPPORTED_CLIENT'),
|
||||
Type.Literal('FAILED'),
|
||||
]);
|
||||
|
||||
export const SubtitleDeliverySchema = Type.Union([
|
||||
Type.Literal('ASS_JASSUB'),
|
||||
Type.Literal('WEBVTT'),
|
||||
Type.Literal('OFF'),
|
||||
]);
|
||||
|
||||
export const ClientCapabilitiesSchema = Type.Object(
|
||||
{
|
||||
mse: Type.Boolean(),
|
||||
nativeHls: Type.Boolean(),
|
||||
hlsJs: Type.Boolean(),
|
||||
assRenderer: Type.Boolean(),
|
||||
supportedCodecs: Type.Array(Type.String({ maxLength: 128 }), { maxItems: 32 }),
|
||||
userAgent: Type.Optional(Type.String({ maxLength: 512 })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const AudioTrackSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
language: Type.String({ minLength: 2, maxLength: 35 }),
|
||||
label: Type.String({ maxLength: 100 }),
|
||||
default: Type.Boolean(),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const SubtitleTrackSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
language: Type.String({ minLength: 2, maxLength: 35 }),
|
||||
label: Type.String({ maxLength: 100 }),
|
||||
default: Type.Boolean(),
|
||||
forced: Type.Boolean(),
|
||||
assUrl: Type.Optional(Type.String()),
|
||||
vttUrl: Type.Optional(Type.String()),
|
||||
fontUrls: Type.Array(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CreatePlaybackSessionSchema = Type.Object(
|
||||
{
|
||||
mediaItemId: UuidSchema,
|
||||
clientCapabilities: ClientCapabilitiesSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PlaybackSessionSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
mediaItemId: UuidSchema,
|
||||
state: PlaybackStateSchema,
|
||||
manifestUrl: Type.Optional(Type.String()),
|
||||
generationId: Type.Optional(UuidSchema),
|
||||
durationSeconds: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
audioTracks: Type.Optional(Type.Array(AudioTrackSchema)),
|
||||
subtitleTracks: Type.Optional(Type.Array(SubtitleTrackSchema)),
|
||||
pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })),
|
||||
reasonCode: Type.Optional(Type.String()),
|
||||
expiresAt: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PlaybackSessionParamsSchema = Type.Object(
|
||||
{ id: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type CompatibilityClass = Static<typeof CompatibilityClassSchema>;
|
||||
export type PlaybackState = Static<typeof PlaybackStateSchema>;
|
||||
export type SubtitleDelivery = Static<typeof SubtitleDeliverySchema>;
|
||||
export type ClientCapabilities = Static<typeof ClientCapabilitiesSchema>;
|
||||
export type AudioTrack = Static<typeof AudioTrackSchema>;
|
||||
export type SubtitleTrack = Static<typeof SubtitleTrackSchema>;
|
||||
export type CreatePlaybackSession = Static<typeof CreatePlaybackSessionSchema>;
|
||||
export type PlaybackSession = Static<typeof PlaybackSessionSchema>;
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CreatePlaybackSessionSchema, MediaCommandSchema } from '../src/index.js';
|
||||
|
||||
describe('public contracts', () => {
|
||||
it('accepts a valid browser capability report', () => {
|
||||
expect(
|
||||
Value.Check(CreatePlaybackSessionSchema, {
|
||||
mediaItemId: '00000000-0000-4000-8000-000000000001',
|
||||
clientCapabilities: {
|
||||
mse: true,
|
||||
nativeHls: false,
|
||||
hlsJs: true,
|
||||
assRenderer: true,
|
||||
supportedCodecs: ['avc1.64001f', 'mp4a.40.2'],
|
||||
},
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps worker commands discriminated and closed', () => {
|
||||
expect(
|
||||
Value.Check(MediaCommandSchema, {
|
||||
type: 'archive.scan.requested',
|
||||
jobId: '00000000-0000-4000-8000-000000000002',
|
||||
full: false,
|
||||
unexpected: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(Value.Check(MediaCommandSchema, {
|
||||
type: 'cache.generation.accessed',
|
||||
sessionId: '00000000-0000-4000-8000-000000000001',
|
||||
generationId: '00000000-0000-4000-8000-000000000002',
|
||||
accessedAt: '2026-07-14T10:00:00.000Z',
|
||||
protectedUntil: '2026-07-14T14:00:00.000Z',
|
||||
})).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"tsBuildInfoFile": "dist/.tsbuildinfo"
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'drizzle-kit';
|
||||
|
||||
if (!process.env.DATABASE_URL) {
|
||||
throw new Error('DATABASE_URL is required to run Drizzle commands');
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
dialect: 'postgresql',
|
||||
schema: './src/schema.ts',
|
||||
out: './migrations',
|
||||
dbCredentials: { url: process.env.DATABASE_URL },
|
||||
strict: true,
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
CREATE TYPE "title_kind" AS ENUM ('MOVIE', 'SERIES');
|
||||
CREATE TYPE "media_kind" AS ENUM ('MOVIE', 'EPISODE');
|
||||
CREATE TYPE "stream_kind" AS ENUM ('VIDEO', 'AUDIO');
|
||||
CREATE TYPE "compatibility_class" AS ENUM ('COPY', 'AUDIO_TRANSCODE', 'VIDEO_TRANSCODE', 'HOLD_HDR', 'INVALID');
|
||||
CREATE TYPE "package_state" AS ENUM ('QUEUED', 'BUILDING', 'READY', 'FAILED', 'EVICTED');
|
||||
CREATE TYPE "job_state" AS ENUM ('QUEUED', 'RUNNING', 'SUCCEEDED', 'FAILED', 'CANCELLED');
|
||||
CREATE TYPE "playback_state" AS ENUM ('PREPARING', 'READY', 'UNSUPPORTED_CLIENT', 'FAILED');
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "titles" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"slug" varchar(240) NOT NULL,
|
||||
"kind" "title_kind" NOT NULL,
|
||||
"name_fa" text,
|
||||
"name_en" text,
|
||||
"synopsis_fa" text,
|
||||
"synopsis_en" text,
|
||||
"poster_url" text,
|
||||
"backdrop_url" text,
|
||||
"release_year" integer,
|
||||
"tmdb_id" integer,
|
||||
"published" boolean DEFAULT false NOT NULL,
|
||||
"published_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "media_items" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"title_id" uuid NOT NULL,
|
||||
"kind" "media_kind" NOT NULL,
|
||||
"season_number" integer,
|
||||
"episode_number" integer,
|
||||
"name_fa" text,
|
||||
"name_en" text,
|
||||
"duration_seconds" double precision,
|
||||
"compatibility" "compatibility_class" DEFAULT 'INVALID' NOT NULL,
|
||||
"compatibility_reason" text,
|
||||
"published" boolean DEFAULT false NOT NULL,
|
||||
"published_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "source_files" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"media_item_id" uuid NOT NULL,
|
||||
"relative_path" text NOT NULL,
|
||||
"size_bytes" bigint NOT NULL,
|
||||
"modified_at_ns" bigint NOT NULL,
|
||||
"matroska_uid" varchar(128),
|
||||
"head_hash" varchar(128) NOT NULL,
|
||||
"tail_hash" varchar(128) NOT NULL,
|
||||
"fingerprint" varchar(128) NOT NULL,
|
||||
"probe_json" jsonb,
|
||||
"present" boolean DEFAULT true NOT NULL,
|
||||
"last_seen_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "media_streams" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"source_file_id" uuid NOT NULL,
|
||||
"stream_index" integer NOT NULL,
|
||||
"kind" "stream_kind" NOT NULL,
|
||||
"codec" varchar(64) NOT NULL,
|
||||
"codec_string" varchar(128),
|
||||
"language" varchar(35),
|
||||
"label" varchar(200),
|
||||
"is_default" boolean DEFAULT false NOT NULL,
|
||||
"channels" integer,
|
||||
"sample_rate" integer,
|
||||
"width" integer,
|
||||
"height" integer,
|
||||
"frame_rate" varchar(32),
|
||||
"bit_depth" integer,
|
||||
"pixel_format" varchar(64),
|
||||
"color_transfer" varchar(64),
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "subtitle_tracks" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"source_file_id" uuid NOT NULL,
|
||||
"stream_index" integer NOT NULL,
|
||||
"codec" varchar(64) NOT NULL,
|
||||
"source_language" varchar(35),
|
||||
"normalized_language" varchar(35) NOT NULL,
|
||||
"label" varchar(200) NOT NULL,
|
||||
"source_default" boolean DEFAULT false NOT NULL,
|
||||
"source_forced" boolean DEFAULT false NOT NULL,
|
||||
"is_default" boolean DEFAULT false NOT NULL,
|
||||
"is_forced" boolean DEFAULT false NOT NULL,
|
||||
"ass_path" text,
|
||||
"webvtt_path" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "font_attachments" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"source_file_id" uuid NOT NULL,
|
||||
"stream_index" integer NOT NULL,
|
||||
"sha256" varchar(64) NOT NULL,
|
||||
"mime_type" varchar(100) NOT NULL,
|
||||
"original_name" text NOT NULL,
|
||||
"storage_path" text,
|
||||
"approved" boolean DEFAULT false NOT NULL,
|
||||
"size_bytes" bigint NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "media_packages" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"media_item_id" uuid NOT NULL,
|
||||
"source_fingerprint" varchar(128) NOT NULL,
|
||||
"profile_version" varchar(64) NOT NULL,
|
||||
"state" "package_state" DEFAULT 'QUEUED' NOT NULL,
|
||||
"manifest_path" text,
|
||||
"size_bytes" bigint DEFAULT 0 NOT NULL,
|
||||
"cache_resident" boolean DEFAULT false NOT NULL,
|
||||
"pinned" boolean DEFAULT false NOT NULL,
|
||||
"last_accessed_at" timestamp with time zone,
|
||||
"error_code" varchar(100),
|
||||
"error_detail" text,
|
||||
"ready_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "jobs" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"type" varchar(100) NOT NULL,
|
||||
"state" "job_state" DEFAULT 'QUEUED' NOT NULL,
|
||||
"progress" real DEFAULT 0 NOT NULL,
|
||||
"payload" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"result" jsonb,
|
||||
"error" text,
|
||||
"attempts" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "admins" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"email" varchar(320) NOT NULL,
|
||||
"password_hash" text NOT NULL,
|
||||
"totp_secret_encrypted" text,
|
||||
"disabled" boolean DEFAULT false NOT NULL,
|
||||
"last_login_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "admin_sessions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"admin_id" uuid NOT NULL,
|
||||
"token_hash" varchar(64) NOT NULL,
|
||||
"csrf_token_hash" varchar(64) NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"revoked_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "playback_sessions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"media_item_id" uuid NOT NULL,
|
||||
"generation_id" uuid,
|
||||
"state" "playback_state" DEFAULT 'PREPARING' NOT NULL,
|
||||
"capabilities" jsonb NOT NULL,
|
||||
"reason_code" varchar(100),
|
||||
"poll_after_ms" integer,
|
||||
"response_json" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "media_items" ADD CONSTRAINT "media_items_title_id_titles_id_fk" FOREIGN KEY ("title_id") REFERENCES "titles"("id") ON DELETE cascade;
|
||||
ALTER TABLE "source_files" ADD CONSTRAINT "source_files_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
|
||||
ALTER TABLE "media_streams" ADD CONSTRAINT "media_streams_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
|
||||
ALTER TABLE "subtitle_tracks" ADD CONSTRAINT "subtitle_tracks_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
|
||||
ALTER TABLE "font_attachments" ADD CONSTRAINT "font_attachments_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
|
||||
ALTER TABLE "media_packages" ADD CONSTRAINT "media_packages_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
|
||||
ALTER TABLE "admin_sessions" ADD CONSTRAINT "admin_sessions_admin_id_admins_id_fk" FOREIGN KEY ("admin_id") REFERENCES "admins"("id") ON DELETE cascade;
|
||||
ALTER TABLE "playback_sessions" ADD CONSTRAINT "playback_sessions_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "titles_slug_uidx" ON "titles" ("slug");
|
||||
CREATE INDEX "titles_published_idx" ON "titles" ("published", "published_at");
|
||||
CREATE INDEX "titles_tmdb_idx" ON "titles" ("tmdb_id");
|
||||
CREATE INDEX "media_items_title_idx" ON "media_items" ("title_id");
|
||||
CREATE UNIQUE INDEX "media_items_episode_uidx" ON "media_items" ("title_id", "season_number", "episode_number");
|
||||
CREATE INDEX "media_items_published_idx" ON "media_items" ("published");
|
||||
CREATE UNIQUE INDEX "source_files_path_uidx" ON "source_files" ("relative_path");
|
||||
CREATE UNIQUE INDEX "source_files_fingerprint_uidx" ON "source_files" ("fingerprint");
|
||||
CREATE INDEX "source_files_media_item_idx" ON "source_files" ("media_item_id");
|
||||
CREATE UNIQUE INDEX "media_streams_source_index_uidx" ON "media_streams" ("source_file_id", "stream_index");
|
||||
CREATE INDEX "media_streams_source_idx" ON "media_streams" ("source_file_id");
|
||||
CREATE UNIQUE INDEX "subtitle_tracks_source_index_uidx" ON "subtitle_tracks" ("source_file_id", "stream_index");
|
||||
CREATE INDEX "subtitle_tracks_source_idx" ON "subtitle_tracks" ("source_file_id");
|
||||
CREATE UNIQUE INDEX "font_attachments_source_index_uidx" ON "font_attachments" ("source_file_id", "stream_index");
|
||||
CREATE INDEX "font_attachments_hash_idx" ON "font_attachments" ("sha256");
|
||||
CREATE UNIQUE INDEX "media_packages_generation_uidx" ON "media_packages" ("media_item_id", "source_fingerprint", "profile_version");
|
||||
CREATE INDEX "media_packages_lru_idx" ON "media_packages" ("cache_resident", "pinned", "last_accessed_at");
|
||||
CREATE INDEX "jobs_state_created_idx" ON "jobs" ("state", "created_at");
|
||||
CREATE UNIQUE INDEX "admins_email_uidx" ON "admins" ("email");
|
||||
CREATE UNIQUE INDEX "admin_sessions_token_uidx" ON "admin_sessions" ("token_hash");
|
||||
CREATE INDEX "admin_sessions_admin_idx" ON "admin_sessions" ("admin_id");
|
||||
CREATE INDEX "playback_sessions_media_idx" ON "playback_sessions" ("media_item_id");
|
||||
CREATE INDEX "playback_sessions_generation_idx" ON "playback_sessions" ("generation_id");
|
||||
CREATE INDEX "playback_sessions_expires_idx" ON "playback_sessions" ("expires_at");
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE "playback_sessions" DROP CONSTRAINT IF EXISTS "playback_sessions_generation_id_media_packages_id_fk";
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "playback_sessions_generation_idx" ON "playback_sessions" ("generation_id");
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1783987200000,
|
||||
"tag": "0000_initial",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1784016000000,
|
||||
"tag": "0001_playback_generation_external",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@easy-stream/database",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./schema": {
|
||||
"types": "./dist/schema.d.ts",
|
||||
"import": "./dist/schema.js"
|
||||
}
|
||||
},
|
||||
"files": ["dist", "migrations"],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p ../contracts/tsconfig.json && tsc -p tsconfig.json",
|
||||
"test": "tsc -p ../contracts/tsconfig.json && vitest run",
|
||||
"migrate": "drizzle-kit migrate",
|
||||
"generate": "drizzle-kit generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@easy-stream/contracts": "workspace:*",
|
||||
"@sinclair/typebox": "^0.34.41",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"postgres": "^3.4.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { CatalogSnapshotSchema, type CatalogSnapshot } from '@easy-stream/contracts';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import type { Database } from './client.js';
|
||||
import { mediaItems, titles } from './schema.js';
|
||||
|
||||
const UPSERT_BATCH_SIZE = 500;
|
||||
|
||||
export interface PreparedCatalogSync {
|
||||
scannedAt: Date;
|
||||
titleRows: Array<typeof titles.$inferInsert>;
|
||||
mediaItemRows: Array<typeof mediaItems.$inferInsert>;
|
||||
}
|
||||
|
||||
export interface CatalogSyncResult {
|
||||
titlesSeen: number;
|
||||
mediaItemsSeen: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and converts the public scan snapshot into database insert rows. Keeping this
|
||||
* conversion separate also makes the scanner/database boundary testable without PostgreSQL.
|
||||
*/
|
||||
export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
|
||||
if (!Value.Check(CatalogSnapshotSchema, snapshot)) {
|
||||
const detail = [...Value.Errors(CatalogSnapshotSchema, snapshot)]
|
||||
.slice(0, 8)
|
||||
.map((error) => `${error.path || '/'} ${error.message}`)
|
||||
.join('; ');
|
||||
throw new Error(`Invalid catalog snapshot: ${detail}`);
|
||||
}
|
||||
|
||||
const catalog = snapshot as CatalogSnapshot;
|
||||
const scannedAt = new Date(catalog.generatedAt);
|
||||
const titleIds = new Set<string>();
|
||||
const slugs = new Set<string>();
|
||||
const mediaItemIds = new Set<string>();
|
||||
const titleRows: PreparedCatalogSync['titleRows'] = [];
|
||||
const mediaItemRows: PreparedCatalogSync['mediaItemRows'] = [];
|
||||
|
||||
for (const title of catalog.titles) {
|
||||
assertUnique(titleIds, title.id, 'title ID');
|
||||
assertUnique(slugs, title.slug, 'title slug');
|
||||
const published = title.mediaItems.some((item) => item.published);
|
||||
titleRows.push({
|
||||
id: title.id,
|
||||
slug: title.slug,
|
||||
kind: title.kind,
|
||||
nameFa: title.name.fa,
|
||||
nameEn: title.name.en ?? null,
|
||||
synopsisFa: title.synopsis.fa ?? null,
|
||||
synopsisEn: title.synopsis.en ?? null,
|
||||
posterUrl: title.posterUrl ?? null,
|
||||
backdropUrl: title.backdropUrl ?? null,
|
||||
releaseYear: title.year ?? null,
|
||||
published,
|
||||
publishedAt: published ? scannedAt : null,
|
||||
createdAt: scannedAt,
|
||||
updatedAt: scannedAt,
|
||||
});
|
||||
|
||||
for (const item of title.mediaItems) {
|
||||
assertUnique(mediaItemIds, item.id, 'media item ID');
|
||||
if ((title.kind === 'MOVIE') !== (item.kind === 'MOVIE')) {
|
||||
throw new Error(`Catalog media item ${item.id} has kind ${item.kind} under ${title.kind}`);
|
||||
}
|
||||
mediaItemRows.push({
|
||||
id: item.id,
|
||||
titleId: title.id,
|
||||
kind: item.kind,
|
||||
seasonNumber: item.seasonNumber ?? null,
|
||||
episodeNumber: item.episodeNumber ?? null,
|
||||
nameFa: item.name?.fa ?? null,
|
||||
nameEn: item.name?.en ?? null,
|
||||
durationSeconds: item.durationSeconds,
|
||||
compatibility: item.compatibility,
|
||||
published: item.published,
|
||||
publishedAt: item.published ? scannedAt : null,
|
||||
createdAt: scannedAt,
|
||||
updatedAt: scannedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { scannedAt, titleRows, mediaItemRows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely imports scanner-owned catalog facts. Existing names, artwork, TMDB matches and all
|
||||
* publication fields are intentionally excluded from conflict updates so an archive rescan
|
||||
* cannot undo an administrator's choices. Rows absent from a snapshot are retained.
|
||||
*/
|
||||
export async function syncCatalogSnapshot(
|
||||
db: Database,
|
||||
snapshot: unknown,
|
||||
): Promise<CatalogSyncResult> {
|
||||
const prepared = prepareCatalogSync(snapshot);
|
||||
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'))`);
|
||||
|
||||
for (const batch of batches(prepared.titleRows, UPSERT_BATCH_SIZE)) {
|
||||
await transaction
|
||||
.insert(titles)
|
||||
.values(batch)
|
||||
.onConflictDoUpdate({
|
||||
target: titles.id,
|
||||
set: {
|
||||
slug: sql`excluded.slug`,
|
||||
kind: sql`excluded.kind`,
|
||||
updatedAt: prepared.scannedAt,
|
||||
},
|
||||
setWhere: sql`${titles.slug} is distinct from excluded.slug or ${titles.kind} is distinct from excluded.kind`,
|
||||
});
|
||||
}
|
||||
|
||||
for (const batch of batches(prepared.mediaItemRows, UPSERT_BATCH_SIZE)) {
|
||||
await transaction
|
||||
.insert(mediaItems)
|
||||
.values(batch)
|
||||
.onConflictDoUpdate({
|
||||
target: mediaItems.id,
|
||||
set: {
|
||||
titleId: sql`excluded.title_id`,
|
||||
kind: sql`excluded.kind`,
|
||||
seasonNumber: sql`excluded.season_number`,
|
||||
episodeNumber: sql`excluded.episode_number`,
|
||||
durationSeconds: sql`excluded.duration_seconds`,
|
||||
compatibility: sql`excluded.compatibility`,
|
||||
updatedAt: prepared.scannedAt,
|
||||
},
|
||||
setWhere: sql`
|
||||
${mediaItems.titleId} is distinct from excluded.title_id
|
||||
or ${mediaItems.kind} is distinct from excluded.kind
|
||||
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
|
||||
`,
|
||||
});
|
||||
}
|
||||
});
|
||||
return {
|
||||
titlesSeen: prepared.titleRows.length,
|
||||
mediaItemsSeen: prepared.mediaItemRows.length,
|
||||
};
|
||||
}
|
||||
|
||||
function assertUnique(values: Set<string>, value: string, label: string): void {
|
||||
if (values.has(value)) throw new Error(`Catalog contains duplicate ${label}: ${value}`);
|
||||
values.add(value);
|
||||
}
|
||||
|
||||
function batches<T>(values: readonly T[], size: number): T[][] {
|
||||
const result: T[][] = [];
|
||||
for (let index = 0; index < values.length; index += size) {
|
||||
result.push(values.slice(index, index + size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js';
|
||||
import postgres from 'postgres';
|
||||
import * as schema from './schema.js';
|
||||
|
||||
export function createDatabase(connectionString: string, options?: { max?: number }) {
|
||||
const client = postgres(connectionString, {
|
||||
max: options?.max ?? 10,
|
||||
prepare: false,
|
||||
transform: { undefined: null },
|
||||
});
|
||||
|
||||
return {
|
||||
client,
|
||||
db: drizzle(client, { schema }),
|
||||
async close(): Promise<void> {
|
||||
await client.end({ timeout: 5 });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type Database = ReturnType<typeof createDatabase>['db'];
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from './catalog-sync.js';
|
||||
export * from './client.js';
|
||||
export * from './job-status.js';
|
||||
export * from './schema.js';
|
||||
@@ -0,0 +1,56 @@
|
||||
import { and, eq, inArray, sql } from 'drizzle-orm';
|
||||
import type { Database } from './client.js';
|
||||
import { jobs } from './schema.js';
|
||||
|
||||
export async function markArchiveScanRunning(db: Database, jobId: string): Promise<boolean> {
|
||||
const [updated] = await db.update(jobs).set({
|
||||
state: 'RUNNING',
|
||||
progress: 0,
|
||||
error: null,
|
||||
attempts: sql`${jobs.attempts} + 1`,
|
||||
updatedAt: new Date(),
|
||||
}).where(and(
|
||||
eq(jobs.id, jobId),
|
||||
eq(jobs.type, 'ARCHIVE_SCAN'),
|
||||
// BullMQ may start a retry immediately after its failed event; accept either side of that
|
||||
// transition so automatic retries can move the same logical job back to RUNNING.
|
||||
inArray(jobs.state, ['QUEUED', 'RUNNING', 'FAILED']),
|
||||
)).returning({ id: jobs.id });
|
||||
return updated !== undefined;
|
||||
}
|
||||
|
||||
export async function markArchiveScanSucceeded(
|
||||
db: Database,
|
||||
jobId: string,
|
||||
result: Record<string, unknown>,
|
||||
): Promise<boolean> {
|
||||
const [updated] = await db.update(jobs).set({
|
||||
state: 'SUCCEEDED',
|
||||
progress: 1,
|
||||
result,
|
||||
error: null,
|
||||
updatedAt: new Date(),
|
||||
}).where(and(
|
||||
eq(jobs.id, jobId),
|
||||
eq(jobs.type, 'ARCHIVE_SCAN'),
|
||||
eq(jobs.state, 'RUNNING'),
|
||||
)).returning({ id: jobs.id });
|
||||
return updated !== undefined;
|
||||
}
|
||||
|
||||
export async function markArchiveScanFailed(
|
||||
db: Database,
|
||||
jobId: string,
|
||||
error: string,
|
||||
): Promise<boolean> {
|
||||
const [updated] = await db.update(jobs).set({
|
||||
state: 'FAILED',
|
||||
error: error.slice(0, 16_000),
|
||||
updatedAt: new Date(),
|
||||
}).where(and(
|
||||
eq(jobs.id, jobId),
|
||||
eq(jobs.type, 'ARCHIVE_SCAN'),
|
||||
inArray(jobs.state, ['QUEUED', 'RUNNING']),
|
||||
)).returning({ id: jobs.id });
|
||||
return updated !== undefined;
|
||||
}
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user