feat: support categorized archives and selectable quality variants
This commit is contained in:
45 files changed
+932
-92
No files matched your search
@@ -10,6 +10,8 @@ import {
|
||||
CacheStatusSchema,
|
||||
CatalogQuerySchema,
|
||||
CatalogResponseSchema,
|
||||
CatalogSectionsQuerySchema,
|
||||
CatalogSectionsResponseSchema,
|
||||
CreatePlaybackSessionSchema,
|
||||
DateTimeSchema,
|
||||
ErrorResponseSchema,
|
||||
@@ -31,6 +33,7 @@ import {
|
||||
UuidSchema,
|
||||
type AdminLogin,
|
||||
type CatalogQuery,
|
||||
type CatalogSectionsQuery,
|
||||
type CreatePlaybackSession,
|
||||
type MetadataMatchBody,
|
||||
type MetadataSearchQuery,
|
||||
@@ -233,6 +236,17 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
||||
async (request) => repository.listCatalog(request.query),
|
||||
);
|
||||
|
||||
app.get<{ Querystring: CatalogSectionsQuery }>(
|
||||
'/api/v1/catalog/sections',
|
||||
{
|
||||
schema: {
|
||||
querystring: CatalogSectionsQuerySchema,
|
||||
response: { 200: CatalogSectionsResponseSchema },
|
||||
},
|
||||
},
|
||||
async (request) => ({ sections: await repository.listCatalogSections(request.query.limitPerSection ?? 12) }),
|
||||
);
|
||||
|
||||
app.get<{ Params: Static<typeof SlugParamsSchema> }>(
|
||||
'/api/v1/titles/:slug',
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
AudioTrack,
|
||||
CacheStatus,
|
||||
CatalogCard,
|
||||
CatalogSection,
|
||||
CatalogQuery,
|
||||
ClientCapabilities,
|
||||
Job,
|
||||
@@ -20,6 +21,14 @@ export interface MediaItemForPlayback {
|
||||
durationSeconds: number;
|
||||
compatibility: 'COPY' | 'AUDIO_TRANSCODE' | 'VIDEO_TRANSCODE' | 'HOLD_HDR' | 'INVALID';
|
||||
published: boolean;
|
||||
variants: Array<{
|
||||
id: string;
|
||||
label: string;
|
||||
height?: number;
|
||||
compatibility: 'COPY' | 'AUDIO_TRANSCODE' | 'VIDEO_TRANSCODE' | 'HOLD_HDR' | 'INVALID';
|
||||
available: boolean;
|
||||
isDefault: boolean;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface CatalogPage {
|
||||
@@ -29,6 +38,7 @@ export interface CatalogPage {
|
||||
|
||||
export interface CatalogRepository {
|
||||
listCatalog(query: CatalogQuery): Promise<CatalogPage>;
|
||||
listCatalogSections(limitPerSection: number): Promise<CatalogSection[]>;
|
||||
searchTitles(query: SearchQuery): Promise<CatalogCard[]>;
|
||||
getTitleBySlug(slug: string): Promise<TitleDetail | undefined>;
|
||||
getMediaItem(id: string): Promise<MediaItemForPlayback | undefined>;
|
||||
@@ -95,12 +105,14 @@ export interface MediaPreparationService {
|
||||
prepare(input: {
|
||||
sessionId: string;
|
||||
mediaItem: MediaItemForPlayback;
|
||||
variantId?: string;
|
||||
capabilities: ClientCapabilities;
|
||||
protectUntil?: string;
|
||||
}): Promise<MediaPreparation>;
|
||||
getStatus(input: {
|
||||
sessionId: string;
|
||||
mediaItem: MediaItemForPlayback;
|
||||
variantId?: string;
|
||||
protectUntil?: string;
|
||||
}): Promise<MediaPreparation>;
|
||||
}
|
||||
|
||||
@@ -52,6 +52,9 @@ export class InMemoryRepository implements AppRepository {
|
||||
const published = [...this.titles.values()]
|
||||
.filter((title) => title.mediaItems.some((item) => item.published))
|
||||
.filter((title) => !query.kind || title.kind === query.kind)
|
||||
.filter((title) => !query.category || (title.categorySlug ?? 'other') === query.category)
|
||||
.filter((title) => !query.year || title.year === query.year)
|
||||
.filter((title) => !query.releaseWindow || title.releaseWindow === query.releaseWindow)
|
||||
.sort((left, right) => left.slug.localeCompare(right.slug));
|
||||
const cursorId = decodeCursor(query.cursor);
|
||||
const start = cursorId ? Math.max(0, published.findIndex((title) => title.id === cursorId) + 1) : 0;
|
||||
@@ -63,6 +66,23 @@ export class InMemoryRepository implements AppRepository {
|
||||
};
|
||||
}
|
||||
|
||||
async listCatalogSections(limitPerSection: number) {
|
||||
const groups = new Map<string, TitleDetail[]>();
|
||||
for (const title of this.titles.values()) {
|
||||
if (!title.mediaItems.some((item) => item.published)) continue;
|
||||
const categorySlug = title.categorySlug ?? 'other';
|
||||
const group = groups.get(categorySlug) ?? [];
|
||||
group.push(title);
|
||||
groups.set(categorySlug, group);
|
||||
}
|
||||
return [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([slug, titles]) => ({
|
||||
slug,
|
||||
name: titles[0]?.category ?? 'Other',
|
||||
items: titles.slice(0, limitPerSection).map(toCard),
|
||||
hasMore: titles.length > limitPerSection,
|
||||
}));
|
||||
}
|
||||
|
||||
async searchTitles(query: SearchQuery) {
|
||||
const needle = normalizeSearch(query.q);
|
||||
const limit = query.limit ?? 20;
|
||||
@@ -94,6 +114,14 @@ export class InMemoryRepository implements AppRepository {
|
||||
durationSeconds: item.durationSeconds,
|
||||
compatibility: item.compatibility,
|
||||
published: item.published,
|
||||
variants: (item.variants ?? []).map((variant) => ({
|
||||
id: variant.id,
|
||||
label: variant.label,
|
||||
...(variant.height ? { height: variant.height } : {}),
|
||||
compatibility: variant.compatibility,
|
||||
available: variant.available,
|
||||
isDefault: variant.isDefault,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
CacheStatus,
|
||||
CatalogCard,
|
||||
CatalogSection,
|
||||
CatalogQuery,
|
||||
Job,
|
||||
MetadataCandidate,
|
||||
@@ -17,7 +18,7 @@ import {
|
||||
titles,
|
||||
type Database,
|
||||
} from '@easy-stream/database';
|
||||
import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';
|
||||
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
||||
import type {
|
||||
AdminRecord,
|
||||
AppRepository,
|
||||
@@ -44,7 +45,13 @@ export class PostgresRepository implements AppRepository {
|
||||
const rows = await this.db
|
||||
.select()
|
||||
.from(titles)
|
||||
.where(and(eq(titles.published, true), query.kind ? eq(titles.kind, query.kind) : undefined))
|
||||
.where(and(
|
||||
eq(titles.published, true),
|
||||
query.kind ? eq(titles.kind, query.kind) : undefined,
|
||||
query.category ? (query.category === 'other' ? isNull(titles.categorySlug) : eq(titles.categorySlug, query.category)) : undefined,
|
||||
query.year ? eq(titles.releaseYear, query.year) : undefined,
|
||||
query.releaseWindow ? eq(titles.releaseWindow, query.releaseWindow) : undefined,
|
||||
))
|
||||
.orderBy(asc(titles.slug), asc(titles.id))
|
||||
.limit(limit + 1)
|
||||
.offset(offset);
|
||||
@@ -56,6 +63,30 @@ export class PostgresRepository implements AppRepository {
|
||||
};
|
||||
}
|
||||
|
||||
async listCatalogSections(limitPerSection: number): Promise<CatalogSection[]> {
|
||||
const rows = await this.db.select().from(titles)
|
||||
.where(eq(titles.published, true))
|
||||
.orderBy(asc(titles.categorySlug), desc(titles.releaseYear), asc(titles.slug));
|
||||
const groups = new Map<string, typeof rows>();
|
||||
for (const row of rows) {
|
||||
const categorySlug = row.categorySlug ?? 'other';
|
||||
const group = groups.get(categorySlug) ?? [];
|
||||
group.push(row);
|
||||
groups.set(categorySlug, group);
|
||||
}
|
||||
const result: CatalogSection[] = [];
|
||||
for (const [slug, group] of groups) {
|
||||
const visible = group.slice(0, limitPerSection);
|
||||
result.push({
|
||||
slug,
|
||||
name: group[0]?.category ?? 'Other',
|
||||
items: await this.cardsForRows(visible),
|
||||
hasMore: group.length > visible.length,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async searchTitles(query: SearchQuery): Promise<CatalogCard[]> {
|
||||
const needle = `%${query.q.trim().replaceAll('%', '\\%').replaceAll('_', '\\_')}%`;
|
||||
const rows = await this.db
|
||||
@@ -101,6 +132,14 @@ export class PostgresRepository implements AppRepository {
|
||||
durationSeconds: row.media.durationSeconds ?? 0,
|
||||
compatibility: row.media.compatibility,
|
||||
published: row.media.published && row.titlePublished,
|
||||
variants: (row.media.variants ?? []).map((variant) => ({
|
||||
id: variant.id,
|
||||
label: variant.label,
|
||||
...(variant.height ? { height: variant.height } : {}),
|
||||
compatibility: variant.compatibility as MediaItemForPlayback['compatibility'],
|
||||
available: variant.available,
|
||||
isDefault: variant.isDefault,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -156,6 +195,7 @@ export class PostgresRepository implements AppRepository {
|
||||
await this.db.insert(playbackSessions).values({
|
||||
id: session.id,
|
||||
mediaItemId: session.mediaItemId,
|
||||
...(session.variantId ? { variantId: session.variantId } : {}),
|
||||
...(session.generationId ? { generationId: session.generationId } : {}),
|
||||
state: session.state,
|
||||
capabilities: session.capabilities,
|
||||
@@ -177,6 +217,7 @@ export class PostgresRepository implements AppRepository {
|
||||
return {
|
||||
id: row.id,
|
||||
mediaItemId: row.mediaItemId,
|
||||
...(row.variantId ? { variantId: row.variantId } : {}),
|
||||
state: row.state,
|
||||
capabilities: row.capabilities as StoredPlaybackSession['capabilities'],
|
||||
expiresAt: row.expiresAt.toISOString(),
|
||||
@@ -185,6 +226,7 @@ export class PostgresRepository implements AppRepository {
|
||||
...(row.pollAfterMs ? { pollAfterMs: row.pollAfterMs } : {}),
|
||||
...(details.manifestUrl ? { manifestUrl: details.manifestUrl } : {}),
|
||||
...(details.durationSeconds !== undefined ? { durationSeconds: details.durationSeconds } : {}),
|
||||
...(details.qualityLabel ? { qualityLabel: details.qualityLabel } : {}),
|
||||
...(details.audioTracks ? { audioTracks: details.audioTracks } : {}),
|
||||
...(details.subtitleTracks ? { subtitleTracks: details.subtitleTracks } : {}),
|
||||
};
|
||||
@@ -196,6 +238,7 @@ export class PostgresRepository implements AppRepository {
|
||||
.set({
|
||||
state: session.state,
|
||||
generationId: session.generationId ?? null,
|
||||
variantId: session.variantId ?? null,
|
||||
reasonCode: session.reasonCode ?? null,
|
||||
pollAfterMs: session.pollAfterMs ?? null,
|
||||
responseJson: publicSessionDetails(session),
|
||||
@@ -344,7 +387,11 @@ function toCatalogCard(
|
||||
...(title.posterUrl ? { posterUrl: title.posterUrl } : {}),
|
||||
...(title.backdropUrl ? { backdropUrl: title.backdropUrl } : {}),
|
||||
...(title.releaseYear !== null ? { year: title.releaseYear } : {}),
|
||||
...(title.category ? { category: title.category } : {}),
|
||||
...(title.categorySlug ? { categorySlug: title.categorySlug } : {}),
|
||||
...(title.releaseWindow ? { releaseWindow: title.releaseWindow } : {}),
|
||||
...(first ? { resumeMediaItemId: first.id } : {}),
|
||||
...(first && first.variants.length ? { variants: first.variants as NonNullable<CatalogCard['variants']> } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -387,6 +434,7 @@ function toTitleDetail(
|
||||
durationSeconds: item.durationSeconds ?? 0,
|
||||
compatibility: item.compatibility,
|
||||
published: item.published,
|
||||
variants: item.variants as NonNullable<TitleDetail['mediaItems'][number]['variants']>,
|
||||
})),
|
||||
updatedAt: title.updatedAt.toISOString(),
|
||||
};
|
||||
@@ -420,6 +468,8 @@ function toJob(job: typeof jobs.$inferSelect): Job {
|
||||
|
||||
function publicSessionDetails(session: StoredPlaybackSession): Record<string, unknown> {
|
||||
return {
|
||||
...(session.variantId ? { variantId: session.variantId } : {}),
|
||||
...(session.qualityLabel ? { qualityLabel: session.qualityLabel } : {}),
|
||||
...(session.manifestUrl ? { manifestUrl: session.manifestUrl } : {}),
|
||||
...(session.durationSeconds !== undefined ? { durationSeconds: session.durationSeconds } : {}),
|
||||
...(session.audioTracks ? { audioTracks: session.audioTracks } : {}),
|
||||
|
||||
@@ -167,6 +167,9 @@ export class AdminService {
|
||||
const preparation = await this.media.getStatus({
|
||||
sessionId: randomUUID(),
|
||||
mediaItem: item,
|
||||
variantId: item.variants.find((variant) => variant.available && variant.isDefault)?.id
|
||||
?? item.variants.find((variant) => variant.available)?.id
|
||||
?? item.id,
|
||||
});
|
||||
if (preparation.state !== 'READY' && !preparation.playable) {
|
||||
throw new AppError(
|
||||
|
||||
@@ -43,24 +43,26 @@ export class FileMediaPreparationService implements MediaPreparationService {
|
||||
) {}
|
||||
|
||||
async prepare(input: Parameters<MediaPreparationService['prepare']>[0]) {
|
||||
const status = await this.find(input.mediaItem.id);
|
||||
const status = await this.find(input.mediaItem.id, input.variantId);
|
||||
const requestKey = `${input.mediaItem.id}:${input.variantId ?? 'legacy'}`;
|
||||
if (status) {
|
||||
if (status.playable || status.state === 'READY' || status.state === 'FAILED') {
|
||||
this.requested.delete(input.mediaItem.id);
|
||||
this.requested.delete(requestKey);
|
||||
}
|
||||
await this.recordCacheAccess(input, status);
|
||||
return status;
|
||||
}
|
||||
if (!this.requested.has(input.mediaItem.id)) {
|
||||
this.requested.add(input.mediaItem.id);
|
||||
if (!this.requested.has(requestKey)) {
|
||||
this.requested.add(requestKey);
|
||||
try {
|
||||
await this.publisher.publish({
|
||||
type: 'media.playback.requested',
|
||||
sessionId: input.sessionId,
|
||||
mediaItemId: input.mediaItem.id,
|
||||
...(input.variantId ? { variantId: input.variantId } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
this.requested.delete(input.mediaItem.id);
|
||||
this.requested.delete(requestKey);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -73,9 +75,10 @@ export class FileMediaPreparationService implements MediaPreparationService {
|
||||
}
|
||||
|
||||
async getStatus(input: Parameters<MediaPreparationService['getStatus']>[0]) {
|
||||
const status = await this.find(input.mediaItem.id);
|
||||
const status = await this.find(input.mediaItem.id, input.variantId);
|
||||
const requestKey = `${input.mediaItem.id}:${input.variantId ?? 'legacy'}`;
|
||||
if (status?.playable || status?.state === 'READY' || status?.state === 'FAILED') {
|
||||
this.requested.delete(input.mediaItem.id);
|
||||
this.requested.delete(requestKey);
|
||||
}
|
||||
const result = status ?? {
|
||||
state: 'PREPARING' as const,
|
||||
@@ -102,9 +105,10 @@ export class FileMediaPreparationService implements MediaPreparationService {
|
||||
});
|
||||
}
|
||||
|
||||
private async find(mediaItemId: string): Promise<MediaPreparation | undefined> {
|
||||
private async find(mediaItemId: string, variantId?: string): Promise<MediaPreparation | undefined> {
|
||||
const registry = await readPackageRegistry(this.registryPath);
|
||||
const entry = registry?.packages.find((candidate) => candidate.mediaItemId === mediaItemId);
|
||||
const entry = registry?.packages.find((candidate) => candidate.mediaItemId === mediaItemId
|
||||
&& (candidate.variantId ?? candidate.mediaItemId) === (variantId ?? mediaItemId));
|
||||
if (!entry) return undefined;
|
||||
return {
|
||||
state: entry.state,
|
||||
@@ -226,7 +230,7 @@ function redisConnection(redisUrl: string): ConnectionOptions {
|
||||
function commandJobId(command: MediaCommand, profile: string): string {
|
||||
switch (command.type) {
|
||||
case 'media.playback.requested':
|
||||
return `playback-${command.mediaItemId}-${profile}`;
|
||||
return `playback-${command.mediaItemId}-${command.variantId ?? 'legacy'}-${profile}`;
|
||||
case 'archive.scan.requested':
|
||||
return `scan-${command.jobId}`;
|
||||
case 'media.publication.changed':
|
||||
|
||||
@@ -23,10 +23,15 @@ export class PlaybackService {
|
||||
|
||||
async create(input: CreatePlaybackSession): Promise<StoredPlaybackSession> {
|
||||
const item = await this.requirePlayableMedia(input.mediaItemId);
|
||||
const variant = selectVariant(item, input.variantId);
|
||||
if (!variant) throw new AppError(404, 'NOT_FOUND', 'Requested quality is unavailable');
|
||||
const selectedItem = { ...item, compatibility: variant.compatibility };
|
||||
const now = Date.now();
|
||||
const base: StoredPlaybackSession = {
|
||||
id: randomUUID(),
|
||||
mediaItemId: item.id,
|
||||
variantId: variant.id,
|
||||
qualityLabel: variant.label,
|
||||
state: 'PREPARING',
|
||||
capabilities: input.clientCapabilities,
|
||||
expiresAt: new Date(now + this.config.playbackTtlSeconds * 1000).toISOString(),
|
||||
@@ -41,7 +46,7 @@ export class PlaybackService {
|
||||
await this.repository.createPlaybackSession(unsupported);
|
||||
return unsupported;
|
||||
}
|
||||
if (item.compatibility === 'HOLD_HDR') {
|
||||
if (selectedItem.compatibility === 'HOLD_HDR') {
|
||||
const unsupported: StoredPlaybackSession = {
|
||||
...base,
|
||||
state: 'UNSUPPORTED_CLIENT',
|
||||
@@ -50,7 +55,7 @@ export class PlaybackService {
|
||||
await this.repository.createPlaybackSession(unsupported);
|
||||
return unsupported;
|
||||
}
|
||||
if (item.compatibility === 'INVALID') {
|
||||
if (selectedItem.compatibility === 'INVALID') {
|
||||
const failed: StoredPlaybackSession = {
|
||||
...base,
|
||||
state: 'FAILED',
|
||||
@@ -63,7 +68,8 @@ export class PlaybackService {
|
||||
await this.repository.createPlaybackSession(base);
|
||||
const preparation = await this.media.prepare({
|
||||
sessionId: base.id,
|
||||
mediaItem: item,
|
||||
mediaItem: selectedItem,
|
||||
variantId: variant.id,
|
||||
capabilities: input.clientCapabilities,
|
||||
protectUntil: base.expiresAt,
|
||||
});
|
||||
@@ -79,9 +85,12 @@ export class PlaybackService {
|
||||
}
|
||||
if (session.state !== 'PREPARING') return session;
|
||||
const item = await this.requirePlayableMedia(session.mediaItemId);
|
||||
const variant = selectVariant(item, session.variantId);
|
||||
if (!variant) throw new AppError(404, 'NOT_FOUND', 'Playback quality is no longer available');
|
||||
const preparation = await this.media.getStatus({
|
||||
sessionId: id,
|
||||
mediaItem: item,
|
||||
mediaItem: { ...item, compatibility: variant.compatibility },
|
||||
variantId: variant.id,
|
||||
protectUntil: session.expiresAt,
|
||||
});
|
||||
const updated = this.mergePreparation(session, preparation);
|
||||
@@ -135,6 +144,28 @@ export class PlaybackService {
|
||||
}
|
||||
}
|
||||
|
||||
function selectVariant(item: MediaItemForPlayback, requestedId?: string) {
|
||||
const available = item.variants.filter((variant) => variant.available);
|
||||
if (requestedId) return available.find((variant) => variant.id === requestedId);
|
||||
if (available.length === 0) {
|
||||
return item.published ? {
|
||||
id: item.id,
|
||||
label: 'Source',
|
||||
compatibility: item.compatibility,
|
||||
available: true,
|
||||
isDefault: true,
|
||||
} : undefined;
|
||||
}
|
||||
return available.find((variant) => variant.isDefault)
|
||||
?? [...available].sort((left, right) => {
|
||||
const leftHeight = left.height ?? 0;
|
||||
const rightHeight = right.height ?? 0;
|
||||
const distance = Math.abs(leftHeight - 720) - Math.abs(rightHeight - 720);
|
||||
if (distance !== 0) return distance;
|
||||
return leftHeight <= 720 && rightHeight > 720 ? -1 : 1;
|
||||
})[0];
|
||||
}
|
||||
|
||||
function supportsHls(capabilities: ClientCapabilities): boolean {
|
||||
return capabilities.nativeHls || (capabilities.mse && capabilities.hlsJs);
|
||||
}
|
||||
|
||||
@@ -61,6 +61,10 @@ describe('viewer API', () => {
|
||||
expect.objectContaining({ id: ids.title, playable: true }),
|
||||
]);
|
||||
|
||||
const sections = await app.inject({ method: 'GET', url: '/api/v1/catalog/sections?limitPerSection=12' });
|
||||
expect(sections.statusCode).toBe(200);
|
||||
expect(sections.json().sections[0]).toEqual(expect.objectContaining({ slug: 'anime', name: 'Anime' }));
|
||||
|
||||
const search = await app.inject({ method: 'GET', url: '/api/v1/search?q=Sample' });
|
||||
expect(search.statusCode).toBe(200);
|
||||
expect(search.json().items[0].slug).toBe('sample-series');
|
||||
@@ -89,6 +93,7 @@ describe('viewer API', () => {
|
||||
url: '/api/v1/playback-sessions',
|
||||
payload: {
|
||||
mediaItemId: ids.media,
|
||||
variantId: ids.variant,
|
||||
clientCapabilities: capabilities(),
|
||||
},
|
||||
});
|
||||
@@ -96,6 +101,7 @@ describe('viewer API', () => {
|
||||
expect(response.json()).toEqual(
|
||||
expect.objectContaining({
|
||||
state: 'READY',
|
||||
variantId: ids.variant,
|
||||
manifestUrl: `http://localhost:8080/media/generations/${ids.generation}/master.m3u8`,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ export const ids = {
|
||||
generation: '30000000-0000-4000-8000-000000000001',
|
||||
audio: '40000000-0000-4000-8000-000000000001',
|
||||
subtitle: '50000000-0000-4000-8000-000000000001',
|
||||
variant: '60000000-0000-4000-8000-000000000001',
|
||||
};
|
||||
|
||||
export const titleFixture: TitleDetail = {
|
||||
@@ -16,6 +17,11 @@ export const titleFixture: TitleDetail = {
|
||||
name: { fa: 'سریال نمونه', en: 'Sample Series' },
|
||||
synopsis: { fa: 'خلاصه نمونه', en: 'Sample synopsis' },
|
||||
playable: true,
|
||||
category: 'Anime',
|
||||
categorySlug: 'anime',
|
||||
releaseWindow: 'SUMMER',
|
||||
year: 2026,
|
||||
variants: [{ id: ids.variant, label: '720p', width: 1280, height: 720, videoCodec: 'h264', compatibility: 'COPY', available: true, isDefault: true }],
|
||||
resumeMediaItemId: ids.media,
|
||||
seasons: [{ number: 1, episodeCount: 1 }],
|
||||
mediaItems: [
|
||||
@@ -28,6 +34,7 @@ export const titleFixture: TitleDetail = {
|
||||
durationSeconds: 1420,
|
||||
compatibility: 'COPY',
|
||||
published: true,
|
||||
variants: [{ id: ids.variant, label: '720p', width: 1280, height: 720, videoCodec: 'h264', compatibility: 'COPY', available: true, isDefault: true }],
|
||||
},
|
||||
],
|
||||
updatedAt: '2026-07-14T00:00:00.000Z',
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
AdminJob,
|
||||
CatalogItem,
|
||||
CatalogPage,
|
||||
CatalogSection,
|
||||
ClientCapabilities,
|
||||
EpisodeItem,
|
||||
LocalizedText,
|
||||
@@ -10,6 +11,7 @@ import type {
|
||||
PlaybackSession,
|
||||
PlaybackState,
|
||||
PlaybackSubtitleTrack,
|
||||
QualityVariant,
|
||||
SeasonItem,
|
||||
TitleDetail,
|
||||
} from '@/types'
|
||||
@@ -67,6 +69,20 @@ function array(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : []
|
||||
}
|
||||
|
||||
function normalizeVariant(input: unknown): QualityVariant {
|
||||
const item = record(input)
|
||||
return {
|
||||
id: text(item.id) ?? '',
|
||||
label: text(item.label) ?? `${number(item.height) ?? 0}p`,
|
||||
...(number(item.width) ? { width: number(item.width) } : {}),
|
||||
...(number(item.height) ? { height: number(item.height) } : {}),
|
||||
...(text(item.videoCodec) ? { videoCodec: text(item.videoCodec) } : {}),
|
||||
compatibility: text(item.compatibility) ?? 'INVALID',
|
||||
available: boolean(item.available),
|
||||
isDefault: boolean(item.isDefault),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCatalogItem(input: unknown): CatalogItem {
|
||||
const item = record(input)
|
||||
const metadata = record(item.metadata)
|
||||
@@ -95,6 +111,10 @@ function normalizeCatalogItem(input: unknown): CatalogItem {
|
||||
...(posterUrl ? { posterUrl } : {}),
|
||||
...(backdropUrl ? { backdropUrl } : {}),
|
||||
...(number(item.year ?? metadata.year) !== undefined ? { year: number(item.year ?? metadata.year) } : {}),
|
||||
...(text(item.category) ? { category: text(item.category) } : {}),
|
||||
...(text(item.categorySlug) ? { categorySlug: text(item.categorySlug) } : {}),
|
||||
...(text(item.releaseWindow) ? { releaseWindow: text(item.releaseWindow) } : {}),
|
||||
variants: array(item.variants).map(normalizeVariant).filter((variant) => variant.id),
|
||||
...(number(item.runtimeSeconds ?? item.durationSeconds) !== undefined
|
||||
? { runtimeSeconds: number(item.runtimeSeconds ?? item.durationSeconds) }
|
||||
: {}),
|
||||
@@ -121,6 +141,7 @@ function normalizeEpisode(input: unknown, seasonNumber: number): EpisodeItem {
|
||||
? { durationSeconds: number(item.durationSeconds ?? item.runtimeSeconds) }
|
||||
: {}),
|
||||
published: item.published === undefined ? true : boolean(item.published),
|
||||
variants: array(item.variants).map(normalizeVariant).filter((variant) => variant.id),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,6 +228,8 @@ export function normalizePlaybackSession(input: unknown): PlaybackSession {
|
||||
id,
|
||||
state: normalizeState(payload.state ?? payload.status),
|
||||
mediaItemId: text(payload.mediaItemId) ?? '',
|
||||
...(text(payload.variantId) ? { variantId: text(payload.variantId) } : {}),
|
||||
...(text(payload.qualityLabel) ? { qualityLabel: text(payload.qualityLabel) } : {}),
|
||||
...(manifestUrl ? { manifestUrl } : {}),
|
||||
...(number(payload.durationSeconds ?? payload.duration) !== undefined
|
||||
? { durationSeconds: number(payload.durationSeconds ?? payload.duration) }
|
||||
@@ -270,7 +293,7 @@ function withSignal(signal: AbortSignal | undefined, init: RequestInit = {}): Re
|
||||
}
|
||||
|
||||
export const api = {
|
||||
async catalog(options: { cursor?: string; limit?: number; kind?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
|
||||
async catalog(options: { cursor?: string; limit?: number; kind?: string; category?: string; year?: number; releaseWindow?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
|
||||
const body = await request(`/catalog${queryString({ ...options })}`, withSignal(signal))
|
||||
const source = record(body)
|
||||
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
|
||||
@@ -284,6 +307,19 @@ export const api = {
|
||||
}
|
||||
},
|
||||
|
||||
async catalogSections(limitPerSection = 12, signal?: AbortSignal): Promise<CatalogSection[]> {
|
||||
const body = record(await request(`/catalog/sections${queryString({ limitPerSection })}`, withSignal(signal)))
|
||||
return array(body.sections).map((input) => {
|
||||
const section = record(input)
|
||||
return {
|
||||
slug: text(section.slug) ?? '',
|
||||
name: text(section.name) ?? text(section.slug) ?? '',
|
||||
items: array(section.items).map(normalizeCatalogItem).filter((item) => item.id),
|
||||
hasMore: boolean(section.hasMore),
|
||||
}
|
||||
}).filter((section) => section.slug && section.items.length)
|
||||
},
|
||||
|
||||
async search(term: string, signal?: AbortSignal): Promise<CatalogPage> {
|
||||
const body = await request(`/search${queryString({ q: term, limit: 40 })}`, withSignal(signal))
|
||||
const source = record(body)
|
||||
@@ -334,11 +370,12 @@ export const api = {
|
||||
async createPlaybackSession(
|
||||
mediaItemId: string,
|
||||
clientCapabilities: ClientCapabilities,
|
||||
variantId?: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PlaybackSession> {
|
||||
const body = await request('/playback-sessions', withSignal(signal, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mediaItemId, clientCapabilities }),
|
||||
body: JSON.stringify({ mediaItemId, ...(variantId ? { variantId } : {}), clientCapabilities }),
|
||||
}))
|
||||
const session = normalizePlaybackSession(body)
|
||||
return { ...session, mediaItemId: session.mediaItemId || mediaItemId }
|
||||
@@ -436,7 +473,7 @@ export const api = {
|
||||
const body = record(await request('/admin/scans', {
|
||||
method: 'POST',
|
||||
headers: { 'x-csrf-token': csrfToken },
|
||||
body: JSON.stringify({ full: false }),
|
||||
body: JSON.stringify({ full: true }),
|
||||
}))
|
||||
const jobId = text(body.id ?? body.jobId ?? record(body.data).jobId)
|
||||
return { ...(jobId ? { jobId } : {}) }
|
||||
|
||||
@@ -14,6 +14,7 @@ const item: CatalogItem = {
|
||||
title: { fa: 'فیلم نمونه', en: 'Sample movie' },
|
||||
overview: {},
|
||||
playable: true,
|
||||
variants: [],
|
||||
year: 2026,
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ function play() {
|
||||
if (!props.item.playable || !props.item.mediaItemId) return
|
||||
player.play({
|
||||
mediaItemId: props.item.mediaItemId,
|
||||
...(props.item.variants.length ? { variants: props.item.variants } : {}),
|
||||
title: title.value,
|
||||
...(props.item.posterUrl ? { posterUrl: props.item.posterUrl } : {}),
|
||||
})
|
||||
|
||||
@@ -36,7 +36,7 @@ const currentTime = ref(0)
|
||||
const duration = ref(0)
|
||||
const buffered = ref(0)
|
||||
const controlsVisible = ref(true)
|
||||
const menu = ref<'subtitles' | 'audio' | null>(null)
|
||||
const menu = ref<'subtitles' | 'audio' | 'quality' | null>(null)
|
||||
const session = ref<PlaybackSession | null>(null)
|
||||
const selectedSubtitle = ref('off')
|
||||
const selectedAudio = ref('')
|
||||
@@ -442,7 +442,17 @@ async function start(request: PlayRequest) {
|
||||
}
|
||||
|
||||
try {
|
||||
const initial = await api.createPlaybackSession(request.mediaItemId, capabilities, requestController.signal)
|
||||
const variants = (request.variants ?? []).filter((variant) => variant.available)
|
||||
const selectedVariant = request.variantId
|
||||
? variants.find((variant) => variant.id === request.variantId)
|
||||
: variants.find((variant) => variant.height === ui.preferences.preferredQualityHeight)
|
||||
?? variants.find((variant) => variant.isDefault)
|
||||
const initial = await api.createPlaybackSession(
|
||||
request.mediaItemId,
|
||||
capabilities,
|
||||
selectedVariant?.id,
|
||||
requestController.signal,
|
||||
)
|
||||
await resolveSession(initial, sequence, requestController.signal)
|
||||
} catch (error) {
|
||||
if ((error as { name?: string }).name === 'AbortError' || sequence !== requestSequence) return
|
||||
@@ -503,11 +513,23 @@ function toggleMute() {
|
||||
void ui.setVolume(element.volume, element.muted)
|
||||
}
|
||||
|
||||
function toggleMenu(target: 'subtitles' | 'audio') {
|
||||
function toggleMenu(target: 'subtitles' | 'audio' | 'quality') {
|
||||
menu.value = menu.value === target ? null : target
|
||||
showControls()
|
||||
}
|
||||
|
||||
async function chooseQuality(variant: NonNullable<PlayRequest['variants']>[number]) {
|
||||
const request = currentRequest.value
|
||||
if (!request || session.value?.variantId === variant.id) {
|
||||
menu.value = null
|
||||
return
|
||||
}
|
||||
await saveProgress(true)
|
||||
if (variant.height) await ui.setPreferredQuality(variant.height)
|
||||
menu.value = null
|
||||
await start({ ...request, variantId: variant.id })
|
||||
}
|
||||
|
||||
function formatTime(seconds: number): string {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return '00:00'
|
||||
const hours = Math.floor(seconds / 3600)
|
||||
@@ -671,6 +693,20 @@ onBeforeUnmount(() => {
|
||||
|
||||
<span class="control-spacer" />
|
||||
|
||||
<div v-if="currentRequest?.variants?.some((variant) => variant.available)" class="control-menu-wrap">
|
||||
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('quality')">{{ t('quality') }}</button>
|
||||
<div v-if="menu === 'quality'" class="track-menu">
|
||||
<button
|
||||
v-for="variant in currentRequest.variants.filter((candidate) => candidate.available)"
|
||||
:key="variant.id"
|
||||
type="button"
|
||||
data-tv-focus
|
||||
:class="{ selected: variant.id === session?.variantId }"
|
||||
@click="chooseQuality(variant)"
|
||||
>{{ variant.label }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="session?.audioTracks.length" class="control-menu-wrap">
|
||||
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('audio')">{{ t('audio') }}</button>
|
||||
<div v-if="menu === 'audio'" class="track-menu">
|
||||
|
||||
@@ -61,6 +61,12 @@ const fa = {
|
||||
unavailable: 'ناموجود',
|
||||
unsupported: 'پشتیبانینشده',
|
||||
year: 'سال',
|
||||
quality: 'کیفیت',
|
||||
browse: 'مرور',
|
||||
browseAll: 'مشاهده همه',
|
||||
allYears: 'همه سالها',
|
||||
releaseWindow: 'بازه انتشار',
|
||||
allSeasons: 'همه فصلها',
|
||||
} as const
|
||||
|
||||
const en: Record<keyof typeof fa, string> = {
|
||||
@@ -122,6 +128,12 @@ const en: Record<keyof typeof fa, string> = {
|
||||
unavailable: 'Unavailable',
|
||||
unsupported: 'Unsupported',
|
||||
year: 'Year',
|
||||
quality: 'Quality',
|
||||
browse: 'Browse',
|
||||
browseAll: 'Browse all',
|
||||
allYears: 'All years',
|
||||
releaseWindow: 'Release season',
|
||||
allSeasons: 'All seasons',
|
||||
}
|
||||
|
||||
export type TranslationKey = keyof typeof fa
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
|
||||
|
||||
import AdminView from '@/views/AdminView.vue'
|
||||
import CatalogView from '@/views/CatalogView.vue'
|
||||
import BrowseView from '@/views/BrowseView.vue'
|
||||
import SearchView from '@/views/SearchView.vue'
|
||||
import TitleView from '@/views/TitleView.vue'
|
||||
|
||||
@@ -11,6 +12,7 @@ export const router = createRouter({
|
||||
routes: [
|
||||
{ path: '/', name: 'catalog', component: CatalogView },
|
||||
{ path: '/search', name: 'search', component: SearchView },
|
||||
{ path: '/browse/:category', name: 'browse', component: BrowseView },
|
||||
{ path: '/title/:slug', name: 'title', component: TitleView },
|
||||
{ path: '/admin', name: 'admin', component: AdminView },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
|
||||
@@ -18,6 +18,7 @@ describe('viewer storage', () => {
|
||||
audioLanguage: 'ja',
|
||||
volume: 0.7,
|
||||
muted: false,
|
||||
preferredQualityHeight: 1080,
|
||||
})
|
||||
|
||||
await expect(readPreferences()).resolves.toMatchObject({ uiLanguage: 'en', subtitleLanguage: 'en', volume: 0.7 })
|
||||
|
||||
@@ -11,6 +11,7 @@ export const defaultPreferences: ViewerPreferences = {
|
||||
audioLanguage: 'ja',
|
||||
volume: 1,
|
||||
muted: false,
|
||||
preferredQualityHeight: 720,
|
||||
}
|
||||
|
||||
let databasePromise: Promise<IDBDatabase | null> | undefined
|
||||
|
||||
@@ -3,6 +3,8 @@ import { markRaw } from 'vue'
|
||||
|
||||
export interface PlayRequest {
|
||||
mediaItemId: string
|
||||
variantId?: string
|
||||
variants?: import('@/types').QualityVariant[]
|
||||
title: string
|
||||
posterUrl?: string
|
||||
}
|
||||
|
||||
@@ -43,5 +43,10 @@ export const useUiStore = defineStore('ui', {
|
||||
this.preferences.muted = muted
|
||||
await writePreferences({ ...this.preferences })
|
||||
},
|
||||
|
||||
async setPreferredQuality(height: number) {
|
||||
this.preferences.preferredQualityHeight = Math.max(1, Math.round(height))
|
||||
await writePreferences({ ...this.preferences })
|
||||
},
|
||||
},
|
||||
})
|
||||
+46
-1
@@ -39,7 +39,8 @@ body {
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
input,
|
||||
select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
@@ -1356,3 +1357,47 @@ button:disabled,
|
||||
animation-iteration-count: 1 !important;
|
||||
}
|
||||
}
|
||||
|
||||
.section-heading,
|
||||
.browse-header,
|
||||
.browse-filters {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.category-rail {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scroll-snap-type: x proximity;
|
||||
padding-block: .5rem 1rem;
|
||||
}
|
||||
|
||||
.category-rail > * {
|
||||
flex: 0 0 clamp(10rem, 17vw, 15rem);
|
||||
scroll-snap-align: start;
|
||||
}
|
||||
|
||||
.browse-view {
|
||||
padding: 7rem clamp(1rem, 4vw, 4rem) 4rem;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.browse-header { margin-bottom: 2rem; align-items: end; }
|
||||
.browse-header h1 { margin: .25rem 0 0; font-size: clamp(2rem, 5vw, 4rem); }
|
||||
.browse-filters select {
|
||||
min-width: 10rem;
|
||||
padding: .75rem 1rem;
|
||||
color: var(--text);
|
||||
background: var(--panel-raised);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: .8rem;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.browse-header { align-items: stretch; flex-direction: column; }
|
||||
.browse-filters { align-items: stretch; }
|
||||
.browse-filters select { min-width: 0; flex: 1; }
|
||||
}
|
||||
@@ -6,6 +6,17 @@ export interface LocalizedText {
|
||||
en?: string | undefined
|
||||
}
|
||||
|
||||
export interface QualityVariant {
|
||||
id: string
|
||||
label: string
|
||||
width?: number | undefined
|
||||
height?: number | undefined
|
||||
videoCodec?: string | undefined
|
||||
compatibility: string
|
||||
available: boolean
|
||||
isDefault: boolean
|
||||
}
|
||||
|
||||
export interface CatalogItem {
|
||||
id: string
|
||||
mediaItemId: string
|
||||
@@ -16,6 +27,10 @@ export interface CatalogItem {
|
||||
posterUrl?: string | undefined
|
||||
backdropUrl?: string | undefined
|
||||
year?: number | undefined
|
||||
category?: string | undefined
|
||||
categorySlug?: string | undefined
|
||||
releaseWindow?: string | undefined
|
||||
variants: QualityVariant[]
|
||||
runtimeSeconds?: number | undefined
|
||||
seasonCount?: number | undefined
|
||||
episodeCount?: number | undefined
|
||||
@@ -34,6 +49,7 @@ export interface EpisodeItem {
|
||||
posterUrl?: string | undefined
|
||||
durationSeconds?: number | undefined
|
||||
published: boolean
|
||||
variants: QualityVariant[]
|
||||
}
|
||||
|
||||
export interface SeasonItem {
|
||||
@@ -54,6 +70,13 @@ export interface CatalogPage {
|
||||
total?: number | undefined
|
||||
}
|
||||
|
||||
export interface CatalogSection {
|
||||
slug: string
|
||||
name: string
|
||||
items: CatalogItem[]
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
export type PlaybackState = 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED'
|
||||
export type SubtitleDelivery = 'ASS_JASSUB' | 'WEBVTT' | 'OFF'
|
||||
|
||||
@@ -79,6 +102,8 @@ export interface PlaybackSession {
|
||||
id: string
|
||||
state: PlaybackState
|
||||
mediaItemId: string
|
||||
variantId?: string | undefined
|
||||
qualityLabel?: string | undefined
|
||||
manifestUrl?: string | undefined
|
||||
durationSeconds?: number | undefined
|
||||
pollAfterMs: number
|
||||
@@ -115,6 +140,7 @@ export interface ViewerPreferences {
|
||||
audioLanguage: string
|
||||
volume: number
|
||||
muted: boolean
|
||||
preferredQualityHeight: number
|
||||
}
|
||||
|
||||
export interface AdminJob {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { api } from '@/api/client'
|
||||
import LoadingState from '@/components/LoadingState.vue'
|
||||
import MediaCard from '@/components/MediaCard.vue'
|
||||
import { useSpatialNavigation } from '@/composables/spatial-navigation'
|
||||
import { useI18n } from '@/i18n'
|
||||
import type { CatalogItem } from '@/types'
|
||||
|
||||
const route = useRoute()
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const items = ref<CatalogItem[]>([])
|
||||
const sourceItems = ref<CatalogItem[]>([])
|
||||
const year = ref('')
|
||||
const releaseWindow = ref('')
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
let controller: AbortController | undefined
|
||||
const { t } = useI18n()
|
||||
useSpatialNavigation(root, { restoreKey: 'browse-focus' })
|
||||
const category = computed(() => String(route.params.category ?? ''))
|
||||
const categoryName = computed(() => sourceItems.value[0]?.category ?? category.value)
|
||||
const years = computed(() => [...new Set(sourceItems.value.map((item) => item.year).filter((value): value is number => value !== undefined))].sort((a, b) => b - a))
|
||||
const windows = computed(() => [...new Set(sourceItems.value.map((item) => item.releaseWindow).filter((value): value is string => Boolean(value)))])
|
||||
|
||||
async function load() {
|
||||
controller?.abort()
|
||||
controller = new AbortController()
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const page = await api.catalog({
|
||||
category: category.value,
|
||||
limit: 100,
|
||||
...(year.value ? { year: Number(year.value) } : {}),
|
||||
...(releaseWindow.value ? { releaseWindow: releaseWindow.value } : {}),
|
||||
}, controller.signal)
|
||||
items.value = page.items
|
||||
if (!year.value && !releaseWindow.value) sourceItems.value = page.items
|
||||
} catch (reason) {
|
||||
if ((reason as { name?: string }).name !== 'AbortError') error.value = reason instanceof Error ? reason.message : t('networkError')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch([category, year, releaseWindow], () => void load(), { immediate: true })
|
||||
onBeforeUnmount(() => controller?.abort())
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main ref="root" class="browse-view">
|
||||
<header class="browse-header">
|
||||
<div><p class="eyebrow">{{ t('browse') }}</p><h1>{{ categoryName }}</h1></div>
|
||||
<div class="browse-filters">
|
||||
<select v-model="year" data-tv-focus class="focus-ring" :aria-label="t('year')">
|
||||
<option value="">{{ t('allYears') }}</option>
|
||||
<option v-for="value in years" :key="value" :value="String(value)">{{ value }}</option>
|
||||
</select>
|
||||
<select v-model="releaseWindow" data-tv-focus class="focus-ring" :aria-label="t('releaseWindow')">
|
||||
<option value="">{{ t('allSeasons') }}</option>
|
||||
<option v-for="value in windows" :key="value" :value="value">{{ value }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</header>
|
||||
<LoadingState v-if="loading" :label="t('loadingCatalog')" />
|
||||
<section v-else-if="error" class="center-state error-state"><p>{{ error }}</p></section>
|
||||
<section v-else-if="items.length" class="media-grid">
|
||||
<MediaCard v-for="item in items" :key="item.id" :item="item" />
|
||||
</section>
|
||||
<section v-else class="center-state"><h2>{{ t('emptyCatalog') }}</h2></section>
|
||||
</main>
|
||||
</template>
|
||||
@@ -8,15 +8,16 @@ import { useSpatialNavigation } from '@/composables/spatial-navigation'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { listProgress } from '@/storage/viewer-db'
|
||||
import { usePlayerStore } from '@/stores/player'
|
||||
import type { CatalogItem } from '@/types'
|
||||
import type { CatalogItem, CatalogSection } from '@/types'
|
||||
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const items = ref<CatalogItem[]>([])
|
||||
const sections = ref<CatalogSection[]>([])
|
||||
const progress = ref<Record<string, number>>({})
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
const { localize, t } = useI18n()
|
||||
const player = usePlayerStore()
|
||||
const items = computed(() => sections.value.flatMap((section) => section.items))
|
||||
const featured = computed(() => items.value.find((item) => item.playable) ?? items.value[0])
|
||||
const { restoreFocus } = useSpatialNavigation(root, { restoreKey: 'catalog-focus' })
|
||||
|
||||
@@ -25,6 +26,7 @@ function playFeatured() {
|
||||
if (!item?.playable || !item.mediaItemId) return
|
||||
player.play({
|
||||
mediaItemId: item.mediaItemId,
|
||||
...(item.variants.length ? { variants: item.variants } : {}),
|
||||
title: localize(item.title, item.slug),
|
||||
...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
|
||||
})
|
||||
@@ -34,8 +36,8 @@ async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [catalog, storedProgress] = await Promise.all([api.catalog({ limit: 60 }), listProgress()])
|
||||
items.value = catalog.items
|
||||
const [catalogSections, storedProgress] = await Promise.all([api.catalogSections(12), listProgress()])
|
||||
sections.value = catalogSections
|
||||
progress.value = Object.fromEntries(storedProgress.map((entry) => [
|
||||
entry.mediaItemId,
|
||||
entry.durationSeconds > 0 ? (entry.positionSeconds / entry.durationSeconds) * 100 : 0,
|
||||
@@ -96,11 +98,16 @@ onMounted(() => void load())
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="catalog-section" aria-labelledby="catalog-heading">
|
||||
<h2 id="catalog-heading">{{ t('allTitles') }}</h2>
|
||||
<div class="media-grid">
|
||||
<section v-for="section in sections" :key="section.slug" class="catalog-section">
|
||||
<div class="section-heading">
|
||||
<h2>{{ section.name }}</h2>
|
||||
<RouterLink class="secondary-button focus-ring" data-tv-focus :to="{ name: 'browse', params: { category: section.slug } }">
|
||||
{{ t('browseAll') }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
<div class="media-grid category-rail">
|
||||
<MediaCard
|
||||
v-for="item in items"
|
||||
v-for="item in section.items"
|
||||
:key="item.id"
|
||||
:item="item"
|
||||
:progress="progress[item.mediaItemId]"
|
||||
|
||||
@@ -31,6 +31,7 @@ function playTitle() {
|
||||
if (!detail.value || !mediaItemId) return
|
||||
player.play({
|
||||
mediaItemId,
|
||||
...(detail.value.variants.length ? { variants: detail.value.variants } : {}),
|
||||
title: title.value,
|
||||
...(detail.value.posterUrl ? { posterUrl: detail.value.posterUrl } : {}),
|
||||
})
|
||||
@@ -39,6 +40,7 @@ function playTitle() {
|
||||
function playEpisode(episode: EpisodeItem) {
|
||||
player.play({
|
||||
mediaItemId: episode.mediaItemId,
|
||||
...(episode.variants.length ? { variants: episode.variants } : {}),
|
||||
title: `${title.value} · ${t('episode')} ${episode.number}`,
|
||||
...(episode.posterUrl ? { posterUrl: episode.posterUrl } : {}),
|
||||
})
|
||||
|
||||
+191
-29
@@ -1,4 +1,5 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { access, copyFile, mkdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
assDialogueText,
|
||||
@@ -23,6 +24,11 @@ export interface ParsedMediaIdentity {
|
||||
seasonNumber?: number;
|
||||
episodeNumber?: number;
|
||||
episodeTitle?: string;
|
||||
category?: string;
|
||||
categorySlug?: string;
|
||||
year?: number;
|
||||
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
|
||||
titleDirectory?: string;
|
||||
}
|
||||
|
||||
export interface SnapshotSubtitle {
|
||||
@@ -38,16 +44,15 @@ export interface SnapshotSubtitle {
|
||||
forced: false;
|
||||
}
|
||||
|
||||
export interface SnapshotMediaItem {
|
||||
export interface SnapshotMediaVariant {
|
||||
id: string;
|
||||
titleId: string;
|
||||
kind: 'MOVIE' | 'EPISODE';
|
||||
sourcePath: string;
|
||||
durationSeconds: number;
|
||||
seasonNumber?: number;
|
||||
episodeNumber?: number;
|
||||
title: { en: string; fa?: string };
|
||||
published: boolean;
|
||||
qualityLabel: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
videoCodec?: string;
|
||||
available: boolean;
|
||||
compatibility: Classification['class'];
|
||||
compatibilityReasons: string[];
|
||||
fingerprint: SourceFingerprint;
|
||||
@@ -55,6 +60,16 @@ export interface SnapshotMediaItem {
|
||||
subtitles: SnapshotSubtitle[];
|
||||
}
|
||||
|
||||
export interface SnapshotMediaItem extends SnapshotMediaVariant {
|
||||
titleId: string;
|
||||
kind: 'MOVIE' | 'EPISODE';
|
||||
seasonNumber?: number;
|
||||
episodeNumber?: number;
|
||||
title: { en: string; fa?: string };
|
||||
published: boolean;
|
||||
variants?: SnapshotMediaVariant[];
|
||||
}
|
||||
|
||||
export interface SnapshotSeason {
|
||||
number: number;
|
||||
title: { en: string };
|
||||
@@ -66,6 +81,11 @@ export interface SnapshotTitle {
|
||||
slug: string;
|
||||
kind: CatalogKind;
|
||||
title: { en: string; fa?: string };
|
||||
category?: string;
|
||||
categorySlug?: string;
|
||||
year?: number;
|
||||
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
|
||||
posterUrl?: string;
|
||||
published: boolean;
|
||||
playable: boolean;
|
||||
mediaItemId: string;
|
||||
@@ -93,6 +113,16 @@ export interface PublicMediaItem {
|
||||
durationSeconds: number;
|
||||
compatibility: Classification['class'];
|
||||
published: boolean;
|
||||
variants?: Array<{
|
||||
id: string;
|
||||
label: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
videoCodec?: string;
|
||||
compatibility: Classification['class'];
|
||||
available: boolean;
|
||||
isDefault: boolean;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface PublicTitleDetail {
|
||||
@@ -100,8 +130,14 @@ export interface PublicTitleDetail {
|
||||
slug: string;
|
||||
kind: CatalogKind;
|
||||
name: { fa: string; en?: string };
|
||||
posterUrl?: string;
|
||||
category?: string;
|
||||
categorySlug?: string;
|
||||
year?: number;
|
||||
releaseWindow?: 'SPRING' | 'SUMMER' | 'FALL' | 'WINTER' | 'MOVIE';
|
||||
playable: boolean;
|
||||
resumeMediaItemId?: string;
|
||||
variants?: PublicMediaItem['variants'];
|
||||
synopsis: { fa?: string; en?: string };
|
||||
seasons?: Array<{ number: number; episodeCount: number }>;
|
||||
mediaItems: PublicMediaItem[];
|
||||
@@ -146,16 +182,33 @@ export function slugify(value: string): string {
|
||||
export function parseMediaIdentity(relativePath: string): ParsedMediaIdentity {
|
||||
const extension = path.extname(relativePath);
|
||||
const filename = path.basename(relativePath, extension);
|
||||
const parent = path.basename(path.dirname(relativePath));
|
||||
const segments = relativePath.split('/').filter(Boolean);
|
||||
const immediateParent = segments.at(-2) ?? '';
|
||||
const qualityDirectory = /^(?:\d{3,4}p?)(?:[\s._-]+(?:x26[45]|hevc|av1))?$|^(?:x26[45]|hevc|av1)$/iu.test(immediateParent);
|
||||
const titleDirectory = segments.at(qualityDirectory ? -3 : -2) ?? immediateParent;
|
||||
const titleIndex = Math.max(0, segments.length - (qualityDirectory ? 3 : 2));
|
||||
const hierarchy = segments.slice(0, titleIndex);
|
||||
const categorySource = hierarchy[0];
|
||||
const yearSource = hierarchy.find((segment) => /^(?:18|19|20|21|22)\d{2}$/u.test(segment));
|
||||
const releaseSource = hierarchy.find((segment) => /^(?:spring|summer|fall|winter|movie)$/iu.test(segment));
|
||||
const releaseWindow = releaseSource?.toLocaleUpperCase('en-US') as ParsedMediaIdentity['releaseWindow'];
|
||||
const category = categorySource ? cleanName(categorySource).replace(/^./u, (value) => value.toLocaleUpperCase('en-US')) : undefined;
|
||||
const combined = filename.match(/\bS(?:eason)?\s*(\d{1,3})\s*E(?:p(?:isode)?)?\s*(\d{1,4})\b/iu);
|
||||
const parentSeason = parent.match(/^(.*?)(?:[\s._-]+S(?:eason)?\s*(\d{1,3}))$/iu);
|
||||
const parentSeason = titleDirectory.match(/^(.*?)(?:[\s._-]+S(?:eason)?\s*(\d{1,3}))$/iu);
|
||||
const episode = combined?.[2]
|
||||
?? filename.match(/(?:-|–)\s*(\d{1,4})(?=(?:[.\s_\[]|$))/u)?.[1]
|
||||
?? filename.match(/\bE(?:p(?:isode)?)?\s*(\d{1,4})\b/iu)?.[1];
|
||||
if (episode !== undefined) {
|
||||
const common = {
|
||||
...(category ? { category, categorySlug: slugify(category) } : {}),
|
||||
...(yearSource ? { year: Number(yearSource) } : {}),
|
||||
...(releaseWindow ? { releaseWindow } : {}),
|
||||
...(titleDirectory ? { titleDirectory: segments.slice(0, titleIndex + 1).join('/') } : {}),
|
||||
};
|
||||
if (episode !== undefined && releaseWindow !== 'MOVIE') {
|
||||
const season = Number(combined?.[1] ?? parentSeason?.[2] ?? 1);
|
||||
const title = cleanName(parentSeason?.[1] ?? parent);
|
||||
const title = cleanName(parentSeason?.[1] ?? titleDirectory);
|
||||
return {
|
||||
...common,
|
||||
kind: 'SERIES',
|
||||
title: title || cleanName(filename),
|
||||
seasonNumber: season,
|
||||
@@ -163,7 +216,7 @@ export function parseMediaIdentity(relativePath: string): ParsedMediaIdentity {
|
||||
episodeTitle: `Episode ${Number(episode)}`,
|
||||
};
|
||||
}
|
||||
return { kind: 'MOVIE', title: cleanName(filename) };
|
||||
return { ...common, kind: 'MOVIE', title: cleanName(titleDirectory || filename) };
|
||||
}
|
||||
|
||||
export interface ScanArchiveOptions {
|
||||
@@ -171,6 +224,7 @@ export interface ScanArchiveOptions {
|
||||
ffmpegPath?: string;
|
||||
ffprobePath?: string;
|
||||
onFile?: (relativePath: string, current: number) => void;
|
||||
artworkRoot?: string;
|
||||
}
|
||||
|
||||
const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']);
|
||||
@@ -185,7 +239,7 @@ async function inspectFile(
|
||||
sourcePath: string,
|
||||
archiveRoot: string,
|
||||
options: ScanArchiveOptions,
|
||||
): Promise<{ identity: ParsedMediaIdentity; media: SnapshotMediaItem }> {
|
||||
): Promise<{ identity: ParsedMediaIdentity; variant: SnapshotMediaVariant }> {
|
||||
const relativePath = path.relative(archiveRoot, sourcePath).split(path.sep).join('/');
|
||||
const identity = parseMediaIdentity(relativePath);
|
||||
const [probe, fingerprint] = await Promise.all([
|
||||
@@ -193,8 +247,7 @@ async function inspectFile(
|
||||
fingerprintSource(archiveRoot, sourcePath),
|
||||
]);
|
||||
const compatibility = classifyMedia(probe);
|
||||
const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`);
|
||||
const mediaId = deterministicUuid(`media:${relativePath}`);
|
||||
const variantId = deterministicUuid(`variant:${relativePath}`);
|
||||
const tracks = normalizeTracks(probe);
|
||||
const subtitles: SnapshotSubtitle[] = [];
|
||||
for (const stream of probe.streams.filter((candidate) => candidate.codec_type === 'subtitle')) {
|
||||
@@ -234,19 +287,20 @@ async function inspectFile(
|
||||
});
|
||||
}
|
||||
const duration = Number(probe.format.duration);
|
||||
const published = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class);
|
||||
const video = probe.streams.find((stream) => stream.codec_type === 'video');
|
||||
const available = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class);
|
||||
const qualityLabel = video?.height ? `${video.height}p` : cleanName(path.basename(path.dirname(relativePath))) || 'Source';
|
||||
return {
|
||||
identity,
|
||||
media: {
|
||||
id: mediaId,
|
||||
titleId,
|
||||
kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE',
|
||||
variant: {
|
||||
id: variantId,
|
||||
sourcePath: relativePath,
|
||||
durationSeconds: Number.isFinite(duration) ? duration : 0,
|
||||
...(identity.seasonNumber === undefined ? {} : { seasonNumber: identity.seasonNumber }),
|
||||
...(identity.episodeNumber === undefined ? {} : { episodeNumber: identity.episodeNumber }),
|
||||
title: { en: identity.episodeTitle ?? identity.title },
|
||||
published,
|
||||
qualityLabel,
|
||||
...(video?.width ? { width: video.width } : {}),
|
||||
...(video?.height ? { height: video.height } : {}),
|
||||
...(video?.codec_name ? { videoCodec: video.codec_name } : {}),
|
||||
available,
|
||||
compatibility: compatibility.class,
|
||||
compatibilityReasons: compatibility.reasons,
|
||||
fingerprint,
|
||||
@@ -258,19 +312,48 @@ async function inspectFile(
|
||||
|
||||
export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArchiveResult> {
|
||||
const root = path.resolve(options.archiveRoot);
|
||||
const grouped = new Map<string, { identity: ParsedMediaIdentity; media: SnapshotMediaItem[] }>();
|
||||
const grouped = new Map<string, { identity: ParsedMediaIdentity; variants: SnapshotMediaVariant[] }>();
|
||||
let current = 0;
|
||||
for await (const sourcePath of walkArchive(root)) {
|
||||
current += 1;
|
||||
const relative = path.relative(root, sourcePath).split(path.sep).join('/');
|
||||
options.onFile?.(relative, current);
|
||||
const inspected = await inspectFile(sourcePath, root, options);
|
||||
const key = `${inspected.identity.kind}:${inspected.identity.title.toLocaleLowerCase('en-US')}`;
|
||||
const group = grouped.get(key) ?? { identity: inspected.identity, media: [] };
|
||||
group.media.push(inspected.media);
|
||||
const logical = inspected.identity.kind === 'MOVIE'
|
||||
? 'movie'
|
||||
: `s${inspected.identity.seasonNumber ?? 1}e${inspected.identity.episodeNumber ?? 0}`;
|
||||
const key = `${inspected.identity.kind}:${inspected.identity.title.toLocaleLowerCase('en-US')}:${logical}`;
|
||||
const group = grouped.get(key) ?? { identity: inspected.identity, variants: [] };
|
||||
group.variants.push(inspected.variant);
|
||||
grouped.set(key, group);
|
||||
}
|
||||
const items: SnapshotTitle[] = [...grouped.values()].map(({ identity, media }) => {
|
||||
const logicalItems = [...grouped.values()].map(({ identity, variants }) => {
|
||||
variants.sort(compareVariants);
|
||||
const selected = variants[0];
|
||||
if (!selected) throw new Error('Internal media group has no source variants');
|
||||
const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`);
|
||||
const logicalKey = identity.kind === 'MOVIE' ? 'movie' : `s${identity.seasonNumber ?? 1}e${identity.episodeNumber ?? 0}`;
|
||||
const media: SnapshotMediaItem = {
|
||||
...selected,
|
||||
id: deterministicUuid(`media:${titleId}:${logicalKey}`),
|
||||
titleId,
|
||||
kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE',
|
||||
...(identity.seasonNumber === undefined ? {} : { seasonNumber: identity.seasonNumber }),
|
||||
...(identity.episodeNumber === undefined ? {} : { episodeNumber: identity.episodeNumber }),
|
||||
title: { en: identity.episodeTitle ?? identity.title },
|
||||
published: variants.some((variant) => variant.available),
|
||||
variants,
|
||||
};
|
||||
return { identity, media };
|
||||
});
|
||||
const byTitle = new Map<string, { identity: ParsedMediaIdentity; media: SnapshotMediaItem[] }>();
|
||||
for (const entry of logicalItems) {
|
||||
const key = `${entry.identity.kind}:${entry.identity.title.toLocaleLowerCase('en-US')}`;
|
||||
const title = byTitle.get(key) ?? { identity: entry.identity, media: [] };
|
||||
title.media.push(entry.media);
|
||||
byTitle.set(key, title);
|
||||
}
|
||||
const items: SnapshotTitle[] = [...byTitle.values()].map(({ identity, media }) => {
|
||||
media.sort((left, right) => (left.seasonNumber ?? 0) - (right.seasonNumber ?? 0)
|
||||
|| (left.episodeNumber ?? 0) - (right.episodeNumber ?? 0));
|
||||
const first = media[0];
|
||||
@@ -291,6 +374,10 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
|
||||
slug: slugify(identity.title),
|
||||
kind: identity.kind,
|
||||
title: { en: identity.title },
|
||||
...(identity.category ? { category: identity.category } : {}),
|
||||
...(identity.categorySlug ? { categorySlug: identity.categorySlug } : {}),
|
||||
...(identity.year ? { year: identity.year } : {}),
|
||||
...(identity.releaseWindow ? { releaseWindow: identity.releaseWindow } : {}),
|
||||
published,
|
||||
playable: published,
|
||||
mediaItemId: first.id,
|
||||
@@ -301,6 +388,18 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
|
||||
mediaItems: media,
|
||||
};
|
||||
});
|
||||
for (const item of items) {
|
||||
const identity = byTitle.get(`${item.kind}:${item.title.en.toLocaleLowerCase('en-US')}`)?.identity;
|
||||
if (!identity?.titleDirectory) continue;
|
||||
const source = await findThumbnail(path.join(root, identity.titleDirectory));
|
||||
if (!source) continue;
|
||||
const extension = path.extname(source).toLocaleLowerCase('en-US').replace('.jpeg', '.jpg');
|
||||
item.posterUrl = `/images/archive/${item.id}${extension}`;
|
||||
if (options.artworkRoot) {
|
||||
await mkdir(options.artworkRoot, { recursive: true, mode: 0o750 });
|
||||
await copyFile(source, path.join(options.artworkRoot, `${item.id}${extension}`));
|
||||
}
|
||||
}
|
||||
items.sort((left, right) => left.title.en.localeCompare(right.title.en));
|
||||
const generatedAt = new Date().toISOString();
|
||||
const titles: PublicTitleDetail[] = items.map((item) => ({
|
||||
@@ -309,8 +408,25 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
|
||||
kind: item.kind,
|
||||
// Filename-derived text is a safe temporary fallback until metadata matching supplies Persian.
|
||||
name: { fa: item.title.fa ?? item.title.en, en: item.title.en },
|
||||
...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
|
||||
...(item.category ? { category: item.category } : {}),
|
||||
...(item.categorySlug ? { categorySlug: item.categorySlug } : {}),
|
||||
...(item.year ? { year: item.year } : {}),
|
||||
...(item.releaseWindow ? { releaseWindow: item.releaseWindow } : {}),
|
||||
playable: item.playable,
|
||||
...(item.playable ? { resumeMediaItemId: item.resumeMediaItemId } : {}),
|
||||
...(item.mediaItems[0]?.variants ? {
|
||||
variants: item.mediaItems[0].variants.map((variant, index) => ({
|
||||
id: variant.id,
|
||||
label: variant.qualityLabel,
|
||||
...(variant.width ? { width: variant.width } : {}),
|
||||
...(variant.height ? { height: variant.height } : {}),
|
||||
...(variant.videoCodec ? { videoCodec: variant.videoCodec } : {}),
|
||||
compatibility: variant.compatibility,
|
||||
available: variant.available,
|
||||
isDefault: index === 0,
|
||||
})),
|
||||
} : {}),
|
||||
synopsis: {},
|
||||
...(item.kind === 'SERIES'
|
||||
? { seasons: item.seasons.map((season) => ({ number: season.number, episodeCount: season.episodes.length })) }
|
||||
@@ -324,6 +440,16 @@ export async function scanArchive(options: ScanArchiveOptions): Promise<ScanArch
|
||||
durationSeconds: media.durationSeconds,
|
||||
compatibility: media.compatibility,
|
||||
published: media.published,
|
||||
variants: (media.variants ?? [media]).map((variant, index) => ({
|
||||
id: variant.id,
|
||||
label: variant.qualityLabel,
|
||||
...(variant.width ? { width: variant.width } : {}),
|
||||
...(variant.height ? { height: variant.height } : {}),
|
||||
...(variant.videoCodec ? { videoCodec: variant.videoCodec } : {}),
|
||||
compatibility: variant.compatibility,
|
||||
available: variant.available,
|
||||
isDefault: index === 0,
|
||||
})),
|
||||
})),
|
||||
updatedAt: generatedAt,
|
||||
}));
|
||||
@@ -337,3 +463,39 @@ export function findMediaItem(snapshot: InventorySnapshot, idOrPath: string): Sn
|
||||
return snapshot.items.flatMap((item) => item.mediaItems)
|
||||
.find((media) => media.id === idOrPath || media.sourcePath === idOrPath);
|
||||
}
|
||||
|
||||
export function findMediaVariant(
|
||||
snapshot: InventorySnapshot,
|
||||
mediaItemId: string,
|
||||
variantId?: string,
|
||||
): SnapshotMediaItem | undefined {
|
||||
const media = findMediaItem(snapshot, mediaItemId);
|
||||
if (!media || variantId === undefined) return media;
|
||||
const variant = media.variants?.find((candidate) => candidate.id === variantId);
|
||||
return variant ? { ...media, ...variant, id: media.id, ...(media.variants ? { variants: media.variants } : {}) } : undefined;
|
||||
}
|
||||
|
||||
function compareVariants(left: SnapshotMediaVariant, right: SnapshotMediaVariant): number {
|
||||
if (left.available !== right.available) return left.available ? -1 : 1;
|
||||
const leftHeight = left.height ?? 0;
|
||||
const rightHeight = right.height ?? 0;
|
||||
const leftDistance = Math.abs(leftHeight - 720);
|
||||
const rightDistance = Math.abs(rightHeight - 720);
|
||||
if (leftDistance !== rightDistance) return leftDistance - rightDistance;
|
||||
if ((leftHeight <= 720) !== (rightHeight <= 720)) return leftHeight <= 720 ? -1 : 1;
|
||||
if (left.compatibility !== right.compatibility) return left.compatibility === 'COPY' ? -1 : 1;
|
||||
return left.sourcePath.localeCompare(right.sourcePath);
|
||||
}
|
||||
|
||||
async function findThumbnail(directory: string): Promise<string | undefined> {
|
||||
for (const filename of ['thumbnail.jpg', 'thumbnail.jpeg', 'thumbnail.png', 'thumbnail.webp']) {
|
||||
const candidate = path.join(directory, filename);
|
||||
try {
|
||||
await access(candidate);
|
||||
return candidate;
|
||||
} catch {
|
||||
// Continue to the next supported local artwork extension.
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
+48
-11
@@ -29,6 +29,7 @@ import {
|
||||
import {
|
||||
deterministicUuid,
|
||||
findMediaItem,
|
||||
findMediaVariant,
|
||||
scanArchive,
|
||||
type InventorySnapshot,
|
||||
type SnapshotMediaItem,
|
||||
@@ -111,12 +112,21 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
|
||||
}
|
||||
const result = await scanArchive({
|
||||
archiveRoot,
|
||||
...(output === undefined ? {} : { artworkRoot: path.join(path.dirname(output), 'artwork') }),
|
||||
...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }),
|
||||
...(flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }),
|
||||
onFile(relativePath, current) {
|
||||
process.stderr.write(`[scan ${current}] ${relativePath}\n`);
|
||||
},
|
||||
});
|
||||
// Direct scans stay portable; the long-running worker passes DATABASE_URL explicitly.
|
||||
const databaseUrl = flag(arguments_, 'database');
|
||||
const databaseSync = databaseUrl === undefined
|
||||
? undefined
|
||||
: await withDatabase(databaseUrl, (database) => syncCatalogSnapshot(database, result.catalog, {
|
||||
authoritative: arguments_.flags.has('full'),
|
||||
}));
|
||||
if (databaseSync) applyMediaIdMap(result, databaseSync.mediaIdMap);
|
||||
if (output !== undefined) {
|
||||
await Promise.all([
|
||||
writeJsonAtomic(output, result.catalog),
|
||||
@@ -124,12 +134,6 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
|
||||
]);
|
||||
}
|
||||
|
||||
// Direct scans stay portable; the long-running worker passes DATABASE_URL explicitly.
|
||||
const databaseUrl = flag(arguments_, 'database');
|
||||
const databaseSync = databaseUrl === undefined
|
||||
? undefined
|
||||
: await withDatabase(databaseUrl, (database) => syncCatalogSnapshot(database, result.catalog));
|
||||
|
||||
if (output === undefined) process.stdout.write(`${JSON.stringify(result.catalog, null, 2)}\n`);
|
||||
else {
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
@@ -137,11 +141,26 @@ async function scanCommand(arguments_: Arguments): Promise<void> {
|
||||
...(inventoryOutput === undefined ? {} : { inventoryOutput: path.resolve(inventoryOutput) }),
|
||||
titles: result.catalog.titles.length,
|
||||
mediaItems: result.catalog.titles.reduce((sum, item) => sum + item.mediaItems.length, 0),
|
||||
...(databaseSync === undefined ? {} : { databaseSync }),
|
||||
...(databaseSync === undefined ? {} : { databaseSync: { titlesSeen: databaseSync.titlesSeen, mediaItemsSeen: databaseSync.mediaItemsSeen } }),
|
||||
})}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
function applyMediaIdMap(result: Awaited<ReturnType<typeof scanArchive>>, mediaIdMap: Record<string, string>): void {
|
||||
for (const title of result.inventory.items) {
|
||||
for (const media of title.mediaItems) media.id = mediaIdMap[media.id] ?? media.id;
|
||||
title.mediaItemId = mediaIdMap[title.mediaItemId] ?? title.mediaItemId;
|
||||
title.resumeMediaItemId = mediaIdMap[title.resumeMediaItemId] ?? title.resumeMediaItemId;
|
||||
for (const season of title.seasons) {
|
||||
for (const media of season.episodes) media.id = mediaIdMap[media.id] ?? media.id;
|
||||
}
|
||||
}
|
||||
for (const title of result.catalog.titles) {
|
||||
if (title.resumeMediaItemId) title.resumeMediaItemId = mediaIdMap[title.resumeMediaItemId] ?? title.resumeMediaItemId;
|
||||
for (const media of title.mediaItems) media.id = mediaIdMap[media.id] ?? media.id;
|
||||
}
|
||||
}
|
||||
|
||||
async function withDatabase<T>(
|
||||
connectionString: string,
|
||||
action: (database: Database) => Promise<T>,
|
||||
@@ -163,8 +182,9 @@ async function loadInventory(snapshotPath: string): Promise<InventorySnapshot> {
|
||||
async function sourceSelection(
|
||||
arguments_: Arguments,
|
||||
archiveRoot: string,
|
||||
): Promise<{ media: SnapshotMediaItem; sourcePath: string }> {
|
||||
): Promise<{ media: SnapshotMediaItem; sourcePath: string; variantId: string }> {
|
||||
const mediaItem = flag(arguments_, 'media-item');
|
||||
const variantId = flag(arguments_, 'variant-id');
|
||||
const requestedSource = flag(arguments_, 'source');
|
||||
const inventoryPath = flag(arguments_, 'inventory', './data/inventory.json') ?? './data/inventory.json';
|
||||
let inventory: InventorySnapshot | undefined;
|
||||
@@ -175,9 +195,14 @@ async function sourceSelection(
|
||||
}
|
||||
const selected = mediaItem === undefined
|
||||
? (requestedSource === undefined ? undefined : inventory === undefined ? undefined : findMediaItem(inventory, requestedSource))
|
||||
: inventory === undefined ? undefined : findMediaItem(inventory, mediaItem);
|
||||
: inventory === undefined ? undefined : findMediaVariant(inventory, mediaItem, variantId);
|
||||
if (selected !== undefined) {
|
||||
return { media: selected, sourcePath: await resolveInside(archiveRoot, path.join(archiveRoot, selected.sourcePath)) };
|
||||
const selectedVariantId = selected.variants?.find((variant) => variant.sourcePath === selected.sourcePath)?.id ?? selected.id;
|
||||
return {
|
||||
media: selected,
|
||||
variantId: selectedVariantId,
|
||||
sourcePath: await resolveInside(archiveRoot, path.join(archiveRoot, selected.sourcePath)),
|
||||
};
|
||||
}
|
||||
if (mediaItem !== undefined) throw new Error(`Media item was not found in ${inventoryPath}: ${mediaItem}`);
|
||||
if (requestedSource === undefined) throw new Error('package requires --media-item ID or --source PATH');
|
||||
@@ -192,12 +217,17 @@ async function sourceSelection(
|
||||
const classification = classifyMedia(probe);
|
||||
return {
|
||||
sourcePath,
|
||||
variantId: deterministicUuid(`variant:${relative}`),
|
||||
media: {
|
||||
id: deterministicUuid(`media:${relative}`),
|
||||
titleId: deterministicUuid(`title:${relative}`),
|
||||
kind: 'MOVIE',
|
||||
sourcePath: relative,
|
||||
durationSeconds: Number(probe.format.duration) || 0,
|
||||
qualityLabel: probe.streams.find((stream) => stream.codec_type === 'video')?.height
|
||||
? `${probe.streams.find((stream) => stream.codec_type === 'video')?.height}p`
|
||||
: 'Source',
|
||||
available: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class),
|
||||
title: { en: path.basename(relative, path.extname(relative)) },
|
||||
published: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class),
|
||||
compatibility: classification.class,
|
||||
@@ -232,6 +262,7 @@ async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): P
|
||||
const preparing = async (error?: string): Promise<void> => {
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
variantId: selected.variantId,
|
||||
generationId,
|
||||
state: error === undefined ? 'PREPARING' : 'FAILED',
|
||||
playable: false,
|
||||
@@ -304,6 +335,7 @@ async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): P
|
||||
const fontUrls = fonts.map((font) => `/media/${generationPath}/fonts/${font.sha256}.${font.format}`);
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
variantId: selected.variantId,
|
||||
generationId,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
@@ -378,6 +410,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
|
||||
const generationId = deterministicUuid(`generation:compat-h264-v1:${fingerprint.digest}`);
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
variantId: selected.variantId,
|
||||
generationId,
|
||||
state: 'PREPARING',
|
||||
playable: false,
|
||||
@@ -416,6 +449,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
|
||||
const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio');
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
variantId: selected.variantId,
|
||||
generationId,
|
||||
state: 'READY',
|
||||
playable: true,
|
||||
@@ -442,6 +476,7 @@ async function prepareCommand(arguments_: Arguments): Promise<void> {
|
||||
} catch (error) {
|
||||
await updateRegistry(registryPath, selected.media.id, {
|
||||
mediaItemId: selected.media.id,
|
||||
variantId: selected.variantId,
|
||||
generationId,
|
||||
state: 'FAILED',
|
||||
playable: false,
|
||||
@@ -482,7 +517,8 @@ async function workCommand(arguments_: Arguments): Promise<void> {
|
||||
if (command.type === 'media.playback.requested') {
|
||||
await main([
|
||||
'package', '--root', archiveRoot, '--cache', cacheRoot, '--inventory', inventory,
|
||||
'--registry', registry, '--media-item', command.mediaItemId, ...mediaTools,
|
||||
'--registry', registry, '--media-item', command.mediaItemId,
|
||||
...(command.variantId ? ['--variant-id', command.variantId] : []), ...mediaTools,
|
||||
], { protectedCacheKeys: () => running.protectedCacheGenerations() });
|
||||
} else if (command.type === 'archive.scan.requested') {
|
||||
if (databaseUrl !== undefined) {
|
||||
@@ -491,6 +527,7 @@ async function workCommand(arguments_: Arguments): Promise<void> {
|
||||
}
|
||||
await main([
|
||||
'scan', '--root', archiveRoot, '--output', catalog, '--inventory-output', inventory,
|
||||
...(command.full ? ['--full'] : []),
|
||||
...(databaseUrl === undefined ? [] : ['--database', databaseUrl]),
|
||||
...mediaTools,
|
||||
]);
|
||||
|
||||
@@ -45,6 +45,7 @@ export interface RegistrySubtitleTrack {
|
||||
|
||||
export interface RegistryGeneration {
|
||||
mediaItemId: string;
|
||||
variantId?: string;
|
||||
state: 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED';
|
||||
generationId?: string;
|
||||
manifestPath?: string;
|
||||
@@ -104,7 +105,8 @@ export async function updateRegistry(
|
||||
const current = previous.catch(() => undefined).then(async () => {
|
||||
const registry = await readRegistry(key);
|
||||
registry.updatedAt = new Date().toISOString();
|
||||
const index = registry.packages.findIndex((entry) => entry.mediaItemId === mediaItemId);
|
||||
const index = registry.packages.findIndex((entry) => entry.mediaItemId === mediaItemId
|
||||
&& (entry.variantId ?? entry.mediaItemId) === (generation.variantId ?? generation.mediaItemId));
|
||||
if (index < 0) registry.packages.push(generation);
|
||||
else {
|
||||
const current = registry.packages[index];
|
||||
|
||||
@@ -4,7 +4,15 @@ import { deterministicUuid, parseMediaIdentity, shouldInspectSubtitleContent, sl
|
||||
describe('catalog filename parsing', () => {
|
||||
it('groups the supplied season folder and episode filename', () => {
|
||||
expect(parseMediaIdentity('Mushoku Tensei S3/Mushoku Tensei S3 - 01.[SS][720p][MixFlixTop].mkv'))
|
||||
.toEqual({ kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 1, episodeTitle: 'Episode 1' });
|
||||
.toEqual({ kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 1, episodeTitle: 'Episode 1', titleDirectory: 'Mushoku Tensei S3' });
|
||||
});
|
||||
|
||||
it('uses the title above a nested quality folder and derives archive taxonomy', () => {
|
||||
expect(parseMediaIdentity('anime/2026/Summer/Mushoku Tensei S3/720/Mushoku Tensei S3 - 02.mkv'))
|
||||
.toMatchObject({
|
||||
kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 2,
|
||||
category: 'Anime', categorySlug: 'anime', year: 2026, releaseWindow: 'SUMMER',
|
||||
});
|
||||
});
|
||||
|
||||
it('creates stable UUIDs and Unicode-safe slugs', () => {
|
||||
|
||||
@@ -12,6 +12,22 @@ import {
|
||||
} from '../src/registry.js';
|
||||
|
||||
describe('local generation registry', () => {
|
||||
it('keeps independent generations for quality variants of one episode', async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-variants-'));
|
||||
const registryPath = path.join(directory, 'package-registry.json');
|
||||
const mediaItemId = '11111111-1111-4111-8111-111111111111';
|
||||
for (const [variantId, generationId] of [
|
||||
['22222222-2222-4222-8222-222222222222', '33333333-3333-4333-8333-333333333333'],
|
||||
['44444444-4444-4444-8444-444444444444', '55555555-5555-4555-8555-555555555555'],
|
||||
] as const) {
|
||||
await updateRegistry(registryPath, mediaItemId, {
|
||||
mediaItemId, variantId, generationId, state: 'READY', playable: true,
|
||||
manifestPath: `/media/generations/${generationId}/master.m3u8`,
|
||||
});
|
||||
}
|
||||
expect((await readRegistry(registryPath)).packages).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('atomically records API-loadable per-media status', async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-'));
|
||||
const registryPath = path.join(directory, 'package-registry.json');
|
||||
|
||||
Reference in new issue
Block a user