feat: downloads, RSS, subtitles, Bangumi, watcher, stats, profile, audit

Backend
  - service/bangumi.go: Bangumi (bgm.tv) scraper for anime libraries.
  - service/episode_parser.go: SxxExx / NxE / EPxx / 第NN集 parser with
    unit tests; consumed by the scanner for tv/anime libraries.
  - service/scraper.go: provider chain orchestrator picks Bangumi for
    anime libraries (TMDb fallback), TMDb for everything else; emits
    'no_match' rows so we don't retry forever; AnyEnabled() for the
    scanner kick.
  - service/scanner.go: writes season/episode numbers for tv/anime libs
    and reports a 'probed' counter alongside 'added'.
  - service/transcoder.go (existing): unchanged, stays per-media.
  - service/subtitle.go: discovers external subtitles next to the source
    file (.srt/.vtt/.ass/.ssa) and converts SRT/ASS to WebVTT on the fly.
  - service/qbittorrent.go: thread-safe qBittorrent v2 Web UI client
    (login / add / list / delete) with cookie-jar reuse.
  - service/downloads.go: persists download tasks, reads runtime
    qbittorrent.* settings, polls /torrents/info every 5 s and pushes
    the result to WS subscribers ('download' topic).
  - service/subscription.go: 10-minute RSS poller with regex filter,
    GUID dedup persisted in the settings table, and 'subscription' WS
    events on enqueue.
  - service/watcher.go: fsnotify watcher with 5 s coalescing debouncer
    that triggers per-library rescans on create/rename/remove.
  - service/stats.go: dashboard snapshot — totals, recently added,
    gopsutil-driven CPU/mem/disk readings.
  - service/profile.go: non-credential profile patch + admin role mutator.
  - service/audit.go: best-effort writer for the access_logs table.
  - service/service.go: container wires every new service; Boot() spins
    up watcher / downloads poller / subscription scheduler; Close()
    tears them down on graceful shutdown.

Handlers
  - new files: downloads.go, subscriptions.go, subtitles.go, series.go,
    stats.go, profile.go, util.go.
  - handler.go: registers PATCH /me, /libraries/:id/seasons,
    /media/:id/subtitles, /subtitles/:id, /downloads*, /subscriptions*,
    /stats, /admin/users/:id/role.
  - auth.go / media.go: write audit rows for login + library CRUD and
    refresh the watcher when libraries change.

Frontend
  - api: new helpers for downloads, subscriptions, profile, series, stats,
    subtitles; library helper gained scrape().
  - hooks/useWebSocket.ts: shared connection with 3 s reconnect.
  - components/GlobalEvents.tsx: surfaces scan / scrape / subscription
    completion as toasts (mounted at app root).
  - pages: Library now switches to a season-grouped layout for tv/anime
    libraries; Player attaches WebVTT <track> elements; new pages for
    Downloads (live torrent table), Subscriptions, Profile, Stats.
  - components/Layout.tsx + App.tsx: sidebar groups (媒体库 / 自动化 /
    账号 / 管理) and routes for the new pages; /stats and /admin remain
    admin-only.
  - types/index.ts: new types — Subscription, DownloadTask, QBitTorrent,
    Hardware, StatsSnapshot.

Verified: go build, go vet, go test (incl. ParseEpisode + srtToVTT +
stripASSTags) all pass; tsc -b && vite build emits 17 route chunks plus
the deferred hls chunk; main bundle 247 KB / 83 KB gzipped.
This commit is contained in:
Kiro
2026-05-14 16:07:49 +00:00
parent 0f30c34463
commit 7bd6bcfb1b
50 changed files with 3134 additions and 146 deletions
+21
View File
@@ -30,6 +30,16 @@ const PlayerPage = lazy(() =>
import('./pages/PlayerPage').then((m) => ({ default: m.PlayerPage })),
)
const AdminPage = lazy(() => import('./pages/AdminPage').then((m) => ({ default: m.AdminPage })))
const DownloadsPage = lazy(() =>
import('./pages/DownloadsPage').then((m) => ({ default: m.DownloadsPage })),
)
const SubscriptionsPage = lazy(() =>
import('./pages/SubscriptionsPage').then((m) => ({ default: m.SubscriptionsPage })),
)
const ProfilePage = lazy(() =>
import('./pages/ProfilePage').then((m) => ({ default: m.ProfilePage })),
)
const StatsPage = lazy(() => import('./pages/StatsPage').then((m) => ({ default: m.StatsPage })))
// Fallback shown while a chunk is loading.
const Loading = () => <p className="px-6 py-8 text-slate-500">加载中…</p>
@@ -55,6 +65,17 @@ export default function App() {
<Route path="playlist/:id" element={<PlaylistDetailPage />} />
<Route path="media/:id" element={<MediaDetailPage />} />
<Route path="play/:id" element={<PlayerPage />} />
<Route path="downloads" element={<DownloadsPage />} />
<Route path="subscriptions" element={<SubscriptionsPage />} />
<Route path="profile" element={<ProfilePage />} />
<Route
path="stats"
element={
<RequireAdmin>
<StatsPage />
</RequireAdmin>
}
/>
<Route
path="admin"
element={
+23
View File
@@ -0,0 +1,23 @@
import { api } from './client'
import type { DownloadTask, QBitTorrent } from '../types'
export interface DownloadsState {
tasks: DownloadTask[]
torrents: QBitTorrent[] | null
}
export const downloadsAPI = {
list: () => api.get<DownloadsState>('/downloads').then((r) => r.data),
add: (url: string, savePath = '') =>
api
.post<DownloadTask>('/downloads', { url, save_path: savePath })
.then((r) => r.data),
remove: (hash: string, deleteFiles = false) =>
api
.delete(`/downloads/${hash}?delete_files=${deleteFiles ? 'true' : 'false'}`)
.then((r) => r.data),
reload: () => api.post('/downloads/reload').then((r) => r.data),
}
+3
View File
@@ -19,6 +19,9 @@ export const libraryAPI = {
scan: (id: string) =>
api.post<ScanResult>(`/libraries/${id}/scan`).then((r) => r.data),
scrape: (id: string) =>
api.post(`/libraries/${id}/scrape`).then((r) => r.data),
listMedia: (id: string, page = 1, pageSize = 50) =>
api
.get<MediaPage>(`/libraries/${id}/media`, {
+10
View File
@@ -0,0 +1,10 @@
import { api } from './client'
import type { User } from '../types'
export const profileAPI = {
update: (patch: { email?: string; avatar_url?: string }) =>
api.patch<User>('/me', patch).then((r) => r.data),
adminUpdateRole: (id: string, role: 'admin' | 'user') =>
api.patch<User>(`/admin/users/${id}/role`, { role }).then((r) => r.data),
}
+14
View File
@@ -0,0 +1,14 @@
import { api } from './client'
import type { Media } from '../types'
export interface SeasonGroup {
season: number
episodes: Media[]
}
export const seriesAPI = {
seasons: (libraryID: string) =>
api
.get<{ seasons: SeasonGroup[] }>(`/libraries/${libraryID}/seasons`)
.then((r) => r.data.seasons),
}
+6
View File
@@ -0,0 +1,6 @@
import { api } from './client'
import type { StatsSnapshot } from '../types'
export const statsAPI = {
snapshot: () => api.get<StatsSnapshot>('/stats').then((r) => r.data),
}
+15
View File
@@ -0,0 +1,15 @@
import { api } from './client'
import type { Subscription } from '../types'
export const subscriptionsAPI = {
list: () =>
api.get<{ items: Subscription[] }>('/subscriptions').then((r) => r.data.items),
create: (input: { name: string; feed_url: string; filter?: string; enabled?: boolean }) =>
api.post<Subscription>('/subscriptions', input).then((r) => r.data),
remove: (id: string) => api.delete(`/subscriptions/${id}`).then((r) => r.data),
runNow: (id: string) =>
api.post<{ queued: number }>(`/subscriptions/${id}/run`).then((r) => r.data),
}
+24
View File
@@ -0,0 +1,24 @@
import { api } from './client'
import { useAuthStore } from '../stores/auth'
export interface SubtitleTrack {
lang: string
label: string
path: string
url: string
codec: string
}
export const subtitlesAPI = {
list: (mediaId: string) =>
api
.get<{ tracks: SubtitleTrack[] }>(`/media/${mediaId}/subtitles`)
.then((r) => r.data.tracks),
url: (mediaId: string, path: string) => {
const token = useAuthStore.getState().token ?? ''
return `/api/subtitles/${encodeURIComponent(mediaId)}?path=${encodeURIComponent(
path,
)}&token=${encodeURIComponent(token)}`
},
}
+27
View File
@@ -0,0 +1,27 @@
import { useCallback } from 'react'
import toast from 'react-hot-toast'
import { useWebSocket } from '../hooks/useWebSocket'
// GlobalEvents subscribes to the WS hub and surfaces interesting events
// as toasts. Lives at the top of the component tree so every page sees
// the same stream without re-opening connections.
export function GlobalEvents() {
const onEvent = useCallback((topic: string, payload: unknown) => {
if (!payload || typeof payload !== 'object') return
const p = payload as Record<string, unknown>
if (topic === 'scan' && p.finished) {
toast.success(`扫描完成:已添加 ${p.added ?? 0} 项,已探测 ${p.probed ?? 0} 项`)
}
if (topic === 'scrape' && p.finished) {
toast.success(`刮削完成:成功匹配 ${p.matched ?? 0} 项`)
}
if (topic === 'subscription') {
const queued = (p.queued as number | undefined) ?? 0
if (queued > 0) toast.success(`订阅「${p.name}」已加入 ${queued} 项下载`)
}
}, [])
useWebSocket(onEvent)
return null
}
+17 -1
View File
@@ -1,14 +1,18 @@
import { useEffect, useState } from 'react'
import { Link, NavLink, Outlet, useNavigate } from 'react-router-dom'
import {
Activity,
CloudDownload,
Film,
Heart,
Home,
ListMusic,
LogOut,
Rss,
Search,
Settings,
Library as LibraryIcon,
User as UserIcon,
} from 'lucide-react'
import clsx from 'clsx'
@@ -42,7 +46,7 @@ export function Layout() {
</span>
</Link>
<nav className="flex-1 space-y-1">
<nav className="flex-1 space-y-1 overflow-y-auto pr-1">
<SidebarLink to="/" icon={<Home size={18} />} label="首页" end />
<SidebarLink to="/search" icon={<Search size={18} />} label="搜索" />
<SidebarLink to="/favourites" icon={<Heart size={18} />} label="收藏" />
@@ -63,11 +67,23 @@ export function Layout() {
/>
))}
<div className="mt-6 px-2 text-xs uppercase tracking-wider text-slate-500">
自动化
</div>
<SidebarLink to="/downloads" icon={<CloudDownload size={18} />} label="下载" />
<SidebarLink to="/subscriptions" icon={<Rss size={18} />} label="RSS 订阅" />
<div className="mt-6 px-2 text-xs uppercase tracking-wider text-slate-500">
账号
</div>
<SidebarLink to="/profile" icon={<UserIcon size={18} />} label="个人资料" />
{user?.role === 'admin' && (
<>
<div className="mt-6 px-2 text-xs uppercase tracking-wider text-slate-500">
管理
</div>
<SidebarLink to="/stats" icon={<Activity size={18} />} label="运行状态" />
<SidebarLink to="/admin" icon={<Settings size={18} />} label="管理后台" />
</>
)}
+45
View File
@@ -0,0 +1,45 @@
import { useEffect, useRef } from 'react'
import { useAuthStore } from '../stores/auth'
// useWebSocket opens a single connection to /api/ws and dispatches every
// message to the supplied handler. Auto-reconnects with a 3 s back-off
// while the auth token is present.
export function useWebSocket(onEvent: (topic: string, payload: unknown) => void) {
const ref = useRef<WebSocket | null>(null)
const token = useAuthStore((s) => s.token)
useEffect(() => {
if (!token) return
let closed = false
let timer: number | undefined
const open = () => {
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
const url = `${proto}//${window.location.host}/api/ws?token=${encodeURIComponent(token)}`
const ws = new WebSocket(url)
ref.current = ws
ws.onmessage = (ev) => {
try {
const msg = JSON.parse(ev.data)
if (msg && typeof msg.topic === 'string') {
onEvent(msg.topic, msg.payload)
}
} catch {
// ignore malformed frames
}
}
ws.onclose = () => {
if (closed) return
timer = window.setTimeout(open, 3_000)
}
}
open()
return () => {
closed = true
if (timer) window.clearTimeout(timer)
ref.current?.close()
}
}, [token, onEvent])
}
+2
View File
@@ -4,12 +4,14 @@ import { BrowserRouter } from 'react-router-dom'
import { Toaster } from 'react-hot-toast'
import App from './App'
import { GlobalEvents } from './components/GlobalEvents'
import './index.css'
// Application root: BrowserRouter + global toast container.
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<BrowserRouter>
<GlobalEvents />
<App />
<Toaster
position="top-right"
+177
View File
@@ -0,0 +1,177 @@
import { FormEvent, useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { Download, Trash2 } from 'lucide-react'
import { downloadsAPI } from '../api/downloads'
import { useAuthStore } from '../stores/auth'
import type { DownloadTask, QBitTorrent } from '../types'
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]}`
}
function fmtSpeed(n: number): string {
return `${fmtBytes(n)}/s`
}
// DownloadsPage: shows running torrents (live) + persisted task rows.
export function DownloadsPage() {
const role = useAuthStore((s) => s.user?.role)
const [tasks, setTasks] = useState<DownloadTask[]>([])
const [torrents, setTorrents] = useState<QBitTorrent[] | null>(null)
const [url, setURL] = useState('')
const [savePath, setSavePath] = useState('')
const refresh = () =>
downloadsAPI.list().then((d) => {
setTasks(d.tasks)
setTorrents(d.torrents)
})
useEffect(() => {
void refresh().catch(() => undefined)
const id = window.setInterval(() => void refresh().catch(() => undefined), 5_000)
return () => window.clearInterval(id)
}, [])
const onAdd = async (e: FormEvent) => {
e.preventDefault()
try {
await downloadsAPI.add(url, savePath)
toast.success('已加入下载队列')
setURL('')
setSavePath('')
await refresh()
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ??
'提交失败'
toast.error(msg)
}
}
return (
<div className="space-y-6">
<h1 className="font-display text-3xl font-bold text-white">下载</h1>
<form onSubmit={onAdd} className="glass-panel grid gap-3 md:grid-cols-[1fr_1fr_auto]">
<input
required
className="input-base md:col-span-2"
placeholder="磁力链接 / .torrent URL"
value={url}
onChange={(e) => setURL(e.target.value)}
/>
<input
className="input-base"
placeholder="保存路径 (可选)"
value={savePath}
onChange={(e) => setSavePath(e.target.value)}
/>
<button type="submit" className="neon-button md:col-span-3">
<Download size={16} /> 添加
</button>
</form>
<section className="glass-panel">
<h2 className="mb-3 font-display text-lg font-semibold text-white">实时状态</h2>
{torrents === null && (
<p className="text-slate-500">尚未连接到 qBittorrent — 请在管理后台配置 qbittorrent.url / username / password。</p>
)}
{torrents && torrents.length === 0 && <p className="text-slate-500">暂无运行中任务。</p>}
{torrents && 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>
<th>体积</th>
{role === 'admin' && <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">
↓ {fmtSpeed(t.dlspeed)} / ↑ {fmtSpeed(t.upspeed)}
</td>
<td className="text-slate-300">{fmtBytes(t.size)}</td>
{role === 'admin' && (
<td className="py-2 text-right">
<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(`删除「${t.name}」?`)) return
await downloadsAPI.remove(t.hash, false)
toast.success('已删除任务')
await refresh()
}}
>
<Trash2 size={12} />
</button>
</td>
)}
</tr>
))}
</tbody>
</table>
)}
</section>
{tasks.length > 0 && (
<section className="glass-panel">
<h2 className="mb-3 font-display text-lg font-semibold text-white">历史记录</h2>
<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>URL</th>
<th>保存路径</th>
<th>时间</th>
</tr>
</thead>
<tbody>
{tasks.map((t) => (
<tr key={t.id} className="border-t border-white/5">
<td className="py-2 text-slate-300">{t.source}</td>
<td className="max-w-md truncate text-slate-300" title={t.url}>
{t.url}
</td>
<td className="text-slate-300">{t.save_path || '—'}</td>
<td className="text-slate-500">
{new Date(t.created_at).toLocaleString()}
</td>
</tr>
))}
</tbody>
</table>
</section>
)}
</div>
)
}
+110 -26
View File
@@ -1,42 +1,67 @@
import { useEffect, useState } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import toast from 'react-hot-toast'
import { libraryAPI } from '../api/library'
import type { Media } from '../types'
import { seriesAPI, type SeasonGroup } from '../api/series'
import type { Library, Media } from '../types'
import { MediaCard } from '../components/MediaCard'
import { useAuthStore } from '../stores/auth'
// Browse a single library. Admins also get a "scan" button that triggers
// a fresh scan run on the backend.
// LibraryPage renders one of two layouts depending on the library type:
//
// - movie / music / default → flat poster grid with pagination.
// - tv / anime → grouped by season with an episode list.
//
// Admins also get scan + scrape buttons in the header.
export function LibraryPage() {
const { id = '' } = useParams()
const role = useAuthStore((s) => s.user?.role)
const [library, setLibrary] = useState<Library | null>(null)
const [items, setItems] = useState<Media[]>([])
const [seasons, setSeasons] = useState<SeasonGroup[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [scanning, setScanning] = useState(false)
const [scraping, setScraping] = useState(false)
const isSeries = library?.type === 'tv' || library?.type === 'anime'
useEffect(() => {
if (!id) return
setLoading(true)
libraryAPI
.listMedia(id)
.then((d) => {
setItems(d.items)
setTotal(d.total)
})
.finally(() => setLoading(false))
Promise.all([
libraryAPI.list().then((all) => all.find((l) => l.id === id) ?? null),
]).then(([lib]) => setLibrary(lib))
}, [id])
useEffect(() => {
if (!id || !library) return
setLoading(true)
if (library.type === 'tv' || library.type === 'anime') {
seriesAPI
.seasons(id)
.then((s) => setSeasons(s))
.finally(() => setLoading(false))
} else {
libraryAPI
.listMedia(id)
.then((d) => {
setItems(d.items)
setTotal(d.total)
})
.finally(() => setLoading(false))
}
}, [id, library])
const handleScan = async () => {
setScanning(true)
try {
const r = await libraryAPI.scan(id)
toast.success(`扫描完成:新增 ${r.added} 个文件`)
const d = await libraryAPI.listMedia(id)
setItems(d.items)
setTotal(d.total)
toast.success(`扫描完成:新增 ${r.added} 项,探测 ${r.probed} 项`)
// Force a reload by toggling library state.
setLibrary((l) => (l ? { ...l } : l))
} catch {
toast.error('扫描失败')
} finally {
@@ -44,25 +69,84 @@ export function LibraryPage() {
}
}
const handleScrape = async () => {
setScraping(true)
try {
await libraryAPI.scrape(id)
toast.success('刮削已加入后台队列')
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ??
'刮削失败'
toast.error(msg)
} finally {
setScraping(false)
}
}
const heading = useMemo(
() => (library ? `${library.name}` : '媒体库'),
[library],
)
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="font-display text-3xl font-bold text-white">
媒体库 <span className="text-slate-500">({total})</span>
</h1>
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="font-display text-3xl font-bold text-white">
{heading}
{!isSeries && <span className="text-slate-500"> ({total})</span>}
</h1>
{library && (
<p className="text-sm text-slate-400">
{library.type} · {library.path}
</p>
)}
</div>
{role === 'admin' && (
<button onClick={handleScan} disabled={scanning} className="neon-button">
{scanning ? '扫描中…' : '立即扫描'}
</button>
<div className="flex gap-2">
<button onClick={handleScan} disabled={scanning} className="neon-button">
{scanning ? '扫描中…' : '立即扫描'}
</button>
<button onClick={handleScrape} disabled={scraping} className="neon-button">
{scraping ? '刮削中…' : '刮削元数据'}
</button>
</div>
)}
</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) => (
<MediaCard key={m.id} media={m} />
{!isSeries && (
<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) => (
<MediaCard key={m.id} media={m} />
))}
</div>
)}
{isSeries &&
seasons.map((s) => (
<section key={s.season} className="space-y-3">
<h2 className="font-display text-xl font-semibold text-white">
{s.season > 0 ? `第 ${s.season} 季` : '未分季'} ({s.episodes.length})
</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">
{s.episodes.map((e) => (
<div key={e.id} className="space-y-1">
<MediaCard media={e} />
{e.episode_num > 0 && (
<p className="px-1 text-xs text-slate-400">第 {e.episode_num} 集</p>
)}
</div>
))}
</div>
</section>
))}
</div>
{isSeries && !loading && seasons.length === 0 && (
<p className="text-slate-400">该库尚未发现任何剧集,触发一次扫描后再来看看。</p>
)}
</div>
)
}
+23 -12
View File
@@ -7,6 +7,7 @@ import toast from 'react-hot-toast'
import { mediaAPI } from '../api/library'
import { hlsURL, streamURL } from '../api/client'
import { playbackAPI } from '../api/playback'
import { subtitlesAPI, type SubtitleTrack } from '../api/subtitles'
import type { Media } from '../types'
type Mode = 'direct' | 'hls'
@@ -19,6 +20,9 @@ type Mode = 'direct' | 'hls'
// 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.
//
// External subtitles next to the source file are auto-discovered and
// attached as <track> elements.
export function PlayerPage() {
const { id = '' } = useParams()
const [params, setParams] = useSearchParams()
@@ -30,6 +34,7 @@ export function PlayerPage() {
const [media, setMedia] = useState<Media | null>(null)
const [mode, setMode] = useState<Mode>('direct')
const [subs, setSubs] = useState<SubtitleTrack[]>([])
// Load metadata and pick a default mode.
useEffect(() => {
@@ -40,6 +45,10 @@ export function PlayerPage() {
const auto = pickMode(m)
setMode(forced ?? auto)
})
subtitlesAPI
.list(id)
.then(setSubs)
.catch(() => setSubs([]))
}, [id, params])
// Wire up the actual <video> element when we know the mode.
@@ -48,14 +57,9 @@ export function PlayerPage() {
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)
@@ -81,10 +85,7 @@ export function PlayerPage() {
video.src = streamURL(media.id)
void video.play().catch(() => undefined)
}
return () => {
cancelled = true
teardownHls()
}
return teardownHls
}, [media, mode, params, setParams])
// Persist resume position every 10 seconds while playing.
@@ -161,8 +162,20 @@ export function PlayerPage() {
ref={ref}
controls
autoPlay
crossOrigin="use-credentials"
className="max-h-screen w-full max-w-[1600px] bg-black"
/>
>
{subs.map((t, i) => (
<track
key={t.path}
kind="subtitles"
src={subtitlesAPI.url(media.id, t.path)}
srcLang={t.lang}
label={t.label || t.lang}
default={i === 0}
/>
))}
</video>
) : (
<p className="text-slate-500">加载中…</p>
)}
@@ -175,8 +188,6 @@ 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()
+114
View File
@@ -0,0 +1,114 @@
import { FormEvent, useState } from 'react'
import toast from 'react-hot-toast'
import { KeyRound, Save } from 'lucide-react'
import { authAPI } from '../api/auth'
import { profileAPI } from '../api/profile'
import { useAuthStore } from '../stores/auth'
export function ProfilePage() {
const user = useAuthStore((s) => s.user)
const setUser = useAuthStore((s) => s.setUser)
const [email, setEmail] = useState(user?.email ?? '')
const [avatar, setAvatar] = useState(user?.avatar_url ?? '')
const [oldPwd, setOldPwd] = useState('')
const [newPwd, setNewPwd] = useState('')
const onProfile = async (e: FormEvent) => {
e.preventDefault()
try {
const u = await profileAPI.update({ email, avatar_url: avatar })
setUser(u)
toast.success('资料已更新')
} catch {
toast.error('保存失败')
}
}
const onPwd = async (e: FormEvent) => {
e.preventDefault()
try {
await authAPI.changePassword(oldPwd, newPwd)
toast.success('密码已更新')
setOldPwd('')
setNewPwd('')
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ??
'密码更新失败'
toast.error(msg)
}
}
return (
<div className="space-y-6">
<h1 className="font-display text-3xl font-bold text-white">个人资料</h1>
<form onSubmit={onProfile} className="glass-panel space-y-4">
<h2 className="font-display text-lg font-semibold text-white">基本信息</h2>
<Field label="用户名">
<input className="input-base" value={user?.username ?? ''} disabled />
</Field>
<Field label="角色">
<input className="input-base" value={user?.role ?? ''} disabled />
</Field>
<Field label="电子邮箱">
<input
type="email"
className="input-base"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</Field>
<Field label="头像 URL">
<input
className="input-base"
value={avatar}
onChange={(e) => setAvatar(e.target.value)}
/>
</Field>
<button type="submit" className="neon-button">
<Save size={16} /> 保存
</button>
</form>
<form onSubmit={onPwd} className="glass-panel space-y-4">
<h2 className="font-display text-lg font-semibold text-white">修改密码</h2>
<Field label="当前密码">
<input
required
type="password"
className="input-base"
value={oldPwd}
onChange={(e) => setOldPwd(e.target.value)}
autoComplete="current-password"
/>
</Field>
<Field label="新密码">
<input
required
type="password"
className="input-base"
minLength={6}
value={newPwd}
onChange={(e) => setNewPwd(e.target.value)}
autoComplete="new-password"
/>
</Field>
<button type="submit" className="neon-button">
<KeyRound size={16} /> 更新密码
</button>
</form>
</div>
)
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<label className="block">
<span className="mb-1 block text-sm text-slate-300">{label}</span>
{children}
</label>
)
}
+137
View File
@@ -0,0 +1,137 @@
import { useEffect, useState } from 'react'
import { Activity, Cpu, Database, Film, HardDrive, Users } from 'lucide-react'
import { statsAPI } from '../api/stats'
import { MediaCard } from '../components/MediaCard'
import type { StatsSnapshot } from '../types'
// fmtBytes is a tiny helper shared by the dashboard cards.
function fmtBytes(n: number): string {
if (!n || n <= 0) return '—'
const u = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
let v = n
let i = 0
while (v >= 1024 && i < u.length - 1) {
v /= 1024
i++
}
return `${v.toFixed(2)} ${u[i]}`
}
function fmtHours(seconds: number): string {
if (!seconds || seconds <= 0) return '—'
const h = Math.floor(seconds / 3600)
return `${h.toLocaleString()} h`
}
// StatsPage renders the operator dashboard. Refreshes every 10 s.
export function StatsPage() {
const [snap, setSnap] = useState<StatsSnapshot | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
let cancelled = false
const tick = () =>
statsAPI.snapshot().then((s) => {
if (!cancelled) setSnap(s)
})
tick().finally(() => setLoading(false))
const id = window.setInterval(tick, 10_000)
return () => {
cancelled = true
window.clearInterval(id)
}
}, [])
if (loading) return <p className="text-slate-500">加载中…</p>
if (!snap) return <p className="text-slate-500">无法获取统计数据</p>
const memPct =
snap.hardware.memory_total > 0
? (snap.hardware.memory_used / snap.hardware.memory_total) * 100
: 0
const diskPct =
snap.hardware.disk_total > 0
? (snap.hardware.disk_used / snap.hardware.disk_total) * 100
: 0
return (
<div className="space-y-8">
<header>
<h1 className="font-display text-3xl font-bold text-white">运行状态</h1>
<p className="text-sm text-slate-400">
快照时间:{new Date(snap.generated_at).toLocaleString()}
</p>
</header>
<section className="grid gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
<Tile icon={<Database size={20} />} label="媒体库" value={snap.libraries.toLocaleString()} />
<Tile icon={<Film size={20} />} label="媒体总数" value={snap.media_count.toLocaleString()} />
<Tile icon={<Users size={20} />} label="用户" value={snap.users_count.toLocaleString()} />
<Tile icon={<HardDrive size={20} />} label="入库容量" value={fmtBytes(snap.total_size_bytes)} />
<Tile icon={<Activity size={20} />} label="累计时长" value={fmtHours(snap.total_seconds)} />
<Tile icon={<Cpu size={20} />} label="CPU 占用" value={`${snap.hardware.cpu_percent.toFixed(1)}%`} />
<Tile icon={<Cpu size={20} />} label="内存占用" value={`${memPct.toFixed(1)}%`} />
<Tile icon={<HardDrive size={20} />} label="数据盘占用" value={`${diskPct.toFixed(1)}%`} />
</section>
<section className="space-y-3">
<h2 className="font-display text-xl font-semibold text-white">系统</h2>
<div className="glass-panel grid gap-2 text-sm">
<Row label="Go 运行时" value={snap.hardware.go_version} />
<Row label="Goroutines" value={snap.hardware.goroutines.toLocaleString()} />
<Row
label="内存"
value={`${fmtBytes(snap.hardware.memory_used)} / ${fmtBytes(snap.hardware.memory_total)}`}
/>
<Row
label="数据盘"
value={`${fmtBytes(snap.hardware.disk_used)} / ${fmtBytes(snap.hardware.disk_total)}`}
/>
</div>
</section>
{snap.recently_added.length > 0 && (
<section className="space-y-3">
<h2 className="font-display text-xl font-semibold text-white">最近入库</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">
{snap.recently_added.map((m) => (
<MediaCard key={m.id} media={m} />
))}
</div>
</section>
)}
</div>
)
}
function Tile({
icon,
label,
value,
}: {
icon: React.ReactNode
label: string
value: string
}) {
return (
<div className="glass-panel flex items-center gap-3 !p-4">
<div className="rounded-lg border border-primary-400/40 bg-primary-400/10 p-2 text-primary-400">
{icon}
</div>
<div>
<p className="text-xs uppercase tracking-wider text-slate-500">{label}</p>
<p className="font-display text-lg font-semibold text-white">{value}</p>
</div>
</div>
)
}
function Row({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-center justify-between border-b border-white/5 pb-1 text-sm last:border-0">
<span className="text-slate-400">{label}</span>
<span className="font-mono text-white">{value}</span>
</div>
)
}
+130
View File
@@ -0,0 +1,130 @@
import { FormEvent, useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { Play, Plus, Trash2 } from 'lucide-react'
import { subscriptionsAPI } from '../api/subscriptions'
import type { Subscription } from '../types'
export function SubscriptionsPage() {
const [items, setItems] = useState<Subscription[]>([])
const [name, setName] = useState('')
const [feed, setFeed] = useState('')
const [filter, setFilter] = useState('')
const [loading, setLoading] = useState(true)
const refresh = () =>
subscriptionsAPI
.list()
.then(setItems)
.finally(() => setLoading(false))
useEffect(() => {
refresh().catch(() => undefined)
}, [])
const onCreate = async (e: FormEvent) => {
e.preventDefault()
try {
await subscriptionsAPI.create({ name, feed_url: feed, filter })
toast.success('已创建订阅')
setName('')
setFeed('')
setFilter('')
await refresh()
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ?? '创建失败'
toast.error(msg)
}
}
return (
<div className="space-y-6">
<h1 className="font-display text-3xl font-bold text-white">RSS 订阅</h1>
<p className="text-sm text-slate-400">
定期轮询 RSS 源(每 10 分钟一次),将匹配过滤器的项目自动加入下载队列。
</p>
<form onSubmit={onCreate} className="glass-panel grid gap-3 md:grid-cols-[1fr_1fr_1fr_auto]">
<input
required
className="input-base"
placeholder="名称(显示用)"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
required
className="input-base"
placeholder="RSS 地址"
value={feed}
onChange={(e) => setFeed(e.target.value)}
/>
<input
className="input-base"
placeholder="过滤器(正则,可选)"
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
<button type="submit" className="neon-button">
<Plus size={16} /> 添加
</button>
</form>
{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>RSS</th>
<th>过滤器</th>
<th>最近运行</th>
<th className="text-right">操作</th>
</tr>
</thead>
<tbody>
{items.map((s) => (
<tr key={s.id} className="border-t border-white/5">
<td className="py-2 text-white">{s.name}</td>
<td className="max-w-md truncate text-slate-300" title={s.feed_url}>
{s.feed_url}
</td>
<td className="text-slate-300">{s.filter || '—'}</td>
<td className="text-slate-500">
{s.last_run_at ? new Date(s.last_run_at).toLocaleString() : '—'}
</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 () => {
const r = await subscriptionsAPI.runNow(s.id)
toast.success(`已加入 ${r.queued} 项`)
}}
>
<Play 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(`删除订阅「${s.name}」?`)) return
await subscriptionsAPI.remove(s.id)
toast.success('已删除')
await refresh()
}}
>
<Trash2 size={12} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)
}
+58
View File
@@ -82,3 +82,61 @@ export interface AccessLog {
detail: string
created_at: string
}
export interface Subscription {
id: string
user_id: string
name: string
feed_url: string
filter: string
enabled: boolean
last_run_at?: string
created_at: string
updated_at: string
}
export interface DownloadTask {
id: string
user_id: string
source: string
url: string
save_path: string
status: string
progress: number
created_at: string
updated_at: string
}
export interface QBitTorrent {
hash: string
name: string
state: string
progress: number
dlspeed: number
upspeed: number
num_seeds: number
num_leechs: number
size: number
save_path: string
}
export interface Hardware {
cpu_percent: number
memory_used: number
memory_total: number
disk_used: number
disk_total: number
go_version: string
goroutines: number
}
export interface StatsSnapshot {
libraries: number
media_count: number
users_count: number
total_size_bytes: number
total_seconds: number
recently_added: Media[]
hardware: Hardware
generated_at: string
}