feat: 完善媒体维护、备份恢复与播放诊断

This commit is contained in:
jason jia
2026-10-20 14:01:26 +00:00
parent e34e81cce0
commit 1e8fe2396e
53 changed files with 2049 additions and 238 deletions
+28
View File
@@ -0,0 +1,28 @@
import { api, LONG_REQUEST_TIMEOUT } from './client'
export interface BackupInfo {
filename: string
size: number
created_at: string
automatic: boolean
}
export const backupAPI = {
list: () => api.get<{ items: BackupInfo[] }>('/admin/backups').then((r) => r.data.items ?? []),
create: () => api.post<BackupInfo>('/admin/backups', {}, { timeout: LONG_REQUEST_TIMEOUT }).then((r) => r.data),
remove: (filename: string) => api.delete('/admin/backups', { params: { filename } }),
restore: (filename: string) => api.post<{ message: string; restart_required: boolean }>('/admin/backups/restore', null, { params: { filename }, timeout: LONG_REQUEST_TIMEOUT }).then((r) => r.data),
download: async (filename: string) => {
const response = await api.get<Blob>('/admin/backups/download', {
params: { filename },
responseType: 'blob',
timeout: LONG_REQUEST_TIMEOUT,
})
const url = URL.createObjectURL(response.data)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = filename
anchor.click()
URL.revokeObjectURL(url)
},
}
+14 -1
View File
@@ -262,7 +262,15 @@ export const mediaAPI = {
})
.then((r) => r.data),
searchPage: (q: string, page = 1, pageSize = 50, options?: { groupVersions?: boolean; groupSeries?: boolean }) =>
searchPage: (q: string, page = 1, pageSize = 50, options?: {
groupVersions?: boolean
groupSeries?: boolean
libraryId?: string
yearMin?: number
yearMax?: number
genres?: string[]
sort?: 'title_asc' | 'year_desc' | 'rating_desc'
}) =>
api
.get<MediaSearchPage>('/media', {
params: {
@@ -271,6 +279,11 @@ export const mediaAPI = {
page_size: pageSize,
group_versions: options?.groupVersions === false ? 0 : undefined,
...(options?.groupSeries ? { group_series: 1 } : {}),
...(options?.libraryId ? { library_id: options.libraryId } : {}),
...(options?.yearMin ? { year_min: options.yearMin } : {}),
...(options?.yearMax ? { year_max: options.yearMax } : {}),
...(options?.genres?.length ? { genre: options.genres } : {}),
...(options?.sort ? { sort: options.sort } : {}),
},
timeout: LONG_REQUEST_TIMEOUT,
})
+16
View File
@@ -0,0 +1,16 @@
import { api } from './client'
import type { Media } from '../types'
export type MediaQualityIssue = 'missing' | 'unmatched' | 'poster'
export interface MediaQualityRow {
issue: MediaQualityIssue
media: Media
}
export const qualityAPI = {
list: (issue: MediaQualityIssue, page = 1, pageSize = 50) =>
api.get<{ items: MediaQualityRow[]; total: number; page: number; page_size: number }>('/admin/quality', {
params: { issue, page, page_size: pageSize },
}).then((r) => r.data),
}
+2
View File
@@ -249,6 +249,8 @@ export const readerAPI = {
deleteSource: (id: string) => api.delete(`/reader/sources/${id}`),
debugSource: (id: string, key: string) =>
api.post<{ logs: string[] }>(`/reader/sources/${id}/debug`, { key }, longOpts).then((r) => r.data.logs),
smokeSource: (id: string, key: string) =>
api.post<{ logs: string[] }>(`/reader/sources/${id}/debug`, { key }, { timeout: 60_000 }).then((r) => r.data.logs),
// ── 书源登录与源变量 ──
// 取登录界面描述(loginUi 控件 + 已保存值 + 当前 Cookie 状态)
+27
View File
@@ -0,0 +1,27 @@
import { api } from './client'
export interface BackgroundTask {
id: string
kind: string
name: string
status: 'running' | 'completed' | 'failed' | 'interrupted' | string
stage?: string
source_path?: string
dest_path?: string
message?: string
error?: string
details?: string[]
metrics?: Record<string, number>
started_at: string
updated_at: string
finished_at?: string
}
export interface TaskSnapshot {
active: BackgroundTask[]
recent: BackgroundTask[]
}
export const tasksAPI = {
snapshot: () => api.get<TaskSnapshot>('/admin/tasks').then((r) => r.data),
}
+4
View File
@@ -50,6 +50,8 @@ const StrmUploadQueuePage = lazy(() =>
)
const ScraperQueuePage = lazy(() => import('./pages/ScraperQueuePage').then((m) => ({ default: m.ScraperQueuePage })))
const TaskQueuePage = lazy(() => import('./pages/TaskQueuePage').then((m) => ({ default: m.TaskQueuePage })))
const MediaQualityPage = lazy(() => import('./pages/MediaQualityPage').then((m) => ({ default: m.MediaQualityPage })))
const SetupWizardPage = lazy(() => import('./pages/SetupWizardPage').then((m) => ({ default: m.SetupWizardPage })))
// 常用页面的路由 chunk 空闲预取:应用加载完成后浏览器一空闲就把浏览路径
// (库列表/库详情/媒体详情/收藏/历史等)的 chunk 拉下来,
@@ -125,5 +127,7 @@ export const appRoutes: AppRoute[] = [
{ path: 'strm/uploads', element: <StrmUploadQueuePage />, adminOnly: true },
{ path: 'scraper/queue', element: <ScraperQueuePage />, adminOnly: true },
{ path: 'queue', element: <TaskQueuePage />, adminOnly: true },
{ path: 'quality', element: <MediaQualityPage />, adminOnly: true },
{ path: 'setup', element: <SetupWizardPage />, adminOnly: true },
{ path: 'admin', element: <AdminPage />, adminOnly: true },
]
+5
View File
@@ -89,6 +89,11 @@ export const MediaCard = memo(function MediaCard({
<span>{displayRating.toFixed(1)}</span>
</span>
)}
{media.availability_state === 'missing' && (
<span className="absolute left-2 top-2 rounded-lg border border-amber-300/30 bg-[#111827]/90 px-2 py-1 text-[10px] font-bold text-amber-300 shadow-sm">
文件失联
</span>
)}
{/* Premium Hover Overlay(CSS 过渡替代 framer-motion 逐卡动画实例) */}
<div className={`absolute inset-0 bg-gradient-to-t from-[#111827]/90 via-[#111827]/30 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col justify-end ${
+6
View File
@@ -1,6 +1,8 @@
import type { LucideIcon } from 'lucide-react'
import {
Clock,
AlertTriangle,
ListChecks as SetupIcon,
FileOutput,
FolderOpen,
Heart,
@@ -41,6 +43,8 @@ export const LAYOUT_NAV_ITEMS: LayoutNavItem[] = [
{ to: '/profile', label: '个人资料', icon: User },
{ to: '/libraries?from=admin', label: '媒体库', icon: Library },
{ to: '/queue', label: '任务队列', icon: ListChecks, adminOnly: true },
{ to: '/quality', label: '媒体质量', icon: AlertTriangle, adminOnly: true },
{ to: '/setup', label: '首次配置', icon: SetupIcon, adminOnly: true },
{ to: '/admin', label: '用户管理', icon: Users, adminOnly: true },
{ to: '/files', label: '文件管理', icon: FolderOpen, adminOnly: true },
{ to: '/emby-mount', label: 'Emby 挂载', icon: Tv, adminOnly: true },
@@ -159,6 +163,8 @@ export function resolveHeaderBack(pathname: string): HeaderBackTarget | null {
pathname === '/admin' ||
pathname === '/files' ||
pathname === '/queue' ||
pathname === '/quality' ||
pathname === '/setup' ||
pathname === '/emby-mount' ||
pathname === '/strm'
) {
+85
View File
@@ -0,0 +1,85 @@
import { useCallback, useEffect, useState } from 'react'
import { Activity, AlertTriangle, CheckCircle2, Clock3, RefreshCw } from 'lucide-react'
import { tasksAPI, type BackgroundTask, type TaskSnapshot } from '../api/tasks'
import { useWebSocket } from '../hooks/useWebSocket'
function statusLabel(status: string) {
switch (status) {
case 'running': return '运行中'
case 'completed': return '已完成'
case 'failed': return '失败'
case 'interrupted': return '进程中断'
default: return status
}
}
function TaskRow({ task }: { task: BackgroundTask }) {
const Icon = task.status === 'running' ? Activity : task.status === 'completed' ? CheckCircle2 : AlertTriangle
const tone = task.status === 'running' ? 'text-blue-500' : task.status === 'completed' ? 'text-emerald-500' : 'text-amber-600'
return (
<article className="rounded-xl border border-sand-200 bg-white/60 p-3">
<div className="flex items-start gap-3">
<Icon size={17} className={`mt-0.5 shrink-0 ${tone}`} />
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="break-words text-sm font-semibold text-ink-600">{task.name}</h3>
<span className={`text-xs font-semibold ${tone}`}>{statusLabel(task.status)}</span>
</div>
<p className="mt-1 text-xs text-ink-50">{task.message || task.stage || '—'} · {new Date(task.started_at).toLocaleString()}</p>
{task.error && <p className="mt-2 break-words text-xs text-red-500">{task.error}</p>}
{task.details && task.details.length > 0 && (
<details className="mt-2 text-xs text-ink-50"><summary className="cursor-pointer">查看执行详情({task.details.length})</summary>
<ul className="mt-2 space-y-1">{task.details.map((line, index) => <li key={`${index}-${line}`} className="break-words">{line}</li>)}</ul>
</details>
)}
</div>
</div>
</article>
)
}
export function BackgroundTasksPanel() {
const [snapshot, setSnapshot] = useState<TaskSnapshot>({ active: [], recent: [] })
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const refresh = useCallback(async () => {
setLoading(true)
try {
const result = await tasksAPI.snapshot()
setSnapshot({ active: result.active ?? [], recent: result.recent ?? [] })
setError('')
} catch {
setError('读取后台任务失败,请刷新重试')
} finally { setLoading(false) }
}, [])
useEffect(() => { void refresh() }, [refresh])
useWebSocket((topic, payload) => {
if (topic !== 'task' || !payload || typeof payload !== 'object') return
const task = payload as BackgroundTask
if (!task.id || !task.status) return
setSnapshot((current) => {
const active = current.active.filter((item) => item.id !== task.id)
const recent = current.recent.filter((item) => item.id !== task.id)
if (task.status === 'running') active.unshift(task)
else recent.unshift(task)
recent.sort((left, right) => right.started_at.localeCompare(left.started_at))
return { active, recent: recent.slice(0, 30) }
})
})
return (
<section className="glass-panel space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2"><Activity size={18} className="text-brand-500" /><h2 className="font-display text-xl font-bold text-ink-600">后台扫描与整理</h2></div>
<button type="button" className="btn-outline" onClick={() => void refresh()} disabled={loading}><RefreshCw size={14} />刷新</button>
</div>
{error && <p role="alert" className="text-sm text-red-500">{error}</p>}
{snapshot.active.length > 0 && <div className="space-y-2"><h3 className="text-xs font-bold uppercase tracking-wide text-ink-50">进行中</h3>{snapshot.active.map((task) => <TaskRow key={task.id} task={task} />)}</div>}
<div className="space-y-2">
<h3 className="flex items-center gap-1 text-xs font-bold uppercase tracking-wide text-ink-50"><Clock3 size={13} />最近任务</h3>
{snapshot.recent.length > 0 ? snapshot.recent.map((task) => <TaskRow key={task.id} task={task} />) : !error && <p className="rounded-xl border border-dashed border-sand-300 px-4 py-6 text-center text-sm text-ink-50">{loading ? '正在读取任务…' : '暂无历史任务'}</p>}
</div>
</section>
)
}
+157
View File
@@ -0,0 +1,157 @@
import { useCallback, useEffect, useState } from 'react'
import { Archive, Download, LoaderCircle, RefreshCw, RotateCcw, Trash2 } from 'lucide-react'
import toast from 'react-hot-toast'
import { backupAPI, type BackupInfo } from '../api/backup'
import { adminAPI } from '../api/admin'
import { confirmAction } from '../components/confirmAction'
function formatBytes(value: number) {
if (value < 1024) return `${value} B`
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`
return `${(value / (1024 * 1024)).toFixed(1)} MB`
}
export function BackupSettingsPanel() {
const [items, setItems] = useState<BackupInfo[]>([])
const [loading, setLoading] = useState(true)
const [creating, setCreating] = useState(false)
const [autoEnabled, setAutoEnabled] = useState(false)
const [autoTime, setAutoTime] = useState('03:00')
const [retention, setRetention] = useState('7')
const [savingPolicy, setSavingPolicy] = useState(false)
const refresh = useCallback(async () => {
setLoading(true)
try {
setItems(await backupAPI.list())
} catch {
toast.error('读取备份列表失败')
} finally {
setLoading(false)
}
}, [])
useEffect(() => { void refresh() }, [refresh])
useEffect(() => {
void adminAPI.listSettings().then((settings) => {
const values = new Map(settings.map((setting) => [setting.key, setting.value]))
setAutoEnabled(['true', '1'].includes(values.get('backup.auto_enabled') ?? 'false'))
setAutoTime(values.get('backup.auto_time') || '03:00')
setRetention(values.get('backup.retention') || '7')
}).catch(() => toast.error('读取自动备份设置失败'))
}, [])
const savePolicy = async () => {
const count = Number(retention)
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(autoTime) || !Number.isInteger(count) || count < 1 || count > 365) {
toast.error('请填写有效时间,并将保留份数设为 1 到 365')
return
}
setSavingPolicy(true)
try {
await adminAPI.updateSetting('backup.auto_time', autoTime)
await adminAPI.updateSetting('backup.retention', String(count))
await adminAPI.updateSetting('backup.auto_enabled', String(autoEnabled))
toast.success('自动备份设置已保存')
} catch {
toast.error('保存自动备份设置失败')
} finally {
setSavingPolicy(false)
}
}
const create = async () => {
setCreating(true)
try {
const item = await backupAPI.create()
toast.success(`备份已创建:${item.filename}`)
await refresh()
} catch {
toast.error('创建备份失败,请查看服务日志')
} finally {
setCreating(false)
}
}
const remove = async (item: BackupInfo) => {
if (!await confirmAction({ title: '删除备份', message: `确定删除 ${item.filename}?此操作无法撤销。` })) return
try {
await backupAPI.remove(item.filename)
setItems((current) => current.filter((entry) => entry.filename !== item.filename))
toast.success('备份已删除')
} catch {
toast.error('删除备份失败')
}
}
const restore = async (item: BackupInfo) => {
const ok = await confirmAction({
title: '恢复数据库备份',
message: `将恢复 ${item.filename}。SQLite 会先校验并暂存备份,在重启时应用;PostgreSQL 会立即事务恢复。请先保存当前数据库备份,并在操作后重启 MeBox。`,
confirmText: '恢复备份',
danger: true,
})
if (!ok) return
try {
const result = await backupAPI.restore(item.filename)
toast.success(result.message, { duration: 8000 })
} catch (error) {
const message = (error as { response?: { data?: { error?: string } } })?.response?.data?.error
toast.error(message || '恢复失败,请查看服务日志')
}
}
return (
<section className="glass-panel space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-3">
<Archive className="text-brand-500" size={20} />
<div>
<h2 className="font-display text-xl font-bold text-ink-600">数据库备份</h2>
<p className="text-xs text-ink-50">备份保存在服务器数据目录的 backups 文件夹中;请另行复制到其他设备。</p>
</div>
</div>
<div className="flex gap-2">
<button type="button" className="btn-outline" onClick={() => void refresh()} disabled={loading}><RefreshCw size={14} />刷新</button>
<button type="button" className="btn-primary" onClick={() => void create()} disabled={creating}>
{creating ? <LoaderCircle className="animate-spin" size={14} /> : <Archive size={14} />}立即备份
</button>
</div>
</div>
<div className="grid gap-3 rounded-xl border border-sand-200 p-4 sm:grid-cols-[1fr_auto_auto_auto] sm:items-end">
<label className="flex items-center gap-2 text-sm font-semibold text-ink-600">
<input type="checkbox" checked={autoEnabled} onChange={(event) => setAutoEnabled(event.target.checked)} />
每日自动备份
</label>
<label className="space-y-1 text-xs text-ink-50">执行时间
<input type="time" value={autoTime} onChange={(event) => setAutoTime(event.target.value)} className="block rounded-lg border border-sand-300 bg-white px-3 py-2 text-sm text-ink-600" />
</label>
<label className="space-y-1 text-xs text-ink-50">自动备份保留份数
<input type="number" min={1} max={365} value={retention} onChange={(event) => setRetention(event.target.value)} className="block w-28 rounded-lg border border-sand-300 bg-white px-3 py-2 text-sm text-ink-600" />
</label>
<button type="button" className="btn-outline" onClick={() => void savePolicy()} disabled={savingPolicy}>{savingPolicy ? '保存中…' : '保存策略'}</button>
</div>
{loading ? <div className="py-8 text-center text-sm text-ink-50">正在读取备份…</div> : items.length === 0 ? (
<div className="rounded-xl border border-dashed border-sand-300 px-4 py-8 text-center text-sm text-ink-50">还没有数据库备份</div>
) : (
<div className="divide-y divide-sand-200">
{items.map((item) => (
<div key={item.filename} className="flex flex-wrap items-center justify-between gap-3 py-3">
<div className="min-w-0">
<div className="break-all text-sm font-semibold text-ink-600">{item.filename}</div>
<div className="mt-1 text-xs text-ink-50">{item.automatic ? '自动备份' : '手动备份'} · {new Date(item.created_at).toLocaleString()} · {formatBytes(item.size)}</div>
</div>
<div className="flex flex-wrap gap-2">
<button type="button" className="btn-outline" onClick={() => void backupAPI.download(item.filename).catch(() => toast.error('下载备份失败'))}><Download size={14} />下载</button>
<button type="button" className="btn-outline" onClick={() => void restore(item)}><RotateCcw size={14} />恢复</button>
<button type="button" className="btn-outline text-red-500" onClick={() => void remove(item)}><Trash2 size={14} />删除</button>
</div>
</div>
))}
</div>
)}
</section>
)
}
+74
View File
@@ -0,0 +1,74 @@
import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { AlertTriangle, ChevronLeft, ChevronRight, ImageOff, Search, WifiOff } from 'lucide-react'
import { qualityAPI, type MediaQualityIssue, type MediaQualityRow } from '../api/quality'
const tabs: { key: MediaQualityIssue; label: string; icon: typeof AlertTriangle }[] = [
{ key: 'unmatched', label: '未匹配元数据', icon: Search },
{ key: 'poster', label: '缺少海报', icon: ImageOff },
{ key: 'missing', label: '文件失联', icon: WifiOff },
]
const PAGE_SIZE = 50
export function MediaQualityPage() {
const [params, setParams] = useSearchParams()
const rawIssue = params.get('issue')
const issue: MediaQualityIssue = rawIssue === 'poster' || rawIssue === 'missing' ? rawIssue : 'unmatched'
const page = Math.max(1, Number.parseInt(params.get('page') ?? '1', 10) || 1)
const [items, setItems] = useState<MediaQualityRow[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [revision, setRevision] = useState(0)
useEffect(() => {
let cancelled = false
setLoading(true)
setError('')
void qualityAPI.list(issue, page, PAGE_SIZE).then((result) => {
if (!cancelled) { setItems(result.items ?? []); setTotal(result.total ?? 0) }
}).catch(() => {
if (!cancelled) setError('读取质量检查结果失败,请重试')
}).finally(() => { if (!cancelled) setLoading(false) })
return () => { cancelled = true }
}, [issue, page, revision])
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
const changePage = (nextPage: number) => setParams((current) => {
const next = new URLSearchParams(current)
if (nextPage <= 1) next.delete('page')
else next.set('page', String(nextPage))
return next
})
return (
<div className="space-y-5">
<header>
<h1 className="font-display text-3xl font-bold text-ink-600">媒体质量检查</h1>
<p className="mt-1 text-sm text-ink-50">集中查看待匹配、缺少海报和文件失联的媒体条目。</p>
</header>
<nav className="flex flex-wrap gap-2 border-b border-sand-200 pb-3">
{tabs.map((tab) => {
const Icon = tab.icon
return <button key={tab.key} type="button" onClick={() => setParams(tab.key === 'unmatched' ? {} : { issue: tab.key })} className={`inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold ${issue === tab.key ? 'bg-brand-500 text-white' : 'text-ink-100 hover:bg-brand-50'}`}><Icon size={15} />{tab.label}</button>
})}
<span className="ml-auto self-center text-sm text-ink-50">{loading ? '正在检查…' : error ? '读取失败' : `共 ${total} 项`}</span>
</nav>
{error && <div role="alert" className="glass-panel text-sm text-red-500">{error}<button type="button" className="ml-3 underline" onClick={() => setRevision((value) => value + 1)}>重试</button></div>}
{!error && !loading && (items.length === 0 ? <div className="glass-panel py-12 text-center text-sm text-ink-50">{page > 1 ? '本页没有结果,请返回上一页。' : '当前分类没有待处理媒体。'}</div> : (
<div className="divide-y divide-sand-200 overflow-hidden rounded-2xl border border-sand-200 bg-white/60">
{items.map(({ media }) => <article key={media.id} className="flex flex-wrap items-center justify-between gap-3 p-4">
<div className="min-w-0"><Link to={`/media/${media.id}`} className="break-words font-semibold text-ink-600 hover:text-brand-500">{media.title}</Link><p className="mt-1 break-all text-xs text-ink-50">{media.library_name || '未知媒体库'} · {media.path}</p><p className="mt-1 text-xs text-ink-50">{media.year || '年份未知'}{media.scrape_status ? ` · ${media.scrape_status}` : ''}{media.missing_since ? ` · 失联于 ${new Date(media.missing_since).toLocaleString()}` : ''}</p></div>
<Link to={`/media/${media.id}`} className="btn-outline">查看并处理</Link>
</article>)}
</div>
))}
{!loading && !error && (totalPages > 1 || page > 1) && <nav aria-label="媒体质量检查分页" className="flex items-center justify-center gap-4 py-3 text-sm">
<button type="button" className="btn-outline" disabled={page <= 1} onClick={() => changePage(page - 1)}><ChevronLeft size={15} />上一页</button>
<span className="text-ink-50">第 {page} / {totalPages} 页</span>
<button type="button" className="btn-outline" disabled={page >= totalPages} onClick={() => changePage(page + 1)}>下一页<ChevronRight size={15} /></button>
</nav>}
</div>
)
}
+77 -12
View File
@@ -1,14 +1,16 @@
import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { useLocation, useSearchParams } from 'react-router-dom'
import { ChevronLeft, ChevronRight, LoaderCircle, RefreshCw, Search } from 'lucide-react'
import { mediaAPI, type MediaSearchPage as SearchPageData } from '../api/library'
import { libraryAPI } from '../api/library'
import { MediaCard } from '../components/MediaCard'
import type { Library } from '../types'
import { PageBackButton } from '../components/PageBackButton'
import { normalizeListPosition } from '../hooks/useListPositionMemory'
import { useAuthStore } from '../stores/auth'
import { usePlayProfileStore } from '../stores/playProfile'
import { favouriteMediaLink, mediaSearchLink } from '../utils/mediaNavigation'
import { favouriteMediaLink } from '../utils/mediaNavigation'
const PAGE_SIZE = 48
const CACHE_TTL_MS = 5 * 60_000
@@ -29,40 +31,72 @@ export function MediaSearchPage() {
const [params, setParams] = useSearchParams()
const query = (params.get('q') ?? '').trim()
const page = normalizeListPosition(params.get('page'))
const filters = {
libraryId: params.get('library_id') ?? '',
yearMin: params.get('year_min') ?? '',
yearMax: params.get('year_max') ?? '',
genres: params.get('genre') ?? '',
sort: params.get('sort') ?? '',
}
const userId = useAuthStore((s) => s.user?.id)
const profileId = usePlayProfileStore((s) => s.activeProfileId)
const cacheKey = JSON.stringify([userId, profileId, query, page])
const cacheKey = JSON.stringify([userId, profileId, query, page, filters])
const changePage = (next: number) => {
const nextParams = new URLSearchParams({ q: query })
const nextParams = new URLSearchParams(params)
nextParams.set('q', query)
if (next > 1) nextParams.set('page', String(next))
else nextParams.delete('page')
setParams(nextParams)
}
const changeFilter = (key: keyof typeof filters, value: string) => {
const next = new URLSearchParams(params)
const queryKey = { libraryId: 'library_id', yearMin: 'year_min', yearMax: 'year_max', genres: 'genre', sort: 'sort' }[key]
if (value.trim()) next.set(queryKey, value)
else next.delete(queryKey)
next.delete('page')
setParams(next, { replace: true })
}
return (
<MediaSearchResults
key={cacheKey}
key={JSON.stringify([userId, profileId])}
cacheKey={cacheKey}
query={query}
page={page}
onPageChange={changePage}
filters={filters}
onFilterChange={changeFilter}
/>
)
}
function MediaSearchResults({ cacheKey, query, page, onPageChange }: {
function MediaSearchResults({ cacheKey, query, page, onPageChange, filters, onFilterChange }: {
cacheKey: string
query: string
page: number
onPageChange: (page: number) => void
filters: { libraryId: string; yearMin: string; yearMax: string; genres: string; sort: string }
onFilterChange: (key: keyof { libraryId: string; yearMin: string; yearMax: string; genres: string; sort: string }, value: string) => void
}) {
const location = useLocation()
const [data, setData] = useState(() => readCachedPage(cacheKey))
const [loading, setLoading] = useState(() => !!query && !readCachedPage(cacheKey))
const [error, setError] = useState('')
const [revision, setRevision] = useState(0)
const [libraries, setLibraries] = useState<Library[]>([])
useEffect(() => { void libraryAPI.list().then(setLibraries).catch(() => setLibraries([])) }, [])
useEffect(() => {
if (!query) return
if (!query) {
setData(null)
setLoading(false)
setError('')
return
}
setError('')
const cached = readCachedPage(cacheKey)
if (cached) {
setData(cached)
@@ -72,8 +106,15 @@ function MediaSearchResults({ cacheKey, query, page, onPageChange }: {
let cancelled = false
setLoading(true)
setError('')
mediaAPI.searchPage(query, page, PAGE_SIZE, { groupSeries: true })
setData(null)
mediaAPI.searchPage(query, page, PAGE_SIZE, {
groupSeries: true,
libraryId: filters.libraryId || undefined,
yearMin: Number(filters.yearMin) || undefined,
yearMax: Number(filters.yearMax) || undefined,
genres: filters.genres.split(/[,,]/).map((value) => value.trim()).filter(Boolean),
sort: filters.sort === 'title_asc' || filters.sort === 'year_desc' || filters.sort === 'rating_desc' ? filters.sort : undefined,
})
.then((result) => {
if (cancelled) return
// 限制缓存大小,避免长时间搜索大量关键词后占用过多内存。
@@ -89,7 +130,7 @@ function MediaSearchResults({ cacheKey, query, page, onPageChange }: {
})
return () => { cancelled = true }
}, [cacheKey, query, page, revision])
}, [cacheKey, query, page, revision, filters.libraryId, filters.yearMin, filters.yearMax, filters.genres, filters.sort])
const refresh = () => {
pageCache.delete(cacheKey)
@@ -99,7 +140,7 @@ function MediaSearchResults({ cacheKey, query, page, onPageChange }: {
const items = data?.items ?? []
const total = data?.total ?? items.length
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
const from = mediaSearchLink(query, page)
const from = location.pathname + location.search
return (
<div className="space-y-6">
@@ -126,6 +167,30 @@ function MediaSearchResults({ cacheKey, query, page, onPageChange }: {
)}
</div>
{query && (
<div className="grid gap-3 rounded-2xl border border-[var(--app-border)] bg-[var(--app-panel)] p-4 sm:grid-cols-2 lg:grid-cols-5">
<label className="space-y-1 text-xs text-[var(--app-muted)]">媒体库
<select value={filters.libraryId} onChange={(event) => onFilterChange('libraryId', event.target.value)} className="block w-full rounded-lg border border-[var(--app-border)] bg-[var(--app-panel-soft)] px-3 py-2 text-sm text-[var(--app-text)]">
<option value="">所有媒体库</option>{libraries.map((library) => <option key={library.id} value={library.id}>{library.name}</option>)}
</select>
</label>
<label className="space-y-1 text-xs text-[var(--app-muted)]">年份从
<input type="number" min={1870} max={2200} value={filters.yearMin} onChange={(event) => onFilterChange('yearMin', event.target.value)} placeholder="不限" className="block w-full rounded-lg border border-[var(--app-border)] bg-[var(--app-panel-soft)] px-3 py-2 text-sm text-[var(--app-text)]" />
</label>
<label className="space-y-1 text-xs text-[var(--app-muted)]">年份至
<input type="number" min={1870} max={2200} value={filters.yearMax} onChange={(event) => onFilterChange('yearMax', event.target.value)} placeholder="不限" className="block w-full rounded-lg border border-[var(--app-border)] bg-[var(--app-panel-soft)] px-3 py-2 text-sm text-[var(--app-text)]" />
</label>
<label className="space-y-1 text-xs text-[var(--app-muted)]">类型(逗号分隔)
<input value={filters.genres} onChange={(event) => onFilterChange('genres', event.target.value)} placeholder="动画,科幻" className="block w-full rounded-lg border border-[var(--app-border)] bg-[var(--app-panel-soft)] px-3 py-2 text-sm text-[var(--app-text)]" />
</label>
<label className="space-y-1 text-xs text-[var(--app-muted)]">排序
<select value={filters.sort} onChange={(event) => onFilterChange('sort', event.target.value)} className="block w-full rounded-lg border border-[var(--app-border)] bg-[var(--app-panel-soft)] px-3 py-2 text-sm text-[var(--app-text)]">
<option value="">相关度 / 最近添加</option><option value="title_asc">名称 A–Z</option><option value="year_desc">年份从新到旧</option><option value="rating_desc">评分从高到低</option>
</select>
</label>
</div>
)}
{loading && (
<div role="status" className="flex items-center justify-center gap-2 py-20 text-sm text-[var(--app-muted)]">
<LoaderCircle size={18} className="animate-spin text-brand-500" />
@@ -148,7 +213,7 @@ function MediaSearchResults({ cacheKey, query, page, onPageChange }: {
</div>
)}
{!loading && items.length > 0 && (
{!loading && !error && query && items.length > 0 && (
<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((item) => (
<MediaCard key={item.id} media={item} showLibrary linkTo={favouriteMediaLink(item)} linkState={{ from }} />
+95 -1
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import type Hls from 'hls.js'
import toast from 'react-hot-toast'
import { Activity, Clipboard, X } from 'lucide-react'
import { mediaAPI, libraryAPI } from '../api/library'
import { cloudHlsURL, hlsURL, postPlaybackProgressKeepalive, stopHLSJob, streamURL } from '../api/client'
@@ -80,6 +81,8 @@ type PlaybackProgressSession = {
sequence: number
}
type PlayerDiagnosticEvent = { at: string; phase: string; mode: string; message: string }
// 自动跳过片头后,「已跳过 · 撤销」提示停留的时长。
const SKIP_NOTICE_MS = 6000
@@ -148,6 +151,10 @@ export function PlayerPage() {
vr360DirectProxyRef.current = vr360DirectProxy
}, [vr360DirectProxy])
const [mode, setMode] = useState<PlayerMode>('direct')
const diagnosticModeRef = useRef(mode)
useEffect(() => { diagnosticModeRef.current = mode }, [mode])
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false)
const [diagnosticEvents, setDiagnosticEvents] = useState<PlayerDiagnosticEvent[]>([])
const [subs, setSubs] = useState<SubtitleTrack[]>([])
const [subtitleIndex, setSubtitleIndex] = useState<number>(0)
const authUser = useAuthStore((state) => state.user)
@@ -498,6 +505,8 @@ export function PlayerPage() {
// 切换视频时重置媒体与弹幕状态,确保新视频自动重新识别并加载弹幕
useEffect(() => {
setMedia(null)
setDiagnosticEvents([])
setDiagnosticsOpen(false)
setLoadError('')
vr360TouchedRef.current = false
vr360TextureRetryUsedRef.current = false
@@ -556,6 +565,33 @@ export function PlayerPage() {
setMode(next)
}, [])
const recordDiagnostic = useCallback((phase: string, message: string) => {
const safeMessage = message
.replace(/https?:\/\/[^\s"'<>]+/gi, '[URL]')
.replace(/\b(token|auth|api[_-]?key|password)=([^\s&]+)/gi, '$1=[redacted]')
setDiagnosticEvents((current) => [...current.slice(-39), {
at: new Date().toISOString(), phase, mode: diagnosticModeRef.current, message: safeMessage.slice(0, 300),
}])
}, [])
useEffect(() => {
const video = ref.current
if (!video) return
const bindings: Array<[string, string]> = [
['loadedmetadata', '已读取媒体信息'],
['playing', '开始播放'],
['waiting', '等待缓冲'],
['stalled', '媒体数据停止到达'],
['seeked', '定位完成'],
]
const listeners = bindings.map(([event, message]) => {
const listener = () => recordDiagnostic(event === 'waiting' || event === 'stalled' ? 'buffer' : 'play', message)
video.addEventListener(event, listener)
return [event, listener] as const
})
return () => { for (const [event, listener] of listeners) video.removeEventListener(event, listener) }
}, [media?.id, recordDiagnostic])
const clearFallbackTimer = useCallback(() => {
if (fallbackTimerRef.current) {
clearTimeout(fallbackTimerRef.current)
@@ -569,9 +605,10 @@ export function PlayerPage() {
* 只有画面没有声音」)不走这里,它们播起来之后依然成立。
*/
const showPlayFailure = useCallback((message: string) => {
recordDiagnostic('error', message)
transientPlayErrorRef.current = message
setPlayerError(message)
}, [])
}, [recordDiagnostic])
const clearPlayFailure = useCallback(() => {
const stale = transientPlayErrorRef.current
@@ -1199,6 +1236,7 @@ export function PlayerPage() {
if (Date.now() < directSeekGraceUntilRef.current) return
const current = ref.current
if (current && current.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) return
recordDiagnostic('fallback', `直连失败,原因:${reason}`)
if (isRemoteEmbyID(mediaRef.current?.id) || isDirectStreamMedia(mediaRef.current)) {
const copy = directPlayFailureCopy('remote-emby', reason)
showPlayFailure(copy.banner)
@@ -1234,6 +1272,7 @@ export function PlayerPage() {
directOnly,
hlsUnavailable,
playbackInfo,
recordDiagnostic,
selectedQuality,
setPlaybackMode,
showPlayFailure,
@@ -2381,6 +2420,32 @@ export function PlayerPage() {
// 桌面端与横屏手机保持原来的全屏居中沉浸式布局。
const isMobileTheater = useIsMobileTheater()
const copyDiagnostics = async () => {
const video = ref.current
const snapshot = {
title: media?.title || '',
sourceType: isRemoteEmbyID(media?.id) ? 'remote_emby' : isStrmMedia(media) ? 'strm' : 'local',
mode,
hlsSource: mode === 'hls' ? hlsSource : undefined,
quality: selectedQuality || undefined,
browser: navigator.userAgent,
video: video ? {
errorCode: video.error?.code ?? null,
readyState: video.readyState,
networkState: video.networkState,
currentTime: Number.isFinite(video.currentTime) ? Math.round(video.currentTime) : null,
duration: Number.isFinite(video.duration) ? Math.round(video.duration) : null,
} : null,
events: diagnosticEvents,
}
try {
await navigator.clipboard.writeText(JSON.stringify(snapshot, null, 2))
toast.success('播放诊断信息已复制(未包含播放地址或登录凭证)')
} catch {
toast.error('复制失败,请检查浏览器剪贴板权限')
}
}
return (
<div className="relative flex h-full w-full flex-1 flex-col overflow-hidden bg-black">
<PlayerTopBar
@@ -2543,6 +2608,35 @@ export function PlayerPage() {
}
/>
) : null}
<button
type="button"
onClick={() => setDiagnosticsOpen((open) => !open)}
className="fixed bottom-5 right-4 z-[80] inline-flex items-center gap-2 rounded-full border border-white/15 bg-black/75 px-3 py-2 text-xs font-semibold text-white shadow-lg backdrop-blur hover:bg-black/90"
title="播放诊断"
aria-label="播放诊断"
>
<Activity size={15} />诊断
</button>
{diagnosticsOpen && (
<aside className="fixed bottom-16 right-4 z-[80] max-h-[70vh] w-[min(92vw,420px)] overflow-hidden rounded-2xl border border-white/15 bg-[#111827]/95 text-white shadow-2xl backdrop-blur">
<div className="flex items-center justify-between border-b border-white/10 px-4 py-3">
<div><h2 className="text-sm font-bold">播放诊断</h2><p className="mt-1 text-[11px] text-white/60">记录最近 40 条本地播放事件</p></div>
<div className="flex gap-2">
<button type="button" onClick={() => void copyDiagnostics()} className="inline-flex items-center gap-1 rounded-lg bg-white/10 px-2.5 py-1.5 text-xs hover:bg-white/15"><Clipboard size={13} />复制</button>
<button type="button" onClick={() => setDiagnosticsOpen(false)} className="rounded-lg p-1.5 hover:bg-white/10" aria-label="关闭"><X size={16} /></button>
</div>
</div>
<div className="max-h-[55vh] space-y-2 overflow-y-auto p-3">
<div className="rounded-lg bg-white/5 px-3 py-2 text-xs text-white/70">模式:{mode === 'hls' ? `HLS / ${hlsSource}` : '直连'} · 来源:{isRemoteEmbyID(media?.id) ? '远程 Emby' : isStrmMedia(media) ? 'STRM' : '本地文件'}</div>
{diagnosticEvents.length === 0 ? <p className="py-6 text-center text-xs text-white/50">等待播放事件…</p> : [...diagnosticEvents].reverse().map((event, index) => (
<div key={`${event.at}-${index}`} className="rounded-lg bg-white/5 px-3 py-2">
<div className="flex justify-between gap-2 text-[10px] text-white/45"><span>{event.phase} · {event.mode}</span><time>{new Date(event.at).toLocaleTimeString()}</time></div>
<p className="mt-1 break-words text-xs">{event.message}</p>
</div>
))}
</div>
</aside>
)}
</div>
)
}
+2
View File
@@ -11,6 +11,7 @@ import { FFToolsPanel } from '../components/FFToolsPanel'
import { AboutSettingsPanel } from './AboutSettingsPanel'
import { AdultSettingsPanel } from './AdultSettingsPanel'
import { DatabaseSettingsPanel } from './DatabaseSettingsPanel'
import { BackupSettingsPanel } from './BackupSettingsPanel'
import { RecognitionWordsPanel } from './RecognitionWordsPanel'
import { SettingRow } from './SettingsRow'
import { TelegramNotifyPanel } from './TelegramNotifyPanel'
@@ -172,6 +173,7 @@ export function SettingsPage() {
{!loading && (
<div className="space-y-4">
{group.key === 'database' && <DatabaseSettingsPanel />}
{group.key === 'backup' && <BackupSettingsPanel />}
{group.key === 'api-configs' && <APIConfigsPanel />}
{group.key === 'recognition-words' && <RecognitionWordsPanel />}
{group.key === 'adult' && <AdultSettingsPanel />}
+100
View File
@@ -0,0 +1,100 @@
import { useEffect, useState, type ReactNode } from 'react'
import { Link } from 'react-router-dom'
import { CheckCircle2, Circle, Database, Film, KeyRound, Server, Wrench } from 'lucide-react'
import { adminAPI, type DatabaseStatus } from '../api/admin'
import { apiConfigsAPI, type APIConfig } from '../api/api_configs'
import { libraryAPI, mediaAPI } from '../api/library'
import { toolsAPI, type FFmpegToolsStatus } from '../api/tools'
import type { Library } from '../types'
import type { SeriesCard } from '../utils/groupSeries'
type CheckResult = { ok: boolean; message: string }
type SetupStepProps = { done: boolean; title: string; detail: string; icon: typeof Database; children?: ReactNode }
function SetupStep({ done, title, detail, icon: Icon, children }: SetupStepProps) {
return (
<section className="glass-panel space-y-3">
<div className="flex items-start gap-3"><div className="mt-0.5 text-brand-500"><Icon size={20} /></div><div className="min-w-0 flex-1"><div className="flex items-center gap-2"><h2 className="font-display text-lg font-bold text-ink-600">{title}</h2>{done ? <CheckCircle2 size={16} className="text-emerald-500" /> : <Circle size={16} className="text-ink-50" />}</div><p className="mt-1 text-sm text-ink-50">{detail}</p></div></div>
{children}
</section>
)
}
export function SetupWizardPage() {
const [database, setDatabase] = useState<DatabaseStatus | null>(null)
const [libraries, setLibraries] = useState<Library[]>([])
const [sources, setSources] = useState<APIConfig[]>([])
const [ffmpeg, setFFmpeg] = useState<FFmpegToolsStatus | null>(null)
const [checks, setChecks] = useState<Record<string, CheckResult>>({})
const [busy, setBusy] = useState('')
const [recent, setRecent] = useState<SeriesCard | null>(null)
const [playbackVerified, setPlaybackVerified] = useState(false)
const refresh = async () => {
setBusy('refresh')
try {
const [db, libs, configs, tools, media] = await Promise.allSettled([
adminAPI.getDatabaseStatus(), libraryAPI.list(), apiConfigsAPI.list(), toolsAPI.ffToolsStatus(), mediaAPI.recent(1),
])
if (db.status === 'fulfilled') setDatabase(db.value)
if (libs.status === 'fulfilled') setLibraries(libs.value)
if (configs.status === 'fulfilled') setSources(configs.value)
if (tools.status === 'fulfilled') setFFmpeg(tools.value)
if (media.status === 'fulfilled') setRecent(media.value[0] ?? null)
const failed = [db, libs, configs, tools, media].some((result) => result.status === 'rejected')
setChecks((value) => ({ ...value, load: { ok: !failed, message: failed ? '部分检查项读取失败,请刷新状态后重试' : '' } }))
} finally {
setBusy('')
}
}
useEffect(() => { void refresh() }, [])
const testSources = async () => {
const enabled = sources.filter((source) => source.enabled)
if (!enabled.length) {
setChecks((value) => ({ ...value, sources: { ok: false, message: '尚未启用元数据源,可先前往管理来源配置' } }))
return
}
setBusy('sources')
const results = await Promise.all(enabled.map(async (source) => {
try { const result = await apiConfigsAPI.test(source.provider); return { name: source.provider, ok: !result.error, message: result.error || result.result } }
catch { return { name: source.provider, ok: false, message: '连接测试失败' } }
}))
const failed = results.filter((result) => !result.ok)
setChecks((value) => ({ ...value, sources: { ok: failed.length === 0, message: failed.length ? `${failed.length}/${results.length} 个来源测试失败:${failed.map((result) => `${result.name}(${result.message})`).join('、')}` : `已完成 ${results.length} 个来源的连接测试` } }))
setBusy('')
}
const scanLibrary = async (library: Library) => {
setBusy(library.id)
try {
const result = await libraryAPI.scan(library.id)
setChecks((value) => ({ ...value, [`scan:${library.id}`]: { ok: !result.queued, message: result.message || (result.queued ? '扫描已提交,请在任务队列确认是否完成' : `扫描完成:新增 ${result.added ?? 0} 项`) } }))
} catch {
setChecks((value) => ({ ...value, [`scan:${library.id}`]: { ok: false, message: '扫描失败,请检查容器内路径和目录权限' } }))
} finally { setBusy('') }
}
return (
<div className="mx-auto max-w-4xl space-y-5">
<header className="flex flex-wrap items-end justify-between gap-3"><div><h1 className="font-display text-3xl font-bold text-ink-600">首次配置向导</h1><p className="mt-1 text-sm text-ink-50">逐项检查配置,完成后可以随时回到对应设置调整。</p></div><button type="button" className="btn-outline" disabled={busy !== ''} onClick={() => void refresh()}>刷新状态</button></header>
{checks.load && !checks.load.ok && <p role="alert" className="glass-panel text-sm text-red-500">{checks.load.message}</p>}
<SetupStep done={Boolean(database)} title="数据库" detail={database ? `${database.type.toUpperCase()} · ${database.open_conns} 个连接` : '正在检查数据库'} icon={Database} />
<SetupStep done={Boolean(ffmpeg?.ffmpeg?.installed && ffmpeg?.ffprobe?.installed)} title="播放工具" detail={ffmpeg?.ffmpeg?.installed ? ffmpeg.ffmpeg.version || 'FFmpeg 已安装' : 'FFmpeg 未安装,浏览器不兼容的媒体无法转码'} icon={Wrench}>
{!ffmpeg?.ffmpeg?.installed && <Link to="/settings?group=general" className="btn-outline inline-flex">前往安装 FFmpeg</Link>}
</SetupStep>
<SetupStep done={Boolean(checks.sources?.ok)} title="元数据源" detail={checks.sources?.message || `${sources.filter((source) => source.enabled).length} 个已启用来源`} icon={KeyRound}>
<div className="flex flex-wrap items-center gap-3"><button type="button" className="btn-outline" disabled={busy !== ''} onClick={() => void testSources()}>{busy === 'sources' ? '测试中…' : '测试已配置来源'}</button><Link to="/settings?group=api-configs" className="text-sm text-brand-500">管理来源</Link></div>
</SetupStep>
<SetupStep done={libraries.length > 0 && libraries.every((library) => library.is_remote_emby || checks[`scan:${library.id}`]?.ok)} title="媒体库与目录" detail={libraries.length ? `已配置 ${libraries.length} 个媒体库;扫描会遍历所选本地库的全部目录,请先确认 Compose 中挂载了正确的容器路径` : '请先创建媒体库并填写容器内路径'} icon={Server}>
{libraries.length ? <div className="space-y-2">{libraries.map((library) => <div key={library.id} className="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-sand-200 p-3"><div className="min-w-0"><p className="text-sm font-semibold text-ink-600">{library.name}{library.is_remote_emby && <span className="ml-2 text-xs font-normal text-ink-50">远程只读</span>}</p><p className="break-all text-xs text-ink-50">{library.path}</p>{checks[`scan:${library.id}`] && <p className={`mt-1 text-xs ${checks[`scan:${library.id}`].ok ? 'text-emerald-600' : 'text-red-500'}`}>{checks[`scan:${library.id}`].message}</p>}</div>{!library.is_remote_emby && <button type="button" className="btn-outline" disabled={busy !== ''} onClick={() => void scanLibrary(library)}>{busy === library.id ? '提交中…' : '扫描整个媒体库'}</button>}</div>)}</div> : <Link to="/libraries" className="btn-outline inline-flex">创建媒体库</Link>}
</SetupStep>
<SetupStep done={playbackVerified} title="验证播放" detail={recent ? `最近入库:${recent.rep.title};播放后请确认画面和声音正常` : '先完成媒体库扫描,找到一个可播放条目'} icon={Film}>
{recent && <Link to={`/play/${recent.linkMedia?.id ?? recent.rep.id}`} className="btn-primary inline-flex">播放测试片</Link>}
{recent && <label className="ml-3 inline-flex items-center gap-2 text-sm text-ink-100"><input type="checkbox" checked={playbackVerified} onChange={(event) => setPlaybackVerified(event.target.checked)} />已确认播放正常</label>}
</SetupStep>
<div className="flex flex-wrap gap-3"><Link to="/queue" className="btn-outline">查看任务进度</Link><Link to="/settings" className="btn-outline">打开系统设置</Link></div>
</div>
)
}
+3 -1
View File
@@ -7,6 +7,7 @@ import { scraperAPI } from '../api/scraper'
import { strmAPI } from '../api/strm'
import { ScraperQueuePage } from './ScraperQueuePage'
import { StrmQueuePanel } from './StrmQueuePage'
import { BackgroundTasksPanel } from './BackgroundTasksPanel'
type QueueType = 'all' | 'scrape' | 'download' | 'upload'
@@ -73,6 +74,7 @@ export function TaskQueuePage() {
return (
<div className="space-y-5">
<BackgroundTasksPanel />
<div className="flex flex-wrap items-end justify-between gap-3">
<div>
<h1 className="font-display text-3xl font-bold text-ink-600">任务队列</h1>
@@ -145,4 +147,4 @@ export function TaskQueuePage() {
)}
</div>
)
}
}
@@ -39,6 +39,9 @@ export default function ReaderSourcesPage() {
const [debugKey, setDebugKey] = useState('')
const [debugLogs, setDebugLogs] = useState<string[] | null>(null)
const [debugging, setDebugging] = useState(false)
const [batchKey, setBatchKey] = useState('')
const [batchTesting, setBatchTesting] = useState(false)
const [batchResults, setBatchResults] = useState<Record<string, { ok: boolean; message: string }>>({})
// 登录面板:记录正在登录的书源
const [loginSource, setLoginSource] = useState<ReaderSource | null>(null)
const [loggedInIds, setLoggedInIds] = useState<Record<string, boolean>>({})
@@ -122,6 +125,30 @@ export default function ReaderSourcesPage() {
}
}
const testEnabledSources = async () => {
const key = batchKey.trim()
const enabled = (sources ?? []).filter((source) => source.enabled)
if (!key) { toast.error('先填写用于检测的书名关键词'); return }
if (!enabled.length) { toast.error('没有已启用的书源'); return }
setBatchTesting(true)
setBatchResults({})
for (let offset = 0; offset < enabled.length; offset += 3) {
const batch = enabled.slice(offset, offset + 3)
const results = await Promise.all(batch.map(async (source) => {
try {
const logs = await readerAPI.smokeSource(source.id, key)
const error = logs.find((line) => line.startsWith('[错误]'))
return [source.id, { ok: !error, message: error ? error.replace(/https?:\/\/[^\s"'<>]+/gi, '[URL]') : '搜索、目录和正文链路通过' }] as const
} catch (error) {
const message = ((error as { response?: { data?: { error?: string } } })?.response?.data?.error || '检测超时或请求失败').replace(/https?:\/\/[^\s"'<>]+/gi, '[URL]')
return [source.id, { ok: false, message }] as const
}
}))
setBatchResults((current) => ({ ...current, ...Object.fromEntries(results) }))
}
setBatchTesting(false)
}
return (
<div className="mx-auto min-h-[100dvh] w-full max-w-4xl px-4 pb-16 pt-4 sm:px-6">
<div className="flex items-center gap-3">
@@ -205,6 +232,14 @@ export default function ReaderSourcesPage() {
</div>
)}
<div className="mt-4 flex flex-wrap items-center gap-2 rounded-2xl border border-[var(--app-border)] bg-[var(--app-panel)] p-3">
<input value={batchKey} onChange={(event) => setBatchKey(event.target.value)} placeholder="全链路检测关键词,例如:斗破苍穹" className="min-w-48 flex-1 rounded-xl border border-[var(--app-border)] bg-[var(--app-panel-soft)] px-3 py-2 text-xs text-[var(--app-text)] outline-none" />
<button type="button" className="btn-outline text-xs" disabled={batchTesting || !sources?.some((source) => source.enabled)} onClick={() => void testEnabledSources()}>
{batchTesting ? <><Loader2 size={12} className="mr-1 inline animate-spin" />检测中</> : '检测全部已启用书源'}
</button>
<span className="text-[10px] text-[var(--app-muted)]">每源检查搜索、详情、目录和一章正文,并发最多 3 个</span>
</div>
<div className="mt-6 space-y-2">
{sources === null && (
<div className="flex items-center justify-center py-24 text-[var(--app-muted)]">
@@ -228,6 +263,7 @@ export default function ReaderSourcesPage() {
{src.group && <span className="truncate text-2xs font-normal text-[var(--app-muted)]">{src.group}</span>}
</p>
<p className="mt-0.5 truncate text-xs text-[var(--app-muted)]">{hostOf(src.source_url)}</p>
{batchResults[src.id] && <p className={`mt-1 truncate text-[10px] ${batchResults[src.id].ok ? 'text-emerald-500' : 'text-red-400'}`}>{batchResults[src.id].message}</p>}
</div>
{/* 登录入口:仅对声明了 loginUrl/loginUi 的书源显示 */}
{src.has_login && (
+8
View File
@@ -21,10 +21,18 @@ export const aboutSettingsGroup: SettingGroup = {
items: [],
}
export const backupSettingsGroup: SettingGroup = {
key: 'backup',
label: '备份',
description: '创建、下载、恢复和清理数据库备份',
items: [],
}
export const GROUPS: SettingGroup[] = [
generalSettingsGroup,
deviceNotifySettingsGroup,
databaseSettingsGroup,
backupSettingsGroup,
apiConfigsSettingsGroup,
recognitionWordsSettingsGroup,
adultSettingsGroup,
+2
View File
@@ -1,5 +1,7 @@
export interface Media {
id: string
availability_state?: 'available' | 'missing' | string
missing_since?: string
library_id: string
library_root_id?: string
library_name?: string