init
This commit is contained in:
134 files changed
+18678
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user