Skip to content

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

feat(sources): 统一数据源订阅(点播源+直播源)并调整术语

bestZwei93576d07971a
diff --git a/README.md b/README.md
index 722db40..78dabe3 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@ LibreTV Next.js 迁移版:免费在线视频聚合搜索与观看平台。基
- **直播 / IPTV**:M3U 订阅解析,`/live` 页面按分组浏览、搜索频道并站内播放(HLS + HTTP-FLV),支持 XMLTV 节目单(EPG)与频道收藏;直播流经专用长连接代理(`/api/live/stream`)转发
- **进度同步**:播放进度与观看历史存于本机 IndexedDB,精确到秒的续播
- **换源测速**:跨源搜索同名资源并测速排序,一键切换保留集数位置
-- **源测试与订阅**:一键探活数据源;订阅远程源列表(LibreTV-SourceList JSON),可导出分享
+- **源测试与订阅**:一键探活点播源与直播源;订阅远程源列表(一份 LibreTV-SourceList JSON 可同时下发点播源与直播源),可导出分享
- **首页推荐**:豆瓣(电影/剧集分类浏览)、Bangumi 新番放送表或影视榜单(豆瓣周榜 + 百度热播,经 60s API),设置中切换;均服务端直连 + 缓存,Bangumi/榜单免 key 免配置(`60S_API_BASE` 可指向自部署 60s 实例)
- **PWA**:可安装到桌面 / 主屏幕,亮暗双主题无首屏闪烁
@@ -83,24 +83,24 @@ PASSWORD=your-password npm start # 监听 8080
## 使用说明
-1. **添加数据源**:设置 → 添加 API,填入 Apple CMS 采集站地址(如 `https://example.com/api.php/provide/vod`),可选填详情页地址(部分源需要爬详情页提取播放地址)。
-2. **搜索**:勾选数据源后输入片名;搜索通过服务端聚合,个别源失败不影响整体结果。
+1. **添加点播源**:设置 → 点播源 → 添加 API,填入 Apple CMS 采集站地址(如 `https://example.com/api.php/provide/vod`),可选填详情页地址(部分源需要爬详情页提取播放地址)。
+2. **搜索**:勾选点播源后输入片名;搜索通过服务端聚合,个别源失败不影响整体结果。
3. **播放**:详情弹窗选择剧集进入 `/watch`;支持快捷键(空格/←→/↑↓/F/Alt+←→)、移动端长按 3 倍速、自动连播、换源测速。
4. **进度与历史**:自动保存在本设备 IndexedDB,仅定位信息入库,播放时自动同步最新剧集。
5. **配置迁移**:设置 → 导出/导入配置(兼容旧版 LibreTV-Settings JSON 的历史记录迁移)。
## 直播 / IPTV
-1. **添加直播源**:设置 → 直播源 → 填入 M3U/M3U8 订阅地址(可选填 XMLTV 节目单地址),添加后自动探活并显示频道数量;部署者也可用 `DEFAULT_LIVE_SOURCES` 环境变量预置。
+1. **添加直播源**:设置 → 直播源 → 填入 M3U/M3U8 地址(可选填 XMLTV 节目单地址),添加后自动探活并显示频道数量;也可在「订阅与配置 → 数据源订阅」中与点播源一起订阅导入;部署者还可用 `DEFAULT_LIVE_SOURCES` 环境变量预置。
2. **观看**:进入「直播」页,按分组标签筛选或搜索频道,点击即播;支持 HLS(m3u8)与 HTTP-FLV 两种直播流,直连失败自动走代理通道重试。
3. **节目单**:频道带 `tvg-id` 且订阅配置了 EPG 地址时,展示当前/接下来节目与播放进度。
4. **收藏与导出**:频道可收藏;订阅可一键导出为标准 M3U 文件,供 PotPlayer / VLC 等外部播放器使用。
> ⚠️ 项目不内置任何频道源,也不存储、不制作任何直播内容,仅提供第三方公开播放列表的解析与播放能力,内容的合法性由对应数据源负责。内网自建源默认被 SSRF 防护拦截,自部署者可显式设置 `LIVE_ALLOW_PRIVATE=1` 放行。
-## 源订阅 / 分享
+## 数据源订阅 / 分享
-源列表可以 **导出为 JSON → 托管到公开 URL → 他人在「设置」里填入该 URL 订阅**。
+数据源(点播源 + 直播源)可以 **导出为一份 JSON → 托管到公开 URL → 他人在「设置 → 订阅与配置 → 数据源订阅」里填入该 URL 订阅**。
托管地址没有特殊要求,可用 [npoint.io](https://www.npoint.io/) 免费托管 JSON(粘贴内容即可得到一个公开 URL),Gist、对象存储、任意静态托管同样可用。
@@ -109,23 +109,27 @@ PASSWORD=your-password npm start # 监听 8080
```json
{
"name": "我的源列表",
- "version": 1,
+ "version": 2,
"sources": [
- { "name": "示例源", "url": "https://example.com/api.php/provide/vod" }
+ { "name": "示例点播源", "url": "https://example.com/api.php/provide/vod" }
+ ],
+ "liveSources": [
+ { "name": "示例直播源", "url": "https://example.com/list.m3u", "epg": "https://example.com/epg.xml.gz" }
]
}
```
-- 必填字段只有 `sources[].url`;`detail` 为详情页根地址,`isAdult` 为成人内容标记;
-- 也接受裸数组 `[{ "name": "...", "url": "..." }]`;
-- 按 `url` 去重,最多 100 个源;非公网 http(s) 地址会被静默过滤。
+- `sources` 为点播源(Apple CMS 采集站),必填字段只有 `url`;`detail` 为详情页根地址,`isAdult` 为成人内容标记;
+- `liveSources` 为直播源(M3U 播放列表),必填字段只有 `url`;`epg` 为可选的 XMLTV 节目单地址;
+- 只写 `sources` 的老订阅照常可用(纯点播),只写 `liveSources` 则是纯直播订阅;裸数组 `[{ "name": "...", "url": "..." }]` 视为点播源;
+- 按 `url` 去重,点播源最多 100 个、直播源最多 50 个;非 http(s) 地址会被过滤,点播源另需为公网地址(直播源可用 `LIVE_ALLOW_PRIVATE=1` 放行内网自建源)。
### 订阅行为
-- **订阅**:设置 → 源订阅 / 分享 → 填入订阅地址 → 「订阅」,导入的源自动勾选并带「订阅」标识;
-- **同步**:订阅条目上的 **⟳** 手动强制同步,整体替换该订阅名下的源;
-- **管理边界**:订阅源以远端列表为准,单独编辑会在下次同步时被覆盖,单独移除会在重新同步时恢复;如需调整请改远端列表,或直接删除整个订阅(会一并移除其导入的源);
-- **导出分享**:设置 → 源订阅 / 分享 → 「导出源列表」,把当前全部来源(预置 + 手动 + 订阅,按 URL 去重)导出为上述 JSON。
+- **订阅**:设置 → 订阅与配置 → 数据源订阅 → 填入订阅地址 → 「订阅」,导入的点播源自动勾选、直播源自动启用,均带「订阅」标识,条目上显示「点播 N · 直播 M」;
+- **同步**:订阅条目上的 **⟳** 手动强制同步,整体替换该订阅名下的点播源与直播源;
+- **管理边界**:订阅源以远端列表为准,单独编辑会在下次同步时被覆盖,单独移除会在重新同步时恢复;如需调整请改远端列表,或直接删除整个订阅(会一并移除其导入的点播源与直播源,但**保留已收藏的频道**);
+- **导出分享**:设置 → 订阅与配置 → 数据源订阅 → 「导出数据源」,把当前全部点播源与直播源(预置 + 手动 + 订阅,按 URL 去重)导出为上述 JSON。
> 订阅由服务端拉取(经过 SSRF 校验),因此订阅地址无需配置 CORS。完整说明见 [数据源文档](https://github.com/bestZwei/LibreTV-Next/wiki/Data-Sources)。
diff --git a/src/app/about/page.tsx b/src/app/about/page.tsx
index 314b771..1fcf776 100644
--- a/src/app/about/page.tsx
+++ b/src/app/about/page.tsx
@@ -12,7 +12,7 @@ export default function AboutPage() {
<section>
<h1 className="text-xl font-bold text-content mb-3">关于 LibreTV</h1>
<p className="text-sm text-muted leading-relaxed">
- LibreTV 是一个免费的在线视频搜索与观看平台。输入片名即可在多个数据源中聚合搜索,
+ LibreTV 是一个免费的在线视频搜索与观看平台。输入片名即可在多个点播源中聚合搜索,
无需注册、无内嵌广告、不存储任何视频文件。所有播放内容均来自第三方公开接口。
</p>
</section>
diff --git a/src/app/api/detail/route.ts b/src/app/api/detail/route.ts
index 839cada..fafb44c 100644
--- a/src/app/api/detail/route.ts
+++ b/src/app/api/detail/route.ts
@@ -38,7 +38,7 @@ export async function GET(req: Request) {
return NextResponse.json({ error: '无效的视频ID' }, { status: 400 });
}
if (!source) {
- return NextResponse.json({ error: '无效的数据源配置' }, { status: 400 });
+ return NextResponse.json({ error: '无效的点播源配置' }, { status: 400 });
}
try {
diff --git a/src/app/api/live/playlist/route.ts b/src/app/api/live/playlist/route.ts
index 5bbff83..af31be6 100644
--- a/src/app/api/live/playlist/route.ts
+++ b/src/app/api/live/playlist/route.ts
@@ -1,6 +1,6 @@
import { NextResponse } from 'next/server';
import { guardRequest, jsonError } from '@/lib/api-guard';
-import { checkUpstreamAllowed } from '@/lib/ssrf';
+import { checkLiveUrlAllowed } from '@/lib/ssrf';
import { fetchUpstream, getCache, setCache } from '@/lib/fetch-utils';
import { parseM3u } from '@/lib/m3u-parser';
import type { LivePlaylistResponse } from '@/lib/types';
@@ -56,7 +56,8 @@ export async function GET(req: Request) {
const format = sp.get('format') || 'json';
const force = sp.get('force') === '1';
- const verdict = await checkUpstreamAllowed(url);
+ // 直播专用校验:默认拒绝内网,部署者可设 LIVE_ALLOW_PRIVATE=1 放行自建 IPTV
+ const verdict = await checkLiveUrlAllowed(url);
if (!verdict.ok) return jsonError(verdict.reason, 403);
let playlist: LivePlaylistResponse | undefined = force ? undefined : getCache(cacheKey(url));
diff --git a/src/app/api/live/stream/[url]/route.ts b/src/app/api/live/stream/[url]/route.ts
index 9ea8b26..2719a4f 100644
--- a/src/app/api/live/stream/[url]/route.ts
+++ b/src/app/api/live/stream/[url]/route.ts
@@ -1,6 +1,6 @@
import { NextResponse } from 'next/server';
import { guardRequest, jsonError } from '@/lib/api-guard';
-import { checkUpstreamAllowed, type UpstreamVerdict } from '@/lib/ssrf';
+import { checkLiveUrlAllowed } from '@/lib/ssrf';
import { rewriteM3u8 } from '@/lib/m3u8';
export const runtime = 'nodejs';
@@ -28,24 +28,6 @@ const UA =
process.env.USER_AGENT ||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36';
-function allowPrivate(): boolean {
- return process.env.LIVE_ALLOW_PRIVATE === '1';
-}
-
-/** 直播流地址校验:协议必须 http(s);内网放行仅限显式开启 LIVE_ALLOW_PRIVATE */
-async function checkStreamAllowed(urlString: string): Promise<UpstreamVerdict> {
- try {
- const parsed = new URL(urlString);
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
- return { ok: false, reason: '直播流仅支持 http/https 协议' };
- }
- } catch {
- return { ok: false, reason: '无效的直播流地址' };
- }
- if (allowPrivate()) return { ok: true };
- return checkUpstreamAllowed(urlString);
-}
-
/**
* 带响应头超时的上游抓取:仅首字节(响应头)限时,超时 abort;
* 响应头到达后清除计时器,body 流不再受限。手动逐跳跟随重定向,
@@ -60,7 +42,7 @@ async function fetchLiveUpstream(
): Promise<{ res: Response; finalUrl: string }> {
let current = targetUrl;
for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop++) {
- const verdict = await checkStreamAllowed(current);
+ const verdict = await checkLiveUrlAllowed(current);
if (!verdict.ok) throw new Error(`跳转目标被拒绝: ${verdict.reason}`);
const timer = setTimeout(() => controller.abort(), HEADER_TIMEOUT_MS);
@@ -92,7 +74,7 @@ export async function GET(req: Request, ctx: { params: Promise<{ url: string }>
const guarded = guardRequest(req);
if (guarded) return guarded;
- const verdict = await checkStreamAllowed(targetUrl);
+ const verdict = await checkLiveUrlAllowed(targetUrl);
if (!verdict.ok) return jsonError(verdict.reason, 403);
const controller = new AbortController();
diff --git a/src/app/api/search/route.ts b/src/app/api/search/route.ts
index 8a59cfb..de5b095 100644
--- a/src/app/api/search/route.ts
+++ b/src/app/api/search/route.ts
@@ -57,7 +57,7 @@ export async function POST(req: Request) {
return NextResponse.json({ error: '搜索关键词无效' }, { status: 400 });
}
if (!Array.isArray(body.sources) || body.sources.length === 0) {
- return NextResponse.json({ error: '请至少选择一个数据源' }, { status: 400 });
+ return NextResponse.json({ error: '请至少选择一个点播源' }, { status: 400 });
}
const sources = body.sources.slice(0, 50);
diff --git a/src/app/api/source-list/route.ts b/src/app/api/source-list/route.ts
index a2c1cd0..a855f85 100644
--- a/src/app/api/source-list/route.ts
+++ b/src/app/api/source-list/route.ts
@@ -1,24 +1,21 @@
import { NextResponse } from 'next/server';
import { guardRequest } from '@/lib/api-guard';
-import { checkUpstreamAllowed, isValidProxyUrl } from '@/lib/ssrf';
+import { checkLiveUrlAllowed, checkUpstreamAllowed, isValidProxyUrl } from '@/lib/ssrf';
import { fetchUpstream } from '@/lib/fetch-utils';
+import { parseSourceListPayload } from '@/lib/source-list';
+import type { SourceListPayload } from '@/lib/types';
export const runtime = 'nodejs';
-const MAX_SOURCES = 100;
-
-interface RawSource {
- name?: unknown;
- url?: unknown;
- detail?: unknown;
- isAdult?: unknown;
-}
-
/**
- * 拉取远程源订阅列表。
- * 接受两种格式:
- * 1. LibreTV-SourceList JSON:{ name?, sources: [{name,url,detail?,isAdult?}] }
- * 2. 裸数组:[{name,url,...}, ...]
+ * 拉取远程数据源订阅。
+ * 接受三种形态:
+ * 1. 完整格式:{ name?, sources: [点播源], liveSources: [直播源] }
+ * 2. 老格式:只有 sources(或裸数组),仅点播
+ * 3. 纯直播订阅:只有 liveSources
+ *
+ * 点播源与直播源的地址放行策略不同(点播一律拒绝内网,直播可用 LIVE_ALLOW_PRIVATE 放行),
+ * 因此两类分别校验,不能共用一把尺子。
*/
export async function GET(req: Request) {
const guarded = guardRequest(req);
@@ -40,34 +37,37 @@ export async function GET(req: Request) {
if (!res.ok) {
return NextResponse.json({ error: `订阅地址返回 HTTP ${res.status}` }, { status: 502 });
}
- const json = (await res.json()) as { name?: unknown; sources?: unknown } | RawSource[];
+ const json: unknown = await res.json();
- const rawList = Array.isArray(json)
- ? json
- : Array.isArray((json as { sources?: unknown }).sources)
- ? ((json as { sources: RawSource[] }).sources)
- : null;
- if (!rawList) {
- return NextResponse.json({ error: '订阅内容格式不正确(缺少 sources 数组)' }, { status: 400 });
+ let parsed;
+ try {
+ parsed = parseSourceListPayload(json);
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : '订阅内容格式不正确' },
+ { status: 400 }
+ );
}
- const name = Array.isArray(json) ? undefined : (typeof (json as { name?: unknown }).name === 'string' ? (json as { name: string }).name : undefined);
+ // 点播源:拒绝非公网地址(DNS 层校验在搜索/详情请求时另有兜底)
+ const sources = parsed.sources.filter((s) => isValidProxyUrl(s.url));
+
+ // 直播源:按直播策略校验,EPG 地址非法时丢弃该字段而非整条源
+ const checkedLive = await Promise.all(
+ parsed.liveSources.map(async (s) => {
+ if (!(await checkLiveUrlAllowed(s.url)).ok) return null;
+ if (s.epg && !(await checkLiveUrlAllowed(s.epg)).ok) return { ...s, epg: undefined };
+ return s;
+ })
+ );
- const seenUrls = new Set<string>();
- const sources = rawList.slice(0, MAX_SOURCES).flatMap((s) => {
- const url = typeof s?.url === 'string' ? s.url.trim().replace(/\/+$/, '') : '';
- // 拒绝非公网 http(s) 地址(DNS 层校验在搜索/详情请求时另有兜底)
- if (!isValidProxyUrl(url) || seenUrls.has(url)) return [];
- seenUrls.add(url);
- return [{
- name: typeof s?.name === 'string' && s.name.trim() ? s.name.trim() : new URL(url).hostname,
- url,
- detail: typeof s?.detail === 'string' && s.detail.trim() ? s.detail.trim() : undefined,
- isAdult: s?.isAdult === true,
- }];
- });
+ const payload: SourceListPayload = {
+ name: parsed.name,
+ sources,
+ liveSources: checkedLive.filter((s): s is NonNullable<typeof s> => s !== null),
+ };
- return NextResponse.json({ name, sources });
+ return NextResponse.json(payload);
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : '订阅拉取失败' },
diff --git a/src/app/api/source/test/route.ts b/src/app/api/source/test/route.ts
index 4cee369..2d2c28a 100644
--- a/src/app/api/source/test/route.ts
+++ b/src/app/api/source/test/route.ts
@@ -6,7 +6,7 @@ import { parseSearchList } from '@/lib/cms-parser';
export const runtime = 'nodejs';
-/** 数据源探活:以搜索 "test" 的响应耗时与结果量衡量可用性 */
+/** 点播源探活:以搜索 "test" 的响应耗时与结果量衡量可用性 */
export async function POST(req: Request) {
const guarded = guardRequest(req);
if (guarded) return guarded;
diff --git a/src/app/live/page.tsx b/src/app/live/page.tsx
index 3f69e29..ad078d3 100644
--- a/src/app/live/page.tsx
+++ b/src/app/live/page.tsx
@@ -84,7 +84,7 @@ function LiveContent() {
for (const c of result.value.channels) {
if (seen.has(c.url)) continue;
seen.add(c.url);
- list.push({ ...c, epg: source.epg });
+ list.push({ ...c, epg: source.epg, sourceUrl: source.url });
}
}
const groups = [...new Set(list.map((c) => c.group).filter((g): g is string => Boolean(g)))].sort(
@@ -123,6 +123,7 @@ function LiveContent() {
group: c.group,
tvgId: c.tvgId,
epg: c.epg,
+ sourceUrl: c.sourceUrl,
});
},
[router, store]
diff --git a/src/app/page.tsx b/src/app/page.tsx
index 665e7b5..9adaa6f 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -73,7 +73,7 @@ function HomeContent() {
return;
}
if (selectedSources.length === 0) {
- toast('请先在设置中添加并勾选数据源', 'warning');
+ toast('请先在设置中添加并勾选点播源', 'warning');
return;
}
router.push(`/?s=${encodeURIComponent(query)}`, { scroll: false });
@@ -199,7 +199,7 @@ function HomeContent() {
{failures.length > 0 && (
<div className="mb-3 text-xs text-faint bg-chip rounded-lg px-3 py-2">
- 部分数据源请求失败:{failureNames.join('、')}
+ 部分点播源请求失败:{failureNames.join('、')}
</div>
)}
@@ -214,7 +214,7 @@ function HomeContent() {
d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<h3 className="text-base text-muted">没有找到匹配的结果</h3>
- <p className="text-sm text-faint mt-1">请尝试其他关键词或更换数据源</p>
+ <p className="text-sm text-faint mt-1">请尝试其他关键词或更换点播源</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 items-start">
@@ -271,14 +271,14 @@ function ResultsSkeleton() {
);
}
-/** 无数据源 / 未勾选数据源时的引导(替代旧版首屏静默空白) */
+/** 无点播源 / 未勾选点播源时的引导(替代旧版首屏静默空白) */
function NoSourceGuide({ hasSources = false }: { hasSources?: boolean }) {
return (
<div className="border border-dashed border-line rounded-xl p-10 text-center max-w-lg mx-auto">
- <h3 className="text-content font-medium mb-2">{hasSources ? '尚未勾选数据源' : '先添加一个数据源'}</h3>
+ <h3 className="text-content font-medium mb-2">{hasSources ? '尚未勾选点播源' : '先添加一个点播源'}</h3>
<p className="text-sm text-muted leading-relaxed">
{hasSources ? (
- <>点击右上角「设置」,勾选要参与搜索的数据源后重新搜索。</>
+ <>点击右上角「设置」,勾选要参与搜索的点播源后重新搜索。</>
) : (
<>
LibreTV 不内置任何采集站。点击右上角「设置 → 添加 API」,填入一个
diff --git a/src/app/watch/page.tsx b/src/app/watch/page.tsx
index b51f741..f6c3b38 100644
--- a/src/app/watch/page.tsx
+++ b/src/app/watch/page.tsx
@@ -175,9 +175,9 @@ function WatchContent() {
return (
<div className="min-h-screen flex items-center justify-center px-4">
<div className="text-center max-w-md">
- <h1 className="text-content font-medium mb-2">数据源不存在</h1>
+ <h1 className="text-content font-medium mb-2">点播源不存在</h1>
<p className="text-sm text-muted mb-4">
- 该视频来自数据源「{sourceKey}」,但它可能已被删除。请在设置中重新添加后重试。
+ 该视频来自点播源「{sourceKey}」,但它可能已被删除。请在设置中重新添加后重试。
</p>
<Link href="/" className="btn-primary">返回首页</Link>
</div>
diff --git a/src/components/detail-modal.tsx b/src/components/detail-modal.tsx
index e51d232..8e06c93 100644
--- a/src/components/detail-modal.tsx
+++ b/src/components/detail-modal.tsx
@@ -50,7 +50,7 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;
name: item.sourceName,
});
if (!source) {
- setError('数据源配置不存在(可能已被删除),请在设置中重新添加');
+ setError('点播源配置不存在(可能已被删除),请在设置中重新添加');
return;
}
setLoading(true);
diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsx
index 27cb425..cdca8af 100644
--- a/src/components/live-channel-list.tsx
+++ b/src/components/live-channel-list.tsx
@@ -17,6 +17,8 @@ const PAGE_SIZE = 300;
export interface LiveChannelItem extends LiveChannel {
/** 来源订阅的 EPG 地址(用于节目单查询) */
epg?: string;
+ /** 所属直播源地址(M3U 订阅 URL),写入最近观看以便订阅删除时清理 */
+ sourceUrl?: string;
}
interface ChannelListProps {
diff --git a/src/components/live-source-manager.tsx b/src/components/live-source-manager.tsx
index 0deb602..0de2e8e 100644
--- a/src/components/live-source-manager.tsx
+++ b/src/components/live-source-manager.tsx
@@ -15,6 +15,15 @@ type TestState =
| { status: 'loading' }
| { status: 'done'; ok: boolean; ms?: number; count?: number; error?: string };
+/** 取 hostname 作为名称兜底;地址非法时原样返回 */
+function hostnameOf(url: string): string {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return url;
+ }
+}
+
export function LiveSourceManager() {
const store = useAppStore();
const { toast } = useToast();
@@ -82,7 +91,22 @@ export function LiveSourceManager() {
);
};
- const renderRow = (url: string, label: string, epgUrl?: string, preset = false, lastSync?: number) => (
+ const renderRow = ({
+ url,
+ label,
+ epgUrl,
+ preset = false,
+ lastSync,
+ fromSubscription,
+ }: {
+ url: string;
+ label: string;
+ epgUrl?: string;
+ preset?: boolean;
+ lastSync?: number;
+ /** 该直播源来自哪个订阅 URL;有值时由订阅统一管理,不可单独删除 */
+ fromSubscription?: string;
+ }) => (
<li key={url} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">
<div className="flex items-center gap-2">
<input
@@ -101,6 +125,14 @@ export function LiveSourceManager() {
部署者预置
</span>
)}
+ {fromSubscription && (
+ <span
+ className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent align-middle"
+ title="来自数据源订阅,重新同步时此源的名称/地址会以订阅内容为准"
+ >
+ 订阅
+ </span>
+ )}
</div>
<div className="text-xs text-faint truncate">
{url}
@@ -117,14 +149,25 @@ export function LiveSourceManager() {
>
⇩
</button>
- {!preset && (
+ {fromSubscription ? (
<button
- className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-red-400"
- onClick={() => store.removeLiveSubscription(url)}
- aria-label="删除订阅"
+ className="rounded-md p-1.5 text-muted/40"
+ onClick={() => toast('该直播源来自数据源订阅;请到「订阅与配置 → 数据源订阅」中删除整个订阅', 'info')}
+ aria-label="订阅源不可单独删除"
+ title="该源来自订阅,单独删除会在下次同步时恢复;如需移除请删除整个订阅"
>
✕
</button>
+ ) : (
+ !preset && (
+ <button
+ className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-red-400"
+ onClick={() => store.removeLiveSubscription(url)}
+ aria-label="删除直播源"
+ >
+ ✕
+ </button>
+ )
)}
</div>
</li>
@@ -171,12 +214,20 @@ export function LiveSourceManager() {
</div>
{store.liveEnvSources.length === 0 && store.liveSubscriptions.length === 0 ? (
<p className="text-xs text-faint">
- 添加 M3U 订阅后即可在「直播」页按分组浏览与播放频道;部署者也可通过 DEFAULT_LIVE_SOURCES 环境变量预置。
+ 添加 M3U 地址后即可在「直播」页按分组浏览与播放频道;也可在「订阅与配置 → 数据源订阅」中一次导入点播源与直播源;部署者还可通过 DEFAULT_LIVE_SOURCES 环境变量预置。
</p>
) : (
<ul className="space-y-2 max-h-[50vh] overflow-y-auto scrollbar-thin pr-1">
- {store.liveEnvSources.map((s) => renderRow(s.url, s.name, s.epg, true))}
- {store.liveSubscriptions.map((s) => renderRow(s.url, s.name || new URL(s.url).hostname, s.epg, false, s.lastSync))}
+ {store.liveEnvSources.map((s) => renderRow({ url: s.url, label: s.name, epgUrl: s.epg, preset: true }))}
+ {store.liveSubscriptions.map((s) =>
+ renderRow({
+ url: s.url,
+ label: s.name || hostnameOf(s.url),
+ epgUrl: s.epg,
+ lastSync: s.lastSync,
+ fromSubscription: s.fromSubscription,
+ })
+ )}
</ul>
)}
</section>
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index 0c79a8f..aee8613 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -2,7 +2,7 @@
import { useEffect, useState } from 'react';
import { Drawer } from './header';
-import { useAppStore } from '@/lib/store';
+import { subKeyPrefix, useAppStore } from '@/lib/store';
import { useToast } from './toast';
import { formatRelativeTime, validateSourceUrl, cn } from '@/lib/utils';
import { exportConfig, importConfig } from '@/lib/db';
@@ -11,7 +11,7 @@ import { api } from '@/lib/client-api';
import { LiveSourceManager } from './live-source-manager';
/**
- * 设置抽屉:顶部 Tab 分类(数据源 / 直播源 / 播放设置 / 配置),
+ * 设置抽屉:顶部 Tab 分类(点播源 / 直播源 / 播放设置 / 订阅与配置),
* 每次只渲染一类内容,避免源很多时长距离滚动。
*/
@@ -22,10 +22,10 @@ type TestState =
type SettingsTab = 'sources' | 'live' | 'playback' | 'config';
const SETTINGS_TABS: { id: SettingsTab; label: string }[] = [
- { id: 'sources', label: '数据源' },
+ { id: 'sources', label: '点播源' },
{ id: 'live', label: '直播源' },
{ id: 'playback', label: '播放设置' },
- { id: 'config', label: '配置' },
+ { id: 'config', label: '订阅与配置' },
];
export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose: () => void }) {
@@ -33,7 +33,7 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
const { toast } = useToast();
const [editing, setEditing] = useState<string | null>(null);
const [tests, setTests] = useState<Record<string, TestState>>({});
- // Tab 选中态不持久化:每次打开抽屉回到「数据源」
+ // Tab 选中态不持久化:每次打开抽屉回到「点播源」
const [settingsTab, setSettingsTab] = useState<SettingsTab>('sources');
const runTest = async (key: string, url: string) => {
@@ -107,10 +107,9 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
{settingsTab === 'sources' && (
<>
- <SourceSubscriptions />
- <section className="mb-6 border-t border-line pt-5">
+ <section className="mb-6 pt-5">
<SectionTitle
- title="数据源"
+ title="点播源"
extra={
<button className="btn-primary !py-1 !px-2.5 text-xs" onClick={() => setEditing('__new__')}>
+ 添加 API
@@ -200,7 +199,7 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
{fromSubscription && (
<span
className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent align-middle"
- title="来自源订阅,重新同步时此源的名称/地址会以订阅内容为准"
+ title="来自数据源订阅,重新同步时此源的名称/地址会以订阅内容为准"
>
订阅
</span>
@@ -335,19 +334,22 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
)}
{settingsTab === 'config' && (
- <section className="pt-5">
+ <>
+ <SourceSubscriptions />
+ <section className="mb-6 pt-5 border-t border-line">
<SectionTitle title="配置" />
<ConfigIoButtons />
</section>
+ </>
)}
</Drawer>
);
}
/**
- * 源订阅 / 分享:
- * - 订阅:填入远程 LibreTV-SourceList JSON 地址,一键拉取导入,可随时重新同步;
- * - 分享:把当前源列表导出为同格式 JSON 文件,托管到任意位置即可被他人订阅。
+ * 数据源订阅 / 分享:
+ * - 订阅:填入远程 LibreTV-SourceList JSON 地址,一次拉取点播源与直播源,可随时重新同步;
+ * - 分享:把当前点播源 + 直播源导出为同格式 JSON 文件,托管到任意位置即可被他人订阅。
*/
function SourceSubscriptions() {
const store = useAppStore();
@@ -358,15 +360,18 @@ function SourceSubscriptions() {
const sync = async (url: string) => {
setSyncing(url);
try {
- const { name, sources } = await api.fetchSourceList(url);
- if (sources.length === 0) {
+ const { name, sources, liveSources } = await api.fetchSourceList(url);
+ if (sources.length === 0 && liveSources.length === 0) {
toast('订阅内容为空', 'warning');
return;
}
- const count = store.applySubscriptionSources(url, sources);
+ const vodCount = store.applySubscriptionSources(url, sources);
+ const liveCount = store.applySubscriptionLive(url, liveSources);
+ // 记录直播源同步时间;未实际导入的源在 store 中不存在,写入会被忽略
+ for (const s of liveSources) store.markLiveSynced(s.url, s.name, s.epg);
store.addSubscription(url, name);
store.markSubscriptionSynced(url, name);
- toast(`已同步 ${count} 个数据源`, 'success');
+ toast(`已同步 ${vodCount} 个点播源、${liveCount} 个直播源`, 'success');
setSubUrl('');
} catch (err) {
toast(err instanceof Error ? err.message : '订阅同步失败', 'error');
@@ -395,7 +400,18 @@ function SourceSubscriptions() {
return true;
})
.map(({ name, url, detail, isAdult }) => ({ name, url, detail, isAdult }));
- const payload = { name: 'LibreTV-SourceList', version: 1, exportedAt: Date.now(), sources };
+
+ // 直播源:预置 + 手动 + 订阅导入,按 URL 去重
+ const liveSeen = new Set<string>();
+ const liveSources = [...store.liveEnvSources, ...store.liveSubscriptions]
+ .filter((s) => {
+ if (liveSeen.has(s.url)) return false;
+ liveSeen.add(s.url);
+ return true;
+ })
+ .map(({ name, url, epg }) => ({ name: name || hostnameOf(url), url, epg }));
+
+ const payload = { name: 'LibreTV-SourceList', version: 2, exportedAt: Date.now(), sources, liveSources };
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -403,16 +419,23 @@ function SourceSubscriptions() {
a.download = `LibreTV-SourceList_${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
- toast(`已导出 ${sources.length} 个源,托管后即可被他人订阅`, 'success');
+ toast(`已导出 ${sources.length} 个点播源、${liveSources.length} 个直播源,托管后即可被他人订阅`, 'success');
};
return (
<section className="mb-6 pt-5">
<SectionTitle
- title="源订阅 / 分享"
+ title="数据源订阅 / 分享"
extra={
- <button className="btn-ghost !py-1 !px-2.5 text-xs" onClick={exportSources} disabled={store.customAPIs.length + store.envSources.length === 0}>
- 导出源列表
+ <button
+ className="btn-ghost !py-1 !px-2.5 text-xs"
+ onClick={exportSources}
+ disabled={
+ store.customAPIs.length + store.envSources.length + store.liveSubscriptions.length + store.liveEnvSources.length ===
+ 0
+ }
+ >
+ 导出数据源
</button>
}
/>
@@ -432,46 +455,63 @@ function SourceSubscriptions() {
</div>
{store.subscriptions.length === 0 ? (
<p className="text-xs text-faint">
- 订阅后源列表可随远端更新一键同步;「导出源列表」生成的 JSON 托管到任意 URL 即可分享给他人订阅。
+ 一份订阅可同时下发点播源与直播源;「导出数据源」生成的 JSON 托管到任意 URL 即可分享给他人订阅。
</p>
) : (
<ul className="space-y-2 max-h-[30vh] overflow-y-auto scrollbar-thin pr-1">
- {store.subscriptions.map((sub) => (
+ {store.subscriptions.map((sub) => {
+ const vodCount = store.customAPIs.filter((a) => a.key.startsWith(subKeyPrefix(sub.url))).length;
+ const liveCount = store.liveSubscriptions.filter((s) => s.fromSubscription === sub.url).length;
+ return (
<li key={sub.url} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">
<div className="flex items-center gap-2">
<div className="flex-1 min-w-0">
- <div className="text-sm font-medium text-content truncate">{sub.name || new URL(sub.url).hostname}</div>
+ <div className="text-sm font-medium text-content truncate">{sub.name || hostnameOf(sub.url)}</div>
<div className="text-xs text-faint truncate">
{sub.url}
{sub.lastSync && ` · 同步于 ${formatRelativeTime(sub.lastSync)}`}
</div>
+ <div className="mt-1 flex gap-1">
+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent">点播 {vodCount}</span>
+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent">直播 {liveCount}</span>
+ </div>
</div>
<button
- className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-accent disabled:opacity-40"
+ className="rounded-md p-1.5 shrink-0 text-muted transition-colors hover:bg-hover hover:text-accent disabled:opacity-40"
disabled={syncing === sub.url}
onClick={() => sync(sub.url)}
aria-label="重新同步"
- title="重新同步"
+ title="重新同步(以远端列表为准,整体替换该订阅名下的点播源与直播源)"
>
{syncing === sub.url ? '…' : '⟳'}
</button>
<button
- className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-red-400"
+ className="rounded-md p-1.5 shrink-0 text-muted transition-colors hover:bg-hover hover:text-red-400"
onClick={() => store.removeSubscription(sub.url)}
aria-label="删除订阅"
- title="删除订阅及其导入的源"
+ title="删除订阅及其导入的点播源与直播源(保留收藏的频道)"
>
✕
</button>
</div>
</li>
- ))}
+ );
+ })}
</ul>
)}
</section>
);
}
+/** 取 hostname 作为名称兜底;地址非法时原样返回 */
+function hostnameOf(url: string): string {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return url;
+ }
+}
+
function SectionTitle({ title, extra }: { title: string; extra?: React.ReactNode }) {
return (
<div className="flex items-center justify-between mb-2.5">
@@ -484,10 +524,12 @@ function SectionTitle({ title, extra }: { title: string; extra?: React.ReactNode
function EmptySourceGuide({ onAdd }: { onAdd: () => void }) {
return (
<div className="border border-dashed border-line rounded-lg p-5 text-center">
- <p className="text-sm text-muted mb-1">还没有添加任何数据源</p>
- <p className="text-xs text-faint mb-3">添加一个 Apple CMS 采集站 API 即可开始搜索影片</p>
+ <p className="text-sm text-muted mb-1">还没有添加任何点播源</p>
+ <p className="text-xs text-faint mb-3">
+ 添加一个 Apple CMS 采集站 API 即可开始搜索影片;也可到「订阅与配置」一次导入点播源与直播源
+ </p>
<button className="btn-primary text-xs" onClick={onAdd}>
- 添加第一个数据源
+ 添加第一个点播源
</button>
</div>
);
diff --git a/src/components/switch-source.tsx b/src/components/switch-source.tsx
index 5664912..2f8fe01 100644
--- a/src/components/switch-source.tsx
+++ b/src/components/switch-source.tsx
@@ -156,7 +156,7 @@ export function SwitchSourceModal({
<p className="text-sm text-muted">{phase === 'searching' ? '搜索各资源中...' : '测速中...'}</p>
</div>
) : sorted.length === 0 ? (
- <p className="text-center text-sm text-faint py-8">其他数据源未找到同名资源</p>
+ <p className="text-center text-sm text-faint py-8">其他点播源未找到同名资源</p>
) : (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
{sorted.map((c) => {
diff --git a/src/lib/client-api.ts b/src/lib/client-api.ts
index a7a8b3b..ce44cf2 100644
--- a/src/lib/client-api.ts
+++ b/src/lib/client-api.ts
@@ -1,6 +1,6 @@
'use client';
-import type { SearchResponse, VideoDetail, DoubanResponse, BangumiCalendarResponse, AuthStatusResponse, SourceConfig, SearchResultItem, LivePlaylistResponse, LiveEpgResponse } from './types';
+import type { SearchResponse, VideoDetail, DoubanResponse, BangumiCalendarResponse, AuthStatusResponse, SourceConfig, SearchResultItem, LivePlaylistResponse, LiveEpgResponse, SourceListPayload } from './types';
/**
* 客户端 API 封装。401 时触发全局事件打开登录框,
@@ -100,7 +100,7 @@ export const api = {
}
},
- /** 数据源探活:以搜索 "test" 的耗时与结果量衡量可用性 */
+ /** 点播源探活:以搜索 "test" 的耗时与结果量衡量可用性 */
testSource: (url: string) =>
request<{ ok: boolean; ms: number; count?: number; error?: string }>('/api/source/test', {
method: 'POST',
@@ -108,10 +108,10 @@ export const api = {
body: JSON.stringify({ url }),
}),
- /** 拉取远程源订阅列表(LibreTV-SourceList JSON) */
+ /** 拉取远程数据源订阅(LibreTV-SourceList JSON:点播源 sources + 直播源 liveSources) */
fetchSourceList: (url: string) => {
const sp = new URLSearchParams({ url });
- return request<{ name?: string; sources: SourceConfig[] }>(`/api/source-list?${sp.toString()}`);
+ return request<SourceListPayload>(`/api/source-list?${sp.toString()}`);
},
/** —— 直播 / IPTV —— */
diff --git a/src/lib/source-list.test.ts b/src/lib/source-list.test.ts
new file mode 100644
index 0000000..7e4a32d
--- /dev/null
+++ b/src/lib/source-list.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from 'vitest';
+import { MAX_LIVE_SOURCES, MAX_VOD_SOURCES, parseSourceListPayload } from './source-list';
+
+const vod = (url: string, extra: Record<string, unknown> = {}) => ({ name: `源 ${url}`, url, ...extra });
+const live = (url: string, extra: Record<string, unknown> = {}) => ({ name: `频道 ${url}`, url, ...extra });
+
+describe('parseSourceListPayload', () => {
+ it('解析点播源与直播源', () => {
+ const result = parseSourceListPayload({
+ name: '我的全站源',
+ version: 2,
+ sources: [vod('https://vod.example.com/api.php/provide/vod', { detail: 'https://vod.example.com', isAdult: true })],
+ liveSources: [live('https://live.example.com/list.m3u', { epg: 'https://live.example.com/epg.xml.gz' })],
+ });
+
+ expect(result.name).toBe('我的全站源');
+ expect(result.sources).toEqual([
+ {
+ name: '源 https://vod.example.com/api.php/provide/vod',
+ url: 'https://vod.example.com/api.php/provide/vod',
+ detail: 'https://vod.example.com',
+ isAdult: true,
+ },
+ ]);
+ expect(result.liveSources).toEqual([
+ {
+ name: '频道 https://live.example.com/list.m3u',
+ url: 'https://live.example.com/list.m3u',
+ epg: 'https://live.example.com/epg.xml.gz',
+ },
+ ]);
+ });
+
+ it('缺失名称时用 hostname 兜底', () => {
+ const result = parseSourceListPayload({
+ sources: [{ url: 'https://vod.example.com/api.php/provide/vod' }],
+ liveSources: [{ url: 'https://live.example.com/list.m3u' }],
+ });
+
+ expect(result.sources[0].name).toBe('vod.example.com');
+ expect(result.liveSources[0].name).toBe('live.example.com');
+ });
+
+ it('老格式(只有 sources)兼容为纯点播订阅', () => {
+ const result = parseSourceListPayload({
+ name: '老订阅',
+ sources: [{ url: 'https://vod.example.com/api.php/provide/vod/' }],
+ });
+
+ expect(result.sources).toHaveLength(1);
+ expect(result.liveSources).toEqual([]);
+ });
+
+ it('裸数组视为点播源列表', () => {
+ const result = parseSourceListPayload([{ url: 'https://a.example.com/api.php/provide/vod' }]);
+
+ expect(result.name).toBeUndefined();
+ expect(result.sources).toHaveLength(1);
+ expect(result.liveSources).toEqual([]);
+ });
+
+ it('只含 liveSources 的纯直播订阅可用', () => {
+ const result = parseSourceListPayload({
+ name: '纯直播',
+ liveSources: [{ url: 'https://live.example.com/list.m3u' }],
+ });
+
+ expect(result.sources).toEqual([]);
+ expect(result.liveSources).toHaveLength(1);
+ });
+
+ it('过滤非法协议与空地址', () => {
+ const result = parseSourceListPayload({
+ sources: [
+ { url: 'ftp://vod.example.com/vod' },
+ { url: '' },
+ { name: '无 url' },
+ { url: 'https://ok.example.com/vod' },
+ ],
+ liveSources: [
+ { url: 'rtmp://live.example.com/live' },
+ { url: 'https://live.example.com/list.m3u', epg: 'javascript:alert(1)' },
+ ],
+ });
+
+ expect(result.sources.map((s) => s.url)).toEqual(['https://ok.example.com/vod']);
+ expect(result.liveSources).toHaveLength(1);
+ expect(result.liveSources[0].epg).toBeUndefined();
+ });
+
+ it('按 url 去重(点播去尾部斜杠后比较,直播保留原样)', () => {
+ const result = parseSourceListPayload({
+ sources: [
+ { url: 'https://vod.example.com/vod' },
+ { url: 'https://vod.example.com/vod/' },
+ ],
+ liveSources: [
+ { url: 'https://live.example.com/list.m3u' },
+ { url: 'https://live.example.com/list.m3u' },
+ { url: 'https://live.example.com/other.m3u' },
+ ],
+ });
+
+ expect(result.sources).toHaveLength(1);
+ expect(result.liveSources).toHaveLength(2);
+ });
+
+ it('超出上限时截断', () => {
+ const sources = Array.from({ length: MAX_VOD_SOURCES + 10 }, (_, i) => ({
+ url: `https://vod${i}.example.com/vod`,
+ }));
+ const liveSources = Array.from({ length: MAX_LIVE_SOURCES + 10 }, (_, i) => ({
+ url: `https://live${i}.example.com/list.m3u`,
+ }));
+
+ const result = parseSourceListPayload({ sources, liveSources });
+
+ expect(result.sources).toHaveLength(MAX_VOD_SOURCES);
+ expect(result.liveSources).toHaveLength(MAX_LIVE_SOURCES);
+ });
+
+ it('既无点播也无直播时抛错', () => {
+ expect(() => parseSourceListPayload({ name: '空的' })).toThrow(/格式不正确/);
+ expect(() => parseSourceListPayload({ sources: [] })).toThrow(/格式不正确/);
+ expect(() => parseSourceListPayload(null)).toThrow(/格式不正确/);
+ });
+});
diff --git a/src/lib/source-list.ts b/src/lib/source-list.ts
new file mode 100644
index 0000000..0483f19
--- /dev/null
+++ b/src/lib/source-list.ts
@@ -0,0 +1,102 @@
+import type { SourceListPayload } from './types';
+
+/**
+ * 数据源订阅(LibreTV-SourceList JSON)的纯解析层:只做字段裁剪、去重与上限,
+ * 不涉及网络与 SSRF 判定(点播/直播的地址放行策略不同,由调用方按类型分别校验)。
+ *
+ * 支持三种形态:
+ * 1. 完整格式:{ name?, sources: [...点播源], liveSources: [...直播源] }
+ * 2. 老格式:只有 sources(或裸数组),直播源为空 —— 保持向后兼容
+ * 3. 纯直播订阅:只有 liveSources
+ */
+
+export const MAX_VOD_SOURCES = 100;
+export const MAX_LIVE_SOURCES = 50;
+
+interface RawItem {
+ name?: unknown;
+ url?: unknown;
+ detail?: unknown;
+ isAdult?: unknown;
+ epg?: unknown;
+}
+
+/** 规范化为 http(s) 地址;trimV2 控制是否去掉尾部斜杠(点播去、直播保留) */
+function normalizeUrl(raw: unknown, trimTrailingSlash: boolean): string | undefined {
+ if (typeof raw !== 'string') return undefined;
+ const trimmed = raw.trim();
+ if (!trimmed) return undefined;
+ if (!/^https?:\/\//i.test(trimmed)) return undefined;
+ try {
+ new URL(trimmed);
+ } catch {
+ return undefined;
+ }
+ return trimTrailingSlash ? trimmed.replace(/\/+$/, '') : trimmed;
+}
+
+function optionalString(raw: unknown): string | undefined {
+ return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined;
+}
+
+function hostnameOf(url: string): string {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return url;
+ }
+}
+
+/**
+ * 解析订阅 JSON。
+ * @throws 内容既无点播源也无直播源时抛错(提示格式问题)
+ */
+export function parseSourceListPayload(json: unknown): SourceListPayload {
+ const asArray = Array.isArray(json) ? json : null;
+ const asObject = asArray ? null : (json as { name?: unknown; sources?: unknown; liveSources?: unknown } | null);
+
+ const rawVod: RawItem[] = asArray
+ ? asArray
+ : Array.isArray(asObject?.sources)
+ ? (asObject?.sources as RawItem[])
+ : [];
+ const rawLive: RawItem[] = Array.isArray(asObject?.liveSources) ? (asObject?.liveSources as RawItem[]) : [];
+
+ if (rawVod.length === 0 && rawLive.length === 0) {
+ throw new Error('订阅内容格式不正确(缺少 sources / liveSources 数组)');
+ }
+
+ const seenVod = new Set<string>();
+ const sources = rawVod.slice(0, MAX_VOD_SOURCES).flatMap((s) => {
+ const url = normalizeUrl(s?.url, true);
+ if (!url || seenVod.has(url)) return [];
+ seenVod.add(url);
+ return [
+ {
+ name: optionalString(s?.name) || hostnameOf(url),
+ url,
+ detail: optionalString(s?.detail),
+ isAdult: s?.isAdult === true,
+ },
+ ];
+ });
+
+ const seenLive = new Set<string>();
+ const liveSources = rawLive.slice(0, MAX_LIVE_SOURCES).flatMap((s) => {
+ const url = normalizeUrl(s?.url, false);
+ if (!url || seenLive.has(url)) return [];
+ seenLive.add(url);
+ const epg = normalizeUrl(s?.epg, false);
+ return [
+ {
+ name: optionalString(s?.name) || hostnameOf(url),
+ url,
+ epg,
+ },
+ ];
+ });
+
+ const name = asObject ? optionalString(asObject.name) : undefined;
+
+ return { name, sources, liveSources };
+}
diff --git a/src/lib/ssrf.ts b/src/lib/ssrf.ts
index 1631017..90e07cd 100644
--- a/src/lib/ssrf.ts
+++ b/src/lib/ssrf.ts
@@ -61,3 +61,28 @@ export async function checkUpstreamAllowed(urlString: string): Promise<UpstreamV
}
return { ok: true };
}
+
+/** 直播场景是否放行内网地址(自建 IPTV);由部署者显式开启 */
+export function allowLivePrivate(): boolean {
+ return process.env.LIVE_ALLOW_PRIVATE === '1';
+}
+
+/**
+ * 直播地址专用校验:协议必须 http(s),默认仍拒绝内网,但部署者可用
+ * LIVE_ALLOW_PRIVATE=1 显式放行(自建 IPTV 常位于内网)。
+ *
+ * 与点播侧 checkUpstreamAllowed 的区别只在这一处开关:
+ * 订阅/播放列表若沿用点播那把尺子,会静默过滤掉内网自建源。
+ */
+export async function checkLiveUrlAllowed(urlString: string): Promise<UpstreamVerdict> {
+ try {
+ const parsed = new URL(urlString);
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ return { ok: false, reason: '直播地址仅支持 http/https 协议' };
+ }
+ } catch {
+ return { ok: false, reason: '无效的直播地址' };
+ }
+ if (allowLivePrivate()) return { ok: true };
+ return checkUpstreamAllowed(urlString);
+}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 14102fb..00cbe0b 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -22,7 +22,10 @@ export interface AppSettings {
customImageProxy: string;
}
-/** 源订阅:远程源列表(LibreTV-SourceList JSON),可一键同步更新 */
+/**
+ * 数据源订阅:远程源列表(LibreTV-SourceList JSON),可一键同步更新。
+ * 一份订阅同时下发点播源与直播源;老订阅只有点播源。
+ */
export interface SourceSubscription {
url: string;
/** 订阅列表自带名称 */
@@ -31,7 +34,7 @@ export interface SourceSubscription {
lastSync?: number;
}
-/** 直播订阅:远程 M3U 播放列表(独立于采集站订阅模型,避免 key 前缀冲突) */
+/** 直播源:远程 M3U 播放列表;可来自用户手动添加,也可来自统一订阅 */
export interface LiveSubscription {
url: string;
name?: string;
@@ -39,6 +42,11 @@ export interface LiveSubscription {
epg?: string;
/** 上次同步成功时间 */
lastSync?: number;
+ /**
+ * 该直播源来自哪个订阅 URL;手动添加时为空。
+ * 删除订阅时按此归属精确清理,避免误删用户手动添加的源。
+ */
+ fromSubscription?: string;
}
/** 直播最近观看条目(上限 20 条,按 url 去重) */
@@ -50,6 +58,8 @@ export interface LiveRecentEntry {
tvgId?: string;
/** 来源订阅地址(用于回查 EPG) */
epg?: string;
+ /** 所属直播源地址(M3U 订阅 URL),删除订阅时按此清理;旧数据缺失则自然淘汰 */
+ sourceUrl?: string;
timestamp: number;
}
@@ -84,7 +94,7 @@ interface AppState extends AppSettings {
liveEnvSources: LiveSourceConfig[];
/** 已出现过的预置直播源 key(持久化:用于「首次自动可见」去重) */
liveEnvKeysSeen: string[];
- /** 用户添加的 M3U 订阅 */
+ /** 用户直播源:手动添加的 M3U + 订阅导入的 M3U(后者带 fromSubscription) */
liveSubscriptions: LiveSubscription[];
/** 已启用的直播源(按订阅 URL 唯一标识,首次出现自动勾选) */
liveSelectedUrls: string[];
@@ -103,8 +113,10 @@ interface AppState extends AppSettings {
addSubscription: (url: string, name?: string) => void;
removeSubscription: (url: string) => void;
markSubscriptionSynced: (url: string, name?: string) => void;
- /** 用订阅内容整体替换该订阅名下的源,返回新增数量 */
+ /** 用订阅内容整体替换该订阅名下的点播源,返回新增数量 */
applySubscriptionSources: (subUrl: string, list: Omit<SourceConfig, 'key'>[]) => number;
+ /** 用订阅内容整体替换该订阅名下的直播源,返回新增数量 */
+ applySubscriptionLive: (subUrl: string, list: Omit<LiveSourceConfig, 'key'>[]) => number;
setLiveEnvSources: (list: LiveSourceConfig[]) => void;
addLiveSubscription: (url: string, name?: string, epg?: string) => void;
removeLiveSubscription: (url: string) => void;
@@ -217,10 +229,18 @@ export const useAppStore = create<AppState>()(
removeSubscription: (url) => {
const prefix = subKeyPrefix(url);
+ // 该订阅名下的直播源(M3U 地址集合),用于清理启用状态与最近观看
+ const ownedLive = new Set(
+ get().liveSubscriptions.filter((s) => s.fromSubscription === url).map((s) => s.url)
+ );
set({
subscriptions: get().subscriptions.filter((s) => s.url !== url),
customAPIs: get().customAPIs.filter((a) => !a.key.startsWith(prefix)),
selectedKeys: get().selectedKeys.filter((k) => !k.startsWith(prefix)),
+ liveSubscriptions: get().liveSubscriptions.filter((s) => s.fromSubscription !== url),
+ liveSelectedUrls: get().liveSelectedUrls.filter((u) => !ownedLive.has(u)),
+ // 收藏的频道是用户主动留下的,删除订阅时保留;其余残留状态一并清理
+ liveRecent: get().liveRecent.filter((r) => !r.sourceUrl || !ownedLive.has(r.sourceUrl)),
});
},
@@ -254,6 +274,33 @@ export const useAppStore = create<AppState>()(
return incoming.length;
},
+ applySubscriptionLive: (subUrl, list) => {
+ const existing = get().liveSubscriptions;
+ const owned = existing.filter((s) => s.fromSubscription === subUrl);
+ const ownedUrls = new Set(owned.map((s) => s.url));
+ // 手动添加或其他订阅已占用的 M3U 不再重复导入(手动添加优先)
+ const kept = existing.filter((s) => s.fromSubscription !== subUrl);
+ const keptUrls = new Set(kept.map((s) => s.url));
+ const incoming: LiveSubscription[] = list
+ .filter((s) => !keptUrls.has(s.url))
+ .map((s) => ({ url: s.url, name: s.name, epg: s.epg, fromSubscription: subUrl }));
+ // 本次订阅里已消失的旧源:其最近观看记录一并清掉,收藏保留
+ const stillPresent = new Set(list.map((s) => s.url));
+ const droppedUrls = new Set([...ownedUrls].filter((u) => !stillPresent.has(u)));
+
+ set({
+ liveSubscriptions: [...kept, ...incoming],
+ liveSelectedUrls: [
+ ...new Set([
+ ...get().liveSelectedUrls.filter((u) => !ownedUrls.has(u)),
+ ...incoming.map((s) => s.url),
+ ]),
+ ],
+ liveRecent: get().liveRecent.filter((r) => !r.sourceUrl || !droppedUrls.has(r.sourceUrl)),
+ });
+ return incoming.length;
+ },
+
setLiveEnvSources: (list) => {
// 预置直播源首次出现时自动启用;用户此后停用不会被反复勾回
const seen = new Set(get().liveEnvKeysSeen);
@@ -347,6 +394,20 @@ export const useAppStore = create<AppState>()(
}),
{
name: 'libretv-settings',
+ // v1:直播源新增 fromSubscription 归属字段、最近观看新增 sourceUrl。
+ // 此前未声明 version,存量数据会被视为 v0 并走 migrate 补齐(缺失字段按「手动添加」处理)。
+ version: 1,
+ migrate: (persisted, version) => {
+ const state = (persisted ?? {}) as Partial<AppState>;
+ if (version < 1) {
+ return {
+ ...state,
+ liveSubscriptions: Array.isArray(state.liveSubscriptions) ? state.liveSubscriptions : [],
+ liveRecent: Array.isArray(state.liveRecent) ? state.liveRecent : [],
+ } as AppState;
+ }
+ return state as AppState;
+ },
// envSources 由服务端每次下发,不进 localStorage
partialize: (s) => ({
customAPIs: s.customAPIs,
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 608cc04..88a7c7d 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -142,3 +142,17 @@ export interface LiveEpgResponse {
next?: EpgProgram;
programs: EpgProgram[];
}
+
+// —— 数据源订阅 ——
+
+/**
+ * 远程订阅(LibreTV-SourceList JSON)解析结果。
+ * `sources` 为点播源(Apple CMS 采集站),`liveSources` 为直播源(M3U + 可选 EPG)。
+ * 老格式订阅只有 `sources`,此时 `liveSources` 为空数组。
+ */
+export interface SourceListPayload {
+ /** 订阅列表自带名称 */
+ name?: string;
+ sources: Omit<SourceConfig, 'key'>[];
+ liveSources: Omit<LiveSourceConfig, 'key'>[];
+}