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

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import AppHeader from '@/components/AppHeader.vue'
import BrandMark from '@/components/BrandMark.vue'
import PlayerShell from '@/components/PlayerShell.vue'
import { useSpatialNavigation } from '@/composables/spatial-navigation'
const appRoot = ref<HTMLElement | null>(null)
const router = useRouter()
useSpatialNavigation(appRoot, { onBack: () => router.back() })
</script>
<template>
<div ref="appRoot" class="app-shell">
<AppHeader />
<main id="main-content" class="main-content" tabindex="-1">
<RouterView />
</main>
<footer class="app-footer">
<span class="footer-brand">
<BrandMark />
<span>Easy Stream</span>
</span>
<span class="footer-dot" aria-hidden="true">•</span>
<RouterLink to="/admin">Admin</RouterLink>
</footer>
<PlayerShell />
</div>
</template>
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest'
import { normalizePlaybackSession } from '@/api/client'
describe('normalizePlaybackSession', () => {
it('normalizes the canonical playback response', () => {
const session = normalizePlaybackSession({
id: 'session-1',
state: 'READY',
manifestUrl: '/media/session-1/master.m3u8',
durationSeconds: 1420,
audioTracks: [{ id: 'audio-ja', language: 'ja', label: 'Japanese', default: true }],
subtitleTracks: [{
id: 'sub-fa',
language: 'fa',
label: 'فارسی',
assUrl: '/subtitles/fa.ass',
vttUrl: '/subtitles/fa.vtt',
fontUrls: ['/fonts/one.ttf'],
}],
})
expect(session.state).toBe('READY')
expect(session.manifestUrl).toBe('/media/session-1/master.m3u8')
expect(session.audioTracks[0]).toMatchObject({ language: 'ja', default: true })
expect(session.subtitles[0]).toMatchObject({
language: 'fa',
assUrl: '/subtitles/fa.ass',
vttUrl: '/subtitles/fa.vtt',
fonts: ['/fonts/one.ttf'],
})
})
it('splits and merges a legacy mixed track array', () => {
const session = normalizePlaybackSession({
sessionId: 'session-2',
status: 'building',
tracks: [
{ id: 'fa-ass', kind: 'SUBTITLE', language: 'fa', delivery: 'ASS', url: '/fa.ass' },
{ id: 'fa-vtt', kind: 'SUBTITLE', language: 'fa', delivery: 'WEBVTT', url: '/fa.vtt' },
{ id: 'ja', kind: 'AUDIO', language: 'ja', name: 'Japanese' },
],
})
expect(session.state).toBe('PREPARING')
expect(session.subtitles).toHaveLength(1)
expect(session.subtitles[0]).toMatchObject({ assUrl: '/fa.ass', vttUrl: '/fa.vtt' })
expect(session.audioTracks).toHaveLength(1)
})
})
+444
View File
@@ -0,0 +1,444 @@
import type {
AdminDashboard,
AdminJob,
CatalogItem,
CatalogPage,
ClientCapabilities,
EpisodeItem,
LocalizedText,
PlaybackAudioTrack,
PlaybackSession,
PlaybackState,
PlaybackSubtitleTrack,
SeasonItem,
TitleDetail,
} from '@/types'
const API_BASE = (import.meta.env.VITE_API_BASE_URL ?? '/api/v1').replace(/\/$/, '')
const ADMIN_CSRF_KEY = 'easy-stream-admin-csrf'
const ADMIN_EMAIL_KEY = 'easy-stream-admin-email'
export class ApiError extends Error {
readonly status: number
readonly code: string | undefined
constructor(message: string, status: number, code?: string) {
super(message)
this.name = 'ApiError'
this.status = status
this.code = code
}
}
type JsonRecord = Record<string, unknown>
function record(value: unknown): JsonRecord {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? (value as JsonRecord)
: {}
}
function text(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value : undefined
}
function number(value: unknown): number | undefined {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim() && Number.isFinite(Number(value))) return Number(value)
return undefined
}
function boolean(value: unknown, fallback = false): boolean {
return typeof value === 'boolean' ? value : fallback
}
function localized(value: unknown, fallback?: unknown): LocalizedText {
if (typeof value === 'string') return { fa: value, en: value }
const source = record(value)
const fa = text(source.fa) ?? text(source.faIR) ?? text(source.persian)
const en = text(source.en) ?? text(source.enUS) ?? text(source.english) ?? text(fallback)
return {
...(fa ? { fa } : {}),
...(en ? { en } : {}),
}
}
function array(value: unknown): unknown[] {
return Array.isArray(value) ? value : []
}
function normalizeCatalogItem(input: unknown): CatalogItem {
const item = record(input)
const metadata = record(item.metadata)
const titleValue = item.name ?? item.title ?? metadata.title
const title = typeof titleValue === 'string'
? { fa: titleValue, en: text(item.titleEn ?? metadata.titleEn) ?? titleValue }
: localized(titleValue, item.name ?? metadata.name)
const id = text(item.id) ?? text(item.titleId) ?? text(item.mediaItemId) ?? ''
const mediaItemId = text(item.resumeMediaItemId) ?? text(item.mediaItemId) ?? text(item.playableMediaItemId) ?? id
const kindValue = (text(item.kind) ?? text(item.type) ?? 'MOVIE').toUpperCase()
const posterUrl = text(item.posterUrl) ?? text(metadata.posterUrl) ?? text(record(item.images).poster)
const backdropUrl = text(item.backdropUrl) ?? text(metadata.backdropUrl) ?? text(record(item.images).backdrop)
return {
id,
mediaItemId,
slug: text(item.slug) ?? id,
kind: kindValue === 'SERIES' || kindValue === 'SHOW' ? 'SERIES' : 'MOVIE',
title,
overview: typeof (item.synopsis ?? item.overview ?? metadata.overview) === 'string'
? {
fa: text(item.synopsis ?? item.overview ?? metadata.overview),
en: text(item.overviewEn ?? metadata.overviewEn) ?? text(item.synopsis ?? item.overview ?? metadata.overview),
}
: localized(item.synopsis ?? item.overview ?? metadata.overview, item.description ?? metadata.description),
...(posterUrl ? { posterUrl } : {}),
...(backdropUrl ? { backdropUrl } : {}),
...(number(item.year ?? metadata.year) !== undefined ? { year: number(item.year ?? metadata.year) } : {}),
...(number(item.runtimeSeconds ?? item.durationSeconds) !== undefined
? { runtimeSeconds: number(item.runtimeSeconds ?? item.durationSeconds) }
: {}),
...(number(item.seasonCount) !== undefined ? { seasonCount: number(item.seasonCount) } : {}),
...(number(item.episodeCount) !== undefined ? { episodeCount: number(item.episodeCount) } : {}),
...(text(item.compatibility) ? { compatibility: text(item.compatibility) } : {}),
playable: item.playable === undefined ? Boolean(mediaItemId) : boolean(item.playable),
...(number(item.progress) !== undefined ? { progress: number(item.progress) } : {}),
}
}
function normalizeEpisode(input: unknown, seasonNumber: number): EpisodeItem {
const item = record(input)
const id = text(item.id) ?? text(item.mediaItemId) ?? ''
return {
id,
mediaItemId: text(item.mediaItemId) ?? id,
number: number(item.number ?? item.episodeNumber) ?? 0,
seasonNumber: number(item.seasonNumber) ?? seasonNumber,
title: localized(item.name ?? item.title),
overview: localized(item.synopsis ?? item.overview, item.description),
...(text(item.posterUrl ?? item.stillUrl) ? { posterUrl: text(item.posterUrl ?? item.stillUrl) } : {}),
...(number(item.durationSeconds ?? item.runtimeSeconds) !== undefined
? { durationSeconds: number(item.durationSeconds ?? item.runtimeSeconds) }
: {}),
published: item.published === undefined ? true : boolean(item.published),
}
}
function normalizeSeason(input: unknown): SeasonItem {
const item = record(input)
const seasonNumber = number(item.number ?? item.seasonNumber) ?? 0
return {
number: seasonNumber,
title: localized(item.title, `Season ${seasonNumber}`),
episodes: array(item.episodes).map((episode) => normalizeEpisode(episode, seasonNumber)),
}
}
function normalizeSubtitle(input: unknown, index: number): PlaybackSubtitleTrack {
const item = record(input)
const urls = record(item.urls)
const language = text(item.language ?? item.lang) ?? 'und'
const delivery = text(item.delivery ?? item.format)?.toUpperCase()
const assUrl = text(item.assUrl) ?? text(urls.ass) ?? (delivery === 'ASS' || delivery === 'ASS_JASSUB' ? text(item.url) : undefined)
const vttUrl = text(item.vttUrl) ?? text(urls.vtt) ?? (delivery === 'VTT' || delivery === 'WEBVTT' ? text(item.url) : undefined)
return {
id: text(item.id) ?? `subtitle-${index}`,
language,
label: text(item.label) ?? language.toUpperCase(),
default: boolean(item.default ?? item.isDefault),
forced: boolean(item.forced ?? item.isForced),
...(assUrl ? { assUrl } : {}),
...(vttUrl ? { vttUrl } : {}),
fonts: array(item.fontUrls ?? item.fonts).flatMap((font) => (typeof font === 'string' ? [font] : [])),
}
}
function normalizeAudio(input: unknown, index: number): PlaybackAudioTrack {
const item = record(input)
const language = text(item.language ?? item.lang) ?? 'und'
return {
id: text(item.id) ?? `audio-${index}`,
language,
label: text(item.label ?? item.name) ?? language.toUpperCase(),
default: boolean(item.default ?? item.isDefault),
}
}
function normalizeState(value: unknown): PlaybackState {
const state = (text(value) ?? 'FAILED').toUpperCase()
if (state === 'READY' || state === 'PREPARING' || state === 'UNSUPPORTED_CLIENT') return state
if (state === 'PENDING' || state === 'BUILDING' || state === 'QUEUED') return 'PREPARING'
return 'FAILED'
}
export function normalizePlaybackSession(input: unknown): PlaybackSession {
const source = record(input)
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
const trackObject = record(payload.tracks)
const mixedTracks = array(payload.tracks)
const id = text(payload.id) ?? text(payload.sessionId) ?? ''
const manifestUrl = text(payload.manifestUrl) ?? text(payload.masterPlaylistUrl) ?? text(payload.url)
const subtitleInputs = array(payload.subtitles ?? payload.subtitleTracks ?? trackObject.subtitles)
const audioInputs = array(payload.audioTracks ?? payload.audio ?? trackObject.audio)
if (!subtitleInputs.length) {
subtitleInputs.push(...mixedTracks.filter((track) => {
const kind = text(record(track).kind ?? record(track).type)?.toUpperCase()
return kind === 'SUBTITLE' || kind === 'TEXT'
}))
}
if (!audioInputs.length) {
audioInputs.push(...mixedTracks.filter((track) => text(record(track).kind ?? record(track).type)?.toUpperCase() === 'AUDIO'))
}
const normalizedSubtitles = subtitleInputs.map(normalizeSubtitle)
const mergedSubtitles = [...normalizedSubtitles.reduce((tracks, track) => {
const key = track.id.replace(/[-_:]?(ass|webvtt|vtt)$/i, '') || track.language
const existing = tracks.get(key) ?? [...tracks.values()].find((candidate) => candidate.language === track.language)
if (existing) {
if (track.assUrl) existing.assUrl = track.assUrl
if (track.vttUrl) existing.vttUrl = track.vttUrl
existing.fonts = [...new Set([...existing.fonts, ...track.fonts])]
} else {
tracks.set(key, track)
}
return tracks
}, new Map<string, PlaybackSubtitleTrack>()).values()]
return {
id,
state: normalizeState(payload.state ?? payload.status),
mediaItemId: text(payload.mediaItemId) ?? '',
...(manifestUrl ? { manifestUrl } : {}),
...(number(payload.durationSeconds ?? payload.duration) !== undefined
? { durationSeconds: number(payload.durationSeconds ?? payload.duration) }
: {}),
pollAfterMs: Math.max(500, number(payload.pollAfterMs) ?? 1_500),
...(number(payload.progress ?? payload.progressPercent) !== undefined
? { progress: number(payload.progress ?? payload.progressPercent) }
: {}),
...(text(payload.message) ? { message: text(payload.message) } : {}),
...(text(payload.reasonCode ?? payload.code) ? { reasonCode: text(payload.reasonCode ?? payload.code) } : {}),
...(text(payload.expiresAt) ? { expiresAt: text(payload.expiresAt) } : {}),
...(text(payload.videoCodec) ? { videoCodec: text(payload.videoCodec) } : {}),
...(text(payload.audioCodec) ? { audioCodec: text(payload.audioCodec) } : {}),
subtitles: mergedSubtitles,
audioTracks: audioInputs.map(normalizeAudio),
}
}
async function request(path: string, init: RequestInit = {}): Promise<unknown> {
const headers = new Headers(init.headers)
if (init.body && !headers.has('content-type')) headers.set('content-type', 'application/json')
headers.set('accept', 'application/json')
const response = await fetch(`${API_BASE}${path}`, {
...init,
headers,
credentials: 'include',
})
const contentType = response.headers.get('content-type') ?? ''
const body: unknown = response.status === 204
? undefined
: contentType.includes('application/json')
? await response.json()
: await response.text()
if (!response.ok) {
const outerError = record(body)
const error = Object.keys(record(outerError.error)).length ? record(outerError.error) : outerError
throw new ApiError(
text(error.message) ?? text(error.error) ?? `Request failed (${response.status})`,
response.status,
text(error.code ?? error.reasonCode),
)
}
return body
}
function queryString(params: Record<string, string | number | undefined>): string {
const query = new URLSearchParams()
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== '') query.set(key, String(value))
})
const encoded = query.toString()
return encoded ? `?${encoded}` : ''
}
function withSignal(signal: AbortSignal | undefined, init: RequestInit = {}): RequestInit {
return signal ? { ...init, signal } : init
}
export const api = {
async catalog(options: { cursor?: string; limit?: number; kind?: string } = {}, signal?: AbortSignal): Promise<CatalogPage> {
const body = await request(`/catalog${queryString({ ...options })}`, withSignal(signal))
const source = record(body)
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
const rawItems = Array.isArray(body) ? body : array(payload.items ?? payload.results)
const nextCursor = text(payload.nextCursor ?? record(payload.pagination).nextCursor)
const total = number(payload.total ?? record(payload.pagination).total)
return {
items: rawItems.map(normalizeCatalogItem).filter((item) => item.id),
...(nextCursor ? { nextCursor } : {}),
...(total !== undefined ? { total } : {}),
}
},
async search(term: string, signal?: AbortSignal): Promise<CatalogPage> {
const body = await request(`/search${queryString({ q: term, limit: 40 })}`, withSignal(signal))
const source = record(body)
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
const rawItems = Array.isArray(body) ? body : array(payload.items ?? payload.results)
return {
items: rawItems.map(normalizeCatalogItem).filter((item) => item.id),
...(number(payload.total) !== undefined ? { total: number(payload.total) } : {}),
}
},
async title(slug: string, signal?: AbortSignal): Promise<TitleDetail> {
const body = await request(`/titles/${encodeURIComponent(slug)}`, withSignal(signal))
const source = record(body)
const payload = Object.keys(record(source.data)).length ? record(source.data) : source
const base = normalizeCatalogItem(payload)
const explicitSeasons = array(payload.seasons).map(normalizeSeason)
const mediaItems = array(payload.mediaItems).map((entry) => record(entry))
const groupedSeasons = new Map<number, EpisodeItem[]>()
mediaItems.forEach((entry) => {
const seasonNumber = number(entry.seasonNumber) ?? 0
const episodes = groupedSeasons.get(seasonNumber) ?? []
episodes.push(normalizeEpisode(entry, seasonNumber))
groupedSeasons.set(seasonNumber, episodes)
})
const seasons = explicitSeasons.some((season) => season.episodes.length)
? explicitSeasons
: [...groupedSeasons.entries()]
.sort(([left], [right]) => left - right)
.map(([seasonNumber, episodes]) => ({
number: seasonNumber,
title: { fa: `فصل ${seasonNumber}`, en: `Season ${seasonNumber}` },
episodes: episodes.sort((left, right) => left.number - right.number),
}))
const firstPublishedMediaItem = mediaItems.find((item) => item.published !== false)
const playableMediaItemId = text(payload.resumeMediaItemId)
?? text(payload.playableMediaItemId)
?? text(firstPublishedMediaItem?.id)
return {
...base,
mediaItemId: playableMediaItemId ?? '',
genres: array(payload.genres).map((genre) => localized(genre, record(genre).name)),
seasons,
...(playableMediaItemId ? { playableMediaItemId } : {}),
}
},
async createPlaybackSession(
mediaItemId: string,
clientCapabilities: ClientCapabilities,
signal?: AbortSignal,
): Promise<PlaybackSession> {
const body = await request('/playback-sessions', withSignal(signal, {
method: 'POST',
body: JSON.stringify({ mediaItemId, clientCapabilities }),
}))
const session = normalizePlaybackSession(body)
return { ...session, mediaItemId: session.mediaItemId || mediaItemId }
},
async playbackSession(id: string, signal?: AbortSignal): Promise<PlaybackSession> {
return normalizePlaybackSession(await request(`/playback-sessions/${encodeURIComponent(id)}`, withSignal(signal)))
},
async clientEvent(event: Record<string, unknown>): Promise<void> {
await request('/client-events', { method: 'POST', body: JSON.stringify(event), keepalive: true })
},
async adminSession(signal?: AbortSignal): Promise<{ authenticated: boolean; name?: string }> {
const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY)
if (!csrfToken) return { authenticated: false }
try {
await request('/admin/jobs', withSignal(signal))
const email = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_EMAIL_KEY) ?? undefined
return { authenticated: true, ...(email ? { name: email } : {}) }
} catch (error) {
if (error instanceof ApiError && error.status === 401) return { authenticated: false }
throw error
}
},
async adminLogin(email: string, password: string, totp?: string): Promise<void> {
const body = record(await request('/admin/login', {
method: 'POST',
body: JSON.stringify({ email, password, ...(totp ? { totp } : {}) }),
}))
const csrfToken = text(body.csrfToken)
if (!csrfToken) throw new ApiError('Administrator login did not return a CSRF token', 500, 'CSRF_TOKEN_MISSING')
if (typeof sessionStorage !== 'undefined') {
sessionStorage.setItem(ADMIN_CSRF_KEY, csrfToken)
sessionStorage.setItem(ADMIN_EMAIL_KEY, text(record(body.admin).email) ?? email)
}
},
async adminLogout(): Promise<void> {
const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY)
try {
await request('/admin/logout', {
method: 'POST',
...(csrfToken ? { headers: { 'x-csrf-token': csrfToken } } : {}),
})
} finally {
if (typeof sessionStorage !== 'undefined') {
sessionStorage.removeItem(ADMIN_CSRF_KEY)
sessionStorage.removeItem(ADMIN_EMAIL_KEY)
}
}
},
async adminDashboard(signal?: AbortSignal): Promise<AdminDashboard> {
const [jobsBody, cacheBody, catalogBody] = await Promise.all([
request('/admin/jobs', withSignal(signal)),
request('/admin/cache', withSignal(signal)),
request('/catalog?limit=100', withSignal(signal)),
])
const jobsPayload = record(jobsBody)
const cache = record(cacheBody)
const catalog = record(catalogBody)
const jobs: AdminJob[] = array(jobsPayload.items ?? jobsPayload.jobs).map((input, index) => {
const item = record(input)
const rawProgress = number(item.progress)
return {
id: text(item.id) ?? `job-${index}`,
type: text(item.type) ?? 'UNKNOWN',
state: text(item.state ?? item.status) ?? 'UNKNOWN',
...(rawProgress !== undefined ? { progress: rawProgress <= 1 ? rawProgress * 100 : rawProgress } : {}),
...(text(item.message ?? item.error) ? { message: text(item.message ?? item.error) } : {}),
...(text(item.createdAt) ? { createdAt: text(item.createdAt) } : {}),
}
})
const catalogItems = array(catalog.items)
return {
catalogCount: catalogItems.length,
publishedCount: catalogItems.filter((item) => record(item).playable === true).length,
reviewCount: 0,
activeJobs: jobs.filter((job) => job.state === 'RUNNING' || job.state === 'QUEUED').length,
...(number(cache.usedBytes) !== undefined
? { cacheUsedBytes: number(cache.usedBytes) }
: {}),
...(number(cache.maxBytes) !== undefined
? { cacheCapacityBytes: number(cache.maxBytes) }
: {}),
jobs,
}
},
async startScan(): Promise<{ jobId?: string }> {
const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY)
if (!csrfToken) throw new ApiError('Administrator session must be renewed', 401, 'ADMIN_SESSION_REQUIRED')
const body = record(await request('/admin/scans', {
method: 'POST',
headers: { 'x-csrf-token': csrfToken },
body: JSON.stringify({ full: false }),
}))
const jobId = text(body.id ?? body.jobId ?? record(body.data).jobId)
return { ...(jobId ? { jobId } : {}) }
},
}
+64
View File
@@ -0,0 +1,64 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import BrandMark from '@/components/BrandMark.vue'
import { useI18n } from '@/i18n'
import { useUiStore } from '@/stores/ui'
const ui = useUiStore()
const router = useRouter()
const { language, t } = useI18n()
const searchTerm = ref('')
function submitSearch() {
const query = searchTerm.value.trim()
void router.push({ name: 'search', query: query ? { q: query } : {} })
}
function toggleLanguage() {
void ui.setLanguage(language.value === 'fa' ? 'en' : 'fa')
}
</script>
<template>
<header class="app-header">
<RouterLink class="brand focus-ring" data-tv-focus data-focus-id="nav-home" to="/" :aria-label="t('home')">
<BrandMark />
<span class="brand-wordmark" aria-hidden="true">
<span class="brand-easy">Easy</span><strong>Stream</strong>
</span>
</RouterLink>
<nav class="primary-nav" :aria-label="t('home')">
<RouterLink class="nav-link focus-ring" data-tv-focus data-focus-id="nav-catalog" to="/">
{{ t('home') }}
</RouterLink>
<RouterLink class="nav-link focus-ring" data-tv-focus data-focus-id="nav-search" to="/search">
{{ t('search') }}
</RouterLink>
</nav>
<form class="header-search" role="search" @submit.prevent="submitSearch">
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="m21 21-4.35-4.35m2.35-5.65a8 8 0 1 1-16 0 8 8 0 0 1 16 0Z" /></svg>
<input
v-model="searchTerm"
data-tv-focus
data-focus-id="header-search"
:aria-label="t('search')"
:placeholder="t('searchPlaceholder')"
/>
</form>
<button
class="language-button focus-ring"
type="button"
data-tv-focus
data-focus-id="language"
:aria-label="t('language')"
@click="toggleLanguage"
>
{{ t('switchLanguage') }}
</button>
</header>
</template>
+17
View File
@@ -0,0 +1,17 @@
import { mount } from '@vue/test-utils'
import BrandMark from './BrandMark.vue'
describe('BrandMark', () => {
it('keeps SVG paint references unique across multiple instances', () => {
const wrapper = mount({
components: { BrandMark },
template: '<div><BrandMark /><BrandMark /></div>',
})
const ids = wrapper.findAll('linearGradient').map((gradient) => gradient.attributes('id'))
expect(new Set(ids).size).toBe(4)
expect(wrapper.findAll('svg')).toHaveLength(2)
expect(wrapper.findAll('svg').every((svg) => svg.attributes('aria-hidden') === 'true')).toBe(true)
})
})
+33
View File
@@ -0,0 +1,33 @@
<script setup lang="ts">
import { useId } from 'vue'
const gradientId = `brand-gold-${useId()}`
const shineId = `brand-shine-${useId()}`
</script>
<template>
<svg
class="brand-symbol"
viewBox="0 0 64 64"
aria-hidden="true"
focusable="false"
>
<defs>
<linearGradient :id="gradientId" x1="10" y1="7" x2="54" y2="58" gradientUnits="userSpaceOnUse">
<stop stop-color="#FFE29A" />
<stop offset="0.46" stop-color="#F5BD43" />
<stop offset="1" stop-color="#D98A08" />
</linearGradient>
<linearGradient :id="shineId" x1="16" y1="11" x2="43" y2="49" gradientUnits="userSpaceOnUse">
<stop stop-color="#FFF5D5" stop-opacity="0.82" />
<stop offset="1" stop-color="#FFF5D5" stop-opacity="0" />
</linearGradient>
</defs>
<rect width="64" height="64" rx="18" fill="#111722" />
<rect x="5" y="5" width="54" height="54" rx="15" :fill="`url(#${gradientId})`" />
<path d="M18 20.5c0-3.04 2.46-5.5 5.5-5.5h17.75a5.5 5.5 0 0 1 4.8 2.82l5.46 9.78a9 9 0 0 1 0 8.8l-5.46 9.78a5.5 5.5 0 0 1-4.8 2.82H23.5a5.5 5.5 0 0 1-5.5-5.5v-23Z" fill="#111722" />
<path d="m30 24.4 12.2 7.6L30 39.6V24.4Z" fill="#FFF8E8" />
<path d="M13.5 23.5h7M11 32h9.5M13.5 40.5h7" fill="none" stroke="#111722" stroke-width="3.5" stroke-linecap="round" />
<path d="M17 12.5h18c8 0 13.2 4.4 16 10.5" fill="none" :stroke="`url(#${shineId})`" stroke-width="2.5" stroke-linecap="round" />
</svg>
</template>
+10
View File
@@ -0,0 +1,10 @@
<script setup lang="ts">
defineProps<{ label: string }>()
</script>
<template>
<div class="center-state" role="status" aria-live="polite">
<span class="spinner" aria-hidden="true" />
<p>{{ label }}</p>
</div>
</template>
+54
View File
@@ -0,0 +1,54 @@
import { createPinia } from 'pinia'
import { mount } from '@vue/test-utils'
import { describe, expect, it, vi } from 'vitest'
import MediaCard from '@/components/MediaCard.vue'
import { usePlayerStore } from '@/stores/player'
import type { CatalogItem } from '@/types'
const item: CatalogItem = {
id: 'title-1',
mediaItemId: 'media-1',
slug: 'sample-title',
kind: 'MOVIE',
title: { fa: 'فیلم نمونه', en: 'Sample movie' },
overview: {},
playable: true,
year: 2026,
}
describe('MediaCard', () => {
it('starts playback directly from the main card action', async () => {
const pinia = createPinia()
const start = vi.fn()
const store = usePlayerStore(pinia)
store.register({ start, close: vi.fn() })
const wrapper = mount(MediaCard, {
props: { item },
global: {
plugins: [pinia],
stubs: {
RouterLink: { template: '<a><slot /></a>' },
},
},
})
await wrapper.get('.media-card-play').trigger('click')
expect(start).toHaveBeenCalledWith(expect.objectContaining({ mediaItemId: 'media-1', title: 'فیلم نمونه' }))
expect(store.visible).toBe(true)
})
it('disables direct play for unpublished media', () => {
const pinia = createPinia()
const wrapper = mount(MediaCard, {
props: { item: { ...item, playable: false } },
global: {
plugins: [pinia],
stubs: { RouterLink: { template: '<a><slot /></a>' } },
},
})
expect(wrapper.get('.media-card-play').attributes('disabled')).toBeDefined()
})
})
+68
View File
@@ -0,0 +1,68 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from '@/i18n'
import { usePlayerStore } from '@/stores/player'
import type { CatalogItem } from '@/types'
const props = defineProps<{
item: CatalogItem
progress?: number | undefined
}>()
const player = usePlayerStore()
const { localize, t } = useI18n()
const title = computed(() => localize(props.item.title, props.item.slug))
const effectiveProgress = computed(() => props.progress ?? props.item.progress ?? 0)
function play() {
if (!props.item.playable || !props.item.mediaItemId) return
player.play({
mediaItemId: props.item.mediaItemId,
title: title.value,
...(props.item.posterUrl ? { posterUrl: props.item.posterUrl } : {}),
})
}
</script>
<template>
<article class="media-card" :class="{ 'is-unavailable': !item.playable }">
<button
class="media-card-play focus-ring"
type="button"
data-tv-focus
:data-focus-id="`media-${item.id}`"
:disabled="!item.playable"
:aria-label="`${effectiveProgress > 0 ? t('resume') : t('play')}: ${title}`"
@click="play"
>
<img v-if="item.posterUrl" :src="item.posterUrl" alt="" loading="lazy" />
<div v-else class="poster-placeholder" aria-hidden="true">
<span>{{ title.slice(0, 1) }}</span>
</div>
<span class="card-gradient" aria-hidden="true" />
<span class="card-play-icon" aria-hidden="true">
<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
</span>
<span v-if="!item.playable" class="availability-badge">{{ t('unavailable') }}</span>
<span v-if="effectiveProgress > 0" class="progress-track" aria-hidden="true">
<span :style="{ width: `${Math.min(100, Math.max(0, effectiveProgress))}%` }" />
</span>
</button>
<div class="card-copy">
<h3>{{ title }}</h3>
<div class="card-meta">
<span v-if="item.year">{{ item.year }}</span>
<span>{{ item.kind === 'SERIES' ? t('series') : t('movies') }}</span>
</div>
<RouterLink
class="card-info focus-ring"
data-tv-focus
:data-focus-id="`info-${item.id}`"
:to="{ name: 'title', params: { slug: item.slug } }"
>
{{ t('details') }}
</RouterLink>
</div>
</article>
</template>
+713
View File
@@ -0,0 +1,713 @@
<script setup lang="ts">
import vazirmatnArabicUrl from '@fontsource/vazirmatn/files/vazirmatn-arabic-400-normal.woff2?url'
import vazirmatnLatinUrl from '@fontsource/vazirmatn/files/vazirmatn-latin-400-normal.woff2?url'
import Hls, { Events, type ErrorData } from 'hls.js'
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import { api } from '@/api/client'
import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import { readProgress, writeProgress } from '@/storage/viewer-db'
import { type PlayRequest, usePlayerStore } from '@/stores/player'
import { useUiStore } from '@/stores/ui'
import type {
ClientCapabilities,
PlaybackAudioTrack,
PlaybackSession,
PlaybackSubtitleTrack,
SubtitleDelivery,
} from '@/types'
type ViewState = 'IDLE' | 'REQUESTING' | 'PREPARING' | 'BUFFERING' | 'PLAYING' | 'UNSUPPORTED' | 'FAILED'
type AssRenderer = { destroy: () => void; ready?: Promise<unknown> }
const shell = ref<HTMLElement | null>(null)
const video = ref<HTMLVideoElement | null>(null)
const player = usePlayerStore()
const ui = useUiStore()
const { t } = useI18n()
const state = ref<ViewState>('IDLE')
const message = ref('')
const reasonCode = ref('')
const preparationProgress = ref<number | undefined>()
const paused = ref(true)
const needsGesture = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const buffered = ref(0)
const controlsVisible = ref(true)
const menu = ref<'subtitles' | 'audio' | null>(null)
const session = ref<PlaybackSession | null>(null)
const selectedSubtitle = ref('off')
const selectedAudio = ref('')
const subtitleDelivery = ref<SubtitleDelivery>('OFF')
const currentRequest = ref<PlayRequest | null>(null)
const fullscreen = ref(false)
const rootVisible = computed(() => player.visible)
const isBusy = computed(() => state.value === 'REQUESTING' || state.value === 'PREPARING' || state.value === 'BUFFERING')
const canSeek = computed(() => Number.isFinite(duration.value) && duration.value > 0)
let hls: Hls | undefined
let assRenderer: AssRenderer | undefined
let requestController: AbortController | undefined
let requestSequence = 0
let hideControlsTimer: ReturnType<typeof setTimeout> | undefined
let lastProgressWrite = 0
let returnFocus: HTMLElement | null = null
function supportsAssRendering(): boolean {
if (typeof window === 'undefined') return false
const videoPrototype = typeof HTMLVideoElement === 'undefined' ? undefined : HTMLVideoElement.prototype
return typeof WebAssembly !== 'undefined'
&& typeof TextDecoder !== 'undefined'
&& typeof Worker !== 'undefined'
&& typeof OffscreenCanvas !== 'undefined'
&& typeof fetch !== 'undefined'
&& Boolean(videoPrototype && ('requestVideoFrameCallback' in videoPrototype || 'getVideoPlaybackQuality' in videoPrototype))
}
function detectClientCapabilities(element: HTMLVideoElement): ClientCapabilities {
const nativeHls = Boolean(
element.canPlayType('application/vnd.apple.mpegurl')
|| element.canPlayType('application/x-mpegURL'),
)
const mse = typeof MediaSource !== 'undefined'
const codec = 'video/mp4; codecs="avc1.64001f,mp4a.40.2"'
const h264Aac = mse && typeof MediaSource.isTypeSupported === 'function'
? MediaSource.isTypeSupported(codec)
: nativeHls
return {
nativeHls,
mse,
hlsJs: Hls.isSupported(),
assRenderer: supportsAssRendering(),
supportedCodecs: h264Aac ? ['avc1.64001f', 'mp4a.40.2'] : [],
...(typeof navigator !== 'undefined' && navigator.userAgent ? { userAgent: navigator.userAgent.slice(0, 512) } : {}),
}
}
function destroyAssRenderer() {
try {
assRenderer?.destroy()
} catch {
// Renderer teardown is best effort when a worker has already failed.
}
assRenderer = undefined
}
function removeExternalTracks() {
const element = video.value
if (!element) return
element.querySelectorAll('track[data-easy-stream]').forEach((track) => track.remove())
}
function destroyMedia(clearSource = true) {
hls?.destroy()
hls = undefined
destroyAssRenderer()
removeExternalTracks()
if (clearSource && video.value) {
video.value.pause()
video.value.removeAttribute('src')
video.value.load()
}
}
function wait(milliseconds: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(resolve, milliseconds)
signal.addEventListener('abort', () => {
clearTimeout(timer)
reject(new DOMException('Aborted', 'AbortError'))
}, { once: true })
})
}
function recordClientEvent(name: string, details: Record<string, unknown> = {}) {
void api.clientEvent({
name,
mediaItemId: currentRequest.value?.mediaItemId,
sessionId: session.value?.id,
occurredAt: new Date().toISOString(),
details,
}).catch(() => undefined)
}
async function saveProgress(force = false) {
const element = video.value
const request = currentRequest.value
if (!element || !request || !Number.isFinite(element.duration) || element.duration <= 0) return
const now = Date.now()
if (!force && now - lastProgressWrite < 10_000) return
lastProgressWrite = now
const ratio = element.currentTime / element.duration
await writeProgress({
mediaItemId: request.mediaItemId,
positionSeconds: Math.max(0, element.currentTime),
durationSeconds: element.duration,
updatedAt: now,
completed: ratio >= 0.95,
})
}
function updateTimeline() {
const element = video.value
if (!element) return
currentTime.value = Number.isFinite(element.currentTime) ? element.currentTime : 0
duration.value = Number.isFinite(element.duration) ? element.duration : session.value?.durationSeconds ?? 0
if (element.buffered.length && duration.value > 0) {
buffered.value = (element.buffered.end(element.buffered.length - 1) / duration.value) * 100
}
void saveProgress()
}
function showControls() {
controlsVisible.value = true
if (hideControlsTimer) clearTimeout(hideControlsTimer)
if (!paused.value && !menu.value) {
hideControlsTimer = setTimeout(() => {
controlsVisible.value = false
}, 4_000)
}
}
async function requestFullscreen() {
const element = shell.value
if (!element || !document.fullscreenEnabled || document.fullscreenElement) return
try {
await element.requestFullscreen({ navigationUI: 'hide' })
} catch {
// Fullscreen is opportunistic; the fixed player still fills the viewport.
}
}
async function toggleFullscreen() {
if (document.fullscreenElement) {
try { await document.exitFullscreen() } catch { /* browser is already leaving fullscreen */ }
return
}
await requestFullscreen()
}
async function applyResumePosition() {
const element = video.value
const request = currentRequest.value
if (!element || !request) return
const progress = await readProgress(request.mediaItemId)
if (!progress || progress.completed || progress.positionSeconds < 60) return
const knownDuration = Number.isFinite(element.duration) ? element.duration : progress.durationSeconds
if (knownDuration > 0 && progress.positionSeconds / knownDuration < 0.95) {
element.currentTime = Math.min(progress.positionSeconds, Math.max(0, knownDuration - 2))
}
}
async function beginPlayback() {
const element = video.value
if (!element) return
await applyResumePosition()
try {
await element.play()
needsGesture.value = false
} catch {
needsGesture.value = true
showControls()
}
}
function selectHlsAudio(language: string) {
if (!hls) return
const index = hls.audioTracks.findIndex((track) => track.lang === language || track.name === language)
if (index >= 0) hls.audioTrack = index
}
function selectNativeAudio(language: string) {
const element = video.value as (HTMLVideoElement & { audioTracks?: { length: number; [index: number]: { language: string; enabled: boolean } } }) | null
if (!element?.audioTracks) return
for (let index = 0; index < element.audioTracks.length; index += 1) {
const track = element.audioTracks[index]
if (track) track.enabled = track.language === language
}
}
async function chooseAudio(track: PlaybackAudioTrack) {
selectedAudio.value = track.id
selectHlsAudio(track.language)
selectNativeAudio(track.language)
await ui.setAudioLanguage(track.language)
menu.value = null
}
function enableVtt(track: PlaybackSubtitleTrack): boolean {
const element = video.value
if (!element || !track.vttUrl) return false
removeExternalTracks()
const trackElement = document.createElement('track')
trackElement.dataset.easyStream = 'true'
trackElement.kind = 'subtitles'
trackElement.src = track.vttUrl
trackElement.srclang = track.language
trackElement.label = track.label
trackElement.default = true
element.append(trackElement)
trackElement.addEventListener('load', () => {
if (trackElement.track) trackElement.track.mode = 'showing'
}, { once: true })
subtitleDelivery.value = 'WEBVTT'
return true
}
async function enableAss(track: PlaybackSubtitleTrack): Promise<boolean> {
const element = video.value
if (!element || !track.assUrl || !supportsAssRendering()) return false
try {
const { default: JASSUB } = await import('jassub')
const renderer = new JASSUB({
video: element,
subUrl: track.assUrl,
fonts: [...new Set([...track.fonts, vazirmatnArabicUrl, vazirmatnLatinUrl])],
defaultFont: 'Vazirmatn',
queryFonts: 'local',
}) as AssRenderer
if (renderer.ready) await renderer.ready
assRenderer = renderer
subtitleDelivery.value = 'ASS_JASSUB'
return true
} catch (error) {
recordClientEvent('subtitle_fallback', { reason: error instanceof Error ? error.message : 'JASSUB_INIT_FAILED' })
return false
}
}
async function chooseSubtitle(track?: PlaybackSubtitleTrack) {
destroyAssRenderer()
removeExternalTracks()
if (!track) {
selectedSubtitle.value = 'off'
subtitleDelivery.value = 'OFF'
menu.value = null
return
}
selectedSubtitle.value = track.id
const renderedAss = await enableAss(track)
if (!renderedAss && !enableVtt(track)) {
selectedSubtitle.value = 'off'
subtitleDelivery.value = 'OFF'
} else {
await ui.setSubtitleLanguage(track.language)
}
menu.value = null
}
function preferredSubtitle(tracks: PlaybackSubtitleTrack[]): PlaybackSubtitleTrack | undefined {
return tracks.find((track) => track.language === ui.preferences.subtitleLanguage)
?? tracks.find((track) => track.default && !track.forced)
?? tracks.find((track) => track.language === 'fa' || track.language.startsWith('fa-'))
?? tracks.find((track) => track.language === 'en' || track.language.startsWith('en-'))
}
function preferredAudio(tracks: PlaybackAudioTrack[]): PlaybackAudioTrack | undefined {
return tracks.find((track) => track.language === ui.preferences.audioLanguage)
?? tracks.find((track) => track.default)
?? tracks[0]
}
async function onManifestReady() {
const activeSession = session.value
if (!activeSession) return
state.value = 'PLAYING'
const audio = preferredAudio(activeSession.audioTracks)
if (audio) await chooseAudio(audio)
const subtitle = preferredSubtitle(activeSession.subtitles)
await chooseSubtitle(subtitle)
await beginPlayback()
recordClientEvent('playback_started', { subtitleDelivery: subtitleDelivery.value })
}
function failPlayback(error: ErrorData | string) {
const detail = typeof error === 'string' ? error : `${error.type}:${error.details}`
state.value = 'FAILED'
message.value = detail
reasonCode.value = 'PLAYER_ERROR'
needsGesture.value = false
recordClientEvent('fatal_player_error', { detail })
}
function attachManifest(activeSession: PlaybackSession) {
const element = video.value
if (!element || !activeSession.manifestUrl) {
failPlayback(activeSession.reasonCode ?? 'MANIFEST_URL_MISSING')
return
}
state.value = 'BUFFERING'
session.value = activeSession
duration.value = activeSession.durationSeconds ?? 0
const capabilities = detectClientCapabilities(element)
element.volume = ui.preferences.volume
element.muted = ui.preferences.muted
if (capabilities.nativeHls) {
element.src = activeSession.manifestUrl
element.addEventListener('loadedmetadata', () => void onManifestReady(), { once: true })
element.addEventListener('error', () => failPlayback('NATIVE_HLS_ERROR'), { once: true })
element.load()
return
}
if (!capabilities.hlsJs) {
state.value = 'UNSUPPORTED'
reasonCode.value = 'MSE_UNAVAILABLE'
return
}
hls = new Hls({
enableWorker: true,
lowLatencyMode: false,
backBufferLength: 60,
maxBufferLength: 30,
manifestLoadingTimeOut: 20_000,
fragLoadingTimeOut: 30_000,
xhrSetup: (xhr) => { xhr.withCredentials = true },
})
hls.on(Events.MEDIA_ATTACHED, () => hls?.loadSource(activeSession.manifestUrl!))
hls.on(Events.MANIFEST_PARSED, () => void onManifestReady())
hls.on(Events.AUDIO_TRACKS_UPDATED, () => {
const audio = preferredAudio(activeSession.audioTracks)
if (audio) selectHlsAudio(audio.language)
})
hls.on(Events.ERROR, (_event, data) => {
if (data.fatal) failPlayback(data)
})
hls.attachMedia(element)
}
async function resolveSession(initial: PlaybackSession, sequence: number, signal: AbortSignal) {
let active = initial
while (active.state === 'PREPARING' && sequence === requestSequence) {
session.value = active
state.value = 'PREPARING'
preparationProgress.value = active.progress
message.value = active.message ?? ''
await wait(active.pollAfterMs, signal)
active = await api.playbackSession(active.id, signal)
}
if (sequence !== requestSequence) return
session.value = active
if (active.state === 'READY') {
attachManifest(active)
} else if (active.state === 'UNSUPPORTED_CLIENT') {
state.value = 'UNSUPPORTED'
reasonCode.value = active.reasonCode ?? 'UNSUPPORTED_CLIENT'
message.value = active.message ?? ''
} else {
state.value = 'FAILED'
reasonCode.value = active.reasonCode ?? 'PREPARATION_FAILED'
message.value = active.message ?? ''
}
}
async function start(request: PlayRequest) {
const element = video.value
if (!element) return
requestSequence += 1
const sequence = requestSequence
requestController?.abort()
requestController = new AbortController()
destroyMedia()
currentRequest.value = request
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null
state.value = 'REQUESTING'
message.value = ''
reasonCode.value = ''
preparationProgress.value = undefined
needsGesture.value = false
selectedSubtitle.value = 'off'
selectedAudio.value = ''
currentTime.value = 0
duration.value = 0
player.visible = true
showControls()
// Both calls happen while the card activation is still the active user gesture.
void element.play().catch(() => undefined)
void requestFullscreen()
await nextTick()
shell.value?.focus({ preventScroll: true })
const capabilities = detectClientCapabilities(element)
if (!capabilities.nativeHls && (!capabilities.hlsJs || capabilities.supportedCodecs.length < 2)) {
state.value = 'UNSUPPORTED'
reasonCode.value = 'MSE_UNAVAILABLE'
return
}
try {
const initial = await api.createPlaybackSession(request.mediaItemId, capabilities, requestController.signal)
await resolveSession(initial, sequence, requestController.signal)
} catch (error) {
if ((error as { name?: string }).name === 'AbortError' || sequence !== requestSequence) return
state.value = 'FAILED'
message.value = error instanceof Error ? error.message : t('networkError')
reasonCode.value = 'SESSION_REQUEST_FAILED'
}
}
async function close() {
requestSequence += 1
requestController?.abort()
await saveProgress(true)
destroyMedia()
state.value = 'IDLE'
session.value = null
currentRequest.value = null
player.visible = false
menu.value = null
if (document.fullscreenElement) {
try { await document.exitFullscreen() } catch { /* already exiting */ }
}
await nextTick()
returnFocus?.focus({ preventScroll: true })
}
function togglePlayback() {
const element = video.value
if (!element) return
if (element.paused) {
void element.play().then(() => { needsGesture.value = false }).catch(() => { needsGesture.value = true })
} else {
element.pause()
}
showControls()
}
function seekBy(seconds: number) {
const element = video.value
if (!element || !canSeek.value) return
element.currentTime = Math.min(element.duration, Math.max(0, element.currentTime + seconds))
updateTimeline()
showControls()
}
function seekTo(event: Event) {
const element = video.value
const target = event.target as HTMLInputElement
if (!element || !canSeek.value) return
element.currentTime = Number(target.value)
updateTimeline()
}
function toggleMute() {
const element = video.value
if (!element) return
element.muted = !element.muted
void ui.setVolume(element.volume, element.muted)
}
function toggleMenu(target: 'subtitles' | 'audio') {
menu.value = menu.value === target ? null : target
showControls()
}
function formatTime(seconds: number): string {
if (!Number.isFinite(seconds) || seconds < 0) return '00:00'
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const remaining = Math.floor(seconds % 60)
return hours > 0
? `${hours}:${String(minutes).padStart(2, '0')}:${String(remaining).padStart(2, '0')}`
: `${String(minutes).padStart(2, '0')}:${String(remaining).padStart(2, '0')}`
}
function onPlayerKeydown(event: KeyboardEvent) {
if (!rootVisible.value) return
showControls()
if (event.key === 'MediaPlayPause' || (event.key === ' ' && event.target === shell.value)) {
event.preventDefault()
togglePlayback()
} else if (event.key === 'MediaRewind') {
event.preventDefault()
seekBy(-10)
} else if (event.key === 'MediaFastForward') {
event.preventDefault()
seekBy(10)
}
}
const controller = { start: (request: PlayRequest) => void start(request), close: () => void close() }
useSpatialNavigation(shell, { onBack: () => void close() })
onMounted(() => {
player.register(controller)
document.addEventListener('keydown', onPlayerKeydown)
document.addEventListener('fullscreenchange', () => { fullscreen.value = Boolean(document.fullscreenElement) })
})
onBeforeUnmount(() => {
player.unregister(controller)
document.removeEventListener('keydown', onPlayerKeydown)
requestController?.abort()
destroyMedia()
})
</script>
<template>
<section
v-show="rootVisible"
ref="shell"
class="player-shell"
:class="{ 'controls-hidden': !controlsVisible }"
role="dialog"
aria-modal="true"
:aria-label="currentRequest?.title ?? t('play')"
tabindex="-1"
@mousemove="showControls"
@click.self="showControls"
>
<video
ref="video"
class="player-video"
playsinline
preload="metadata"
crossorigin="use-credentials"
:poster="currentRequest?.posterUrl"
@click="togglePlayback"
@play="paused = false; showControls()"
@pause="paused = true; showControls(); saveProgress(true)"
@waiting="state = 'BUFFERING'"
@playing="state = 'PLAYING'"
@timeupdate="updateTimeline"
@durationchange="updateTimeline"
@progress="updateTimeline"
@ended="saveProgress(true)"
@volumechange="video && ui.setVolume(video.volume, video.muted)"
/>
<div v-if="isBusy" class="player-status" role="status" aria-live="polite">
<span class="spinner large" aria-hidden="true" />
<h2>{{ state === 'PREPARING' ? t('preparing') : t('loading') }}</h2>
<p v-if="state === 'PREPARING'">{{ message || t('preparingHint') }}</p>
<div v-if="preparationProgress !== undefined" class="preparing-progress">
<span :style="{ width: `${Math.min(100, Math.max(0, preparationProgress))}%` }" />
</div>
</div>
<div v-else-if="state === 'UNSUPPORTED'" class="player-status player-error" role="alert">
<span class="status-symbol" aria-hidden="true">!</span>
<h2>{{ t('incompatibleTitle') }}</h2>
<p>{{ message || t('incompatibleBody') }}</p>
<small v-if="reasonCode">{{ reasonCode }}</small>
<button class="primary-button large focus-ring" type="button" data-tv-focus @click="close">{{ t('close') }}</button>
</div>
<div v-else-if="state === 'FAILED'" class="player-status player-error" role="alert">
<span class="status-symbol" aria-hidden="true">!</span>
<h2>{{ t('playbackFailed') }}</h2>
<p>{{ message }}</p>
<small v-if="reasonCode">{{ reasonCode }}</small>
<div class="hero-actions">
<button
v-if="currentRequest"
class="primary-button focus-ring"
type="button"
data-tv-focus
@click="start(currentRequest)"
>{{ t('retry') }}</button>
<button class="secondary-button focus-ring" type="button" data-tv-focus @click="close">{{ t('close') }}</button>
</div>
</div>
<button
v-if="needsGesture && state === 'PLAYING'"
class="gesture-play focus-ring"
type="button"
data-tv-focus
:aria-label="t('play')"
@click="togglePlayback"
>
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
<span>{{ t('pressPlay') }}</span>
</button>
<div v-if="state === 'PLAYING' || state === 'BUFFERING'" class="player-topbar">
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="t('close')" @click="close">
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6" /></svg>
</button>
<strong>{{ currentRequest?.title }}</strong>
</div>
<div v-if="state === 'PLAYING' || state === 'BUFFERING'" class="player-controls" @click.stop>
<div class="timeline-wrap">
<span>{{ formatTime(currentTime) }}</span>
<div class="timeline">
<span class="buffered" :style="{ width: `${buffered}%` }" aria-hidden="true" />
<input
type="range"
data-tv-focus
min="0"
:max="duration || 0"
step="0.25"
:value="currentTime"
:disabled="!canSeek"
:aria-label="t('play')"
@input="seekTo"
/>
</div>
<span>{{ formatTime(duration) }}</span>
</div>
<div class="control-row">
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="paused ? t('play') : t('pause')" @click="togglePlayback">
<svg v-if="paused" aria-hidden="true" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
<svg v-else aria-hidden="true" viewBox="0 0 24 24"><path d="M7 5h4v14H7zm6 0h4v14h-4z" /></svg>
</button>
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="t('seekBack')" @click="seekBy(-10)">
<span aria-hidden="true">↶</span><small>10</small>
</button>
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="t('seekForward')" @click="seekBy(10)">
<span aria-hidden="true">↷</span><small>10</small>
</button>
<button class="player-icon-button focus-ring" type="button" data-tv-focus aria-label="Mute" @click="toggleMute">
<span aria-hidden="true">{{ video?.muted ? '🔇' : '🔊' }}</span>
</button>
<span class="control-spacer" />
<div v-if="session?.audioTracks.length" class="control-menu-wrap">
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('audio')">{{ t('audio') }}</button>
<div v-if="menu === 'audio'" class="track-menu">
<button
v-for="track in session.audioTracks"
:key="track.id"
type="button"
data-tv-focus
:class="{ selected: track.id === selectedAudio }"
@click="chooseAudio(track)"
>{{ track.label }}</button>
</div>
</div>
<div v-if="session?.subtitles.length" class="control-menu-wrap">
<button class="player-text-button focus-ring" type="button" data-tv-focus @click="toggleMenu('subtitles')">
{{ t('subtitles') }}
</button>
<div v-if="menu === 'subtitles'" class="track-menu">
<button type="button" data-tv-focus :class="{ selected: selectedSubtitle === 'off' }" @click="chooseSubtitle()">
{{ t('subtitleOff') }}
</button>
<button
v-for="track in session.subtitles"
:key="track.id"
type="button"
data-tv-focus
:class="{ selected: track.id === selectedSubtitle }"
@click="chooseSubtitle(track)"
>{{ track.label }}</button>
</div>
</div>
<button class="player-icon-button focus-ring" type="button" data-tv-focus :aria-label="fullscreen ? t('exitFullscreen') : t('fullscreen')" @click="toggleFullscreen">
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M4 9V4h5M4 4l6 6m10-1V4h-5m5 0-6 6M4 15v5h5m-5 0 6-6m10 1v5h-5m5 0-6-6" /></svg>
</button>
</div>
</div>
</section>
</template>
@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from 'vitest'
import { moveSpatialFocus } from '@/composables/spatial-navigation'
function rect(left: number, top: number): DOMRect {
return { left, top, right: left + 100, bottom: top + 60, width: 100, height: 60, x: left, y: top, toJSON: () => ({}) }
}
describe('moveSpatialFocus', () => {
it('moves to the nearest element in the requested physical direction', () => {
const root = document.createElement('div')
const first = document.createElement('button')
const right = document.createElement('button')
const below = document.createElement('button')
for (const button of [first, right, below]) {
button.dataset.tvFocus = ''
root.append(button)
}
document.body.append(root)
vi.spyOn(first, 'getBoundingClientRect').mockReturnValue(rect(0, 0))
vi.spyOn(right, 'getBoundingClientRect').mockReturnValue(rect(180, 0))
vi.spyOn(below, 'getBoundingClientRect').mockReturnValue(rect(0, 120))
first.focus()
expect(moveSpatialFocus(root, 'right')).toBe(true)
expect(document.activeElement).toBe(right)
expect(moveSpatialFocus(root, 'down')).toBe(true)
expect(document.activeElement).toBe(below)
})
it('focuses the first TV target when focus starts outside the region', () => {
const root = document.createElement('div')
const button = document.createElement('button')
button.dataset.tvFocus = ''
root.append(button)
document.body.append(root)
expect(moveSpatialFocus(root, 'down')).toBe(true)
expect(document.activeElement).toBe(button)
})
})
@@ -0,0 +1,108 @@
import { nextTick, onBeforeUnmount, onMounted, type Ref } from 'vue'
type Direction = 'left' | 'right' | 'up' | 'down'
function isTypingTarget(target: EventTarget | null): boolean {
return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement
}
function candidates(root: HTMLElement): HTMLElement[] {
return [...root.querySelectorAll<HTMLElement>('[data-tv-focus]:not([disabled])')]
.filter((element) => element.offsetParent !== null && element.getAttribute('aria-hidden') !== 'true')
}
function scoreCandidate(current: DOMRect, candidate: DOMRect, direction: Direction): number | undefined {
const currentX = current.left + current.width / 2
const currentY = current.top + current.height / 2
const candidateX = candidate.left + candidate.width / 2
const candidateY = candidate.top + candidate.height / 2
const dx = candidateX - currentX
const dy = candidateY - currentY
if (direction === 'left' && dx >= -1) return undefined
if (direction === 'right' && dx <= 1) return undefined
if (direction === 'up' && dy >= -1) return undefined
if (direction === 'down' && dy <= 1) return undefined
const primary = direction === 'left' || direction === 'right' ? Math.abs(dx) : Math.abs(dy)
const secondary = direction === 'left' || direction === 'right' ? Math.abs(dy) : Math.abs(dx)
return primary + secondary * 2.25
}
export function moveSpatialFocus(root: HTMLElement, direction: Direction): boolean {
const focusable = candidates(root)
if (!focusable.length) return false
const active = document.activeElement instanceof HTMLElement && root.contains(document.activeElement)
? document.activeElement
: undefined
if (!active) {
focusable[0]?.focus()
return true
}
const currentRect = active.getBoundingClientRect()
const ranked = focusable
.filter((element) => element !== active)
.map((element) => ({ element, score: scoreCandidate(currentRect, element.getBoundingClientRect(), direction) }))
.filter((result): result is { element: HTMLElement; score: number } => result.score !== undefined)
.sort((left, right) => left.score - right.score)
const next = ranked[0]?.element
if (!next) return false
next.focus()
next.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' })
return true
}
export function useSpatialNavigation(
root: Ref<HTMLElement | null>,
options: { onBack?: () => void; restoreKey?: string } = {},
) {
const onKeydown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return
const element = root.value
if (!element || element.offsetParent === null || isTypingTarget(event.target)) return
const directionByKey: Partial<Record<string, Direction>> = {
ArrowLeft: 'left',
ArrowRight: 'right',
ArrowUp: 'up',
ArrowDown: 'down',
}
const direction = directionByKey[event.key]
if (direction && moveSpatialFocus(element, direction)) {
event.preventDefault()
return
}
if ((event.key === 'Escape' || event.key === 'BrowserBack' || event.key === 'Backspace') && options.onBack) {
event.preventDefault()
options.onBack()
}
}
const rememberFocus = (event: FocusEvent) => {
const target = event.target
if (options.restoreKey && target instanceof HTMLElement && target.dataset.focusId) {
sessionStorage.setItem(options.restoreKey, target.dataset.focusId)
}
}
const restoreFocus = async () => {
await nextTick()
const element = root.value
if (!element) return
const id = options.restoreKey ? sessionStorage.getItem(options.restoreKey) : undefined
const escapedId = id && typeof CSS !== 'undefined' && typeof CSS.escape === 'function' ? CSS.escape(id) : id
const previous = escapedId ? element.querySelector<HTMLElement>(`[data-focus-id="${escapedId}"]`) : undefined
;(previous ?? candidates(element)[0])?.focus()
}
onMounted(() => {
document.addEventListener('keydown', onKeydown)
root.value?.addEventListener('focusin', rememberFocus)
})
onBeforeUnmount(() => {
document.removeEventListener('keydown', onKeydown)
root.value?.removeEventListener('focusin', rememberFocus)
})
return { restoreFocus }
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL?: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
+139
View File
@@ -0,0 +1,139 @@
import { computed } from 'vue'
import { useUiStore } from '@/stores/ui'
const fa = {
home: 'خانه',
search: 'جستجو',
searchPlaceholder: 'نام فیلم یا سریال…',
admin: 'مدیریت',
language: 'زبان',
switchLanguage: 'English',
featured: 'پیشنهاد برای تماشا',
allTitles: 'همه عنوان‌ها',
movies: 'فیلم‌ها',
series: 'سریال‌ها',
play: 'پخش',
resume: 'ادامه پخش',
details: 'جزئیات',
retry: 'تلاش دوباره',
close: 'بستن',
back: 'بازگشت',
loading: 'در حال بارگذاری…',
loadingCatalog: 'در حال آماده‌کردن آرشیو…',
emptyCatalog: 'هنوز عنوان منتشرشده‌ای وجود ندارد.',
noResults: 'نتیجه‌ای پیدا نشد.',
networkError: 'ارتباط با سرور برقرار نشد.',
preparing: 'فیلم برای اولین پخش آماده می‌شود',
preparingHint: 'این صفحه را باز نگه دارید؛ پخش به‌صورت خودکار شروع می‌شود.',
incompatibleTitle: 'این مرورگر امکان پخش این ویدیو را ندارد',
incompatibleBody: 'برای پخش از نسخه جدید Chrome یا Firefox روی دستگاهی با پشتیبانی MSE استفاده کنید.',
playbackFailed: 'پخش ویدیو با مشکل روبه‌رو شد',
pressPlay: 'برای شروع، دکمه پخش را بزنید',
pause: 'مکث',
seekBack: '۱۰ ثانیه عقب',
seekForward: '۱۰ ثانیه جلو',
fullscreen: 'تمام‌صفحه',
exitFullscreen: 'خروج از تمام‌صفحه',
subtitles: 'زیرنویس',
audio: 'صدا',
subtitleOff: 'خاموش',
season: 'فصل',
episode: 'قسمت',
minutes: 'دقیقه',
loginTitle: 'ورود مدیر',
email: 'ایمیل',
password: 'رمز عبور',
totp: 'کد یک‌بارمصرف (اختیاری)',
login: 'ورود',
logout: 'خروج',
invalidLogin: 'اطلاعات ورود پذیرفته نشد.',
dashboard: 'وضعیت سامانه',
catalogCount: 'کل عنوان‌ها',
publishedCount: 'منتشرشده',
reviewCount: 'نیازمند بررسی',
activeJobs: 'کارهای فعال',
cache: 'حافظه موقت',
recentJobs: 'کارهای اخیر',
scanArchive: 'اسکن آرشیو',
scanStarted: 'اسکن آرشیو در صف قرار گرفت.',
refresh: 'به‌روزرسانی',
unavailable: 'ناموجود',
unsupported: 'پشتیبانی‌نشده',
year: 'سال',
} as const
const en: Record<keyof typeof fa, string> = {
home: 'Home',
search: 'Search',
searchPlaceholder: 'Movie or series name…',
admin: 'Admin',
language: 'Language',
switchLanguage: 'فارسی',
featured: 'Featured',
allTitles: 'All titles',
movies: 'Movies',
series: 'Series',
play: 'Play',
resume: 'Resume',
details: 'Details',
retry: 'Try again',
close: 'Close',
back: 'Back',
loading: 'Loading…',
loadingCatalog: 'Loading the archive…',
emptyCatalog: 'No published titles yet.',
noResults: 'No results found.',
networkError: 'Could not reach the server.',
preparing: 'Preparing this title for its first stream',
preparingHint: 'Keep this screen open; playback starts automatically.',
incompatibleTitle: 'This browser cannot play this video',
incompatibleBody: 'Use a recent Chrome or Firefox on a device with Media Source Extensions.',
playbackFailed: 'Playback ran into a problem',
pressPlay: 'Press Play to begin',
pause: 'Pause',
seekBack: 'Back 10 seconds',
seekForward: 'Forward 10 seconds',
fullscreen: 'Fullscreen',
exitFullscreen: 'Exit fullscreen',
subtitles: 'Subtitles',
audio: 'Audio',
subtitleOff: 'Off',
season: 'Season',
episode: 'Episode',
minutes: 'min',
loginTitle: 'Administrator sign in',
email: 'Email',
password: 'Password',
totp: 'One-time code (optional)',
login: 'Sign in',
logout: 'Sign out',
invalidLogin: 'Those credentials were not accepted.',
dashboard: 'System status',
catalogCount: 'Catalog titles',
publishedCount: 'Published',
reviewCount: 'Needs review',
activeJobs: 'Active jobs',
cache: 'Hot cache',
recentJobs: 'Recent jobs',
scanArchive: 'Scan archive',
scanStarted: 'Archive scan was queued.',
refresh: 'Refresh',
unavailable: 'Unavailable',
unsupported: 'Unsupported',
year: 'Year',
}
export type TranslationKey = keyof typeof fa
export function useI18n() {
const ui = useUiStore()
const language = computed(() => ui.preferences.uiLanguage)
const isRtl = computed(() => language.value === 'fa')
const t = (key: TranslationKey): string => (language.value === 'fa' ? fa[key] : en[key])
const localize = (value: { fa?: string | undefined; en?: string | undefined } | undefined, fallback = ''): string => {
if (!value) return fallback
return language.value === 'fa' ? value.fa ?? value.en ?? fallback : value.en ?? value.fa ?? fallback
}
return { language, isRtl, t, localize }
}
+17
View File
@@ -0,0 +1,17 @@
import '@fontsource/vazirmatn/400.css'
import '@fontsource/vazirmatn/700.css'
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from '@/App.vue'
import { router } from '@/router'
import { useUiStore } from '@/stores/ui'
import '@/styles.css'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.use(router)
app.mount('#app')
void useUiStore(pinia).hydrate()
+18
View File
@@ -0,0 +1,18 @@
import { createRouter, createWebHistory } from 'vue-router'
import AdminView from '@/views/AdminView.vue'
import CatalogView from '@/views/CatalogView.vue'
import SearchView from '@/views/SearchView.vue'
import TitleView from '@/views/TitleView.vue'
export const router = createRouter({
history: createWebHistory(),
scrollBehavior: (_to, _from, savedPosition) => savedPosition ?? { top: 0 },
routes: [
{ path: '/', name: 'catalog', component: CatalogView },
{ path: '/search', name: 'search', component: SearchView },
{ path: '/title/:slug', name: 'title', component: TitleView },
{ path: '/admin', name: 'admin', component: AdminView },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
})
+37
View File
@@ -0,0 +1,37 @@
import { beforeEach, describe, expect, it } from 'vitest'
import {
__resetMemoryStorageForTests,
readPreferences,
readProgress,
writePreferences,
writeProgress,
} from '@/storage/viewer-db'
describe('viewer storage', () => {
beforeEach(() => __resetMemoryStorageForTests())
it('persists viewer preferences without requiring an account', async () => {
await writePreferences({
uiLanguage: 'en',
subtitleLanguage: 'en',
audioLanguage: 'ja',
volume: 0.7,
muted: false,
})
await expect(readPreferences()).resolves.toMatchObject({ uiLanguage: 'en', subtitleLanguage: 'en', volume: 0.7 })
})
it('stores resume progress by media item', async () => {
await writeProgress({
mediaItemId: 'episode-1',
positionSeconds: 640,
durationSeconds: 1420,
updatedAt: 10,
completed: false,
})
await expect(readProgress('episode-1')).resolves.toMatchObject({ positionSeconds: 640, completed: false })
})
})
+104
View File
@@ -0,0 +1,104 @@
import type { ProgressRecord, ViewerPreferences } from '@/types'
const DATABASE_NAME = 'easy-stream-viewer'
const DATABASE_VERSION = 1
const SETTINGS_STORE = 'settings'
const PROGRESS_STORE = 'progress'
export const defaultPreferences: ViewerPreferences = {
uiLanguage: 'fa',
subtitleLanguage: 'fa',
audioLanguage: 'ja',
volume: 1,
muted: false,
}
let databasePromise: Promise<IDBDatabase | null> | undefined
let memoryPreferences: ViewerPreferences = { ...defaultPreferences }
const memoryProgress = new Map<string, ProgressRecord>()
function openDatabase(): Promise<IDBDatabase | null> {
if (databasePromise) return databasePromise
databasePromise = new Promise((resolve) => {
if (typeof indexedDB === 'undefined') {
resolve(null)
return
}
const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION)
request.onupgradeneeded = () => {
const database = request.result
if (!database.objectStoreNames.contains(SETTINGS_STORE)) {
database.createObjectStore(SETTINGS_STORE, { keyPath: 'key' })
}
if (!database.objectStoreNames.contains(PROGRESS_STORE)) {
database.createObjectStore(PROGRESS_STORE, { keyPath: 'mediaItemId' })
}
}
request.onsuccess = () => resolve(request.result)
request.onerror = () => resolve(null)
request.onblocked = () => resolve(null)
})
return databasePromise
}
async function getRecord<T>(storeName: string, key: IDBValidKey): Promise<T | undefined> {
const database = await openDatabase()
if (!database) return undefined
return new Promise((resolve) => {
const transaction = database.transaction(storeName, 'readonly')
const request = transaction.objectStore(storeName).get(key)
request.onsuccess = () => resolve(request.result as T | undefined)
request.onerror = () => resolve(undefined)
})
}
async function putRecord(storeName: string, value: unknown): Promise<void> {
const database = await openDatabase()
if (!database) return
await new Promise<void>((resolve) => {
const transaction = database.transaction(storeName, 'readwrite')
transaction.objectStore(storeName).put(value)
transaction.oncomplete = () => resolve()
transaction.onerror = () => resolve()
transaction.onabort = () => resolve()
})
}
export async function readPreferences(): Promise<ViewerPreferences> {
const result = await getRecord<{ key: string; value: Partial<ViewerPreferences> }>(SETTINGS_STORE, 'viewer')
if (!result) return { ...memoryPreferences }
memoryPreferences = { ...defaultPreferences, ...result.value }
return { ...memoryPreferences }
}
export async function writePreferences(preferences: ViewerPreferences): Promise<void> {
memoryPreferences = { ...preferences }
await putRecord(SETTINGS_STORE, { key: 'viewer', value: preferences })
}
export async function readProgress(mediaItemId: string): Promise<ProgressRecord | undefined> {
const result = await getRecord<ProgressRecord>(PROGRESS_STORE, mediaItemId)
return result ?? memoryProgress.get(mediaItemId)
}
export async function writeProgress(progress: ProgressRecord): Promise<void> {
memoryProgress.set(progress.mediaItemId, progress)
await putRecord(PROGRESS_STORE, progress)
}
export async function listProgress(): Promise<ProgressRecord[]> {
const database = await openDatabase()
if (!database) return [...memoryProgress.values()]
return new Promise((resolve) => {
const transaction = database.transaction(PROGRESS_STORE, 'readonly')
const request = transaction.objectStore(PROGRESS_STORE).getAll()
request.onsuccess = () => resolve(request.result as ProgressRecord[])
request.onerror = () => resolve([...memoryProgress.values()])
})
}
export function __resetMemoryStorageForTests(): void {
memoryPreferences = { ...defaultPreferences }
memoryProgress.clear()
}
+42
View File
@@ -0,0 +1,42 @@
import { defineStore } from 'pinia'
import { markRaw } from 'vue'
export interface PlayRequest {
mediaItemId: string
title: string
posterUrl?: string
}
export interface PlayerController {
start(request: PlayRequest): void
close(): void
}
export const usePlayerStore = defineStore('player', {
state: () => ({
visible: false,
controller: undefined as PlayerController | undefined,
current: undefined as PlayRequest | undefined,
}),
actions: {
register(controller: PlayerController) {
this.controller = markRaw(controller)
},
unregister(controller: PlayerController) {
if (this.controller === controller) this.controller = undefined
},
play(request: PlayRequest) {
this.current = request
this.visible = true
this.controller?.start(request)
},
close() {
this.controller?.close()
this.visible = false
},
},
})
+47
View File
@@ -0,0 +1,47 @@
import { defineStore } from 'pinia'
import { defaultPreferences, readPreferences, writePreferences } from '@/storage/viewer-db'
import type { UiLanguage, ViewerPreferences } from '@/types'
function applyDocumentLanguage(language: UiLanguage): void {
if (typeof document === 'undefined') return
document.documentElement.lang = language
document.documentElement.dir = language === 'fa' ? 'rtl' : 'ltr'
}
export const useUiStore = defineStore('ui', {
state: () => ({
preferences: { ...defaultPreferences } as ViewerPreferences,
hydrated: false,
}),
actions: {
async hydrate() {
this.preferences = await readPreferences()
this.hydrated = true
applyDocumentLanguage(this.preferences.uiLanguage)
},
async setLanguage(language: UiLanguage) {
this.preferences.uiLanguage = language
applyDocumentLanguage(language)
await writePreferences({ ...this.preferences })
},
async setSubtitleLanguage(language: string) {
this.preferences.subtitleLanguage = language
await writePreferences({ ...this.preferences })
},
async setAudioLanguage(language: string) {
this.preferences.audioLanguage = language
await writePreferences({ ...this.preferences })
},
async setVolume(volume: number, muted: boolean) {
this.preferences.volume = Math.min(1, Math.max(0, volume))
this.preferences.muted = muted
await writePreferences({ ...this.preferences })
},
},
})
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
import { afterEach, vi } from 'vitest'
Object.defineProperty(HTMLElement.prototype, 'offsetParent', {
configurable: true,
get() {
return this.parentElement
},
})
if (typeof CSS === 'undefined') {
vi.stubGlobal('CSS', { escape: (value: string) => value.replace(/["\\]/g, '\\$&') })
}
HTMLElement.prototype.scrollIntoView = vi.fn()
afterEach(() => {
document.body.innerHTML = ''
vi.restoreAllMocks()
})
+137
View File
@@ -0,0 +1,137 @@
export type UiLanguage = 'fa' | 'en'
export type MediaKind = 'MOVIE' | 'SERIES'
export interface LocalizedText {
fa?: string | undefined
en?: string | undefined
}
export interface CatalogItem {
id: string
mediaItemId: string
slug: string
kind: MediaKind
title: LocalizedText
overview: LocalizedText
posterUrl?: string | undefined
backdropUrl?: string | undefined
year?: number | undefined
runtimeSeconds?: number | undefined
seasonCount?: number | undefined
episodeCount?: number | undefined
compatibility?: string | undefined
playable: boolean
progress?: number | undefined
}
export interface EpisodeItem {
id: string
mediaItemId: string
number: number
seasonNumber: number
title: LocalizedText
overview: LocalizedText
posterUrl?: string | undefined
durationSeconds?: number | undefined
published: boolean
}
export interface SeasonItem {
number: number
title: LocalizedText
episodes: EpisodeItem[]
}
export interface TitleDetail extends CatalogItem {
genres: LocalizedText[]
seasons: SeasonItem[]
playableMediaItemId?: string | undefined
}
export interface CatalogPage {
items: CatalogItem[]
nextCursor?: string | undefined
total?: number | undefined
}
export type PlaybackState = 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED'
export type SubtitleDelivery = 'ASS_JASSUB' | 'WEBVTT' | 'OFF'
export interface PlaybackSubtitleTrack {
id: string
language: string
label: string
default: boolean
forced: boolean
assUrl?: string | undefined
vttUrl?: string | undefined
fonts: string[]
}
export interface PlaybackAudioTrack {
id: string
language: string
label: string
default: boolean
}
export interface PlaybackSession {
id: string
state: PlaybackState
mediaItemId: string
manifestUrl?: string | undefined
durationSeconds?: number | undefined
pollAfterMs: number
progress?: number | undefined
message?: string | undefined
reasonCode?: string | undefined
expiresAt?: string | undefined
videoCodec?: string | undefined
audioCodec?: string | undefined
subtitles: PlaybackSubtitleTrack[]
audioTracks: PlaybackAudioTrack[]
}
export interface ClientCapabilities {
nativeHls: boolean
mse: boolean
hlsJs: boolean
assRenderer: boolean
supportedCodecs: string[]
userAgent?: string | undefined
}
export interface ProgressRecord {
mediaItemId: string
positionSeconds: number
durationSeconds: number
updatedAt: number
completed: boolean
}
export interface ViewerPreferences {
uiLanguage: UiLanguage
subtitleLanguage: string
audioLanguage: string
volume: number
muted: boolean
}
export interface AdminJob {
id: string
type: string
state: string
progress?: number | undefined
message?: string | undefined
createdAt?: string | undefined
}
export interface AdminDashboard {
catalogCount: number
publishedCount: number
reviewCount: number
activeJobs: number
cacheUsedBytes?: number | undefined
cacheCapacityBytes?: number | undefined
jobs: AdminJob[]
}
+218
View File
@@ -0,0 +1,218 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { ApiError, api } from '@/api/client'
import LoadingState from '@/components/LoadingState.vue'
import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import type { AdminDashboard } from '@/types'
const root = ref<HTMLElement | null>(null)
const checking = ref(true)
const authenticated = ref(false)
const name = ref('')
const email = ref('')
const password = ref('')
const totp = ref('')
const submitting = ref(false)
const error = ref('')
const notice = ref('')
const dashboard = ref<AdminDashboard | null>(null)
const { t } = useI18n()
const { restoreFocus } = useSpatialNavigation(root, { restoreKey: 'admin-focus' })
let controller: AbortController | undefined
function formatBytes(bytes?: number): string {
if (bytes === undefined) return '—'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let value = bytes
let unit = units[0]
for (let index = 1; index < units.length && value >= 1024; index += 1) {
value /= 1024
unit = units[index]
}
return `${value.toFixed(value >= 10 ? 1 : 2)} ${unit}`
}
async function loadDashboard() {
controller?.abort()
controller = new AbortController()
error.value = ''
try {
dashboard.value = await api.adminDashboard(controller.signal)
void restoreFocus()
} catch (reason) {
if (reason instanceof ApiError && reason.status === 401) {
authenticated.value = false
dashboard.value = null
return
}
if ((reason as { name?: string }).name !== 'AbortError') {
error.value = reason instanceof Error ? reason.message : t('networkError')
}
}
}
async function checkSession() {
checking.value = true
try {
const session = await api.adminSession()
authenticated.value = session.authenticated
name.value = session.name ?? ''
if (authenticated.value) await loadDashboard()
} catch (reason) {
error.value = reason instanceof Error ? reason.message : t('networkError')
} finally {
checking.value = false
void restoreFocus()
}
}
async function login() {
submitting.value = true
error.value = ''
try {
await api.adminLogin(email.value.trim(), password.value, totp.value.trim() || undefined)
authenticated.value = true
password.value = ''
totp.value = ''
await loadDashboard()
} catch (reason) {
error.value = reason instanceof ApiError && (reason.status === 401 || reason.status === 403)
? t('invalidLogin')
: reason instanceof Error ? reason.message : t('networkError')
} finally {
submitting.value = false
}
}
async function logout() {
try {
await api.adminLogout()
} finally {
authenticated.value = false
dashboard.value = null
}
}
async function scanArchive() {
submitting.value = true
notice.value = ''
error.value = ''
try {
await api.startScan()
notice.value = t('scanStarted')
await loadDashboard()
} catch (reason) {
error.value = reason instanceof Error ? reason.message : t('networkError')
} finally {
submitting.value = false
}
}
onMounted(() => void checkSession())
onBeforeUnmount(() => controller?.abort())
</script>
<template>
<div ref="root" class="page-view admin-view">
<LoadingState v-if="checking" :label="t('loading')" />
<section v-else-if="!authenticated" class="login-panel">
<p class="eyebrow">Easy Stream</p>
<h1>{{ t('loginTitle') }}</h1>
<form @submit.prevent="login">
<label>
<span>{{ t('email') }}</span>
<input v-model="email" data-tv-focus data-focus-id="admin-email" type="email" autocomplete="username" required />
</label>
<label>
<span>{{ t('password') }}</span>
<input
v-model="password"
data-tv-focus
data-focus-id="admin-password"
type="password"
autocomplete="current-password"
required
/>
</label>
<label>
<span>{{ t('totp') }}</span>
<input
v-model="totp"
data-tv-focus
data-focus-id="admin-totp"
type="text"
inputmode="numeric"
autocomplete="one-time-code"
pattern="[0-9]*"
/>
</label>
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
<button class="primary-button large focus-ring" data-tv-focus data-focus-id="admin-login" :disabled="submitting">
{{ submitting ? t('loading') : t('login') }}
</button>
</form>
</section>
<template v-else>
<section class="admin-heading">
<div>
<p class="eyebrow">{{ name || 'Easy Stream' }}</p>
<h1>{{ t('dashboard') }}</h1>
</div>
<div class="admin-actions">
<button class="secondary-button focus-ring" type="button" data-tv-focus @click="loadDashboard">{{ t('refresh') }}</button>
<button
class="primary-button focus-ring"
type="button"
data-tv-focus
:disabled="submitting"
@click="scanArchive"
>
{{ t('scanArchive') }}
</button>
<button class="text-button focus-ring" type="button" data-tv-focus @click="logout">{{ t('logout') }}</button>
</div>
</section>
<p v-if="notice" class="notice" role="status">{{ notice }}</p>
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
<section v-if="dashboard" class="dashboard-grid">
<article class="stat-card"><span>{{ t('catalogCount') }}</span><strong>{{ dashboard.catalogCount }}</strong></article>
<article class="stat-card"><span>{{ t('publishedCount') }}</span><strong>{{ dashboard.publishedCount }}</strong></article>
<article class="stat-card"><span>{{ t('reviewCount') }}</span><strong>{{ dashboard.reviewCount }}</strong></article>
<article class="stat-card"><span>{{ t('activeJobs') }}</span><strong>{{ dashboard.activeJobs }}</strong></article>
<article class="stat-card cache-card">
<span>{{ t('cache') }}</span>
<strong>{{ formatBytes(dashboard.cacheUsedBytes) }}</strong>
<small v-if="dashboard.cacheCapacityBytes">/ {{ formatBytes(dashboard.cacheCapacityBytes) }}</small>
<progress
v-if="dashboard.cacheUsedBytes !== undefined && dashboard.cacheCapacityBytes"
:value="dashboard.cacheUsedBytes"
:max="dashboard.cacheCapacityBytes"
/>
</article>
</section>
<section v-if="dashboard?.jobs.length" class="jobs-panel">
<h2>{{ t('recentJobs') }}</h2>
<div class="jobs-table-wrap">
<table>
<thead><tr><th>Type</th><th>Status</th><th>Progress</th><th>Message</th></tr></thead>
<tbody>
<tr v-for="job in dashboard.jobs" :key="job.id">
<td>{{ job.type }}</td>
<td><span class="status-pill">{{ job.state }}</span></td>
<td>{{ job.progress === undefined ? '—' : `${Math.round(job.progress)}%` }}</td>
<td>{{ job.message ?? '—' }}</td>
</tr>
</tbody>
</table>
</div>
</section>
</template>
</div>
</template>
+116
View File
@@ -0,0 +1,116 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { api } from '@/api/client'
import LoadingState from '@/components/LoadingState.vue'
import MediaCard from '@/components/MediaCard.vue'
import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import { listProgress } from '@/storage/viewer-db'
import { usePlayerStore } from '@/stores/player'
import type { CatalogItem } from '@/types'
const root = ref<HTMLElement | null>(null)
const items = ref<CatalogItem[]>([])
const progress = ref<Record<string, number>>({})
const loading = ref(true)
const error = ref('')
const { localize, t } = useI18n()
const player = usePlayerStore()
const featured = computed(() => items.value.find((item) => item.playable) ?? items.value[0])
const { restoreFocus } = useSpatialNavigation(root, { restoreKey: 'catalog-focus' })
function playFeatured() {
const item = featured.value
if (!item?.playable || !item.mediaItemId) return
player.play({
mediaItemId: item.mediaItemId,
title: localize(item.title, item.slug),
...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
})
}
async function load() {
loading.value = true
error.value = ''
try {
const [catalog, storedProgress] = await Promise.all([api.catalog({ limit: 60 }), listProgress()])
items.value = catalog.items
progress.value = Object.fromEntries(storedProgress.map((entry) => [
entry.mediaItemId,
entry.durationSeconds > 0 ? (entry.positionSeconds / entry.durationSeconds) * 100 : 0,
]))
void restoreFocus()
} catch (reason) {
error.value = reason instanceof Error ? reason.message : t('networkError')
} finally {
loading.value = false
}
}
onMounted(() => void load())
</script>
<template>
<div ref="root" class="catalog-view">
<LoadingState v-if="loading" :label="t('loadingCatalog')" />
<section v-else-if="error" class="center-state error-state" role="alert">
<h1>{{ t('networkError') }}</h1>
<p>{{ error }}</p>
<button class="primary-button focus-ring" type="button" data-tv-focus @click="load">{{ t('retry') }}</button>
</section>
<template v-else-if="items.length">
<section
v-if="featured"
class="hero"
:style="featured.backdropUrl ? { backgroundImage: `url(${featured.backdropUrl})` } : undefined"
>
<div class="hero-scrim" />
<div class="hero-content">
<p class="eyebrow">{{ t('featured') }}</p>
<h1>{{ localize(featured.title, featured.slug) }}</h1>
<p v-if="localize(featured.overview)" class="hero-overview">{{ localize(featured.overview) }}</p>
<div class="hero-actions">
<button
class="primary-button large focus-ring"
type="button"
data-tv-focus
data-focus-id="featured-play"
:disabled="!featured.playable"
@click="playFeatured"
>
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
{{ t('play') }}
</button>
<RouterLink
class="secondary-button large focus-ring"
data-tv-focus
data-focus-id="featured-info"
:to="{ name: 'title', params: { slug: featured.slug } }"
>
{{ t('details') }}
</RouterLink>
</div>
</div>
</section>
<section class="catalog-section" aria-labelledby="catalog-heading">
<h2 id="catalog-heading">{{ t('allTitles') }}</h2>
<div class="media-grid">
<MediaCard
v-for="item in items"
:key="item.id"
:item="item"
:progress="progress[item.mediaItemId]"
/>
</div>
</section>
</template>
<section v-else class="center-state">
<h1>{{ t('emptyCatalog') }}</h1>
</section>
</div>
</template>
+97
View File
@@ -0,0 +1,97 @@
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api } from '@/api/client'
import LoadingState from '@/components/LoadingState.vue'
import MediaCard from '@/components/MediaCard.vue'
import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import type { CatalogItem } from '@/types'
const route = useRoute()
const router = useRouter()
const root = ref<HTMLElement | null>(null)
const input = ref<HTMLInputElement | null>(null)
const term = ref(typeof route.query.q === 'string' ? route.query.q : '')
const items = ref<CatalogItem[]>([])
const loading = ref(false)
const searched = ref(Boolean(term.value))
const error = ref('')
const { t } = useI18n()
const { restoreFocus } = useSpatialNavigation(root, { restoreKey: 'search-focus' })
let timer: ReturnType<typeof setTimeout> | undefined
let controller: AbortController | undefined
async function search() {
controller?.abort()
const query = term.value.trim()
void router.replace({ name: 'search', query: query ? { q: query } : {} })
if (!query) {
items.value = []
searched.value = false
loading.value = false
return
}
controller = new AbortController()
loading.value = true
searched.value = true
error.value = ''
try {
items.value = (await api.search(query, controller.signal)).items
void restoreFocus()
} catch (reason) {
if ((reason as { name?: string }).name !== 'AbortError') {
error.value = reason instanceof Error ? reason.message : t('networkError')
}
} finally {
loading.value = false
}
}
watch(term, () => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => void search(), 300)
})
onMounted(async () => {
if (term.value) await search()
await nextTick()
input.value?.focus()
})
onBeforeUnmount(() => {
controller?.abort()
if (timer) clearTimeout(timer)
})
</script>
<template>
<div ref="root" class="page-view search-view">
<section class="page-heading">
<p class="eyebrow">Easy Stream</p>
<h1>{{ t('search') }}</h1>
<div class="large-search">
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="m21 21-4.35-4.35m2.35-5.65a8 8 0 1 1-16 0 8 8 0 0 1 16 0Z" /></svg>
<input
ref="input"
v-model="term"
type="search"
data-tv-focus
data-focus-id="search-input"
:placeholder="t('searchPlaceholder')"
:aria-label="t('search')"
/>
</div>
</section>
<LoadingState v-if="loading" :label="t('loading')" />
<section v-else-if="error" class="center-state error-state" role="alert">
<p>{{ error }}</p>
<button class="primary-button focus-ring" type="button" data-tv-focus @click="search">{{ t('retry') }}</button>
</section>
<section v-else-if="items.length" class="catalog-section">
<div class="media-grid"><MediaCard v-for="item in items" :key="item.id" :item="item" /></div>
</section>
<section v-else-if="searched" class="center-state"><h2>{{ t('noResults') }}</h2></section>
</div>
</template>
+132
View File
@@ -0,0 +1,132 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api } from '@/api/client'
import LoadingState from '@/components/LoadingState.vue'
import { useSpatialNavigation } from '@/composables/spatial-navigation'
import { useI18n } from '@/i18n'
import { usePlayerStore } from '@/stores/player'
import type { EpisodeItem, TitleDetail } from '@/types'
const route = useRoute()
const router = useRouter()
const root = ref<HTMLElement | null>(null)
const detail = ref<TitleDetail | null>(null)
const loading = ref(true)
const error = ref('')
const player = usePlayerStore()
const { localize, t } = useI18n()
const { restoreFocus } = useSpatialNavigation(root, {
restoreKey: 'title-focus',
onBack: () => router.back(),
})
let controller: AbortController | undefined
const title = computed(() => detail.value ? localize(detail.value.title, detail.value.slug) : '')
const canPlayTitle = computed(() => Boolean(detail.value?.playable && (detail.value.playableMediaItemId ?? detail.value.mediaItemId)))
function playTitle() {
const mediaItemId = detail.value?.playableMediaItemId ?? detail.value?.mediaItemId
if (!detail.value || !mediaItemId) return
player.play({
mediaItemId,
title: title.value,
...(detail.value.posterUrl ? { posterUrl: detail.value.posterUrl } : {}),
})
}
function playEpisode(episode: EpisodeItem) {
player.play({
mediaItemId: episode.mediaItemId,
title: `${title.value} · ${t('episode')} ${episode.number}`,
...(episode.posterUrl ? { posterUrl: episode.posterUrl } : {}),
})
}
async function load() {
controller?.abort()
controller = new AbortController()
loading.value = true
error.value = ''
try {
detail.value = await api.title(String(route.params.slug), controller.signal)
void restoreFocus()
} catch (reason) {
if ((reason as { name?: string }).name !== 'AbortError') {
error.value = reason instanceof Error ? reason.message : t('networkError')
}
} finally {
loading.value = false
}
}
watch(() => route.params.slug, () => void load(), { immediate: true })
onBeforeUnmount(() => controller?.abort())
</script>
<template>
<div ref="root" class="title-view">
<LoadingState v-if="loading" :label="t('loading')" />
<section v-else-if="error" class="center-state error-state" role="alert">
<p>{{ error }}</p>
<button class="primary-button focus-ring" type="button" data-tv-focus @click="load">{{ t('retry') }}</button>
</section>
<template v-else-if="detail">
<section
class="detail-hero"
:style="detail.backdropUrl ? { backgroundImage: `url(${detail.backdropUrl})` } : undefined"
>
<div class="hero-scrim" />
<button class="back-button focus-ring" type="button" data-tv-focus data-focus-id="detail-back" @click="router.back()">
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6" /></svg>
{{ t('back') }}
</button>
<div class="detail-copy">
<p class="eyebrow">{{ detail.kind === 'SERIES' ? t('series') : t('movies') }}</p>
<h1>{{ title }}</h1>
<div class="detail-meta">
<span v-if="detail.year">{{ detail.year }}</span>
<span v-if="detail.runtimeSeconds">{{ Math.ceil(detail.runtimeSeconds / 60) }} {{ t('minutes') }}</span>
<span v-for="genre in detail.genres" :key="localize(genre)">{{ localize(genre) }}</span>
</div>
<p v-if="localize(detail.overview)" class="hero-overview">{{ localize(detail.overview) }}</p>
<button
v-if="canPlayTitle"
class="primary-button large focus-ring"
type="button"
data-tv-focus
data-focus-id="detail-play"
@click="playTitle"
>
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
{{ t('play') }}
</button>
</div>
</section>
<section v-for="season in detail.seasons" :key="season.number" class="episodes-section">
<h2>{{ localize(season.title, `${t('season')} ${season.number}`) }}</h2>
<div class="episode-list">
<button
v-for="episode in season.episodes"
:key="episode.id"
class="episode-row focus-ring"
type="button"
data-tv-focus
:data-focus-id="`episode-${episode.id}`"
:disabled="!episode.published"
@click="playEpisode(episode)"
>
<span class="episode-number">{{ episode.number }}</span>
<span class="episode-copy">
<strong>{{ localize(episode.title, `${t('episode')} ${episode.number}`) }}</strong>
<small v-if="episode.durationSeconds">{{ Math.ceil(episode.durationSeconds / 60) }} {{ t('minutes') }}</small>
</span>
<span class="episode-play" aria-hidden="true">▶</span>
</button>
</div>
</section>
</template>
</div>
</template>