一分钟搭建影视站,支持Docker等部署方式
feat: 支持通过 DEFAULT_SOURCES 环境变量预置采集站
bestZweie17f9bf19ba7
diff --git a/README.md b/README.mdindex 74f3b03..833be4f 100644--- a/README.md+++ b/README.md@@ -53,6 +53,7 @@ PASSWORD=your-password npm start # 监听 8080| --- | --- | --- || `PASSWORD` | 是 | 访问密码;未设置时站点会提示管理员配置 || `PROXY_SECRET` | 否 | 会话/代理签名密钥;不设置时从 PASSWORD 派生(多实例部署建议显式设置) |+| `DEFAULT_SOURCES` | 否 | 预置采集站(JSON 数组),用户端自动出现且默认勾选,详见[配置文档](docs/Configuration) || `REQUEST_TIMEOUT` | 否 | 代理上游请求超时(毫秒),默认 8000 || `MAX_RETRIES` | 否 | 代理请求重试次数,默认 1 || `DEBUG` | 否 | 调试日志 |diff --git a/docker-compose.yml b/docker-compose.ymlindex e39d9b7..fbe5035 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -13,6 +13,8 @@ services:environment:# 必填:访问密码- PASSWORD=${PASSWORD:?请在 .env 中设置 PASSWORD}+ # 可选:预置采集站(JSON 数组),用户端自动出现且默认勾选+ # - DEFAULT_SOURCES=[{"name":"示例源","url":"https://example.com/api.php/provide/vod"}]# 可选:会话/代理签名密钥(多实例部署建议显式设置)# - PROXY_SECRET=your-secret# - REQUEST_TIMEOUT=8000diff --git a/docs/Configuration.md b/docs/Configuration.mdindex ba69623..7a64501 100644--- a/docs/Configuration.md+++ b/docs/Configuration.md@@ -9,10 +9,25 @@| `REQUEST_TIMEOUT` | 否 | `8000` | 代理上游请求超时(毫秒) || `MAX_RETRIES` | 否 | `1` | 代理请求重试次数 || `USER_AGENT` | 否 | Chrome UA | 代理请求使用的 UA(豆瓣防盗链等场景) |+| `DEFAULT_SOURCES` | 否 | — | 预置采集站,JSON 数组,见下文 [预置采集站](#预置采集站default_sources) || `DEBUG` | 否 | `false` | 调试日志 |> 旧版的 `CORS_ORIGIN`、`CACHE_MAX_AGE`、`BLOCKED_HOSTS`、`BLOCKED_IP_PREFIXES`、`FILTERED_HEADERS` 在重构版中已内化为安全默认值,不再需要配置。+### 预置采集站(DEFAULT_SOURCES)++部署者可通过环境变量为所有用户预置数据源,用户无需手动添加即可搜索:++```bash+DEFAULT_SOURCES=[{"name":"示例源","url":"https://example.com/api.php/provide/vod","detail":"https://example.com","isAdult":false}]+```++- 格式为 JSON 数组,每项支持 `name`(必填)、`url`(必填,http/https)、`detail`(可选详情页地址)、`isAdult`(可选成人标记);+- 解析失败会在服务端日志告警并**整体忽略**,不影响站点运行,最多生效 50 个(与搜索接口上限一致);+- 预置源由服务端经 `/api/status` 下发,展示在设置抽屉顶部并带「部署者预置」标记,用户可勾选/取消但**不可编辑或删除**;+- 预置源首次出现时自动勾选(开箱即搜);用户取消勾选后刷新页面不会被反复勾回;+- 预置源不参与用户侧的配置导出(导出文件只含用户自建源),部署者变更环境变量即可全站生效。+## 运行时设置(用户级)以下设置保存在每个用户浏览器的 localStorage(键 `libretv-settings`),通过「设置」抽屉修改:diff --git a/docs/Data-Sources.md b/docs/Data-Sources.mdindex fa6e449..7ac2323 100644--- a/docs/Data-Sources.md+++ b/docs/Data-Sources.md@@ -2,6 +2,9 @@LibreTV-Next 采用**空壳设计**:不内置任何采集站,由部署者/用户自行添加,避免内置源失效与合规风险。+- **部署者预置**:通过 `DEFAULT_SOURCES` 环境变量下发(JSON 数组),所有用户开箱即搜,详见[配置文档](Configuration);+- **用户自建**:设置抽屉「+ 添加 API」手动添加,保存在浏览器 localStorage。+## 支持的数据源类型Apple CMS(苹果CMS)标准采集接口,即提供以下接口的资源站:diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.tsindex 9f859d0..6173632 100644--- a/src/app/api/status/route.ts+++ b/src/app/api/status/route.ts@@ -1,9 +1,10 @@import { NextResponse } from 'next/server';import { isPasswordConfigured, sessionFromCookieHeader } from '@/lib/auth';+import { getEnvSources } from '@/lib/env-sources';export const runtime = 'nodejs';-/** 站点状态:客户端据此决定是否弹出登录框 / 提示管理员配置密码 */+/** 站点状态:客户端据此决定是否弹出登录框 / 提示管理员配置密码,并获取预置采集站 */export async function GET(req: Request) {const passwordRequired = isPasswordConfigured();const verified = passwordRequired && sessionFromCookieHeader(req.headers.get('cookie'));@@ -12,5 +13,7 @@ export async function GET(req: Request) {verified,// 构建时由 next.config.ts 从 package.json 注入version: process.env.APP_VERSION || 'dev',+ // 部署者通过 DEFAULT_SOURCES 预置的采集站+ defaultSources: getEnvSources(),});}diff --git a/src/app/page.tsx b/src/app/page.tsxindex f2d806a..dc3c889 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -80,7 +80,10 @@ function HomeContent() {const failures = searchQuery.data?.failures ?? [];// 失败源显示友好名称而非裸 keyconst failureNames = failures.map(- (f) => store.customAPIs.find((a) => a.key === f.sourceKey)?.name ?? f.sourceKey+ (f) =>+ store.customAPIs.find((a) => a.key === f.sourceKey)?.name ??+ store.envSources.find((a) => a.key === f.sourceKey)?.name ??+ f.sourceKey);return (@@ -196,7 +199,7 @@ function HomeContent() {{searchQuery.isLoading ? (<ResultsSkeleton />) : selectedSources.length === 0 ? (- <NoSourceGuide hasSources={store.customAPIs.length > 0} />+ <NoSourceGuide hasSources={store.customAPIs.length > 0 || store.envSources.length > 0} />) : list.length === 0 ? (<div className="text-center py-16"><svg className="mx-auto h-10 w-10 text-faint mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">diff --git a/src/components/providers.tsx b/src/components/providers.tsxindex e31f136..2506561 100644--- a/src/components/providers.tsx+++ b/src/components/providers.tsx@@ -21,6 +21,15 @@ export function Providers({ children }: { children: ReactNode }) {// 保证 hydration 阶段客户端与服务端渲染结果一致。useEffect(() => {void useAppStore.persist.rehydrate();+ // 拉取部署者通过 DEFAULT_SOURCES 预置的采集站(失败时静默忽略)+ fetch('/api/status')+ .then((r) => (r.ok ? r.json() : null))+ .then((d) => {+ if (d && Array.isArray(d.defaultSources)) {+ useAppStore.getState().setEnvSources(d.defaultSources);+ }+ })+ .catch(() => {});}, []);return (diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsxindex cfad3e7..922d96f 100644--- a/src/components/source-manager.tsx+++ b/src/components/source-manager.tsx@@ -36,10 +36,38 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:setEditing(null);}}/>- {store.customAPIs.length === 0 && editing !== '__new__' ? (+ {store.customAPIs.length === 0 && store.envSources.length === 0 && editing !== '__new__' ? (<EmptySourceGuide onAdd={() => setEditing('__new__')} />) : (- <ul className="space-y-2">+ <>+ {store.envSources.length > 0 && (+ <ul className="space-y-2 mb-2">+ {store.envSources.map((api) => (+ <li key={api.key} className="bg-card rounded-lg p-3">+ <div className="flex items-center gap-2">+ <input+ type="checkbox"+ className="h-4 w-4 accent-[#2563eb]"+ checked={store.selectedKeys.includes(api.key)}+ onChange={() => store.toggleSourceSelected(api.key)}+ aria-label={`选择 ${api.name}`}+ />+ <div className="flex-1 min-w-0">+ <div className="text-sm font-medium text-content truncate">+ {api.name}+ {api.isAdult && <span className="text-pink-400 text-xs ml-1">(18+)</span>}+ <span className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-chip text-faint align-middle">+ 部署者预置+ </span>+ </div>+ <div className="text-xs text-faint truncate">{api.url}</div>+ </div>+ </div>+ </li>+ ))}+ </ul>+ )}+ <ul className="space-y-2">{store.customAPIs.map((api) => (<li key={api.key} className="bg-card rounded-lg p-3">{editing === api.key ? (@@ -86,7 +114,8 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:)}</li>))}- </ul>+ </ul>+ </>)}</section>diff --git a/src/lib/env-sources.ts b/src/lib/env-sources.tsnew file mode 100644index 0000000..cda1b78--- /dev/null+++ b/src/lib/env-sources.ts@@ -0,0 +1,38 @@+import type { SourceConfig } from './types';++/**+ * 部署者通过 DEFAULT_SOURCES 环境变量预置的采集站。+ * 格式为 JSON 数组:[{"name":"源名","url":"https://.../api.php/provide/vod","detail":"https://...","isAdult":false}]+ * 解析失败时告警并整体忽略,不影响站点运行。+ */+export function getEnvSources(): SourceConfig[] {+ const raw = process.env.DEFAULT_SOURCES;+ if (!raw || !raw.trim()) return [];+ try {+ const parsed: unknown = JSON.parse(raw);+ if (!Array.isArray(parsed)) throw new Error('必须是 JSON 数组');+ const list: SourceConfig[] = parsed.map((item, i) => {+ if (typeof item !== 'object' || item === null) {+ throw new Error(`第 ${i + 1} 项不是对象`);+ }+ const { name, url, detail, isAdult } = item as Record<string, unknown>;+ if (typeof name !== 'string' || !name.trim()) {+ throw new Error(`第 ${i + 1} 项缺少 name`);+ }+ if (typeof url !== 'string' || !/^https?:\/\//.test(url.trim())) {+ throw new Error(`第 ${i + 1} 项的 url 必须以 http:// 或 https:// 开头`);+ }+ return {+ key: `env_${i}`,+ name: name.trim(),+ url: url.trim().replace(/\/+$/, ''),+ detail: typeof detail === 'string' && detail.trim() ? detail.trim() : undefined,+ isAdult: isAdult === true,+ };+ });+ return list;+ } catch (err) {+ console.warn('[LibreTV-Next] DEFAULT_SOURCES 解析失败,已忽略:', err instanceof Error ? err.message : err);+ return [];+ }+}diff --git a/src/lib/store.ts b/src/lib/store.tsindex 79c8660..161c5c1 100644--- a/src/lib/store.ts+++ b/src/lib/store.ts@@ -21,11 +21,16 @@ export interface AppSettings {}interface AppState extends AppSettings {+ /** 部署者通过 DEFAULT_SOURCES 环境变量预置的源(服务端下发,不持久化) */+ envSources: SourceConfig[];+ /** 已向用户展示过并自动勾选过的预置源 key(持久化:用户取消勾选后不再反复勾上) */+ envKeysSeen: string[];addCustomApi: (api: Omit<SourceConfig, 'key'> & { key?: string }) => void;updateCustomApi: (key: string, patch: Partial<SourceConfig>) => void;removeCustomApi: (key: string) => void;toggleSourceSelected: (key: string) => void;setSelectedKeys: (keys: string[]) => void;+ setEnvSources: (list: SourceConfig[]) => void;updateSettings: (patch: Partial<Omit<AppSettings, 'customAPIs' | 'selectedKeys'>>) => void;}@@ -40,6 +45,8 @@ export const useAppStore = create<AppState>()(persist((set, get) => ({customAPIs: [],+ envSources: [],+ envKeysSeen: [],selectedKeys: [],yellowFilter: true,adFilter: true,@@ -79,10 +86,33 @@ export const useAppStore = create<AppState>()(setSelectedKeys: (keys) => set({ selectedKeys: keys }),+ setEnvSources: (list) => {+ // 预置源首次出现时自动勾选(开箱即搜);用户此后取消勾选不会被反复勾回+ const seen = new Set(get().envKeysSeen);+ const freshKeys = list.map((s) => s.key).filter((k) => !seen.has(k));+ set({+ envSources: list,+ envKeysSeen: [...get().envKeysSeen, ...freshKeys],+ selectedKeys: [...get().selectedKeys, ...freshKeys],+ });+ },+updateSettings: (patch) => set(patch),}),{name: 'libretv-settings',+ // envSources 由服务端每次下发,不进 localStorage+ partialize: (s) => ({+ customAPIs: s.customAPIs,+ selectedKeys: s.selectedKeys,+ envKeysSeen: s.envKeysSeen,+ yellowFilter: s.yellowFilter,+ adFilter: s.adFilter,+ doubanEnabled: s.doubanEnabled,+ autoplayNext: s.autoplayNext,+ imageProxyMode: s.imageProxyMode,+ customImageProxy: s.customImageProxy,+ }),// 同步 storage 会在模块加载时立即 rehydrate(早于 React hydration),// 一旦首屏渲染依赖持久化状态就会与 SSR 输出不一致。// 改为由 Providers 在挂载后手动 rehydrate。@@ -93,11 +123,11 @@ export const useAppStore = create<AppState>()(/** 获取指定 key 的源配置;找不到时支持从 URL 参数兜底构造 */export function resolveSource(- store: Pick<AppState, 'customAPIs'>,+ store: Pick<AppState, 'customAPIs' | 'envSources'>,key: string,fallback?: { url?: string; detail?: string; name?: string }): SourceConfig | undefined {- const found = store.customAPIs.find((a) => a.key === key);+ const found = store.customAPIs.find((a) => a.key === key) ?? store.envSources.find((a) => a.key === key);if (found) return found;if (fallback?.url) {return {diff --git a/src/lib/types.ts b/src/lib/types.tsindex e201c19..759a1f8 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -79,4 +79,6 @@ export interface AuthStatusResponse {/** 当前会话是否已验证 */verified: boolean;version: string;+ /** 部署者通过 DEFAULT_SOURCES 环境变量预置的采集站(未配置时为空数组) */+ defaultSources: SourceConfig[];}