Skip to content

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

feat(subscription): 支持通过 DEFAULT_SUBSCRIPTIONS 预置数据源订阅链接

bestZweic63eb83eb382
diff --git a/README.md b/README.md
index 78dabe3..9f8929a 100644
--- a/README.md
+++ b/README.md
@@ -78,6 +78,7 @@ PASSWORD=your-password npm start # 监听 8080
| `SEARCH_MAX_PAGES` | 否 | 每个搜索源最多抓取的页数(1-50,默认 5)。第一页会读取源站 `pagecount`,实际页数 = min(源站总页数,该值);页间并行请求,单页失败只丢该页 |
| `60S_API_BASE` | 否 | 影视榜单推荐源(60s API)实例地址,默认官方公共实例 `https://60s.viki.moe`;有限流,高频使用可[自部署](https://github.com/vikiboss/60s) |
| `DEFAULT_LIVE_SOURCES` | 否 | 预置直播源(M3U 订阅),JSON 数组:`[{"name":"源名","url":"https://.../list.m3u","epg":"https://.../epg.xml.gz"}]`,`epg` 为可选的 XMLTV 节目单地址 |
+| `DEFAULT_SUBSCRIPTIONS` | 否 | 预置数据源订阅(LibreTV-SourceList JSON 链接),JSON 数组:`["https://.../sources.json", {"url":"https://.../list.json","name":"名称"}]`。首次访问自动导入点播源与直播源,之后每 24h 静默刷新;用户删除后不再自动加回 |
| `LIVE_ALLOW_PRIVATE` | 否 | 设为 `1` 时允许直播流代理访问内网/保留地址(自建 IPTV 场景),默认关闭以维持 SSRF 防护 |
| `DEBUG` | 否 | 调试日志 |
diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.ts
index 99aedc0..3b2135a 100644
--- a/src/app/api/status/route.ts
+++ b/src/app/api/status/route.ts
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server';
import { isPasswordConfigured, sessionFromCookieHeader } from '@/lib/auth';
import { getEnvSources } from '@/lib/env-sources';
import { getEnvLiveSources } from '@/lib/env-live-sources';
+import { getEnvSubscriptions } from '@/lib/env-subscriptions';
export const runtime = 'nodejs';
@@ -18,5 +19,7 @@ export async function GET(req: Request) {
defaultSources: getEnvSources(),
// 部署者通过 DEFAULT_LIVE_SOURCES 预置的直播源(M3U 订阅)
defaultLiveSources: getEnvLiveSources(),
+ // 部署者通过 DEFAULT_SUBSCRIPTIONS 预置的 SourceList 订阅链接
+ defaultSubscriptions: getEnvSubscriptions(),
});
}
diff --git a/src/components/providers.tsx b/src/components/providers.tsx
index 5748f72..7f9cf29 100644
--- a/src/components/providers.tsx
+++ b/src/components/providers.tsx
@@ -6,6 +6,7 @@ import { ToastProvider } from './toast';
import { AuthProvider } from './auth';
import { ThemeProvider } from './theme';
import { useAppStore } from '@/lib/store';
+import { syncEnvSubscriptions } from '@/lib/subscription-sync';
export function Providers({ children }: { children: ReactNode }) {
const [queryClient] = useState(
@@ -35,6 +36,10 @@ export function Providers({ children }: { children: ReactNode }) {
if (d && Array.isArray(d.defaultLiveSources)) {
useAppStore.getState().setLiveEnvSources(d.defaultLiveSources);
}
+ // 预置订阅(DEFAULT_SUBSCRIPTIONS):首次自动导入,超 24h 静默刷新,失败下次重试
+ if (d && Array.isArray(d.defaultSubscriptions) && d.defaultSubscriptions.length > 0) {
+ void syncEnvSubscriptions(d.defaultSubscriptions);
+ }
})
.catch(() => {});
}, []);
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index 2ba7f66..cbf6e70 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -8,6 +8,7 @@ import { formatRelativeTime, validateSourceUrl, cn } from '@/lib/utils';
import { exportConfig, importConfig } from '@/lib/db';
import { useAuth } from './auth';
import { api } from '@/lib/client-api';
+import { syncSourceSubscription } from '@/lib/subscription-sync';
import { LiveSourceManager } from './live-source-manager';
/**
@@ -360,25 +361,7 @@ function SourceSubscriptions() {
const sync = async (url: string) => {
setSyncing(url);
try {
- const { name, sources, liveSources } = await api.fetchSourceList(url);
- if (sources.length === 0 && liveSources.length === 0) {
- toast('订阅内容为空', 'warning');
- return;
- }
- const vodCount = store.applySubscriptionSources(url, sources);
- const liveCount = store.applySubscriptionLive(url, liveSources);
- // 仅对本订阅实际导入的直播源记录同步时间:
- // 被其他订阅/手动源占用而未导入的 M3U,其 name/epg/lastSync 不得被本订阅覆盖
- const importedLiveUrls = new Set(
- useAppStore.getState().liveSubscriptions
- .filter((s) => s.fromSubscription === url)
- .map((s) => s.url)
- );
- for (const s of liveSources) {
- if (importedLiveUrls.has(s.url)) store.markLiveSynced(s.url, s.name, s.epg);
- }
- store.addSubscription(url, name);
- store.markSubscriptionSynced(url, name);
+ const { vodCount, liveCount } = await syncSourceSubscription(url);
toast(`已同步 ${vodCount} 个点播源、${liveCount} 个直播源`, 'success');
setSubUrl('');
} catch (err) {
diff --git a/src/lib/env-subscriptions.ts b/src/lib/env-subscriptions.ts
new file mode 100644
index 0000000..2920cf4
--- /dev/null
+++ b/src/lib/env-subscriptions.ts
@@ -0,0 +1,34 @@
+/**
+ * 部署者通过 DEFAULT_SUBSCRIPTIONS 环境变量预置的 SourceList 订阅链接。
+ * 格式为 JSON 数组,元素为 URL 字符串或 {url, name} 对象:
+ * ["https://.../sources.json", {"url":"https://.../list.json","name":"名称"}]
+ * 与 DEFAULT_SOURCES / DEFAULT_LIVE_SOURCES 的容错策略一致:解析失败整体忽略。
+ */
+export interface EnvSubscription {
+ url: string;
+ name?: string;
+}
+
+export function getEnvSubscriptions(): EnvSubscription[] {
+ const raw = process.env.DEFAULT_SUBSCRIPTIONS;
+ if (!raw || !raw.trim()) return [];
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) throw new Error('必须是 JSON 数组');
+ const list: EnvSubscription[] = parsed.map((item, i) => {
+ const url = typeof item === 'string' ? item.trim() : typeof item === 'object' && item !== null && typeof (item as Record<string, unknown>).url === 'string' ? String((item as Record<string, unknown>).url).trim() : '';
+ if (!url || !/^https?:\/\//.test(url)) {
+ throw new Error(`第 ${i + 1} 项不是合法的 http(s) 订阅地址`);
+ }
+ const name =
+ typeof item === 'object' && item !== null && typeof (item as Record<string, unknown>).name === 'string'
+ ? String((item as Record<string, unknown>).name).trim() || undefined
+ : undefined;
+ return { url: url.replace(/\/+$/, ''), name };
+ });
+ return list;
+ } catch (err) {
+ console.warn('[LibreTV] DEFAULT_SUBSCRIPTIONS 解析失败,已忽略:', err instanceof Error ? err.message : err);
+ return [];
+ }
+}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index c06535e..67cb421 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -104,6 +104,8 @@ interface AppState extends AppSettings {
liveRecent: LiveRecentEntry[];
/** 测活结果缓存(6 小时有效,跨会话持久化) */
liveProbeResults: Record<string, LiveProbeEntry>;
+ /** 已出现过的 env 预置订阅 URL(持久化:用户删除后不再被自动加回) */
+ envSubsSeen: string[];
addCustomApi: (api: Omit<SourceConfig, 'key'> & { key?: string }) => void;
updateCustomApi: (key: string, patch: Partial<SourceConfig>) => void;
removeCustomApi: (key: string) => void;
@@ -127,6 +129,7 @@ interface AppState extends AppSettings {
/** 合并写入测活结果,并顺带清理过期条目 */
setLiveProbeResults: (entries: Record<string, LiveProbeEntry>) => void;
clearLiveProbeResults: () => void;
+ markEnvSubsSeen: (urls: string[]) => void;
updateSettings: (patch: Partial<Omit<AppSettings, 'customAPIs' | 'selectedKeys'>>) => void;
}
@@ -156,6 +159,7 @@ export const useAppStore = create<AppState>()(
liveFavorites: [],
liveRecent: [],
liveProbeResults: {},
+ envSubsSeen: [],
selectedKeys: [],
yellowFilter: true,
adFilter: true,
@@ -389,6 +393,12 @@ export const useAppStore = create<AppState>()(
clearLiveProbeResults: () => set({ liveProbeResults: {} }),
+ markEnvSubsSeen: (urls) => {
+ const seen = new Set(get().envSubsSeen);
+ for (const u of urls) seen.add(u);
+ set({ envSubsSeen: [...seen] });
+ },
+
updateSettings: (patch) => {
// 打开成人内容过滤时,同步取消勾选所有成人源,避免两者并存
if (patch.yellowFilter === true) {
@@ -434,6 +444,7 @@ export const useAppStore = create<AppState>()(
liveFavorites: s.liveFavorites,
liveRecent: s.liveRecent,
liveProbeResults: s.liveProbeResults,
+ envSubsSeen: s.envSubsSeen,
yellowFilter: s.yellowFilter,
adFilter: s.adFilter,
doubanEnabled: s.doubanEnabled,
diff --git a/src/lib/subscription-sync.ts b/src/lib/subscription-sync.ts
new file mode 100644
index 0000000..afa4e74
--- /dev/null
+++ b/src/lib/subscription-sync.ts
@@ -0,0 +1,75 @@
+'use client';
+
+import { api } from './client-api';
+import { useAppStore } from './store';
+
+/**
+ * SourceList 订阅同步核心逻辑,供两处复用:
+ * - source-manager:用户在设置抽屉中手动添加/重新同步(UI 层加 toast 反馈);
+ * - providers:部署者通过 DEFAULT_SUBSCRIPTIONS 预置的订阅,启动时自动导入与静默重同步。
+ *
+ * applySubscriptionSources / applySubscriptionLive 均按订阅前缀整体替换且保留
+ * 用户勾选状态,同步失败时不调用即无副作用——旧数据自动保留。
+ */
+export interface SubscriptionSyncResult {
+ name?: string;
+ vodCount: number;
+ liveCount: number;
+}
+
+export async function syncSourceSubscription(url: string): Promise<SubscriptionSyncResult> {
+ const { name, sources, liveSources } = await api.fetchSourceList(url);
+ if (sources.length === 0 && liveSources.length === 0) {
+ throw new Error('订阅内容为空');
+ }
+ const store = useAppStore.getState();
+ const vodCount = store.applySubscriptionSources(url, sources);
+ const liveCount = store.applySubscriptionLive(url, liveSources);
+ // 仅对本订阅实际导入的直播源记录同步时间:
+ // 被其他订阅/手动源占用而未导入的 M3U,其 name/epg/lastSync 不得被本订阅覆盖
+ const importedLiveUrls = new Set(
+ useAppStore.getState().liveSubscriptions
+ .filter((s) => s.fromSubscription === url)
+ .map((s) => s.url)
+ );
+ for (const s of liveSources) {
+ if (importedLiveUrls.has(s.url)) store.markLiveSynced(s.url, s.name, s.epg);
+ }
+ store.addSubscription(url, name);
+ store.markSubscriptionSynced(url, name);
+ return { name, vodCount, liveCount };
+}
+
+/** 预置订阅超过该间隔未同步时,启动阶段静默刷新一次 */
+const ENV_SUB_RESYNC_MS = 24 * 60 * 60 * 1000;
+
+/**
+ * 部署者通过 DEFAULT_SUBSCRIPTIONS 预置的订阅:启动时自动导入与静默刷新。
+ *
+ * seen 标记(envSubsSeen)仅在同步成功后写入:
+ * - 同步成功 → 标记 seen,用户此后删除该订阅不会被自动加回;
+ * - 同步失败 → 不标记,下次启动自动重试,已导入的旧数据保持不动。
+ * 已存在的订阅超过 24h 未同步时静默刷新(成功过但 seen 机制上线前的旧数据也会借此补标)。
+ */
+export async function syncEnvSubscriptions(subs: { url: string; name?: string }[]): Promise<void> {
+ for (const sub of subs) {
+ const store = useAppStore.getState();
+ try {
+ const existing = store.subscriptions.find((s) => s.url === sub.url);
+ if (existing) {
+ if (existing.lastSync && Date.now() - existing.lastSync < ENV_SUB_RESYNC_MS) {
+ store.markEnvSubsSeen([sub.url]);
+ continue;
+ }
+ await syncSourceSubscription(sub.url);
+ } else {
+ // 已成功过且被用户删除的预置订阅:尊重用户选择,不再加回
+ if (store.envSubsSeen.includes(sub.url)) continue;
+ await syncSourceSubscription(sub.url);
+ }
+ useAppStore.getState().markEnvSubsSeen([sub.url]);
+ } catch (err) {
+ console.warn('[LibreTV] 预置订阅同步失败(下次启动将重试):', sub.url, err instanceof Error ? err.message : err);
+ }
+ }
+}
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 88a7c7d..fd5adc5 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -91,6 +91,8 @@ export interface AuthStatusResponse {
defaultSources: SourceConfig[];
/** 部署者通过 DEFAULT_LIVE_SOURCES 环境变量预置的直播源(未配置时为空数组) */
defaultLiveSources: LiveSourceConfig[];
+ /** 部署者通过 DEFAULT_SUBSCRIPTIONS 环境变量预置的 SourceList 订阅链接(未配置时为空数组) */
+ defaultSubscriptions: { url: string; name?: string }[];
}
// —— 直播 / IPTV ——