一分钟搭建影视站,支持Docker等部署方式
feat(subscription): 支持导入 TVBOX 配置并放宽 JSON 容错、修复订阅同步若干问题,版本 2.10.2
bestZweib7e940eee2d6
diff --git a/README.md b/README.mdindex 780eaad..04ed08b 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 可同时下发点播源与直播源,也可直接填 TVBOX 配置地址,自动导入其中可直接使用的接口),可导出分享- **首页推荐**:豆瓣(电影/剧集分类浏览)、Bangumi 新番放送表或影视榜单(豆瓣周榜 + 百度热播,经 60s API),设置中切换;均服务端直连 + 缓存,Bangumi/榜单免 key 免配置(`60S_API_BASE` 可指向自部署 60s 实例)- **PWA**:可安装到桌面 / 主屏幕,亮暗双主题无首屏闪烁@@ -85,7 +85,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 静默刷新;用户删除后不再自动加回 |+| `DEFAULT_SUBSCRIPTIONS` | 否 | 预置数据源订阅(LibreTV-SourceList JSON 链接,也接受 TVBOX 配置地址),JSON 数组:`["https://.../sources.json", {"url":"https://.../list.json","name":"名称"}]`。首次访问自动导入点播源与直播源,之后每 24h 静默刷新;用户删除后不再自动加回 || `LIVE_ALLOW_PRIVATE` | 否 | 设为 `1` 时允许直播流代理访问内网/保留地址(自建 IPTV 场景),默认关闭以维持 SSRF 防护 || `DEBUG` | 否 | 调试日志 |@@ -132,11 +132,22 @@ PASSWORD=your-password npm start # 监听 8080- 只写 `sources` 的老订阅照常可用(纯点播),只写 `liveSources` 则是纯直播订阅;裸数组 `[{ "name": "...", "url": "..." }]` 视为点播源;- 按 `url` 去重,点播源最多 100 个、直播源最多 50 个;非 http(s) 地址会被过滤,点播源另需为公网地址(直播源可用 `LIVE_ALLOW_PRIVATE=1` 放行内网自建源)。+### 兼容 TVBOX 配置++订阅地址也可以直接填 **TVBOX 配置**(形如 `{"sites": [...], "lives": [...], "parses": [...]}`):服务端按内容结构自动识别格式,无需手动选择。++- **点播源**:导入 `sites` 中 `type: 1` 的 JSON 接口(即 Apple CMS 采集站);部分共享配置省略 `type` 或写成 `0`,但地址命中 `api.php/provide/vod` 时同样导入;站点自身标记 `searchable: 0`(不可搜索)时跳过;+- **直播源**:导入 `lives` 中 `type: 0`(或省略)的 M3U 播放列表,`epg` 字段一并带上;txt 频道列表与单仓 JSON 不支持;+- **Spider 类站点会跳过**:`type: 3` 的 Spider(`csp_*` / `.jar` / `.js` / `.py`)需要 TVBOX 自身的 Spider 引擎才能运行,Node 侧无法执行;XML 接口、外链 JSON 同理。被跳过的条目不影响其余导入,导入结果会如实提示,如「已同步 8 个点播源、2 个直播源(TVBOX 配置);跳过 96 个不可用条目(Spider 引擎 92、XML 接口 4)」;+- TVBOX 配置常含上百条站点且以 Spider 为主,**只导入个位数到十几个属正常现象**;+- **格式容错**:配置里的 `//` 注释、尾随逗号、字符串内未转义的换行会自动修正后再解析(共享配置中很常见,TVBOX 客户端用的 fastjson 同样容忍这些写法);+- 其他限制:订阅地址需直接返回 JSON(Base64 / 压缩包装的分享链接不支持);TVBOX「多仓」配置(顶层为 `urls` 数组)不支持,请填单仓配置;地址公网校验、去重与数量上限与上方格式完全一致。+### 订阅行为- **订阅**:设置 → 订阅与配置 → 数据源订阅 → 填入订阅地址 → 「订阅」,导入的点播源自动勾选、直播源自动启用,均带「订阅」标识,条目上显示「点播 N · 直播 M」;- **同步**:订阅条目上的 **⟳** 手动强制同步,整体替换该订阅名下的点播源与直播源;-- **管理边界**:订阅源以远端列表为准,单独编辑会在下次同步时被覆盖,单独移除会在重新同步时恢复;如需调整请改远端列表,或直接删除整个订阅(会一并移除其导入的点播源与直播源,但**保留已收藏的频道**);+- **管理边界**:订阅源以远端列表为准,单独编辑会在下次同步时被覆盖,单独移除会在重新同步时恢复;如需调整请改远端列表,或直接删除整个订阅。删除订阅时点播源全部移除;直播源为**多归属共享**——同一 M3U 可被多个订阅引用(名称/EPG 以首次导入为准),删除只移除自己的引用,仅当不再被任何订阅引用时才移除该源,**收藏的频道始终保留**;- **导出分享**:设置 → 订阅与配置 → 数据源订阅 → 「导出数据源」,把当前全部点播源与直播源(预置 + 手动 + 订阅,按 URL 去重)导出为上述 JSON。> 订阅由服务端拉取(经过 SSRF 校验),因此订阅地址无需配置 CORS。完整说明见 [数据源文档](https://github.com/bestZwei/LibreTV-Next/wiki/Data-Sources)。diff --git a/package.json b/package.jsonindex a9a1175..3672f6f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "libretv",- "version": "2.10.1",+ "version": "2.10.2","private": true,"description": "免费在线视频搜索与观看平台(Next.js 重构版)","license": "AGPL-3.0-or-later",diff --git a/src/app/api/source-list/route.test.ts b/src/app/api/source-list/route.test.tsnew file mode 100644index 0000000..58fdf20--- /dev/null+++ b/src/app/api/source-list/route.test.ts@@ -0,0 +1,183 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { GET } from './route';+import { SESSION_COOKIE, signSession } from '@/lib/auth';++/**+ * 订阅接口单测:格式自动识别(LibreTV-SourceList / TVBOX)、统计透传,+ * 以及服务端校验拦下条目时的提示。上游拉取与 SSRF 校验一律 mock,不产生网络请求。+ */++const state = vi.hoisted(() => ({+ body: null as unknown,+ /** 上游原始响应文本(优先于 body),用于模拟非 JSON / 带注释响应 */+ rawText: null as string | null,+ /** 点播源公网校验的模拟实现,默认全部放行 */+ proxyAllowed: (() => true) as (url: string) => boolean,+ /** 直播源校验的模拟开关 */+ liveAllowed: true as boolean,+}));++vi.mock('@/lib/fetch-utils', () => ({+ fetchUpstream: vi.fn(+ async () =>+ new Response(state.rawText ?? JSON.stringify(state.body), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ ),+}));++vi.mock('@/lib/ssrf', () => ({+ checkUpstreamAllowed: vi.fn(async () => ({ ok: true })),+ checkLiveUrlAllowed: vi.fn(async () => ({ ok: state.liveAllowed })),+ isValidProxyUrl: vi.fn((url: string) => state.proxyAllowed(url)),+}));++interface SubPayload {+ name?: string;+ sources?: { name?: string; url: string }[];+ liveSources?: { name?: string; url: string }[];+ stats?: Record<string, unknown>;+ error?: string;+}++async function readJson(res: Response): Promise<SubPayload> {+ return (await res.json()) as SubPayload;+}++function makeRequest(subUrl = 'https://feed.example.com/subscription.json'): Request {+ const { token } = signSession();+ const sp = new URLSearchParams({ url: subUrl });+ return new Request(`https://local.test/api/source-list?${sp.toString()}`, {+ headers: { cookie: `${SESSION_COOKIE}=${token}` },+ });+}++beforeAll(() => {+ process.env.PASSWORD = 'test-password';+ delete process.env.PROXY_SECRET;+});++beforeEach(() => {+ state.body = null;+ state.rawText = null;+ state.proxyAllowed = () => true;+ state.liveAllowed = true;+});++describe('GET /api/source-list', () => {+ it('TVBOX 配置:导入直连类条目并透传跳过统计', async () => {+ state.body = {+ sites: [+ { name: '正版源', type: 1, api: 'https://vod.example.com/api.php/provide/vod' },+ { name: '蜘蛛A', type: 3, api: 'csp_AppYs' },+ { name: '蜘蛛B', type: 3, api: 'csp_XBPQ' },+ { name: 'XML站', type: 0, api: 'https://xml.example.com/api.php/provide/vod/at/xml' },+ ],+ lives: [{ name: '直播', type: 0, url: 'https://live.example.com/list.m3u' }],+ };++ const res = await GET(makeRequest());+ const data = await readJson(res);++ expect(res.status).toBe(200);+ expect(data.sources).toEqual([{ name: '正版源', url: 'https://vod.example.com/api.php/provide/vod' }]);+ expect(data.liveSources).toHaveLength(1);+ expect(data.stats).toMatchObject({ format: 'tvbox', skipped: 3, skippedByReason: { spider: 2, xml: 1 } });+ });++ it('LibreTV 源列表:沿用原格式与默认统计', async () => {+ state.body = {+ name: '我的源列表',+ sources: [{ name: '点播', url: 'https://vod.example.com/api.php/provide/vod' }],+ liveSources: [{ name: '直播', url: 'https://live.example.com/list.m3u' }],+ };++ const res = await GET(makeRequest());+ const data = await readJson(res);++ expect(res.status).toBe(200);+ expect(data.name).toBe('我的源列表');+ expect(data.stats).toEqual({ format: 'libretv', skipped: 0, skippedByReason: {}, truncated: 0 });+ });++ it('全部为 Spider 时返回可读错误并带原因计数', async () => {+ state.body = { sites: [{ name: '蜘蛛A', type: 3, api: 'csp_AppYs' }] };++ const res = await GET(makeRequest());+ const data = await readJson(res);++ expect(res.status).toBe(400);+ expect(data.error).toMatch(/已跳过 1 个条目(Spider 引擎 1)/);+ });++ it('服务端校验拦下全部条目时提示原因而非静默成功', async () => {+ state.body = { sites: [{ name: '内网源', type: 1, api: 'https://192.168.1.2/api.php/provide/vod' }] };+ state.proxyAllowed = () => false;++ const res = await GET(makeRequest());+ const data = await readJson(res);++ expect(res.status).toBe(400);+ expect(data.error).toContain('订阅未导入任何可用源');+ expect(data.error).toContain('地址不可用 1');+ });++ it('部分条目被拦下时仍正常导入,并在统计中说明', async () => {+ state.body = {+ sites: [+ { name: '公网源', type: 1, api: 'https://vod.example.com/api.php/provide/vod' },+ { name: '内网源', type: 1, api: 'https://192.168.1.2/api.php/provide/vod' },+ ],+ };+ state.proxyAllowed = (url) => !url.includes('192.168');++ const res = await GET(makeRequest());+ const data = await readJson(res);++ expect(res.status).toBe(200);+ expect(data.sources).toHaveLength(1);+ expect(data.stats).toMatchObject({ skipped: 1, skippedByReason: { invalidUrl: 1 } });+ });++ it('直播源地址非法时丢弃该条并计入统计', async () => {+ state.body = {+ sites: [{ name: '点播', type: 1, api: 'https://vod.example.com/api.php/provide/vod' }],+ lives: [{ name: '内网直播', type: 0, url: 'http://10.0.0.2/list.m3u' }],+ };+ state.liveAllowed = false;++ const res = await GET(makeRequest());+ const data = await readJson(res);++ expect(res.status).toBe(200);+ expect(data.liveSources).toHaveLength(0);+ expect(data.stats).toMatchObject({ skipped: 1, skippedByReason: { invalidUrl: 1 } });+ });++ it('带注释的配置照常导入(fastjson 式容错)', async () => {+ state.rawText = [+ '{',+ ' // 站点',+ ' "sites": [{ "name": "正版源", "type": 1, "api": "https://vod.example.com/api.php/provide/vod" }],',+ ' "lives": []',+ '}',+ ].join('\n');++ const res = await GET(makeRequest());+ const data = await readJson(res);++ expect(res.status).toBe(200);+ expect(data.sources).toHaveLength(1);+ });++ it('上游返回 HTML 等非 JSON 内容时给出可读错误', async () => {+ state.rawText = '<html>403 Forbidden</html>';++ const res = await GET(makeRequest());+ const data = await readJson(res);++ expect(res.status).toBe(400);+ expect(data.error).toBe('订阅内容不是合法的 JSON');+ });+});diff --git a/src/app/api/source-list/route.ts b/src/app/api/source-list/route.tsindex a855f85..aea29b7 100644--- a/src/app/api/source-list/route.ts+++ b/src/app/api/source-list/route.ts@@ -2,20 +2,19 @@ import { NextResponse } from 'next/server';import { guardRequest } from '@/lib/api-guard';import { checkLiveUrlAllowed, checkUpstreamAllowed, isValidProxyUrl } from '@/lib/ssrf';import { fetchUpstream } from '@/lib/fetch-utils';-import { parseSourceListPayload } from '@/lib/source-list';+import { describeParseStats, parseSubscriptionJson, parseSubscriptionPayload, withSkipped } from '@/lib/tvbox-parser';import type { SourceListPayload } from '@/lib/types';export const runtime = 'nodejs';/**- * 拉取远程数据源订阅。- * 接受三种形态:- * 1. 完整格式:{ name?, sources: [点播源], liveSources: [直播源] }- * 2. 老格式:只有 sources(或裸数组),仅点播- * 3. 纯直播订阅:只有 liveSources+ * 拉取远程数据源订阅,自动识别两种格式:+ * 1. LibreTV-SourceList JSON:{ name?, sources: [点播源], liveSources: [直播源] }(也接受裸数组与老格式);+ * 2. TVBOX 配置 JSON:{ sites: [站点], lives: [直播源] },仅导入直连类条目+ * (type=1 的 Apple CMS 接口与 M3U 直播),Spider / XML 等跳过并计入统计。** 点播源与直播源的地址放行策略不同(点播一律拒绝内网,直播可用 LIVE_ALLOW_PRIVATE 放行),- * 因此两类分别校验,不能共用一把尺子。+ * 因此两类分别校验,不能共用一把尺子;被校验拦下的条目同样计入统计,便于前端说明导入结果。*/export async function GET(req: Request) {const guarded = guardRequest(req);@@ -37,11 +36,12 @@ export async function GET(req: Request) {if (!res.ok) {return NextResponse.json({ error: `订阅地址返回 HTTP ${res.status}` }, { status: 502 });}- const json: unknown = await res.json();+ // 读文本而非 res.json():部分配置带注释/尾随逗号,需要宽容解析+ const text = await res.text();let parsed;try {- parsed = parseSourceListPayload(json);+ parsed = parseSubscriptionPayload(parseSubscriptionJson(text));} catch (err) {return NextResponse.json({ error: err instanceof Error ? err.message : '订阅内容格式不正确' },@@ -60,13 +60,21 @@ export async function GET(req: Request) {return s;}));+ const liveSources = checkedLive.filter((s): s is NonNullable<typeof s> => s !== null);- const payload: SourceListPayload = {- name: parsed.name,- sources,- liveSources: checkedLive.filter((s): s is NonNullable<typeof s> => s !== null),- };+ // 被服务端校验拦下的条目也计入统计,用户能看清「配置里有 N 条却只导入 M 条」的原因+ const dropped = parsed.sources.length - sources.length + (parsed.liveSources.length - liveSources.length);+ const stats = withSkipped(parsed.stats, 'invalidUrl', dropped);+ if (sources.length === 0 && liveSources.length === 0) {+ const detail = describeParseStats(stats);+ return NextResponse.json(+ { error: detail ? `订阅未导入任何可用源:${detail}` : '订阅内容为空' },+ { status: 400 }+ );+ }++ const payload: SourceListPayload = { name: parsed.name, sources, liveSources, stats };return NextResponse.json(payload);} catch (err) {return NextResponse.json(diff --git a/src/components/live-source-manager.tsx b/src/components/live-source-manager.tsxindex 0de2e8e..9659566 100644--- a/src/components/live-source-manager.tsx+++ b/src/components/live-source-manager.tsx@@ -97,15 +97,15 @@ export function LiveSourceManager() {epgUrl,preset = false,lastSync,- fromSubscription,+ fromSubscriptions,}: {url: string;label: string;epgUrl?: string;preset?: boolean;lastSync?: number;- /** 该直播源来自哪个订阅 URL;有值时由订阅统一管理,不可单独删除 */- fromSubscription?: string;+ /** 引用该直播源的订阅 URL 列表(多归属);非空时由订阅统一管理,不可单独删除 */+ fromSubscriptions?: string[];}) => (<li key={url} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50"><div className="flex items-center gap-2">@@ -125,10 +125,10 @@ export function LiveSourceManager() {部署者预置</span>)}- {fromSubscription && (+ {(fromSubscriptions?.length ?? 0) > 0 && (<spanclassName="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent align-middle"- title="来自数据源订阅,重新同步时此源的名称/地址会以订阅内容为准"+ title={`来自 ${fromSubscriptions?.length ?? 0} 个数据源订阅;删除单个订阅不影响此源,仅当不再被任何订阅引用时才会移除`}>订阅</span>@@ -149,7 +149,7 @@ export function LiveSourceManager() {>⇩</button>- {fromSubscription ? (+ {(fromSubscriptions?.length ?? 0) > 0 ? (<buttonclassName="rounded-md p-1.5 text-muted/40"onClick={() => toast('该直播源来自数据源订阅;请到「订阅与配置 → 数据源订阅」中删除整个订阅', 'info')}@@ -225,7 +225,7 @@ export function LiveSourceManager() {label: s.name || hostnameOf(s.url),epgUrl: s.epg,lastSync: s.lastSync,- fromSubscription: s.fromSubscription,+ fromSubscriptions: s.fromSubscriptions,}))}</ul>diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsxindex 193dc30..d8071e2 100644--- a/src/components/source-manager.tsx+++ b/src/components/source-manager.tsx@@ -2,13 +2,14 @@import { useEffect, useState } from 'react';import { Drawer } from './header';-import { isSourceDisabled, subKeyPrefix, useAppStore } from '@/lib/store';+import { isSourceDisabled, keyBelongsToSubscription, subKeyPrefix, useAppStore } from '@/lib/store';import { useToast } from './toast';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 { describeParseStats } from '@/lib/tvbox-parser';import { LiveSourceManager } from './live-source-manager';/**@@ -407,7 +408,8 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:/*** 数据源订阅 / 分享:- * - 订阅:填入远程 LibreTV-SourceList JSON 地址,一次拉取点播源与直播源,可随时重新同步;+ * - 订阅:填入远程订阅地址(LibreTV-SourceList JSON 或 TVBOX 配置 JSON,由服务端自动识别),+ * 一次拉取点播源与直播源,可随时重新同步;* - 分享:把当前点播源 + 直播源导出为同格式 JSON 文件,托管到任意位置即可被他人订阅。*/function SourceSubscriptions() {@@ -419,8 +421,11 @@ function SourceSubscriptions() {const sync = async (url: string) => {setSyncing(url);try {- const { vodCount, liveCount } = await syncSourceSubscription(url);- toast(`已同步 ${vodCount} 个点播源、${liveCount} 个直播源`, 'success');+ const { vodCount, liveCount, stats } = await syncSourceSubscription(url);+ // 如实说明跳过/截断情况,避免用户疑惑「配置里站点很多,为何只导入了个位数」+ const detail = describeParseStats(stats, { includeSamples: false });+ const formatLabel = stats?.format === 'tvbox' ? '(TVBOX 配置)' : '';+ toast(`已同步 ${vodCount} 个点播源、${liveCount} 个直播源${formatLabel}${detail ? `;${detail}` : ''}`, 'success');setSubUrl('');} catch (err) {toast(err instanceof Error ? err.message : '订阅同步失败', 'error');@@ -491,7 +496,7 @@ function SourceSubscriptions() {<div className="flex gap-2 mb-2"><inputclassName="input w-full"- placeholder="订阅地址(LibreTV-SourceList JSON 的 URL)"+ placeholder="订阅地址(LibreTV 源列表或 TVBOX 配置的 JSON URL)"value={subUrl}onChange={(e) => setSubUrl(e.target.value)}onKeyDown={(e) => {@@ -499,18 +504,19 @@ function SourceSubscriptions() {}}/><button className="btn-primary !py-1.5 text-xs shrink-0" disabled={!subUrl.trim() || syncing !== null} onClick={addAndSync}>- 订阅+ {syncing !== null ? '同步中…' : '订阅'}</button></div>{store.subscriptions.length === 0 ? (<p className="text-xs text-faint">- 一份订阅可同时下发点播源与直播源;「导出数据源」生成的 JSON 托管到任意 URL 即可分享给他人订阅。+ 一份订阅可同时下发点播源与直播源,支持 LibreTV 源列表与 TVBOX 配置(仅导入可直接使用的接口,Spider 类站点自动跳过);+ 「导出数据源」生成的 JSON 托管到任意 URL 即可分享给他人订阅。</p>) : (<ul className="space-y-2 max-h-[30vh] overflow-y-auto scrollbar-thin pr-1">{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;+ const vodCount = store.customAPIs.filter((a) => keyBelongsToSubscription(a.key, subKeyPrefix(sub.url))).length;+ const liveCount = store.liveSubscriptions.filter((s) => s.fromSubscriptions.includes(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">@@ -527,7 +533,8 @@ function SourceSubscriptions() {</div><buttonclassName="rounded-md p-1.5 shrink-0 text-muted transition-colors hover:bg-hover hover:text-accent disabled:opacity-40"- disabled={syncing === sub.url}+ // 同一时刻只允许一个同步在跑:syncing 是单值状态,并发会让先完成的提前解锁按钮+ disabled={syncing !== null}onClick={() => sync(sub.url)}aria-label="重新同步"title="重新同步(以远端列表为准,整体替换该订阅名下的点播源与直播源)"diff --git a/src/lib/client-api.ts b/src/lib/client-api.tsindex aaa59de..37ec985 100644--- a/src/lib/client-api.ts+++ b/src/lib/client-api.ts@@ -142,7 +142,7 @@ export const api = {body: JSON.stringify({ url }),}),- /** 拉取远程数据源订阅(LibreTV-SourceList JSON:点播源 sources + 直播源 liveSources) */+ /** 拉取远程数据源订阅(自动识别 LibreTV-SourceList JSON 与 TVBOX 配置 JSON) */fetchSourceList: (url: string) => {const sp = new URLSearchParams({ url });return request<SourceListPayload>(`/api/source-list?${sp.toString()}`);diff --git a/src/lib/source-list.test.ts b/src/lib/source-list.test.tsindex 5f1fb6e..a549122 100644--- a/src/lib/source-list.test.ts+++ b/src/lib/source-list.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { MAX_LIVE_SOURCES, MAX_VOD_SOURCES, parseSourceListPayload } from './source-list';+import { MAX_LIVE_SOURCES, MAX_VOD_SOURCES, normalizeSubscriptionUrl, 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 });@@ -137,3 +137,11 @@ describe('parseSourceListPayload', () => {expect(() => parseSourceListPayload(null)).toThrow(/格式不正确/);});});++describe('normalizeSubscriptionUrl', () => {+ it('trim 并去掉尾部斜杠,避免同一地址被存成两条订阅', () => {+ expect(normalizeSubscriptionUrl(' https://a.example.com/list.json/ ')).toBe('https://a.example.com/list.json');+ expect(normalizeSubscriptionUrl('https://a.example.com/list.json///')).toBe('https://a.example.com/list.json');+ expect(normalizeSubscriptionUrl('https://a.example.com/list.json')).toBe('https://a.example.com/list.json');+ });+});diff --git a/src/lib/source-list.ts b/src/lib/source-list.tsindex fd3ba45..ebf5cca 100644--- a/src/lib/source-list.ts+++ b/src/lib/source-list.ts@@ -13,6 +13,15 @@ import type { SourceListPayload } from './types';export const MAX_VOD_SOURCES = 100;export const MAX_LIVE_SOURCES = 50;+/**+ * 订阅地址统一形态:trim 并去掉尾部斜杠。+ * 手动输入与预置订阅(DEFAULT_SUBSCRIPTIONS)都必须走这一步——+ * 否则同一地址带不带尾斜杠会被存成两条订阅(不同 key 前缀、重复同步、重复拉取)。+ */+export function normalizeSubscriptionUrl(raw: string): string {+ return raw.trim().replace(/\/+$/, '');+}+interface RawItem {name?: unknown;url?: unknown;@@ -21,8 +30,11 @@ interface RawItem {epg?: unknown;}-/** 规范化为 http(s) 地址;trimV2 控制是否去掉尾部斜杠(点播去、直播保留) */-function normalizeUrl(raw: unknown, trimTrailingSlash: boolean): string | undefined {+/**+ * 规范化为 http(s) 地址;trimTrailingSlash 控制是否去掉尾部斜杠(点播去、直播保留)。+ * 导出供 tvbox-parser 复用,保证两种订阅格式的归一化规则完全一致。+ */+export function normalizeUrl(raw: unknown, trimTrailingSlash: boolean): string | undefined {if (typeof raw !== 'string') return undefined;const trimmed = raw.trim();if (!trimmed) return undefined;@@ -35,11 +47,11 @@ function normalizeUrl(raw: unknown, trimTrailingSlash: boolean): string | undefireturn trimTrailingSlash ? trimmed.replace(/\/+$/, '') : trimmed;}-function optionalString(raw: unknown): string | undefined {+export function optionalString(raw: unknown): string | undefined {return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined;}-function hostnameOf(url: string): string {+export function hostnameOf(url: string): string {try {return new URL(url).hostname;} catch {diff --git a/src/lib/store.test.ts b/src/lib/store.test.tsnew file mode 100644index 0000000..7782ef8--- /dev/null+++ b/src/lib/store.test.ts@@ -0,0 +1,185 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++// store.ts 运行时引用 db.ts(IndexedDB),node 测试环境下 mock 掉+vi.mock('./db', () => ({+ db: {},+ clearLiveProbeResultsDb: vi.fn(async () => {}),+ loadLiveProbeResults: vi.fn(async () => ({})),+ saveLiveProbeResults: vi.fn(async () => {}),+}));++import { keyBelongsToSubscription, subKeyPrefix, useAppStore } from './store';+import type { SourceConfig } from './types';++const store = () => useAppStore.getState();++const list = (urls: string[]): Omit<SourceConfig, 'key'>[] => urls.map((url) => ({ name: url, url }));++beforeEach(() => {+ useAppStore.setState({+ customAPIs: [],+ selectedKeys: [],+ subscriptions: [],+ liveSubscriptions: [],+ liveSelectedUrls: [],+ liveFavorites: [],+ liveRecent: [],+ yellowFilter: false,+ });+});++describe('subKeyPrefix / keyBelongsToSubscription', () => {+ it('key 完整形态为 `${prefix}_${i}`,归属判断要求前缀后紧跟分隔符', () => {+ const prefix = subKeyPrefix('https://sub.example.com/list.json');+ expect(prefix.startsWith('sub_')).toBe(true);+ expect(keyBelongsToSubscription(`${prefix}_0`, prefix)).toBe(true);+ expect(keyBelongsToSubscription(prefix, prefix)).toBe(true);+ expect(keyBelongsToSubscription('manual_0', prefix)).toBe(false);+ });++ it('真实碰撞构造:hash 互为前缀的两个订阅互不误伤', () => {+ // hash 部分是 sub_ 之后的 36 进制串+ const hashOf = (url: string) => subKeyPrefix(url).slice(4);++ // 找一个 hash36 为 6 位的基准 URL+ let base = '';+ for (let i = 0; i < 10000 && !base; i++) {+ const p = hashOf(`https://base${i}.example.com/list.json`);+ if (p.length === 6) base = p;+ }+ expect(base).not.toBe('');++ // 暴力搜索一个 hash36 以 base 为前缀的 URL(djb2 32bit,7 位 hash 的前 6 位命中率约 1/36)+ let colliding: string | null = null;+ for (let i = 0; i < 200000 && !colliding; i++) {+ const p = hashOf(`https://collide${i}.example.com/list.json`);+ if (p !== base && p.startsWith(base)) colliding = `https://collide${i}.example.com/list.json`;+ }+ // 找不到说明碰撞概率假设不成立,测试失去意义但也证明当前集合内无碰撞+ if (!colliding) return;++ const collidingPrefix = subKeyPrefix(colliding);+ expect(collidingPrefix.startsWith(base)).toBe(true);+ // 修复前 startsWith(prefix) 会把碰撞订阅的源误判为 base 订阅所有+ expect(keyBelongsToSubscription(`${collidingPrefix}_0`, base)).toBe(false);+ expect(keyBelongsToSubscription(`${base}_0`, base)).toBe(true);+ });+});++describe('订阅同步的 store 语义', () => {+ it('同步导入点播源并自动勾选;再次同步整体替换', () => {+ const url = 'https://a.example.com/list.json';+ expect(store().applySubscriptionSources(url, list(['https://x/api.php/provide/vod', 'https://y/api.php/provide/vod']))).toBe(2);+ expect(store().customAPIs).toHaveLength(2);+ expect(store().selectedKeys).toHaveLength(2);++ expect(store().applySubscriptionSources(url, list(['https://x/api.php/provide/vod', 'https://z/api.php/provide/vod']))).toBe(2);+ expect(store().customAPIs.map((a) => a.url)).toEqual(['https://x/api.php/provide/vod', 'https://z/api.php/provide/vod']);+ });++ it('用户取消勾选后,重新同步不会被反复勾回', () => {+ const url = 'https://a.example.com/list.json';+ store().applySubscriptionSources(url, list(['https://x/api.php/provide/vod']));+ store().toggleSourceSelected(store().customAPIs[0].key);+ expect(store().selectedKeys).toHaveLength(0);++ // 同步后 key 按序号重生成,勾选状态需按 url 对齐保留+ store().applySubscriptionSources(url, list(['https://x/api.php/provide/vod']));+ expect(store().customAPIs).toHaveLength(1);+ expect(store().selectedKeys).toHaveLength(0);+ });++ it('与订阅同 URL 的手动源视为重复,同步后不保留双份', () => {+ useAppStore.setState({+ customAPIs: [{ key: 'manual_0', name: '手动源', url: 'https://x/api.php/provide/vod' }],+ selectedKeys: ['manual_0'],+ });++ store().applySubscriptionSources('https://a.example.com/list.json', list(['https://x/api.php/provide/vod']));++ expect(store().customAPIs).toHaveLength(1);+ expect(store().customAPIs[0].key.startsWith('sub_')).toBe(true);+ });++ it('直播源:新导入自动启用、停用不勾回、消失的源清理启用状态但保留收藏', () => {+ const url = 'https://a.example.com/list.json';+ const m1 = 'https://live.example.com/1.m3u';+ const m2 = 'https://live.example.com/2.m3u';++ store().applySubscriptionLive(url, [+ { name: 'm1', url: m1 },+ { name: 'm2', url: m2 },+ ]);+ expect(store().liveSelectedUrls).toContain(m1);+ expect(store().liveSelectedUrls).toContain(m2);++ // 用户收藏 m2、并主动停用 m2+ useAppStore.setState({ liveFavorites: [m2] });+ store().toggleLiveSelected(m2);++ // 远端列表只剩 m2:m1 随消失清理启用状态;m2 维持用户的停用状态+ store().applySubscriptionLive(url, [{ name: 'm2', url: m2 }]);+ expect(store().liveSelectedUrls).not.toContain(m1);+ expect(store().liveSelectedUrls).not.toContain(m2);+ expect(store().liveFavorites).toContain(m2);+ });++ it('删除订阅:清点播/勾选/直播/启用状态,保留收藏的频道', () => {+ const url = 'https://a.example.com/list.json';+ const m1 = 'https://live.example.com/1.m3u';+ store().applySubscriptionSources(url, list(['https://x/api.php/provide/vod']));+ store().applySubscriptionLive(url, [{ name: 'm1', url: m1 }]);+ useAppStore.setState({ liveFavorites: [m1] });+ store().addSubscription(url, 'A');+ expect(store().subscriptions).toHaveLength(1);++ store().removeSubscription(url);+ expect(store().subscriptions).toHaveLength(0);+ expect(store().customAPIs).toHaveLength(0);+ expect(store().selectedKeys).toHaveLength(0);+ expect(store().liveSubscriptions).toHaveLength(0);+ expect(store().liveSelectedUrls).toHaveLength(0);+ expect(store().liveFavorites).toContain(m1);+ });++ it('同一 M3U 被两个订阅引用时共享归属,不重复导入,名称以首次导入为准', () => {+ const m1 = 'https://live.example.com/1.m3u';+ expect(store().applySubscriptionLive('https://a.example.com/list.json', [{ name: 'm1', url: m1 }])).toBe(1);+ // 第二个订阅也计入自己的引用(计数不再失真)+ expect(store().applySubscriptionLive('https://b.example.com/list.json', [{ name: 'm1 改名', url: m1 }])).toBe(1);+ expect(store().liveSubscriptions).toHaveLength(1);+ expect(store().liveSubscriptions[0].fromSubscriptions).toEqual([+ 'https://a.example.com/list.json',+ 'https://b.example.com/list.json',+ ]);+ expect(store().liveSubscriptions[0].name).toBe('m1');+ });++ it('手动添加的直播源不被订阅接管', () => {+ const m1 = 'https://live.example.com/1.m3u';+ store().addLiveSubscription(m1, '手动');+ expect(store().applySubscriptionLive('https://a.example.com/list.json', [{ name: '订阅名', url: m1 }])).toBe(0);+ expect(store().liveSubscriptions).toHaveLength(1);+ expect(store().liveSubscriptions[0].name).toBe('手动');+ expect(store().liveSubscriptions[0].fromSubscriptions).toEqual([]);+ });++ it('删除订阅:共享的直播源保留给其他订阅,独占的才移除', () => {+ const shared = 'https://live.example.com/shared.m3u';+ const exclusive = 'https://live.example.com/exclusive.m3u';+ store().applySubscriptionLive('https://a.example.com/list.json', [+ { name: '共享', url: shared },+ { name: '独占', url: exclusive },+ ]);+ store().applySubscriptionLive('https://b.example.com/list.json', [{ name: '共享', url: shared }]);+ useAppStore.setState({ liveSelectedUrls: [shared, exclusive], liveFavorites: [exclusive] });++ store().removeSubscription('https://a.example.com/list.json');+ // 共享源保留(归属只剩 B),独占源随订阅移除;启用状态相应清理,收藏保留+ expect(store().liveSubscriptions).toHaveLength(1);+ expect(store().liveSubscriptions[0].url).toBe(shared);+ expect(store().liveSubscriptions[0].fromSubscriptions).toEqual(['https://b.example.com/list.json']);+ expect(store().liveSelectedUrls).toEqual([shared]);+ expect(store().liveFavorites).toContain(exclusive);+ });+});diff --git a/src/lib/store.ts b/src/lib/store.tsindex 1d259ac..6662c76 100644--- a/src/lib/store.ts+++ b/src/lib/store.ts@@ -24,8 +24,8 @@ export interface AppSettings {}/**- * 数据源订阅:远程源列表(LibreTV-SourceList JSON),可一键同步更新。- * 一份订阅同时下发点播源与直播源;老订阅只有点播源。+ * 数据源订阅:远程源列表(LibreTV-SourceList JSON 或 TVBOX 配置 JSON,由服务端自动识别),可一键同步更新。+ * 一份订阅同时下发点播源与直播源;老订阅只有点播源。订阅内容一律归一化为本站源结构,故存储层与格式无关。*/export interface SourceSubscription {url: string;@@ -44,10 +44,12 @@ export interface LiveSubscription {/** 上次同步成功时间 */lastSync?: number;/**- * 该直播源来自哪个订阅 URL;手动添加时为空。- * 删除订阅时按此归属精确清理,避免误删用户手动添加的源。+ * 引用该直播源的订阅 URL 列表(多归属:同一 M3U 可被多个订阅共享引用)。+ * 空数组表示用户手动添加的源;删除某个订阅时只移除自己的归属,+ * 只要列表非空该源就保留。名称/EPG 以首次导入为准,缺失时由后续同步补齐,+ * 避免多个订阅互相覆盖。*/- fromSubscription?: string;+ fromSubscriptions: string[];}/** 直播最近观看条目(上限 20 条,按 url 去重) */@@ -83,13 +85,23 @@ export interface LiveProbeEntry {timestamp: number;}-/** 订阅导入的源 key 前缀:sub_<hash8(url)>_<i>,同步时按前缀整体替换 */+/** 订阅导入的源 key 前缀:sub_<hash36(url)>,实际 key 为 `${prefix}_${i}`,同步时按前缀整体替换 */export function subKeyPrefix(url: string): string {let h = 5381;for (let i = 0; i < url.length; i++) h = ((h << 5) + h + url.charCodeAt(i)) >>> 0;return `sub_${h.toString(36)}`;}+/**+ * 判断源 key 是否属于指定订阅。+ * 不能直接 startsWith(prefix):两个不同订阅的 hash36 可能恰好互为前缀+ * (如 sub_1a 与 sub_1a2b),此时会误删/误替换另一个订阅的源。+ * key 的完整形态是 `${prefix}_${i}`,因此要求前缀后紧跟分隔符。+ */+export function keyBelongsToSubscription(key: string, prefix: string): boolean {+ return key === prefix || key.startsWith(`${prefix}_`);+}+/** 点播源自动停用阈值:连续失败/超时达到该次数即临时摘除 */export const SOURCE_DISABLE_THRESHOLD = 2;/** 点播源自动停用时长:到期后自动恢复参与搜索 */@@ -274,18 +286,25 @@ 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)- );+ // 多归属:删除订阅只移除自己的引用;仍被其他订阅共享的直播源保留,+ // 仅当没有任何订阅再引用时才移除条目(连同启用状态与最近观看,收藏始终保留)+ const removedLive = get().liveSubscriptions+ .filter((s) => s.fromSubscriptions.includes(url))+ .map((s) => {+ const rest = s.fromSubscriptions.filter((u) => u !== url);+ return { entry: s, orphan: rest.length === 0, rest };+ });+ const orphanUrls = new Set(removedLive.filter((r) => r.orphan).map((r) => r.entry.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)),+ customAPIs: get().customAPIs.filter((a) => !keyBelongsToSubscription(a.key, prefix)),+ selectedKeys: get().selectedKeys.filter((k) => !keyBelongsToSubscription(k, prefix)),+ liveSubscriptions: removedLive+ .filter((r) => !r.orphan)+ .map((r) => ({ ...r.entry, fromSubscriptions: r.rest })),+ liveSelectedUrls: get().liveSelectedUrls.filter((u) => !orphanUrls.has(u)),// 收藏的频道是用户主动留下的,删除订阅时保留;其余残留状态一并清理- liveRecent: get().liveRecent.filter((r) => !r.sourceUrl || !ownedLive.has(r.sourceUrl)),+ liveRecent: get().liveRecent.filter((r) => !r.sourceUrl || !orphanUrls.has(r.sourceUrl)),});},@@ -302,9 +321,9 @@ export const useAppStore = create<AppState>()(// 与订阅源 URL 相同的手动添加源视为重复,避免同步后出现双份const subUrls = new Set(list.map((s) => s.url.replace(/\/+$/, '')));const keptCustom = get().customAPIs.filter(- (a) => !a.key.startsWith(prefix) && !subUrls.has(a.url.replace(/\/+$/, ''))+ (a) => !keyBelongsToSubscription(a.key, prefix) && !subUrls.has(a.url.replace(/\/+$/, '')));- const prevOwned = get().customAPIs.filter((a) => a.key.startsWith(prefix));+ const prevOwned = get().customAPIs.filter((a) => keyBelongsToSubscription(a.key, prefix));// key 按序号重生成,勾选状态需按 url 对齐保留;用户停用的源不会被同步反复勾回const prevSelectedUrls = new Set(prevOwned@@ -325,39 +344,55 @@ export const useAppStore = create<AppState>()(.map((s) => s.key);set({customAPIs: [...keptCustom, ...incoming],- selectedKeys: [...get().selectedKeys.filter((k) => !k.startsWith(prefix)), ...toSelect],+ selectedKeys: [...get().selectedKeys.filter((k) => !keyBelongsToSubscription(k, prefix)), ...toSelect],});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)));- // 仅新导入的源自动启用;已有源维持用户的勾选状态(停用不会被同步反复勾回),- // 因此只从勾选中移除本次已消失的源- const freshUrls = incoming.filter((s) => !ownedUrls.has(s.url)).map((s) => s.url);+ const byUrl = new Map(existing.map((s) => [s.url, s]));+ const nextByUrl = new Map<string, LiveSubscription>();+ const orphanUrls = new Set<string>();++ // 多归属:同一 M3U 可被多个订阅共享引用,仅追加归属而不重复导入条目;+ // 手动添加的源(无订阅归属)由用户完全掌控,订阅不接管。+ // 名称/EPG 以首次导入为准,缺失字段由后续同步补齐,避免多个订阅互相覆盖。+ for (const s of list) {+ const current = byUrl.get(s.url);+ if (!current) {+ nextByUrl.set(s.url, { url: s.url, name: s.name, epg: s.epg, fromSubscriptions: [subUrl] });+ } else if (current.fromSubscriptions.length === 0 || current.fromSubscriptions.includes(subUrl)) {+ nextByUrl.set(s.url, current);+ } else {+ nextByUrl.set(s.url, { ...current, fromSubscriptions: [...current.fromSubscriptions, subUrl] });+ }+ }+ // 不在本次列表中的条目原样保留;仅当被本订阅唯一持有且本次消失时才移除+ for (const s of existing) {+ if (nextByUrl.has(s.url)) continue;+ if (s.fromSubscriptions.includes(subUrl) && s.fromSubscriptions.length === 1) {+ orphanUrls.add(s.url);+ } else {+ nextByUrl.set(s.url, s);+ }+ }++ // 仅首次出现的源自动启用;已存在的维持用户勾选(停用不会被同步反复勾回)+ const freshUrls = [...nextByUrl.values()].filter((s) => !byUrl.has(s.url)).map((s) => s.url);set({- liveSubscriptions: [...kept, ...incoming],+ liveSubscriptions: [...nextByUrl.values()],liveSelectedUrls: [...new Set([- ...get().liveSelectedUrls.filter((u) => !droppedUrls.has(u)),+ ...get().liveSelectedUrls.filter((u) => !orphanUrls.has(u)),...freshUrls,]),],- liveRecent: get().liveRecent.filter((r) => !r.sourceUrl || !droppedUrls.has(r.sourceUrl)),+ liveRecent: get().liveRecent.filter((r) => !r.sourceUrl || !orphanUrls.has(r.sourceUrl)),});- return incoming.length;+ // 返回本订阅实际持有的引用数(与订阅条目的「直播 N」计数口径一致)+ return [...nextByUrl.values()].filter((s) => s.fromSubscriptions.includes(subUrl)).length;},setLiveEnvSources: (list) => {@@ -375,7 +410,11 @@ export const useAppStore = create<AppState>()(const trimmed = url.trim();if (!trimmed || get().liveSubscriptions.some((s) => s.url === trimmed)) return;set({- liveSubscriptions: [...get().liveSubscriptions, { url: trimmed, name, epg }],+ // 手动添加的源无订阅归属(fromSubscriptions 为空),订阅同步不会接管+ liveSubscriptions: [+ ...get().liveSubscriptions,+ { url: trimmed, name, epg, fromSubscriptions: [] },+ ],// 新添加的订阅默认启用liveSelectedUrls: [...new Set([...get().liveSelectedUrls, trimmed])],});@@ -401,7 +440,8 @@ export const useAppStore = create<AppState>()(set({liveSubscriptions: get().liveSubscriptions.map((s) =>s.url === url- ? { ...s, lastSync: Date.now(), name: name ?? s.name, epg: epg ?? s.epg }+ ? // 共享源可能被多个订阅先后同步:名称/EPG 以首次导入为准,仅缺失时补齐+ { ...s, lastSync: Date.now(), name: s.name ?? name, epg: s.epg ?? epg }: s),});@@ -511,17 +551,31 @@ export const useAppStore = create<AppState>()(}),{name: 'libretv-settings',- // v1:直播源新增 fromSubscription 归属字段、最近观看新增 sourceUrl。- // 此前未声明 version,存量数据会被视为 v0 并走 migrate 补齐(缺失字段按「手动添加」处理)。- version: 1,+ // v1:直播源新增归属字段、最近观看新增 sourceUrl。+ // v2:直播源归属改为多引用(fromSubscription 单值 → fromSubscriptions 数组)。+ // 此前未声明 version 的存量数据会被视为 v0 并走 migrate 补齐。+ version: 2,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;+ const state = { ...((persisted ?? {}) as Partial<AppState>) };+ if (!Array.isArray(state.liveRecent)) state.liveRecent = [];+ if (!Array.isArray(state.liveSubscriptions)) state.liveSubscriptions = [];+ if (version < 2) {+ state.liveSubscriptions = state.liveSubscriptions.map((s) => {+ const legacy = s as LiveSubscription & { fromSubscription?: unknown };+ const fromSubscriptions = Array.isArray(legacy.fromSubscriptions)+ ? legacy.fromSubscriptions+ : typeof legacy.fromSubscription === 'string' && legacy.fromSubscription+ ? [legacy.fromSubscription]+ : [];+ // 显式构造以剔除旧的单值字段,避免新旧字段并存+ return {+ url: legacy.url,+ name: legacy.name,+ epg: legacy.epg,+ lastSync: legacy.lastSync,+ fromSubscriptions,+ };+ });}return state as AppState;},diff --git a/src/lib/subscription-sync.ts b/src/lib/subscription-sync.tsindex afa4e74..ca74907 100644--- a/src/lib/subscription-sync.ts+++ b/src/lib/subscription-sync.ts@@ -1,13 +1,17 @@'use client';import { api } from './client-api';+import { normalizeSubscriptionUrl } from './source-list';import { useAppStore } from './store';+import { describeParseStats } from './tvbox-parser';+import type { SubscriptionParseStats } from './types';/**- * SourceList 订阅同步核心逻辑,供两处复用:+ * 数据源订阅同步核心逻辑,供两处复用:* - source-manager:用户在设置抽屉中手动添加/重新同步(UI 层加 toast 反馈);* - providers:部署者通过 DEFAULT_SUBSCRIPTIONS 预置的订阅,启动时自动导入与静默重同步。*+ * 订阅内容由服务端自动识别格式(LibreTV-SourceList JSON 或 TVBOX 配置 JSON),* applySubscriptionSources / applySubscriptionLive 均按订阅前缀整体替换且保留* 用户勾选状态,同步失败时不调用即无副作用——旧数据自动保留。*/@@ -15,21 +19,26 @@ export interface SubscriptionSyncResult {name?: string;vodCount: number;liveCount: number;+ /** 解析统计(识别格式、跳过与截断条目),用于导入结果提示 */+ stats?: SubscriptionParseStats;}-export async function syncSourceSubscription(url: string): Promise<SubscriptionSyncResult> {- const { name, sources, liveSources } = await api.fetchSourceList(url);+export async function syncSourceSubscription(rawUrl: string): Promise<SubscriptionSyncResult> {+ // 统一归一化(trim + 去尾斜杠):与 DEFAULT_SUBSCRIPTIONS 预置地址保持同一形态,+ // 避免同一订阅地址因尾斜杠差异被存成两条订阅+ const url = normalizeSubscriptionUrl(rawUrl);+ const { name, sources, liveSources, stats } = 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 不得被本订阅覆盖+ // 仅对本订阅引用的直播源记录同步时间(多归属:共享源也会被标记为新鲜,+ // 但名称/EPG 由 store 的「首次导入为准、缺失补齐」语义保护,不会被本订阅覆盖)const importedLiveUrls = new Set(useAppStore.getState().liveSubscriptions- .filter((s) => s.fromSubscription === url)+ .filter((s) => s.fromSubscriptions.includes(url)).map((s) => s.url));for (const s of liveSources) {@@ -37,7 +46,7 @@ export async function syncSourceSubscription(url: string): Promise<SubscriptionS}store.addSubscription(url, name);store.markSubscriptionSynced(url, name);- return { name, vodCount, liveCount };+ return { name, vodCount, liveCount, stats };}/** 预置订阅超过该间隔未同步时,启动阶段静默刷新一次 */@@ -56,16 +65,21 @@ export async function syncEnvSubscriptions(subs: { url: string; name?: string }[const store = useAppStore.getState();try {const existing = store.subscriptions.find((s) => s.url === sub.url);+ let result: SubscriptionSyncResult | undefined;if (existing) {if (existing.lastSync && Date.now() - existing.lastSync < ENV_SUB_RESYNC_MS) {store.markEnvSubsSeen([sub.url]);continue;}- await syncSourceSubscription(sub.url);+ result = await syncSourceSubscription(sub.url);} else {// 已成功过且被用户删除的预置订阅:尊重用户选择,不再加回if (store.envSubsSeen.includes(sub.url)) continue;- await syncSourceSubscription(sub.url);+ result = await syncSourceSubscription(sub.url);+ }+ // 预置订阅对用户是静默的,跳过/截断情况写入控制台供部署者排查(只记计数,不打印配置内容)+ if (result?.stats && result.stats.skipped > 0) {+ console.info('[LibreTV] 预置订阅部分条目未导入:', sub.url, describeParseStats(result.stats));}useAppStore.getState().markEnvSubsSeen([sub.url]);} catch (err) {diff --git a/src/lib/tvbox-parser.test.ts b/src/lib/tvbox-parser.test.tsnew file mode 100644index 0000000..a09250f--- /dev/null+++ b/src/lib/tvbox-parser.test.ts@@ -0,0 +1,275 @@+import { describe, expect, it } from 'vitest';+import { MAX_LIVE_SOURCES, MAX_VOD_SOURCES } from './source-list';+import {+ describeParseStats,+ isTvboxPayload,+ parseSubscriptionJson,+ parseSubscriptionPayload,+ parseTvboxPayload,+ withSkipped,+} from './tvbox-parser';++const vodSite = (url: string, extra: Record<string, unknown> = {}) => ({+ name: `站点 ${url}`,+ type: 1,+ api: url,+ ...extra,+});++describe('isTvboxPayload', () => {+ it('顶层含 sites / lives 数组即判定为 TVBOX 配置', () => {+ expect(isTvboxPayload({ sites: [], lives: [] })).toBe(true);+ expect(isTvboxPayload({ sites: [{ key: 'a' }] })).toBe(true);+ expect(isTvboxPayload({ lives: [] })).toBe(true);+ });++ it('LibreTV 订阅与非法输入不误判', () => {+ expect(isTvboxPayload({ sources: [], liveSources: [] })).toBe(false);+ expect(isTvboxPayload([{ url: 'https://a.example.com/vod' }])).toBe(false);+ expect(isTvboxPayload(null)).toBe(false);+ expect(isTvboxPayload('text')).toBe(false);+ });+});++describe('parseTvboxPayload', () => {+ it('导入 type=1 点播源与 type=0 直播源(含 EPG)', () => {+ const result = parseTvboxPayload({+ sites: [vodSite('https://vod.example.com/api.php/provide/vod')],+ lives: [+ { name: '直播A', type: 0, url: 'https://live.example.com/list.m3u' },+ {+ name: '直播B',+ type: 0,+ url: 'https://live.example.com/tv.m3u8',+ epg: 'https://live.example.com/epg.xml.gz',+ },+ ],+ });++ expect(result.sources).toEqual([+ { name: '站点 https://vod.example.com/api.php/provide/vod', url: 'https://vod.example.com/api.php/provide/vod' },+ ]);+ expect(result.liveSources).toEqual([+ { name: '直播A', url: 'https://live.example.com/list.m3u', epg: undefined },+ { name: '直播B', url: 'https://live.example.com/tv.m3u8', epg: 'https://live.example.com/epg.xml.gz' },+ ]);+ expect(result.stats).toMatchObject({ format: 'tvbox', skipped: 0, truncated: 0 });+ });++ it('类型缺失或写成 XML,但地址命中 Apple CMS 特征时宽容导入', () => {+ const result = parseTvboxPayload({+ sites: [+ { name: '省略类型', api: 'https://a.example.com/api.php/provide/vod' },+ { name: 'XML 类型', type: 0, api: 'https://b.example.com/api.php/provide/vod/' },+ ],+ });++ expect(result.sources.map((s) => s.url)).toEqual([+ 'https://a.example.com/api.php/provide/vod',+ // 点播地址沿用「去尾部斜杠」的既有归一化规则+ 'https://b.example.com/api.php/provide/vod',+ ]);+ expect(result.stats?.skipped).toBe(0);+ });++ it('Spider、本地资源、XML 与非 CMS 外链站点跳过并分类计数', () => {+ const result = parseTvboxPayload({+ sites: [+ { name: '正版源', type: 1, api: 'https://ok.example.com/api.php/provide/vod' },+ { name: '蜘蛛A', type: 3, api: 'csp_AppYs' },+ { name: '蜘蛛B', api: 'https://cdn.example.com/spider.jar' },+ { name: '本地JS', type: 1, api: './json/heimuer.js' },+ { name: 'XML站', type: 0, api: 'https://xml.example.com/api.php/provide/vod/at/xml' },+ { name: '外链站', type: 4, api: 'https://api.example.com/v1/list' },+ ],+ });++ expect(result.sources.map((s) => s.name)).toEqual(['正版源']);+ expect(result.stats?.skipped).toBe(5);+ expect(result.stats?.skippedByReason).toEqual({ spider: 4, xml: 1 });+ expect(result.stats?.skippedSamples).toEqual(['蜘蛛A', '蜘蛛B', '本地JS']);+ });++ it('声明不可搜索的站点跳过', () => {+ const result = parseTvboxPayload({+ sites: [+ vodSite('https://a.example.com/api.php/provide/vod'),+ vodSite('https://b.example.com/api.php/provide/vod', { searchable: 0 }),+ ],+ });++ expect(result.sources).toHaveLength(1);+ expect(result.stats?.skippedByReason).toEqual({ unsearchable: 1 });+ });++ it('直播:单仓 JSON 与 txt 频道列表跳过,非 M3U 地址计入 invalidUrl', () => {+ const result = parseTvboxPayload({+ sites: [vodSite('https://a.example.com/api.php/provide/vod')],+ lives: [+ { name: '直播A', type: 0, url: 'https://live.example.com/list.m3u' },+ { name: '单仓', type: 1, url: 'https://live.example.com/all.json' },+ { name: 'txt列表', type: 0, url: 'https://live.example.com/tv.txt' },+ { name: '坏地址', type: 0, url: 'ftp://live.example.com/list.m3u' },+ ],+ });++ expect(result.liveSources.map((s) => s.name)).toEqual(['直播A']);+ expect(result.stats?.skipped).toBe(3);+ expect(result.stats?.skippedByReason).toEqual({ nonM3uLive: 2, invalidUrl: 1 });+ });++ it('按地址去重(点播去尾部斜杠后比较,直播保留原样)', () => {+ const result = parseTvboxPayload({+ sites: [+ vodSite('https://a.example.com/api.php/provide/vod'),+ vodSite('https://a.example.com/api.php/provide/vod/'),+ ],+ lives: [+ { name: 'A', type: 0, url: 'https://live.example.com/list.m3u' },+ { name: 'A 重复', type: 0, url: 'https://live.example.com/list.m3u' },+ ],+ });++ expect(result.sources).toHaveLength(1);+ expect(result.liveSources).toHaveLength(1);+ // 重复条目静默跳过,不计入跳过统计+ expect(result.stats?.skipped).toBe(0);+ });++ it('超出上限时截断并计入 truncated(去重后计数)', () => {+ const sites = [+ ...Array.from({ length: 10 }, () => vodSite('https://dup.example.com/api.php/provide/vod')),+ ...Array.from({ length: MAX_VOD_SOURCES + 5 }, (_, i) => vodSite(`https://vod${i}.example.com/api.php/provide/vod`)),+ ];+ const lives = Array.from({ length: MAX_LIVE_SOURCES + 3 }, (_, i) => ({+ name: `直播${i}`,+ type: 0,+ url: `https://live${i}.example.com/list.m3u`,+ }));++ const result = parseTvboxPayload({ sites, lives });++ expect(result.sources).toHaveLength(MAX_VOD_SOURCES);+ expect(result.liveSources).toHaveLength(MAX_LIVE_SOURCES);+ // 前段重复只占 1 个名额:1 + 99 达到上限,余下 6 个点播与 3 个直播被截断+ expect(result.stats?.truncated).toBe(9);+ });++ it('全部不可导入时抛错并带原因计数', () => {+ expect(() =>+ parseTvboxPayload({ sites: [{ name: '蜘蛛A', type: 3, api: 'csp_AppYs' }] })+ ).toThrow(/已跳过 1 个条目(Spider 引擎 1)/);+ });++ it('sites / lives 均为空时提示无可用站点', () => {+ expect(() => parseTvboxPayload({ sites: [], lives: [] })).toThrow(/没有可用的站点/);+ expect(() => parseTvboxPayload({})).toThrow(/没有可用的站点/);+ });++ it('TVBOX 顶层 name 作为订阅名透传', () => {+ const result = parseTvboxPayload({+ name: '某大佬的接口',+ sites: [vodSite('https://a.example.com/api.php/provide/vod')],+ });+ expect(result.name).toBe('某大佬的接口');+ });+});++describe('parseSubscriptionPayload', () => {+ it('TVBOX 配置走 TVBOX 分支', () => {+ const result = parseSubscriptionPayload({+ sites: [{ name: '正版源', type: 1, api: 'https://a.example.com/api.php/provide/vod' }],+ lives: [{ name: '直播', type: 0, url: 'https://live.example.com/list.m3u' }],+ });++ expect(result.stats?.format).toBe('tvbox');+ expect(result.sources).toHaveLength(1);+ expect(result.liveSources).toHaveLength(1);+ });++ it('LibreTV 订阅仍按原逻辑解析并带默认统计', () => {+ const result = parseSubscriptionPayload({+ name: '我的源列表',+ sources: [{ name: '点播', url: 'https://a.example.com/api.php/provide/vod' }],+ liveSources: [{ name: '直播', url: 'https://live.example.com/list.m3u' }],+ });++ expect(result.name).toBe('我的源列表');+ expect(result.sources).toHaveLength(1);+ expect(result.liveSources).toHaveLength(1);+ expect(result.stats).toEqual({ format: 'libretv', skipped: 0, skippedByReason: {}, truncated: 0 });+ });++ it('裸数组老格式仍按 LibreTV 解析', () => {+ const result = parseSubscriptionPayload([{ url: 'https://a.example.com/api.php/provide/vod' }]);+ expect(result.sources).toHaveLength(1);+ expect(result.stats?.format).toBe('libretv');+ });++ it('两种格式都不匹配时抛格式错误', () => {+ expect(() => parseSubscriptionPayload({ name: '空的' })).toThrow(/格式不正确/);+ expect(() => parseSubscriptionPayload(null)).toThrow(/格式不正确/);+ });+});++describe('describeParseStats / withSkipped', () => {+ it('无异常时返回空串,有跳过时给出原因与示例', () => {+ expect(describeParseStats(undefined)).toBe('');+ expect(describeParseStats({ format: 'libretv', skipped: 0, skippedByReason: {}, truncated: 0 })).toBe('');++ const stats = {+ format: 'tvbox' as const,+ skipped: 4,+ skippedByReason: { spider: 3, xml: 1 },+ skippedSamples: ['蜘蛛A', 'XML站'],+ truncated: 2,+ };+ expect(describeParseStats(stats)).toBe('跳过 4 个不可用条目(Spider 引擎 3、XML 接口 1),如「蜘蛛A」「XML站」,超出上限截断 2 条');+ // toast 场景:省略示例名以保持文案精简+ expect(describeParseStats(stats, { includeSamples: false })).toBe('跳过 4 个不可用条目(Spider 引擎 3、XML 接口 1),超出上限截断 2 条');+ });++ it('withSkipped 累加原因计数且不修改原对象', () => {+ const base = { format: 'tvbox' as const, skipped: 1, skippedByReason: { spider: 1 }, truncated: 0 };+ const merged = withSkipped(base, 'invalidUrl', 2);++ expect(merged).toEqual({ format: 'tvbox', skipped: 3, skippedByReason: { spider: 1, invalidUrl: 2 }, truncated: 0 });+ expect(base.skipped).toBe(1);+ expect(withSkipped(undefined, 'invalidUrl', 0)).toEqual({ format: 'libretv', skipped: 0, skippedByReason: {}, truncated: 0 });+ });+});++describe('parseSubscriptionJson', () => {+ it('容忍行注释、块注释与尾随逗号(共享配置常见)', () => {+ const text = [+ '{',+ ' // 站点列表',+ ' "sites": [',+ ' { "name": "A", "type": 1, "api": "https://a.example.com/api.php/provide/vod" }, // 行内注释',+ ' ],',+ ' /* 直播源 */',+ ' "lives": [],',+ '}',+ ].join('\n');++ const json = parseSubscriptionJson(text) as { sites: { api: string }[] };+ expect(json.sites).toHaveLength(1);+ expect(json.sites[0].api).toBe('https://a.example.com/api.php/provide/vod');+ });++ it('字符串内的裸换行/制表符被转义(共享配置的实际写法)', () => {+ const json = parseSubscriptionJson('{"name":"优\n酷","tab":"a\tb"}') as Record<string, string>;+ expect(json.name).toBe('优\n酷');+ expect(json.tab).toBe('a\tb');+ });++ it('字符串内的 // 与转义引号不被误伤', () => {+ const json = parseSubscriptionJson('{"a":"https://x//y","b":"say \\"hi\\""}') as Record<string, string>;+ expect(json.a).toBe('https://x//y');+ expect(json.b).toBe('say "hi"');+ });++ it('非法内容抛出可读错误', () => {+ expect(() => parseSubscriptionJson('<html>403 Forbidden</html>')).toThrow(/不是合法的 JSON/);+ });+});diff --git a/src/lib/tvbox-parser.ts b/src/lib/tvbox-parser.tsnew file mode 100644index 0000000..03718ad--- /dev/null+++ b/src/lib/tvbox-parser.ts@@ -0,0 +1,397 @@+import type { SourceListPayload, SubscriptionParseStats, SubscriptionSkipReason } from './types';+import {+ MAX_LIVE_SOURCES,+ MAX_VOD_SOURCES,+ hostnameOf,+ normalizeUrl,+ optionalString,+ parseSourceListPayload,+} from './source-list';++/**+ * TVBOX 配置 JSON 的解析层:把 `sites` / `lives` 归一化为本站的 SourceListPayload,+ * 使同一份订阅入口同时兼容 LibreTV-SourceList 与 TVBOX 两种格式。+ *+ * 仅导入「直连类」条目(与本站现有能力对齐):+ * - 点播:type=1 的 JSON 接口(即 Apple CMS 采集站);部分共享配置省略 type 或写成 0,+ * 但地址命中 Apple CMS 特征时一并宽容导入;+ * - 直播:type=0(或省略)的 M3U 播放列表,可带 EPG 节目单地址。+ *+ * Spider 类(csp_xxx / jar / js / py)需要 TVBOX 引擎才能在 Node 侧运行,XML 接口、+ * 单仓 JSON 与 txt 频道列表本站同样不支持:一律跳过并计入统计,不阻断其余条目导入。+ *+ * 本模块只做字段裁剪、去重与上限控制,不涉及网络与 SSRF(由调用方负责校验)。+ */++/** TVBOX 站点类型:0=XML 接口,1=JSON 接口,3=Spider,4=JSON 外链 */+const SITE_TYPE_XML = 0;+const SITE_TYPE_JSON = 1;+const SITE_TYPE_SPIDER = 3;+const SITE_TYPE_API = 4;++/** TVBOX 直播源类型:0=普通播放列表(m3u/txt),1=单仓 JSON */+const LIVE_TYPE_PLAYLIST = 0;++/** Spider 特征:csp_ 前缀,或 jar / js / py 资源(含查询串) */+const SPIDER_PATTERN = /^csp_|\.(?:jar|js|py)(?:[?#].*)?$/i;+/** 非 http(s) 的相对/本地资源(如 ./json/xxx.json)同样需要 TVBOX 引擎 */+const LOCAL_ASSET_PATTERN = /^\.{0,2}\//;+/**+ * Apple CMS 直连接口特征(type 缺失或写成 XML / 外链时用于宽容识别):+ * 需为 api.php/provide/vod 接口,且排除 XML 通道(/at/xml)——后者本站解析不了。+ */+const CMS_API_PATTERN = /\/api\.php\/provide\/vod(?![^?#]*\/at\/xml)(?:[/?#]|$)/i;+/** M3U 播放列表特征 */+const M3U_PATTERN = /\.m3u8?(?:[?#].*)?$/i;+/** 纯文本频道列表特征(TVBOX 的 txt 直播源,本站无法解析) */+const TXT_PATTERN = /\.txt(?:[?#].*)?$/i;++/** 跳过原因示例名最多保留条数(提示文案不宜过长) */+const SKIPPED_SAMPLE_LIMIT = 3;++const SKIP_REASON_LABELS: Record<SubscriptionSkipReason, string> = {+ spider: 'Spider 引擎',+ xml: 'XML 接口',+ unsearchable: '不支持搜索',+ nonM3uLive: '非 M3U 直播',+ invalidUrl: '地址不可用',+};++/** 固定展示顺序,避免同类统计在不同配置下提示文案抖动 */+const SKIP_REASON_ORDER: SubscriptionSkipReason[] = ['spider', 'xml', 'unsearchable', 'nonM3uLive', 'invalidUrl'];++interface SkipCounter {+ count: number;+ byReason: Partial<Record<SubscriptionSkipReason, number>>;+ samples: string[];+}++/** 空统计(LibreTV-SourceList 格式的默认值) */+function emptyStats(format: SubscriptionParseStats['format']): SubscriptionParseStats {+ return { format, skipped: 0, skippedByReason: {}, truncated: 0 };+}++/**+ * 宽容 JSON 解析:部分共享配置带行注释、块注释或尾随逗号+ * (TVBOX 客户端用的 fastjson 默认容忍,标准 JSON.parse 会直接失败)。+ * 这里在字符串外部剥离这些痕迹后再解析,字符串内的 `//`(如 https://)不受影响。+ */+export function parseSubscriptionJson(text: string): unknown {+ try {+ return JSON.parse(stripJsonArtifacts(text.replace(/^\uFEFF/, '')));+ } catch {+ throw new Error('订阅内容不是合法的 JSON');+ }+}++/**+ * 剥离 JSON 中的注释与尾随逗号(仅作用于字符串外部)。+ * 必须先剥注释再剥尾随逗号:`[1, // 注释\n]` 里的逗号隔着注释,+ * 只有先删掉注释才能正确识别为尾随逗号。+ */+function stripJsonArtifacts(text: string): string {+ return stripTrailingCommas(stripComments(text));+}++/** 把字符串内的裸控制字符转成合法转义序列 */+function escapeControlChar(code: number): string {+ if (code === 0x0a) return '\\n';+ if (code === 0x0d) return '\\r';+ if (code === 0x09) return '\\t';+ return `\\u${code.toString(16).padStart(4, '0')}`;+}++/** 剥离字符串外部的行注释与块注释 */+function stripComments(text: string): string {+ let out = '';+ let inString = false;+ let inLineComment = false;+ let inBlockComment = false;++ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ const next = text[i + 1];++ if (inLineComment) {+ if (ch === '\n' || ch === '\r') {+ inLineComment = false;+ out += ch;+ }+ continue;+ }+ if (inBlockComment) {+ if (ch === '*' && next === '/') {+ inBlockComment = false;+ i += 1;+ }+ continue;+ }+ if (inString) {+ // 部分配置在字符串里留了裸换行等控制字符(fastjson 容忍,标准 JSON 不允许)+ const code = ch.charCodeAt(0);+ if (code < 0x20) {+ out += escapeControlChar(code);+ continue;+ }+ out += ch;+ // 转义字符连同其后一位原样保留,避免 \" 被误判为字符串结束+ if (ch === '\\') {+ out += next ?? '';+ i += 1;+ } else if (ch === '"') {+ inString = false;+ }+ continue;+ }+ if (ch === '"') {+ inString = true;+ out += ch;+ continue;+ }+ if (ch === '/' && next === '/') {+ inLineComment = true;+ i += 1;+ continue;+ }+ if (ch === '/' && next === '*') {+ inBlockComment = true;+ i += 1;+ continue;+ }+ out += ch;+ }++ return out;+}++/** 剥离尾随逗号(`{"a":1,}` / `[1,2,]`),此时文本已不含注释 */+function stripTrailingCommas(text: string): string {+ let out = '';+ let inString = false;++ for (let i = 0; i < text.length; i++) {+ const ch = text[i];++ if (inString) {+ out += ch;+ if (ch === '\\') {+ out += text[i + 1] ?? '';+ i += 1;+ } else if (ch === '"') {+ inString = false;+ }+ continue;+ }+ if (ch === '"') {+ inString = true;+ out += ch;+ continue;+ }+ if (ch === ',') {+ let j = i + 1;+ while (j < text.length && /\s/.test(text[j])) j += 1;+ if (text[j] === '}' || text[j] === ']') continue;+ }+ out += ch;+ }++ return out;+}++/** TVBOX 配置判别:顶层出现 sites / lives 数组即视为 TVBOX 配置 */+export function isTvboxPayload(json: unknown): boolean {+ if (!json || typeof json !== 'object' || Array.isArray(json)) return false;+ const record = json as Record<string, unknown>;+ return Array.isArray(record.sites) || Array.isArray(record.lives);+}++/**+ * 解析订阅 JSON:自动识别格式(先判 TVBOX,后判 LibreTV-SourceList)。+ * 两者均不匹配时由 parseSourceListPayload 抛出格式错误。+ */+export function parseSubscriptionPayload(json: unknown): SourceListPayload {+ if (isTvboxPayload(json)) return parseTvboxPayload(json);+ return { ...parseSourceListPayload(json), stats: emptyStats('libretv') };+}++/** 解析 TVBOX 配置:sites / lives → 本站点播源与直播源,附带跳过与截断统计 */+export function parseTvboxPayload(json: unknown): SourceListPayload {+ const record = (json ?? {}) as Record<string, unknown>;+ const rawSites = Array.isArray(record.sites) ? record.sites : [];+ const rawLives = Array.isArray(record.lives) ? record.lives : [];+ const skipped: SkipCounter = { count: 0, byReason: {}, samples: [] };++ const vod = collectVodSources(rawSites, skipped);+ const live = collectLiveSources(rawLives, skipped);++ if (vod.sources.length === 0 && live.liveSources.length === 0) {+ throw new Error(+ skipped.count > 0+ ? `配置中没有可直接导入的源:已跳过 ${skipped.count} 个条目(${describeReasons(skipped.byReason)})`+ : '配置中没有可用的站点(sites / lives 均为空)'+ );+ }++ return {+ name: optionalString(record.name),+ sources: vod.sources,+ liveSources: live.liveSources,+ stats: {+ format: 'tvbox',+ skipped: skipped.count,+ skippedByReason: skipped.byReason,+ skippedSamples: skipped.samples.length > 0 ? skipped.samples : undefined,+ truncated: vod.truncated + live.truncated,+ },+ };+}++/** 追加一处跳过计数(服务端在 SSRF 过滤后再丢弃条目时调用),返回新对象 */+export function withSkipped(+ stats: SubscriptionParseStats | undefined,+ reason: SubscriptionSkipReason,+ count: number+): SubscriptionParseStats {+ const base = stats ?? emptyStats('libretv');+ if (count <= 0) return base;+ return {+ ...base,+ skipped: base.skipped + count,+ skippedByReason: { ...base.skippedByReason, [reason]: (base.skippedByReason[reason] ?? 0) + count },+ };+}++/**+ * 生成导入结果的补充说明(跳过与截断情况),无异常时返回空串。+ * 服务端错误消息与前端提示共用,保证两处文案一致;+ * `includeSamples` 为 false 时省略示例站点名(toast 展示时长有限,文案需精简)。+ */+export function describeParseStats(+ stats: SubscriptionParseStats | undefined,+ options?: { includeSamples?: boolean }+): string {+ if (!stats) return '';+ const parts: string[] = [];+ if (stats.skipped > 0) {+ parts.push(`跳过 ${stats.skipped} 个不可用条目(${describeReasons(stats.skippedByReason)})`);+ }+ if (options?.includeSamples !== false && stats.skippedSamples && stats.skippedSamples.length > 0) {+ parts.push(`如「${stats.skippedSamples.join('」「')}」`);+ }+ if (stats.truncated > 0) {+ parts.push(`超出上限截断 ${stats.truncated} 条`);+ }+ return parts.join(',');+}++/** 收集点播源:只接受 Apple CMS 直连接口 */+function collectVodSources(rawSites: unknown[], skipped: SkipCounter) {+ const seen = new Set<string>();+ const sources: SourceListPayload['sources'] = [];+ let truncated = 0;++ for (const raw of rawSites) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;+ const site = raw as Record<string, unknown>;+ const name = optionalString(site.name);+ const api = optionalString(site.api);+ const type = toNumber(site.type);++ if (!api) {+ markSkipped(skipped, 'invalidUrl', name);+ continue;+ }+ // Spider 类与本地资源需要 TVBOX 引擎,Node 侧无法运行+ if (type === SITE_TYPE_SPIDER || SPIDER_PATTERN.test(api)) {+ markSkipped(skipped, 'spider', name);+ continue;+ }+ if (!/^https?:\/\//i.test(api)) {+ markSkipped(skipped, LOCAL_ASSET_PATTERN.test(api) ? 'spider' : 'invalidUrl', name);+ continue;+ }+ // 站点自身声明不可搜索:本站只有搜索入口,导入后无从使用+ if (site.searchable === 0 || site.searchable === '0') {+ markSkipped(skipped, 'unsearchable', name);+ continue;+ }++ // 可导入判定:显式 JSON 接口,或类型缺失/写成 XML、外链但地址命中 Apple CMS 特征+ const importable =+ type === SITE_TYPE_JSON ||+ ((type === undefined || type === SITE_TYPE_XML || type === SITE_TYPE_API) && CMS_API_PATTERN.test(api));+ if (!importable) {+ markSkipped(skipped, type === SITE_TYPE_API ? 'spider' : 'xml', name);+ continue;+ }++ const url = normalizeUrl(api, true);+ if (!url) {+ markSkipped(skipped, 'invalidUrl', name);+ continue;+ }+ if (seen.has(url)) continue; // 重复条目静默跳过,与 LibreTV 订阅语义一致+ if (sources.length >= MAX_VOD_SOURCES) {+ truncated += 1;+ continue;+ }+ seen.add(url);+ sources.push({ name: name || hostnameOf(url), url });+ }++ return { sources, truncated };+}++/** 收集直播源:只接受 M3U 播放列表 */+function collectLiveSources(rawLives: unknown[], skipped: SkipCounter) {+ const seen = new Set<string>();+ const liveSources: SourceListPayload['liveSources'] = [];+ let truncated = 0;++ for (const raw of rawLives) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;+ const live = raw as Record<string, unknown>;+ const name = optionalString(live.name);+ const url = normalizeUrl(live.url, false);+ if (!url) {+ markSkipped(skipped, 'invalidUrl', name);+ continue;+ }+ const type = toNumber(live.type);+ // 单仓 JSON 直播订阅本站不支持;txt 频道列表无法被 M3U 解析器识别+ if ((type !== undefined && type !== LIVE_TYPE_PLAYLIST) || (!M3U_PATTERN.test(url) && TXT_PATTERN.test(url))) {+ markSkipped(skipped, 'nonM3uLive', name);+ continue;+ }+ if (seen.has(url)) continue;+ if (liveSources.length >= MAX_LIVE_SOURCES) {+ truncated += 1;+ continue;+ }+ seen.add(url);+ liveSources.push({ name: name || hostnameOf(url), url, epg: normalizeUrl(live.epg, false) });+ }++ return { liveSources, truncated };+}++function toNumber(raw: unknown): number | undefined {+ if (typeof raw === 'number' && Number.isFinite(raw)) return raw;+ if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) return Number(raw);+ return undefined;+}++function markSkipped(counter: SkipCounter, reason: SubscriptionSkipReason, name?: string): void {+ counter.count += 1;+ counter.byReason[reason] = (counter.byReason[reason] ?? 0) + 1;+ if (name && counter.samples.length < SKIPPED_SAMPLE_LIMIT && !counter.samples.includes(name)) {+ counter.samples.push(name);+ }+}++/** 按固定顺序拼装原因明细,如「Spider 引擎 20、XML 接口 5」 */+function describeReasons(byReason: Partial<Record<SubscriptionSkipReason, number>>): string {+ return SKIP_REASON_ORDER.filter((reason) => (byReason[reason] ?? 0) > 0)+ .map((reason) => `${SKIP_REASON_LABELS[reason]} ${byReason[reason]}`)+ .join('、');+}diff --git a/src/lib/types.ts b/src/lib/types.tsindex b4fec6a..e541f66 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -156,9 +156,37 @@ export interface LiveEpgResponse {// —— 数据源订阅 ——+/** 订阅条目未被导入(跳过)的原因分类 */+export type SubscriptionSkipReason =+ /** Spider 类站点(csp_* / jar / js / py),需 TVBOX 引擎才能运行 */+ | 'spider'+ /** 仅提供 XML 接口或不支持的类型 */+ | 'xml'+ /** 站点自身标记为不可搜索(本站只有搜索入口,导入后无法使用) */+ | 'unsearchable'+ /** 直播源不是 M3U 播放列表(如 txt 频道列表、单仓 JSON) */+ | 'nonM3uLive'+ /** 地址非法、非 http(s) 或未通过服务端公网校验 */+ | 'invalidUrl';++/** 订阅解析统计:说明跳过与截断情况,用于导入结果提示 */+export interface SubscriptionParseStats {+ /** 识别出的订阅格式 */+ format: 'libretv' | 'tvbox';+ /** 被跳过的条目总数 */+ skipped: number;+ /** 跳过原因分类计数 */+ skippedByReason: Partial<Record<SubscriptionSkipReason, number>>;+ /** 被跳过条目的名称示例(最多 3 个),便于用户定位 */+ skippedSamples?: string[];+ /** 因超出数量上限被截断的条目数 */+ truncated: number;+}+/**- * 远程订阅(LibreTV-SourceList JSON)解析结果。+ * 远程订阅解析结果。* `sources` 为点播源(Apple CMS 采集站),`liveSources` 为直播源(M3U + 可选 EPG)。+ * 兼容两种订阅格式:LibreTV-SourceList JSON 与 TVBOX 配置 JSON(`sites` / `lives`)。* 老格式订阅只有 `sources`,此时 `liveSources` 为空数组。*/export interface SourceListPayload {@@ -166,4 +194,6 @@ export interface SourceListPayload {name?: string;sources: Omit<SourceConfig, 'key'>[];liveSources: Omit<LiveSourceConfig, 'key'>[];+ /** 解析统计(格式、跳过与截断),老数据可能缺失 */+ stats?: SubscriptionParseStats;}