feat(showcase): add portable static export for generic hosting
ci / verify (push) Successful in 5m14s

This commit is contained in:
Meghdad committed 2026-07-15 04:45:49 +03:30
1 parent acb192c64a
commit a624d195da
17 files changed
+740 -116

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const snapshot = {
version: 1,
generatedAt: '2026-07-15T00:00:00.000Z',
sections: [{
slug: 'anime', name: 'Anime', hasMore: false,
items: [{ id: 'title-1', slug: 'demo', kind: 'MOVIE', name: { fa: 'دمو', en: 'Demo' }, playable: true, resumeMediaItemId: 'media-1', variants: [{ id: 'variant-1', label: '720p', available: true, isDefault: true, compatibility: 'COPY' }] }],
}],
titles: [{
id: 'title-1', slug: 'demo', kind: 'MOVIE', name: { fa: 'دمو', en: 'Demo' }, playable: true,
resumeMediaItemId: 'media-1', variants: [{ id: 'variant-1', label: '720p', available: true, isDefault: true, compatibility: 'COPY' }],
mediaItems: [{ id: 'media-1', kind: 'MOVIE', name: { fa: 'دمو', en: 'Demo' }, published: true, variants: [{ id: 'variant-1', label: '720p', available: true, isDefault: true, compatibility: 'COPY' }] }],
}],
defaultVariantByMedia: { 'media-1': 'variant-1' },
playbackByVariant: {
'variant-1': { mediaItemId: 'media-1', variantId: 'variant-1', qualityLabel: '720p', manifestUrl: './media/master.m3u8', durationSeconds: 60, audioTracks: [], subtitleTracks: [] },
},
}
describe('static showcase API', () => {
beforeEach(() => {
vi.resetModules()
vi.stubEnv('VITE_APP_EDITION', 'showcase')
vi.stubEnv('VITE_SHOWCASE_CATALOG_URL', './catalog.json')
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(snapshot), { status: 200, headers: { 'content-type': 'application/json' } })))
vi.stubGlobal('crypto', { randomUUID: () => 'session-1' })
})
it('serves catalog and playback entirely from the static snapshot', async () => {
const { api } = await import('@/api/client')
const sections = await api.catalogSections()
expect(sections[0]?.items[0]).toMatchObject({ slug: 'demo', mediaItemId: 'media-1' })
const detail = await api.title('demo')
expect(detail.playableMediaItemId).toBe('media-1')
const session = await api.createPlaybackSession('media-1', {
nativeHls: false, mse: true, hlsJs: true, assRenderer: true, supportedCodecs: ['avc1', 'mp4a'],
})
expect(session).toMatchObject({ id: 'session-1', state: 'READY', manifestUrl: './media/master.m3u8' })
expect(await api.playbackSession('session-1')).toEqual(session)
expect(fetch).toHaveBeenCalledTimes(1)
})
});
+101 -30
View File
@@ -17,6 +17,9 @@ import type {
} from '@/types'
const API_BASE = (import.meta.env.VITE_API_BASE_URL ?? '/api/v1').replace(/\/$/, '')
const SHOWCASE = import.meta.env.VITE_APP_EDITION === 'showcase'
const SHOWCASE_CATALOG_URL = import.meta.env.VITE_SHOWCASE_CATALOG_URL
const STATIC_SHOWCASE = SHOWCASE && Boolean(SHOWCASE_CATALOG_URL)
const ADMIN_CSRF_KEY = 'easy-stream-admin-csrf'
const ADMIN_EMAIL_KEY = 'easy-stream-admin-email'
@@ -34,6 +37,9 @@ export class ApiError extends Error {
type JsonRecord = Record<string, unknown>
let showcaseSnapshotPromise: Promise<JsonRecord> | undefined
const showcaseSessions = new Map<string, PlaybackSession>()
function record(value: unknown): JsonRecord {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? (value as JsonRecord)
@@ -69,6 +75,22 @@ function array(value: unknown): unknown[] {
return Array.isArray(value) ? value : []
}
async function showcaseSnapshot(signal?: AbortSignal): Promise<JsonRecord> {
if (!SHOWCASE_CATALOG_URL) throw new ApiError('VITE_SHOWCASE_CATALOG_URL is not configured', 500, 'SHOWCASE_CATALOG_MISSING')
showcaseSnapshotPromise ??= fetch(SHOWCASE_CATALOG_URL, { headers: { accept: 'application/json' } }).then(async (response) => {
if (!response.ok) throw new ApiError(`Showcase catalog failed to load (${response.status})`, response.status, 'SHOWCASE_CATALOG_LOAD_FAILED')
const snapshot = record(await response.json())
if (number(snapshot.version) !== 1) throw new ApiError('Unsupported Showcase catalog version', 500, 'SHOWCASE_CATALOG_VERSION')
return snapshot
}).catch((error) => {
showcaseSnapshotPromise = undefined
throw error
})
const snapshot = await showcaseSnapshotPromise
if (signal?.aborted) throw new DOMException('Request aborted', 'AbortError')
return snapshot
}
function normalizeVariant(input: unknown): QualityVariant {
const item = record(input)
return {
@@ -155,6 +177,39 @@ function normalizeSeason(input: unknown): SeasonItem {
}
}
function normalizeTitleDetail(payload: JsonRecord): TitleDetail {
const base = normalizeCatalogItem(payload)
const explicitSeasons = array(payload.seasons).map(normalizeSeason)
const mediaItems = array(payload.mediaItems).map((entry) => record(entry))
const groupedSeasons = new Map<number, EpisodeItem[]>()
mediaItems.forEach((entry) => {
const seasonNumber = number(entry.seasonNumber) ?? 0
const episodes = groupedSeasons.get(seasonNumber) ?? []
episodes.push(normalizeEpisode(entry, seasonNumber))
groupedSeasons.set(seasonNumber, episodes)
})
const seasons = explicitSeasons.some((season) => season.episodes.length)
? explicitSeasons
: [...groupedSeasons.entries()]
.sort(([left], [right]) => left - right)
.map(([seasonNumber, episodes]) => ({
number: seasonNumber,
title: { fa: `فصل ${seasonNumber}`, en: `Season ${seasonNumber}` },
episodes: episodes.sort((left, right) => left.number - right.number),
}))
const firstPublishedMediaItem = mediaItems.find((item) => item.published !== false)
const playableMediaItemId = text(payload.resumeMediaItemId)
?? text(payload.playableMediaItemId)
?? text(firstPublishedMediaItem?.id)
return {
...base,
mediaItemId: playableMediaItemId ?? '',
genres: array(payload.genres).map((genre) => localized(genre, record(genre).name)),
seasons,
...(playableMediaItemId ? { playableMediaItemId } : {}),
}
}
function normalizeSubtitle(input: unknown, index: number): PlaybackSubtitleTrack {
const item = record(input)
const urls = record(item.urls)
@@ -294,6 +349,16 @@ function withSignal(signal: AbortSignal | undefined, init: RequestInit = {}): Re
export const api = {
async catalog(options: { cursor?: string; limit?: number; kind?: string; category?: string; year?: number; releaseWindow?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
if (STATIC_SHOWCASE) {
const snapshot = await showcaseSnapshot(signal)
let items = array(snapshot.titles).map(normalizeCatalogItem)
if (options.kind) items = items.filter((item) => item.kind === options.kind)
if (options.category) items = items.filter((item) => item.categorySlug === options.category)
if (options.year) items = items.filter((item) => item.year === options.year)
if (options.releaseWindow) items = items.filter((item) => item.releaseWindow === options.releaseWindow)
const limit = options.limit ?? 40
return { items: items.slice(0, limit), total: items.length }
}
const body = await request(`/catalog${queryString({ ...options })}`, withSignal(signal))
const source = record(body)
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
@@ -308,6 +373,14 @@ export const api = {
},
async catalogSections(limitPerSection = 12, signal?: AbortSignal): Promise<CatalogSection[]> {
if (STATIC_SHOWCASE) {
const snapshot = await showcaseSnapshot(signal)
return array(snapshot.sections).map((input) => {
const section = record(input)
const items = array(section.items).map(normalizeCatalogItem).filter((item) => item.id)
return { slug: text(section.slug) ?? '', name: text(section.name) ?? '', items: items.slice(0, limitPerSection), hasMore: items.length > limitPerSection }
}).filter((section) => section.slug && section.items.length)
}
const body = record(await request(`/catalog/sections${queryString({ limitPerSection })}`, withSignal(signal)))
return array(body.sections).map((input) => {
const section = record(input)
@@ -332,39 +405,16 @@ export const api = {
},
async title(slug: string, signal?: AbortSignal): Promise<TitleDetail> {
if (STATIC_SHOWCASE) {
const snapshot = await showcaseSnapshot(signal)
const payload = array(snapshot.titles).map(record).find((title) => text(title.slug) === slug)
if (!payload) throw new ApiError('Title not found', 404, 'NOT_FOUND')
return normalizeTitleDetail(payload)
}
const body = await request(`/titles/${encodeURIComponent(slug)}`, withSignal(signal))
const source = record(body)
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
const base = normalizeCatalogItem(payload)
const explicitSeasons = array(payload.seasons).map(normalizeSeason)
const mediaItems = array(payload.mediaItems).map((entry) => record(entry))
const groupedSeasons = new Map<number, EpisodeItem[]>()
mediaItems.forEach((entry) => {
const seasonNumber = number(entry.seasonNumber) ?? 0
const episodes = groupedSeasons.get(seasonNumber) ?? []
episodes.push(normalizeEpisode(entry, seasonNumber))
groupedSeasons.set(seasonNumber, episodes)
})
const seasons = explicitSeasons.some((season) => season.episodes.length)
? explicitSeasons
: [...groupedSeasons.entries()]
.sort(([left], [right]) => left - right)
.map(([seasonNumber, episodes]) => ({
number: seasonNumber,
title: { fa: `فصل ${seasonNumber}`, en: `Season ${seasonNumber}` },
episodes: episodes.sort((left, right) => left.number - right.number),
}))
const firstPublishedMediaItem = mediaItems.find((item) => item.published !== false)
const playableMediaItemId = text(payload.resumeMediaItemId)
?? text(payload.playableMediaItemId)
?? text(firstPublishedMediaItem?.id)
return {
...base,
mediaItemId: playableMediaItemId ?? '',
genres: array(payload.genres).map((genre) => localized(genre, record(genre).name)),
seasons,
...(playableMediaItemId ? { playableMediaItemId } : {}),
}
return normalizeTitleDetail(payload)
},
async createPlaybackSession(
@@ -373,6 +423,20 @@ export const api = {
variantId?: string,
signal?: AbortSignal,
): Promise<PlaybackSession> {
if (STATIC_SHOWCASE) {
const snapshot = await showcaseSnapshot(signal)
const defaults = record(snapshot.defaultVariantByMedia)
const selectedVariantId = variantId ?? text(defaults[mediaItemId])
const playback = selectedVariantId ? record(record(snapshot.playbackByVariant)[selectedVariantId]) : {}
if (!selectedVariantId || text(playback.mediaItemId) !== mediaItemId) throw new ApiError('This media is not prepared for playback', 404, 'NOT_PREPARED')
const id = crypto.randomUUID()
const session = normalizePlaybackSession({
id, state: 'READY', ...playback, pollAfterMs: 1000,
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
})
showcaseSessions.set(id, session)
return session
}
const body = await request('/playback-sessions', withSignal(signal, {
method: 'POST',
body: JSON.stringify({ mediaItemId, ...(variantId ? { variantId } : {}), clientCapabilities }),
@@ -382,10 +446,17 @@ export const api = {
},
async playbackSession(id: string, signal?: AbortSignal): Promise<PlaybackSession> {
if (STATIC_SHOWCASE) {
if (signal?.aborted) throw new DOMException('Request aborted', 'AbortError')
const session = showcaseSessions.get(id)
if (!session) throw new ApiError('Playback session not found', 404, 'NOT_FOUND')
return session
}
return normalizePlaybackSession(await request(`/playback-sessions/${encodeURIComponent(id)}`, withSignal(signal)))
},
async clientEvent(event: Record<string, unknown>): Promise<void> {
if (STATIC_SHOWCASE) return
await request('/client-events', { method: 'POST', body: JSON.stringify(event), keepalive: true })
},
+1 -1
View File
@@ -367,7 +367,7 @@ function attachManifest(activeSession: PlaybackSession) {
maxBufferLength: 30,
manifestLoadingTimeOut: 20_000,
fragLoadingTimeOut: 30_000,
xhrSetup: (xhr) => { xhr.withCredentials = true },
xhrSetup: (xhr) => { xhr.withCredentials = !import.meta.env.VITE_SHOWCASE_CATALOG_URL },
})
hls.on(Events.MEDIA_ATTACHED, () => hls?.loadSource(activeSession.manifestUrl!))
hls.on(Events.MANIFEST_PARSED, () => void onManifestReady())
+2
View File
@@ -3,6 +3,8 @@
interface ImportMetaEnv {
readonly VITE_APP_EDITION?: 'production' | 'showcase'
readonly VITE_API_BASE_URL?: string
readonly VITE_SHOWCASE_CATALOG_URL?: string
readonly VITE_SHOWCASE_STATIC?: string
}
interface ImportMeta {
+3 -2
View File
@@ -1,12 +1,13 @@
import { createRouter, createWebHistory } from 'vue-router'
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import CatalogView from '@/views/CatalogView.vue'
import TitleView from '@/views/TitleView.vue'
const showcase = import.meta.env.VITE_APP_EDITION === 'showcase'
const staticShowcase = showcase && Boolean(import.meta.env.VITE_SHOWCASE_CATALOG_URL)
export const router = createRouter({
history: createWebHistory(),
history: staticShowcase ? createWebHashHistory() : createWebHistory(),
scrollBehavior: (_to, _from, savedPosition) => savedPosition ?? { top: 0 },
routes: [
{ path: '/', name: 'catalog', component: CatalogView },
+1
View File
@@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
export default defineConfig({
base: process.env.VITE_SHOWCASE_STATIC === 'true' ? './' : '/',
plugins: [vue()],
resolve: {
alias: {