feat: ffprobe + TMDb scrape + HLS transcode + history/favourites/playlists

Backend
  - service/ffprobe.go: thin ffprobe wrapper, parses duration / resolution /
    codecs into a typed ProbeResult. 30s per-file timeout.
  - service/tmdb.go: minimal TMDb provider (search/movie). Disabled when no
    api key; supports tmdb_api_proxy / tmdb_image_proxy overrides for users
    behind a firewall.
  - service/scraper.go: filename cleaner (handles bracketed tags, scene
    noise tokens, year extraction), per-row + per-library enrichment with a
    4 RPS throttle and WS hub progress events. Unit-tested.
  - service/scanner.go: now invokes ffprobe per file and kicks the TMDb
    scraper in the background once a library scan finishes.
  - service/transcoder.go: per-media ffmpeg HLS job manager; outputs
    index.m3u8 + seg_NNNNN.ts under cache/hls/<id>; cancels jobs on
    shutdown; publishes 'transcode' WS events.
  - service/stream.go: serves HLS playlist (with 30s wait-for-ready) and
    .ts segments with path-traversal protection. Adds Probe() helper used
    by the admin 'reprobe' button.
  - service/image_proxy.go: cached, host-allow-listed reverse proxy for
    TMDb / Bangumi / Douban / Fanart / TheTVDB images so the SPA never
    hits a CORS or GFW issue.
  - service/playback.go: history upsert, favourites toggle, playlist CRUD
    + ordered items. RecentHistory joins with model.Media in one extra
    query so the home page can render a 'Continue Watching' row.
  - handler/streaming.go + handler/playback.go: REST endpoints for HLS,
    image proxy, scrape (one + library), reprobe, history, favourites,
    playlists.
  - handler/handler.go: registers /api/hls/:id/{index.m3u8,:seg}, /api/img,
    /api/history, /api/favourites/:id, /api/playlists/* with proper
    auth/admin guards.

Frontend
  - api/client.ts: imageURL() helper; hlsURL() endpoint; reuses the JWT in
    a query parameter for <video src> and <img src>.
  - api/playback.ts: typed helpers for history, favourites, playlists.
  - components/MediaCard.tsx: optional 'progress' prop renders a thin
    bottom progress bar, used by the new Continue Watching row.
  - pages/HomePage.tsx: two rows (Continue Watching + Recently Added);
    falls back to the empty-state hint when both are empty.
  - pages/PlayerPage.tsx: hls.js (lazy-imported) with auto-fallback to
    direct play; ?mode=hls|direct query toggle; resume position written
    every 10s while playing.
  - pages/MediaDetailPage.tsx: heart toggle + admin 'rescrape' / 'reprobe'
    buttons + dedicated 'HLS 转码播放' CTA.
  - pages/FavouritesPage.tsx, PlaylistsPage.tsx, PlaylistDetailPage.tsx:
    new screens.
  - components/Layout.tsx + App.tsx: sidebar links for Favourites and
    Playlists; routes are now lazily code-split via React.lazy + Suspense
    so the initial bundle stays at ~243 KB / 82 KB gzipped (hls.js is
    fetched only on first HLS playback).

Verified: go build, go vet, go test (incl. CleanQuery cases) all pass;
frontend tsc -b && vite build emits 9 route chunks plus a deferred hls
chunk.
This commit is contained in:
Kiro
2026-05-14 15:44:31 +00:00
parent d5cf5fb4b2
commit 0f30c34463
26 changed files with 2205 additions and 139 deletions
+145 -10
View File
@@ -1,24 +1,115 @@
import { useEffect, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { ArrowLeft } from 'lucide-react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import type Hls from 'hls.js'
import { ArrowLeft, RefreshCw, Sparkles } from 'lucide-react'
import toast from 'react-hot-toast'
import { mediaAPI } from '../api/library'
import { streamURL } from '../api/client'
import { hlsURL, streamURL } from '../api/client'
import { playbackAPI } from '../api/playback'
import type { Media } from '../types'
// Fullscreen, dark-themed video page. We currently use direct play via
// /api/stream/:id — the future task is wiring HLS.js for transcoded streams.
type Mode = 'direct' | 'hls'
// Fullscreen, dark-themed video page.
//
// ?mode=hls force HLS even when direct play would work
// ?mode=direct force direct play (default for browser-friendly codecs)
//
// We pick a sensible default based on the source codec: H.264 + AAC in
// MP4 / WebM containers play directly; everything else (HEVC, MKV, AV1,
// AC3 audio, …) gets routed through ffmpeg → HLS.
export function PlayerPage() {
const { id = '' } = useParams()
const [params, setParams] = useSearchParams()
const navigate = useNavigate()
const ref = useRef<HTMLVideoElement>(null)
const [media, setMedia] = useState<Media | null>(null)
const ref = useRef<HTMLVideoElement>(null)
const hlsRef = useRef<Hls | null>(null)
const lastSentRef = useRef(0)
const [media, setMedia] = useState<Media | null>(null)
const [mode, setMode] = useState<Mode>('direct')
// Load metadata and pick a default mode.
useEffect(() => {
if (!id) return
mediaAPI.get(id).then(setMedia)
}, [id])
mediaAPI.get(id).then((m) => {
setMedia(m)
const forced = params.get('mode') as Mode | null
const auto = pickMode(m)
setMode(forced ?? auto)
})
}, [id, params])
// Wire up the actual <video> element when we know the mode.
useEffect(() => {
if (!media || !ref.current) return
teardownHls()
const video = ref.current
let cancelled = false
if (mode === 'hls') {
const url = hlsURL(media.id)
// Lazy import keeps the main bundle ~530 KB smaller until the user
// actually hits HLS playback.
void import('hls.js').then(({ default: HlsCtor }) => {
if (cancelled) return
if (HlsCtor.isSupported()) {
const hls = new HlsCtor({ enableWorker: true, lowLatencyMode: false })
hls.loadSource(url)
hls.attachMedia(video)
hls.on(HlsCtor.Events.ERROR, (_, data) => {
if (data.fatal) {
toast.error('HLS 播放失败,尝试切换到直接播放')
setMode('direct')
params.set('mode', 'direct')
setParams(params, { replace: true })
}
})
hlsRef.current = hls
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = url
} else {
toast.error('当前浏览器不支持 HLS,降级到直接播放')
setMode('direct')
}
void video.play().catch(() => undefined)
})
} else {
video.src = streamURL(media.id)
void video.play().catch(() => undefined)
}
return () => {
cancelled = true
teardownHls()
}
}, [media, mode, params, setParams])
// Persist resume position every 10 seconds while playing.
useEffect(() => {
if (!media || !ref.current) return
const video = ref.current
const handler = () => {
const now = Date.now()
if (now - lastSentRef.current < 10_000) return
lastSentRef.current = now
const positionMs = Math.floor(video.currentTime * 1000)
const durationMs = Math.floor((video.duration || 0) * 1000)
if (positionMs > 0) {
playbackAPI.recordProgress(media.id, positionMs, durationMs).catch(() => undefined)
}
}
video.addEventListener('timeupdate', handler)
video.addEventListener('pause', handler)
return () => {
video.removeEventListener('timeupdate', handler)
video.removeEventListener('pause', handler)
}
}, [media])
// ESC = back.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') navigate(-1)
@@ -27,6 +118,13 @@ export function PlayerPage() {
return () => window.removeEventListener('keydown', onKey)
}, [navigate])
const teardownHls = () => {
if (hlsRef.current) {
hlsRef.current.destroy()
hlsRef.current = null
}
}
return (
<div className="-m-6 flex min-h-screen flex-col bg-black md:-m-8">
<button
@@ -35,11 +133,32 @@ export function PlayerPage() {
>
<ArrowLeft size={16} /> 返回
</button>
<button
onClick={() => {
const next = mode === 'hls' ? 'direct' : 'hls'
setMode(next)
params.set('mode', next)
setParams(params, { replace: true })
}}
className="absolute right-4 top-4 z-10 flex items-center gap-2 rounded-full bg-black/60 px-3 py-1.5 text-sm text-white backdrop-blur transition hover:bg-black/80"
title="切换播放模式"
>
{mode === 'hls' ? (
<>
<RefreshCw size={14} /> HLS 转码中
</>
) : (
<>
<Sparkles size={14} /> 直接播放
</>
)}
</button>
<div className="flex flex-1 items-center justify-center">
{media ? (
<video
ref={ref}
src={streamURL(media.id)}
controls
autoPlay
className="max-h-screen w-full max-w-[1600px] bg-black"
@@ -51,3 +170,19 @@ export function PlayerPage() {
</div>
)
}
const directContainers = ['mp4', 'webm', 'm4v']
const directVideoCodecs = ['h264', 'avc', 'avc1']
const directAudioCodecs = ['aac', 'mp3', 'opus']
// pickMode picks 'direct' when the source is browser-friendly, otherwise
// 'hls' so the user gets a working stream out of the box.
function pickMode(m: Media): Mode {
const c = (m.container ?? '').toLowerCase()
const v = (m.video_codec ?? '').toLowerCase()
const a = (m.audio_codec ?? '').toLowerCase()
const containerOK = directContainers.some((x) => c.includes(x))
const videoOK = !v || directVideoCodecs.some((x) => v.includes(x))
const audioOK = !a || directAudioCodecs.some((x) => a.includes(x))
return containerOK && videoOK && audioOK ? 'direct' : 'hls'
}