feat: hwaccel + Fanart/TheTVDB + AI + Discover + NFO + Tasks + Recycle bin

Backend
  - service/transcoder.go: encoder selector (software / nvenc / qsv /
    vaapi) with proper hwaccel + scale_* filters per encoder; configurable
    bitrate/preset/height/segment-seconds via transcoder.* config; new
    Active() snapshot + ActiveJob struct for the Tasks panel; unit-tested
    via buildFFmpegArgs(...).
  - service/thetvdb.go: TheTVDB v4 provider — login() caches the JWT for
    24h, SearchSeries() returns Match struct.
  - service/fanart.go: Fanart.tv provider — high-res movie artwork keyed
    by TMDb id; used to upgrade poster/backdrop after a successful match.
  - service/scraper.go: provider chain reworked — anime → Bangumi, tv →
    TheTVDB, default → TMDb, with optional Fanart upgrade post-match.
  - service/discover.go: TMDb /trending/movie/day + /movie/popular for
    the Discover rail.
  - service/ai.go: OpenAI-compatible client. SmartSearch() turns a free-
    form query into a structured SearchIntent JSON; Recommend() emits a
    short list of titles given the user's history. Disabled when
    ai.api_key is empty.
  - service/nfo.go: per-movie .nfo writer (Kodi/Jellyfin schema) +
    library-scope batch exporter.
  - service/media.go: SoftDelete / Restore / Purge / ListRecycleBin
    helpers backed by gorm Unscoped().
  - service/service.go: container wires Fanart, TheTVDB, Discover, AI,
    NFO; everything still tears down cleanly via Close().
  - config: new transcoder.* section (encoder, preset, video_bitrate,
    max_rate, buf_size, max_height, segment_seconds) with sensible
    defaults.

Handlers / routes
  - new files: discover.go, recycle.go, nfo.go, ai.go, tasks.go.
  - registers GET /tasks, /discover/{trending,popular},
    /ai/{status,search,recommend}; admin-only GET /recycle and
    DELETE/POST /media/:id (soft delete / restore / purge); admin-only
    POST /media/:id/nfo and /libraries/:id/nfo.

Frontend
  - new pages: DiscoverPage, TasksPage, RecycleBinPage; SearchPage gains
    an optional AI smart-search toggle that calls /api/ai/search.
  - MediaDetailPage gains admin actions for 导出 NFO and 移至回收站.
  - new api/ helpers: ai.ts, discover.ts, recycle.ts, tasks.ts.
  - App.tsx routes /discover, /tasks, /recycle (last two admin-only).
  - Layout sidebar groups now include Discover + Tasks + Recycle Bin.

Docker / config
  - Dockerfile: adds intel-media-driver / libva-utils / mesa-va-gallium
    so QSV + VAAPI work out of the box on Intel iGPUs.
  - docker-compose.yml: documents devices + group_add + nvidia runtime
    overrides for hardware transcoding.

Verified: go build, go vet, go test (incl. new TestBuildFFmpegArgs across
software / nvenc / qsv / vaapi encoder profiles); tsc -b && vite build
emits 22 route chunks plus the deferred hls chunk; main bundle 248 KB /
83 KB gzipped.
This commit is contained in:
Kiro
2026-05-14 16:22:08 +00:00
parent 7bd6bcfb1b
commit 8824638efb
32 changed files with 1795 additions and 83 deletions
+24 -1
View File
@@ -40,8 +40,14 @@ const ProfilePage = lazy(() =>
import('./pages/ProfilePage').then((m) => ({ default: m.ProfilePage })),
)
const StatsPage = lazy(() => import('./pages/StatsPage').then((m) => ({ default: m.StatsPage })))
const DiscoverPage = lazy(() =>
import('./pages/DiscoverPage').then((m) => ({ default: m.DiscoverPage })),
)
const TasksPage = lazy(() => import('./pages/TasksPage').then((m) => ({ default: m.TasksPage })))
const RecycleBinPage = lazy(() =>
import('./pages/RecycleBinPage').then((m) => ({ default: m.RecycleBinPage })),
)
// Fallback shown while a chunk is loading.
const Loading = () => <p className="px-6 py-8 text-slate-500">加载中…</p>
export default function App() {
@@ -59,6 +65,7 @@ export default function App() {
>
<Route index element={<HomePage />} />
<Route path="library/:id" element={<LibraryPage />} />
<Route path="discover" element={<DiscoverPage />} />
<Route path="search" element={<SearchPage />} />
<Route path="favourites" element={<FavouritesPage />} />
<Route path="playlists" element={<PlaylistsPage />} />
@@ -68,6 +75,22 @@ export default function App() {
<Route path="downloads" element={<DownloadsPage />} />
<Route path="subscriptions" element={<SubscriptionsPage />} />
<Route path="profile" element={<ProfilePage />} />
<Route
path="tasks"
element={
<RequireAdmin>
<TasksPage />
</RequireAdmin>
}
/>
<Route
path="recycle"
element={
<RequireAdmin>
<RecycleBinPage />
</RequireAdmin>
}
/>
<Route
path="stats"
element={
+25
View File
@@ -0,0 +1,25 @@
import { api } from './client'
import type { Media } from '../types'
export interface SearchIntent {
query: string
year?: number
genre?: string
type?: string
sort?: string
language?: string
}
export const aiAPI = {
status: () =>
api
.get<{ enabled: boolean; provider: string; model: string }>('/ai/status')
.then((r) => r.data),
smartSearch: (query: string) =>
api
.post<{ intent: SearchIntent; items: Media[] }>('/ai/search', { query })
.then((r) => r.data),
recommend: () => api.get<{ titles: string[] }>('/ai/recommend').then((r) => r.data.titles),
}
+21
View File
@@ -0,0 +1,21 @@
import { api } from './client'
import type { Media } from '../types'
// TMDb-derived "Match" rows used by trending/popular rails. We re-use the
// Media interface — only TMDb id / poster / overview are populated.
export interface DiscoverItem extends Partial<Media> {
tmdb_id: number
title: string
overview: string
poster_url: string
backdrop_url: string
year: number
rating: number
}
export const discoverAPI = {
trending: () =>
api.get<{ items: DiscoverItem[] }>('/discover/trending').then((r) => r.data.items),
popular: () =>
api.get<{ items: DiscoverItem[] }>('/discover/popular').then((r) => r.data.items),
}
+18
View File
@@ -0,0 +1,18 @@
import { api } from './client'
import type { Media } from '../types'
export const recycleAPI = {
list: () => api.get<{ items: Media[] }>('/recycle').then((r) => r.data.items),
softDelete: (id: string) => api.delete(`/media/${id}`).then((r) => r.data),
restore: (id: string) => api.post(`/media/${id}/restore`).then((r) => r.data),
purge: (id: string) => api.delete(`/media/${id}/purge`).then((r) => r.data),
exportNFO: (id: string) =>
api.post<{ path: string }>(`/media/${id}/nfo`).then((r) => r.data),
exportLibraryNFO: (id: string) =>
api.post<{ written: number }>(`/libraries/${id}/nfo`).then((r) => r.data),
}
+18
View File
@@ -0,0 +1,18 @@
import { api } from './client'
import type { QBitTorrent } from '../types'
export interface ActiveTranscode {
media_id: string
encoder: string
started_at: string
playlist_ok: boolean
}
export interface TasksSnapshot {
transcodes: ActiveTranscode[]
torrents: QBitTorrent[] | null
}
export const tasksAPI = {
snapshot: () => api.get<TasksSnapshot>('/tasks').then((r) => r.data),
}
+6
View File
@@ -3,14 +3,17 @@ import { Link, NavLink, Outlet, useNavigate } from 'react-router-dom'
import {
Activity,
CloudDownload,
Compass,
Film,
Heart,
Home,
ListChecks,
ListMusic,
LogOut,
Rss,
Search,
Settings,
Trash2,
Library as LibraryIcon,
User as UserIcon,
} from 'lucide-react'
@@ -48,6 +51,7 @@ export function Layout() {
<nav className="flex-1 space-y-1 overflow-y-auto pr-1">
<SidebarLink to="/" icon={<Home size={18} />} label="首页" end />
<SidebarLink to="/discover" icon={<Compass size={18} />} label="发现" />
<SidebarLink to="/search" icon={<Search size={18} />} label="搜索" />
<SidebarLink to="/favourites" icon={<Heart size={18} />} label="收藏" />
<SidebarLink to="/playlists" icon={<ListMusic size={18} />} label="播放列表" />
@@ -83,7 +87,9 @@ export function Layout() {
<div className="mt-6 px-2 text-xs uppercase tracking-wider text-slate-500">
管理
</div>
<SidebarLink to="/tasks" icon={<ListChecks size={18} />} label="实时任务" />
<SidebarLink to="/stats" icon={<Activity size={18} />} label="运行状态" />
<SidebarLink to="/recycle" icon={<Trash2 size={18} />} label="回收站" />
<SidebarLink to="/admin" icon={<Settings size={18} />} label="管理后台" />
</>
)}
+98
View File
@@ -0,0 +1,98 @@
import { useEffect, useState } from 'react'
import { Sparkles } from 'lucide-react'
import { discoverAPI, type DiscoverItem } from '../api/discover'
import { imageURL } from '../api/client'
// DiscoverPage shows TMDb trending + popular rails. Rows are empty when
// no TMDb API key is configured (the backend simply returns []).
export function DiscoverPage() {
const [trending, setTrending] = useState<DiscoverItem[]>([])
const [popular, setPopular] = useState<DiscoverItem[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
Promise.all([
discoverAPI.trending().catch(() => [] as DiscoverItem[]),
discoverAPI.popular().catch(() => [] as DiscoverItem[]),
])
.then(([t, p]) => {
setTrending(t)
setPopular(p)
})
.finally(() => setLoading(false))
}, [])
return (
<div className="space-y-10">
<header className="flex items-center gap-3">
<Sparkles className="h-6 w-6 text-primary-400" />
<div>
<h1 className="font-display text-3xl font-bold text-white">发现</h1>
<p className="text-sm text-slate-400">
来自 TMDb 的当日热门与流行榜单(需在 secrets.tmdb_api_key 配置 API Key)。
</p>
</div>
</header>
{loading && <p className="text-slate-500">加载中…</p>}
{trending.length > 0 && <Row title="今日趋势" items={trending} />}
{popular.length > 0 && <Row title="热门电影" items={popular} />}
{!loading && trending.length === 0 && popular.length === 0 && (
<div className="glass-panel">
<p className="text-slate-300">
还没有可用的发现数据。前往 <span className="text-primary-400">管理后台 → 设置</span>
,在 secrets.tmdb_api_key 中填写一个有效的 TMDb API Key。
</p>
</div>
)}
</div>
)
}
function Row({ title, items }: { title: string; items: DiscoverItem[] }) {
return (
<section className="space-y-3">
<h2 className="font-display text-xl font-semibold text-white">{title}</h2>
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{items.map((m) => (
<DiscoverCard key={m.tmdb_id} item={m} />
))}
</div>
</section>
)
}
function DiscoverCard({ item }: { item: DiscoverItem }) {
return (
<div className="overflow-hidden rounded-xl border border-white/5 bg-surface-800/60">
<div className="aspect-[2/3] w-full bg-surface-900">
{item.poster_url ? (
<img
src={imageURL(item.poster_url)}
alt={item.title}
loading="lazy"
referrerPolicy="no-referrer"
className="h-full w-full object-cover"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-slate-600">
无海报
</div>
)}
</div>
<div className="px-3 py-2">
<p className="truncate text-sm font-medium text-white">{item.title}</p>
<div className="flex items-center justify-between text-xs text-slate-400">
{item.year > 0 && <span>{item.year}</span>}
{item.rating > 0 && (
<span className="rounded border border-yellow-400/40 px-1.5 py-0.5 text-yellow-400">
★ {item.rating.toFixed(1)}
</span>
)}
</div>
</div>
</div>
)
}
+34 -2
View File
@@ -1,10 +1,11 @@
import { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { Heart, Play, RefreshCw, Sparkles } from 'lucide-react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { FileText, Heart, Play, RefreshCw, Sparkles, Trash2 } from 'lucide-react'
import toast from 'react-hot-toast'
import { mediaAPI } from '../api/library'
import { playbackAPI } from '../api/playback'
import { recycleAPI } from '../api/recycle'
import { imageURL } from '../api/client'
import { useAuthStore } from '../stores/auth'
import { api } from '../api/client'
@@ -39,6 +40,7 @@ function fmtSize(bytes: number): string {
// - Re-probe (admin only, refreshes ffprobe metadata)
export function MediaDetailPage() {
const { id = '' } = useParams()
const navigate = useNavigate()
const role = useAuthStore((s) => s.user?.role)
const [media, setMedia] = useState<Media | null>(null)
const [favourite, setFavourite] = useState(false)
@@ -81,6 +83,27 @@ export function MediaDetailPage() {
await refresh()
}
const exportNFO = async () => {
if (!media) return
try {
const r = await recycleAPI.exportNFO(media.id)
toast.success(`NFO 已写入 ${r.path}`)
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ??
'导出失败'
toast.error(msg)
}
}
const softDelete = async () => {
if (!media) return
if (!confirm(`将「${media.title}」移至回收站? (磁盘文件保留)`)) return
await recycleAPI.softDelete(media.id)
toast.success('已移至回收站')
navigate(-1)
}
if (loading) return <p className="text-slate-500">加载中…</p>
if (!media) return <p className="text-slate-500">媒体不存在</p>
@@ -149,6 +172,15 @@ export function MediaDetailPage() {
<button onClick={reprobe} className="neon-button">
<RefreshCw size={16} /> 重新探测
</button>
<button onClick={exportNFO} className="neon-button">
<FileText size={16} /> 导出 NFO
</button>
<button
onClick={softDelete}
className="neon-button !border-red-400/40 !bg-red-400/10 !text-red-400"
>
<Trash2 size={16} /> 移至回收站
</button>
</>
)}
</div>
+80
View File
@@ -0,0 +1,80 @@
import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { RotateCcw, Trash2 } from 'lucide-react'
import { recycleAPI } from '../api/recycle'
import type { Media } from '../types'
export function RecycleBinPage() {
const [items, setItems] = useState<Media[]>([])
const [loading, setLoading] = useState(true)
const refresh = () =>
recycleAPI
.list()
.then(setItems)
.finally(() => setLoading(false))
useEffect(() => {
refresh().catch(() => undefined)
}, [])
return (
<div className="space-y-6">
<h1 className="font-display text-3xl font-bold text-white">回收站</h1>
<p className="text-sm text-slate-400">
软删除的媒体保留在数据库中,可以恢复。彻底删除不会移除磁盘上的文件,只会从数据库清除条目。
</p>
{loading && <p className="text-slate-500">加载中…</p>}
{!loading && items.length === 0 && <p className="text-slate-400">回收站为空。</p>}
{items.length > 0 && (
<div className="glass-panel">
<table className="w-full text-left text-sm">
<thead className="text-xs uppercase tracking-wider text-slate-500">
<tr>
<th className="py-2">标题</th>
<th>路径</th>
<th className="text-right">操作</th>
</tr>
</thead>
<tbody>
{items.map((m) => (
<tr key={m.id} className="border-t border-white/5">
<td className="py-2 text-white">{m.title}</td>
<td className="max-w-md truncate text-slate-400" title={m.path}>
{m.path}
</td>
<td className="space-x-2 py-2 text-right">
<button
className="rounded border border-primary-400/40 px-2 py-1 text-xs text-primary-400 hover:bg-primary-400/10"
onClick={async () => {
await recycleAPI.restore(m.id)
toast.success('已恢复')
await refresh()
}}
>
<RotateCcw size={12} />
</button>
<button
className="rounded border border-red-400/40 px-2 py-1 text-xs text-red-400 hover:bg-red-400/10"
onClick={async () => {
if (!confirm(`彻底删除「${m.title}」? (磁盘文件保留)`)) return
await recycleAPI.purge(m.id)
toast.success('已彻底删除')
await refresh()
}}
>
<Trash2 size={12} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)
}
+84 -12
View File
@@ -1,36 +1,108 @@
import { ChangeEvent, useEffect, useState } from 'react'
import { ChangeEvent, FormEvent, useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { Sparkles } from 'lucide-react'
import { aiAPI, type SearchIntent } from '../api/ai'
import { mediaAPI } from '../api/library'
import { MediaCard } from '../components/MediaCard'
import type { Media } from '../types'
// Search-as-you-type with a 300ms debounce.
// SearchPage runs a fast LIKE search by default, with an optional AI
// "smart search" toggle that calls /api/ai/search to produce a structured
// intent before executing the library lookup.
export function SearchPage() {
const [q, setQ] = useState('')
const [items, setItems] = useState<Media[]>([])
const [loading, setLoading] = useState(false)
const [aiOn, setAiOn] = useState(false)
const [aiAvailable, setAiAvailable] = useState(false)
const [intent, setIntent] = useState<SearchIntent | null>(null)
useEffect(() => {
aiAPI
.status()
.then((s) => setAiAvailable(s.enabled))
.catch(() => setAiAvailable(false))
}, [])
// Fast LIKE search-as-you-type when AI mode is OFF.
useEffect(() => {
if (aiOn) return
const t = setTimeout(() => {
setLoading(true)
mediaAPI
.search(q, 60)
.then((d) => setItems(d.items))
.then((d) => {
setItems(d.items)
setIntent(null)
})
.finally(() => setLoading(false))
}, 300)
return () => clearTimeout(t)
}, [q])
}, [q, aiOn])
const onAISubmit = async (e: FormEvent) => {
e.preventDefault()
if (!q.trim()) return
setLoading(true)
try {
const data = await aiAPI.smartSearch(q)
setItems(data.items)
setIntent(data.intent)
} catch {
toast.error('AI 搜索失败')
} finally {
setLoading(false)
}
}
return (
<div className="space-y-6">
<h1 className="font-display text-3xl font-bold text-white">搜索</h1>
<input
autoFocus
className="input-base"
placeholder="按标题搜索…"
value={q}
onChange={(e: ChangeEvent<HTMLInputElement>) => setQ(e.target.value)}
/>
<header className="flex items-center justify-between">
<h1 className="font-display text-3xl font-bold text-white">搜索</h1>
<button
disabled={!aiAvailable}
className={
'neon-button !px-3 !py-1 !text-xs ' +
(aiOn ? '!border-accent-400 !bg-accent-400/20 !text-accent-400' : '')
}
onClick={() => setAiOn((on) => !on)}
title={aiAvailable ? '启用 AI 智能搜索' : '请先在 ai.* 中配置 API Key'}
>
<Sparkles size={12} /> {aiOn ? 'AI 已开启' : 'AI 智能搜索'}
</button>
</header>
{aiOn ? (
<form onSubmit={onAISubmit} className="flex gap-2">
<input
autoFocus
className="input-base"
placeholder='例如:“2010 年后的科幻电影” / “最近的动漫”'
value={q}
onChange={(e: ChangeEvent<HTMLInputElement>) => setQ(e.target.value)}
/>
<button type="submit" className="neon-button">
搜索
</button>
</form>
) : (
<input
autoFocus
className="input-base"
placeholder="按标题搜索…"
value={q}
onChange={(e: ChangeEvent<HTMLInputElement>) => setQ(e.target.value)}
/>
)}
{intent && (
<div className="glass-panel !p-3 text-xs text-slate-300">
AI 解析:
<span className="ml-2 font-mono text-primary-400">{JSON.stringify(intent)}</span>
</div>
)}
{loading && <p className="text-slate-500">搜索中…</p>}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{items.map((m) => (
+125
View File
@@ -0,0 +1,125 @@
import { useEffect, useState } from 'react'
import { Activity } from 'lucide-react'
import { tasksAPI, type TasksSnapshot } from '../api/tasks'
function fmtBytes(n: number): string {
if (!n || n <= 0) return '0 B'
const u = ['B', 'KB', 'MB', 'GB', 'TB']
let v = n
let i = 0
while (v >= 1024 && i < u.length - 1) {
v /= 1024
i++
}
return `${v.toFixed(2)} ${u[i]}`
}
// TasksPage shows everything the backend is doing right now: ffmpeg
// transcodes + qBittorrent downloads. Refreshes every 3 s.
export function TasksPage() {
const [snap, setSnap] = useState<TasksSnapshot | null>(null)
useEffect(() => {
let cancelled = false
const tick = () =>
tasksAPI.snapshot().then((s) => {
if (!cancelled) setSnap(s)
})
void tick()
const id = window.setInterval(tick, 3_000)
return () => {
cancelled = true
window.clearInterval(id)
}
}, [])
if (!snap) return <p className="text-slate-500">加载中…</p>
const torrents = snap.torrents ?? []
return (
<div className="space-y-8">
<header className="flex items-center gap-3">
<Activity className="h-6 w-6 text-primary-400" />
<h1 className="font-display text-3xl font-bold text-white">实时任务</h1>
</header>
<section className="glass-panel">
<h2 className="mb-3 font-display text-lg font-semibold text-white">转码任务</h2>
{snap.transcodes.length === 0 && <p className="text-slate-500">暂无运行中转码。</p>}
{snap.transcodes.length > 0 && (
<table className="w-full text-left text-sm">
<thead className="text-xs uppercase tracking-wider text-slate-500">
<tr>
<th className="py-2">媒体 ID</th>
<th>编码器</th>
<th>开始时间</th>
<th>就绪</th>
</tr>
</thead>
<tbody>
{snap.transcodes.map((t) => (
<tr key={t.media_id} className="border-t border-white/5">
<td className="py-2 font-mono text-xs text-white">{t.media_id}</td>
<td className="text-slate-300">{t.encoder || 'libx264'}</td>
<td className="text-slate-300">{new Date(t.started_at).toLocaleTimeString()}</td>
<td>
{t.playlist_ok ? (
<span className="rounded border border-emerald-400/40 px-1.5 py-0.5 text-xs text-emerald-400">
ready
</span>
) : (
<span className="rounded border border-yellow-400/40 px-1.5 py-0.5 text-xs text-yellow-400">
starting
</span>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
</section>
<section className="glass-panel">
<h2 className="mb-3 font-display text-lg font-semibold text-white">下载任务</h2>
{torrents.length === 0 && <p className="text-slate-500">暂无运行中下载。</p>}
{torrents.length > 0 && (
<table className="w-full text-left text-sm">
<thead className="text-xs uppercase tracking-wider text-slate-500">
<tr>
<th className="py-2">名称</th>
<th>状态</th>
<th>进度</th>
<th>体积</th>
</tr>
</thead>
<tbody>
{torrents.map((t) => (
<tr key={t.hash} className="border-t border-white/5 align-top">
<td className="max-w-md truncate py-2 text-white" title={t.name}>
{t.name}
</td>
<td className="text-slate-300">{t.state}</td>
<td className="text-slate-300">
<div className="flex items-center gap-2">
<div className="h-1 w-24 overflow-hidden rounded bg-white/10">
<div
className="h-full bg-primary-400"
style={{ width: `${Math.round(t.progress * 100)}%` }}
/>
</div>
{(t.progress * 100).toFixed(1)}%
</div>
</td>
<td className="text-slate-300">{fmtBytes(t.size)}</td>
</tr>
))}
</tbody>
</table>
)}
</section>
</div>
)
}