fix: reduce emby load and stabilize strm scan

This commit is contained in:
ShukeBta
2026-06-11 00:18:51 +08:00
parent 859d6e9d24
commit 542e85a067
22 changed files with 1040 additions and 91 deletions
+3
View File
@@ -10,6 +10,9 @@ export const api = axios.create({
timeout: 30000,
})
export const LONG_REQUEST_TIMEOUT = 120_000
export const BATCH_REQUEST_TIMEOUT = 300_000
// Flag to prevent multiple simultaneous refresh attempts
let isRefreshing = false
let refreshSubscribers: Array<{
+4 -3
View File
@@ -1,4 +1,4 @@
import { api } from './client'
import { api, BATCH_REQUEST_TIMEOUT, LONG_REQUEST_TIMEOUT } from './client'
import type { Library, Media, ScanResult } from '../types'
export interface MediaPage {
@@ -22,15 +22,16 @@ export const libraryAPI = {
remove: (id: string) => api.delete(`/libraries/${id}`).then((r) => r.data),
scan: (id: string) =>
api.post<ScanResult>(`/libraries/${id}/scan`).then((r) => r.data),
api.post<ScanResult>(`/libraries/${id}/scan`, null, { timeout: BATCH_REQUEST_TIMEOUT }).then((r) => r.data),
scrape: (id: string) =>
api.post(`/libraries/${id}/scrape`).then((r) => r.data),
api.post(`/libraries/${id}/scrape`, null, { timeout: BATCH_REQUEST_TIMEOUT }).then((r) => r.data),
listMedia: (id: string, page = 1, pageSize = 50) =>
api
.get<MediaPage>(`/libraries/${id}/media`, {
params: { page, page_size: pageSize },
timeout: LONG_REQUEST_TIMEOUT,
})
.then((r) => r.data),
}
+10 -3
View File
@@ -1,4 +1,4 @@
import { api } from './client'
import { api, BATCH_REQUEST_TIMEOUT, LONG_REQUEST_TIMEOUT } from './client'
export type StorageType = 'alist' | 'openlist' | 's3' | 'webdav' | 'cloud115' | 'quark' | 'clouddrive2'
@@ -85,6 +85,8 @@ export const storageAPI = {
.post<{ ok: boolean; error?: string }>(`/admin/storage/${type}/test`, {
type,
config,
}, {
timeout: LONG_REQUEST_TIMEOUT,
})
.then((r) => r.data),
@@ -99,7 +101,9 @@ export const storageAPI = {
},
) =>
api
.post<{ result: CloudUploadResult; error?: string }>(`/admin/storage/${type}/upload-local`, input)
.post<{ result: CloudUploadResult; error?: string }>(`/admin/storage/${type}/upload-local`, input, {
timeout: BATCH_REQUEST_TIMEOUT,
})
.then((r) => r.data),
scanAllCloud: () =>
@@ -126,6 +130,7 @@ export const cloudAPI = {
api
.get<{ items: CloudEntry[]; error?: string }>(`/admin/cloud/${type}/list`, {
params: { dir },
timeout: LONG_REQUEST_TIMEOUT,
})
.then((r) => r.data),
@@ -136,7 +141,9 @@ export const cloudAPI = {
mount: (type: StorageType, dir = '', name = '', media_type = 'movie', dir_path = '') =>
api
.post(`/admin/cloud/${type}/mount`, { dir, dir_path, name, media_type })
.post(`/admin/cloud/${type}/mount`, { dir, dir_path, name, media_type }, {
timeout: LONG_REQUEST_TIMEOUT,
})
.then((r) => r.data),
qrStart: (type: StorageType) =>
+4 -2
View File
@@ -1,4 +1,4 @@
import { api } from './client'
import { api, BATCH_REQUEST_TIMEOUT } from './client'
export type GenerateSTRMInput = {
library_id: string
@@ -33,5 +33,7 @@ export const strmAPI = {
importURL: (libraryID: string, title: string, url: string) =>
api.post('/strm/import', { library_id: libraryID, title, url }).then((r) => r.data),
generate: (input: GenerateSTRMInput) =>
api.post<GenerateSTRMResult>('/strm/generate', input).then((r) => r.data),
api
.post<GenerateSTRMResult>('/strm/generate', input, { timeout: BATCH_REQUEST_TIMEOUT })
.then((r) => r.data),
}
+14 -3
View File
@@ -2,9 +2,12 @@ import { useEffect, useRef } from 'react'
import { useAuthStore } from '../stores/auth'
const MAX_RECONNECT_ATTEMPTS = 5
// 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.
// message to the supplied handler. Auto-reconnects with back-off while the
// auth token is present, but stops after repeated failures so an expired token
// cannot create an endless /api/ws 401 loop.
export function useWebSocket(onEvent: (topic: string, payload: unknown) => void) {
const ref = useRef<WebSocket | null>(null)
const token = useAuthStore((s) => s.token)
@@ -13,12 +16,18 @@ export function useWebSocket(onEvent: (topic: string, payload: unknown) => void)
if (!token) return
let closed = false
let timer: number | undefined
let reconnectAttempts = 0
const open = () => {
if (closed) return
if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) return
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.onopen = () => {
reconnectAttempts = 0
}
ws.onmessage = (ev) => {
try {
const msg = JSON.parse(ev.data)
@@ -31,7 +40,9 @@ export function useWebSocket(onEvent: (topic: string, payload: unknown) => void)
}
ws.onclose = () => {
if (closed) return
timer = window.setTimeout(open, 3_000)
reconnectAttempts += 1
const delay = Math.min(3_000 * reconnectAttempts, 30_000)
timer = window.setTimeout(open, delay)
}
}
+11 -1
View File
@@ -13,6 +13,8 @@ import { useAuthStore } from '../stores/auth'
import { getSeriesKey, groupSeries, isEpisodeLike, seriesTitle, type SeriesCard } from '../utils/groupSeries'
import { useWebSocket } from '../hooks/useWebSocket'
const MAX_LIBRARY_ITEMS_IN_BROWSER = 3_000
export function LibraryPage() {
const { id = '' } = useParams()
const [searchParams, setSearchParams] = useSearchParams()
@@ -77,9 +79,10 @@ export function LibraryPage() {
setLoading(true)
setItems([])
const loadAll = async () => {
const pageSize = 2000
const pageSize = 500
let page = 1
let collected: Media[] = []
let warnedLargeLibrary = false
try {
for (;;) {
const d = await libraryAPI.listMedia(id, page, pageSize)
@@ -88,6 +91,13 @@ export function LibraryPage() {
setItems(collected)
setTotal(d.total)
if (collected.length >= d.total || d.items.length < pageSize) break
if (collected.length >= MAX_LIBRARY_ITEMS_IN_BROWSER) {
if (!warnedLargeLibrary) {
warnedLargeLibrary = true
toast(`媒体库条目较多,已先加载前 ${MAX_LIBRARY_ITEMS_IN_BROWSER} 条,避免浏览器卡死。请使用搜索或更细的媒体库目录浏览。`)
}
break
}
page += 1
}
} finally {
+2 -2
View File
@@ -304,8 +304,8 @@ const GROUPS: SettingGroup[] = [
key: 'cloud.auto_sync_enabled',
label: '自动同步网盘媒体库',
type: 'toggle',
hint: '开启后后台会按间隔刷新已挂载的 cloud:// 媒体库,自动生成或更新 302/STRM 播放入口;不会下载网盘文件到本地。',
defaultValue: 'true',
hint: '默认关闭,避免 NAS 反复递归读取大型网盘目录。需要定时刷新时再开启;手动扫描仍可在外部存储页面执行。',
defaultValue: 'false',
},
{
key: 'cloud.sync_interval_seconds',
+61 -4
View File
@@ -1,5 +1,5 @@
import { FormEvent, useEffect, useState } from 'react'
import { Link as LinkIcon, Loader2, Plus, Search, Trash2, Wand2 } from 'lucide-react'
import { Link as LinkIcon, Loader2, Plus, Save, Search, Trash2, Wand2 } from 'lucide-react'
import toast from 'react-hot-toast'
import { adminAPI } from '../api/admin'
@@ -21,6 +21,9 @@ export function StrmPage() {
const [generateLibraryID, setGenerateLibraryID] = useState('')
const [baseURL, setBaseURL] = useState('')
const [outputDir, setOutputDir] = useState('')
const [strmEnabled, setStrmEnabled] = useState(true)
const [autoGenerate, setAutoGenerate] = useState(false)
const [savingSettings, setSavingSettings] = useState(false)
const [overwrite, setOverwrite] = useState(false)
const [generating, setGenerating] = useState(false)
const [generateResult, setGenerateResult] = useState<GenerateSTRMResult | null>(null)
@@ -45,6 +48,8 @@ export function StrmPage() {
const settings = Object.fromEntries(rows.map((row) => [row.key, row.value]))
setBaseURL(settings['app.server_url'] || settings['strm.base_url'] || '')
setOutputDir(settings['strm.output_dir'] || '')
setStrmEnabled(settings['strm.enabled'] !== 'false')
setAutoGenerate(settings['strm.auto_generate_enabled'] === 'true')
})
.catch(() => undefined)
}, [])
@@ -69,7 +74,7 @@ export function StrmPage() {
base_url: baseURL.trim().replace(/\/+$/, ''),
output_dir: outputDir.trim(),
overwrite,
enabled: true,
enabled: autoGenerate,
include_local: true,
})
setGenerateResult(result)
@@ -85,6 +90,24 @@ export function StrmPage() {
}
}
const saveSTRMSettings = async () => {
setSavingSettings(true)
try {
await Promise.all([
adminAPI.updateSetting('strm.enabled', String(strmEnabled)),
adminAPI.updateSetting('strm.auto_generate_enabled', String(autoGenerate)),
])
toast.success(strmEnabled ? 'STRM 播放已启用' : 'STRM 播放已关闭')
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ??
'保存 STRM 开关失败'
toast.error(msg)
} finally {
setSavingSettings(false)
}
}
const onImport = async (e: FormEvent) => {
e.preventDefault()
if (!libraryID || !title.trim() || !url.trim()) return
@@ -185,10 +208,44 @@ export function StrmPage() {
只需要填写自己的访问域名,系统会按媒体库内每个媒体批量生成可播放的 .strm 文件。
</p>
</div>
<span className="rounded-full border border-emerald-300/40 bg-emerald-400/10 px-3 py-1 text-xs font-semibold text-emerald-500">
开启后可 STRM 播放
<span className={`rounded-full border px-3 py-1 text-xs font-semibold ${
strmEnabled
? 'border-emerald-300/40 bg-emerald-400/10 text-emerald-500'
: 'border-red-300/40 bg-red-400/10 text-red-500'
}`}>
{strmEnabled ? 'STRM 播放已启用' : 'STRM 播放已关闭'}
</span>
</div>
<div className="grid gap-3 rounded-2xl border border-gray-200 bg-white/70 p-4 md:grid-cols-[1fr_1fr_auto]">
<label className="flex items-start gap-3 text-sm text-ink-100">
<input
type="checkbox"
className="mt-1 h-4 w-4 accent-primary-400"
checked={strmEnabled}
onChange={(e) => setStrmEnabled(e.target.checked)}
/>
<span>
<span className="block font-medium text-ink-600">启用 STRM 播放</span>
<span className="text-xs text-ink-50">关闭后不会跳转 STRM/网盘直链;本地文件仍按本地文件播放。</span>
</span>
</label>
<label className="flex items-start gap-3 text-sm text-ink-100">
<input
type="checkbox"
className="mt-1 h-4 w-4 accent-primary-400"
checked={autoGenerate}
onChange={(e) => setAutoGenerate(e.target.checked)}
/>
<span>
<span className="block font-medium text-ink-600">扫描后自动刷新 STRM 文件</span>
<span className="text-xs text-ink-50">默认关闭,避免扫描大型网盘库时重复写文件。</span>
</span>
</label>
<button type="button" className="neon-button self-center" disabled={savingSettings} onClick={saveSTRMSettings}>
{savingSettings ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
保存开关
</button>
</div>
<form onSubmit={onGenerate} className="grid gap-3 md:grid-cols-4">
<select
required