Skip to content

一分钟搭建影视站,支持Docker等部署方式

fix: 导入配置前先 flush 节流持久化缓冲,修复导入被旧状态覆盖静默丢失的竞态

bestZweiee31138f96e4
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index 349aa71..32c4fc0 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -23,6 +23,7 @@ import type { SourceConfig } from '@/lib/types';
import { useToast } from './toast';
import { formatRelativeTime, hostnameOf, validateSourceUrl, cn } from '@/lib/utils';
import { exportConfig, importConfig } from '@/lib/db';
+import { PERSIST_KEY } from '@/lib/persist-storage';
import { useAuth } from './auth';
import { api } from '@/lib/client-api';
import { syncSourceSubscription } from '@/lib/subscription-sync';
@@ -1098,7 +1099,7 @@ function summarizeConfig(text: string): string {
if (cfg.name !== 'LibreTV-Settings') throw new Error('不是 LibreTV 的配置文件');
const parts: string[] = [];
- const settingsRaw = cfg.data?.['libretv-settings'];
+ const settingsRaw = cfg.data?.[PERSIST_KEY];
if (typeof settingsRaw === 'string') {
try {
const state = (JSON.parse(settingsRaw) as { state?: Record<string, unknown> }).state ?? {};
diff --git a/src/lib/db.ts b/src/lib/db.ts
index 2d15f4b..484160d 100644
--- a/src/lib/db.ts
+++ b/src/lib/db.ts
@@ -2,6 +2,7 @@ import Dexie, { type EntityTable } from 'dexie';
import type { SourceConfig } from './types';
// 仅类型引入:store.ts 运行时会引用本模块,反向只取类型不会形成运行时循环
import type { LiveProbeEntry } from './store';
+import { PERSIST_KEY, flushPendingPersist } from './persist-storage';
/**
* IndexedDB 持久化(替代旧版 localStorage 数据库):
@@ -170,13 +171,15 @@ export async function clearLiveProbeResultsDb(): Promise<void> {
// —— 配置导入导出(兼容旧版 LibreTV-Settings JSON 结构的导出格式) ——
export async function exportConfig(): Promise<string> {
+ // 导出前 flush:把节流缓冲中的最新设置落盘,避免导出的是 800ms 前的旧快照
+ flushPendingPersist();
const history = await db.history.toArray();
- const settings = localStorage.getItem('libretv-settings');
+ const settings = localStorage.getItem(PERSIST_KEY);
const data: Record<string, unknown> = {
viewingHistory: JSON.stringify(history),
};
- if (settings) data['libretv-settings'] = settings;
+ if (settings) data[PERSIST_KEY] = settings;
return JSON.stringify({
name: 'LibreTV-Settings',
@@ -194,8 +197,11 @@ export async function importConfig(content: string): Promise<void> {
if (config.name !== 'LibreTV-Settings') throw new Error('配置文件格式不正确');
const data = config.data || {};
- if (typeof data['libretv-settings'] === 'string') {
- localStorage.setItem('libretv-settings', data['libretv-settings']);
+ if (typeof data[PERSIST_KEY] === 'string') {
+ // 关键:先 flush 节流缓冲中的旧状态再写导入配置,否则缓冲会在
+ // 之后 flush 时用导入前的旧状态覆盖刚写入的配置(导入静默丢失)
+ flushPendingPersist();
+ localStorage.setItem(PERSIST_KEY, data[PERSIST_KEY]);
}
if (typeof data['viewingHistory'] === 'string') {
diff --git a/src/lib/persist-storage.ts b/src/lib/persist-storage.ts
new file mode 100644
index 0000000..39ca3bb
--- /dev/null
+++ b/src/lib/persist-storage.ts
@@ -0,0 +1,75 @@
+/**
+ * zustand persist 用的节流 localStorage 包装(独立成模块的原因:
+ * db.ts 的 importConfig 需要 flush 节流缓冲,而运行时依赖方向是 store → db,
+ * db.ts 不能反向 import store,故把两者共用的存储逻辑放在这个无依赖的底层模块)。
+ */
+
+import type { StateStorage } from 'zustand/middleware';
+
+/** store 持久化在 localStorage 中的键(store.ts 的 persist name 与 importConfig 共用) */
+export const PERSIST_KEY = 'libretv-settings';
+
+/** 节流窗口:搜索/测活等高频 set 合并为 800ms 一次落盘 */
+const THROTTLE_MS = 800;
+
+let timer: ReturnType<typeof setTimeout> | null = null;
+let pending: [string, string] | null = null;
+
+function flush(): void {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ if (!pending) return;
+ const [key, value] = pending;
+ pending = null;
+ try {
+ localStorage.setItem(key, value);
+ } catch {
+ // 配额不足 / 隐私模式下静默放弃持久化,内存态仍可用
+ }
+}
+
+if (typeof window !== 'undefined') {
+ window.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') flush();
+ });
+ window.addEventListener('beforeunload', flush);
+}
+
+/**
+ * 立即落盘缓冲中的待写状态。
+ * importConfig 直接写 localStorage 前必须先调用,否则缓冲中的旧状态
+ * 会在导入后 flush 覆盖刚写入的配置(竞态见 db.ts importConfig)。
+ */
+export function flushPendingPersist(): void {
+ flush();
+}
+
+/**
+ * 节流写入的 localStorage 包装。
+ * 搜索会逐源写健康度、测活每 200ms 合并写回,这些都会触发 persist 的整份序列化 + 写盘;
+ * 这里把写入合并为 800ms 一次,并在页面隐藏/卸载时立即 flush,确保不丢最后一次修改。
+ */
+export function createThrottledStorage(): StateStorage {
+ return {
+ getItem: (name) => {
+ try {
+ return localStorage.getItem(name);
+ } catch {
+ return null;
+ }
+ },
+ setItem: (name, value) => {
+ pending = [name, value];
+ if (!timer) timer = setTimeout(flush, THROTTLE_MS);
+ },
+ removeItem: (name) => {
+ try {
+ localStorage.removeItem(name);
+ } catch {
+ // 忽略
+ }
+ },
+ };
+}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 7136a20..0de397a 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -1,9 +1,10 @@
'use client';
import { create } from 'zustand';
-import { createJSONStorage, persist, type StateStorage } from 'zustand/middleware';
+import { createJSONStorage, persist } from 'zustand/middleware';
import type { SourceConfig, LiveSourceConfig, SourceSearchOutcome } from './types';
import { clearLiveProbeResultsDb, loadLiveProbeResults, saveLiveProbeResults } from './db';
+import { PERSIST_KEY, createThrottledStorage } from './persist-storage';
/**
* 全局设置(zustand + localStorage 持久化)。
@@ -261,57 +262,9 @@ function nextCustomKey(apiList: SourceConfig[]): string {
}
/**
- * 节流写入的 localStorage 包装。
- * 搜索会逐源写健康度、测活每 200ms 合并写回,这些都会触发 persist 的整份序列化 + 写盘;
- * 这里把写入合并为 800ms 一次,并在页面隐藏/卸载时立即 flush,确保不丢最后一次修改。
+ * 节流写入的 localStorage 包装已抽至 persist-storage.ts(db.ts 的 importConfig
+ * 需要在直接写盘前 flush 缓冲,而运行时依赖方向是 store → db,不能反向引用)。
*/
-function createThrottledStorage(): StateStorage {
- let timer: ReturnType<typeof setTimeout> | null = null;
- let pending: [string, string] | null = null;
-
- const flush = () => {
- if (timer) {
- clearTimeout(timer);
- timer = null;
- }
- if (!pending) return;
- const [key, value] = pending;
- pending = null;
- try {
- localStorage.setItem(key, value);
- } catch {
- // 配额不足 / 隐私模式下静默放弃持久化,内存态仍可用
- }
- };
-
- if (typeof window !== 'undefined') {
- window.addEventListener('visibilitychange', () => {
- if (document.visibilityState === 'hidden') flush();
- });
- window.addEventListener('beforeunload', flush);
- }
-
- return {
- getItem: (name) => {
- try {
- return localStorage.getItem(name);
- } catch {
- return null;
- }
- },
- setItem: (name, value) => {
- pending = [name, value];
- if (!timer) timer = setTimeout(flush, 800);
- },
- removeItem: (name) => {
- try {
- localStorage.removeItem(name);
- } catch {
- // 忽略
- }
- },
- };
-}
export const useAppStore = create<AppState>()(
persist(
@@ -745,7 +698,7 @@ export const useAppStore = create<AppState>()(
},
}),
{
- name: 'libretv-settings',
+ name: PERSIST_KEY,
// 节流写入:搜索 / 测活等高频 set 不再每次都整份序列化写盘
storage: createJSONStorage(createThrottledStorage),
// v1:直播源新增归属字段、最近观看新增 sourceUrl。