Skip to content

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

feat(live): 新增直播/IPTV模块

bestZwei1b6fbc136129
diff --git a/.codebuddy/plans/libretv-iptv-live-module_1d20a03d.md b/.codebuddy/plans/libretv-iptv-live-module_1d20a03d.md
new file mode 100644
index 0000000..ea86907
--- /dev/null
+++ b/.codebuddy/plans/libretv-iptv-live-module_1d20a03d.md
@@ -0,0 +1,256 @@
+---
+name: libretv-iptv-live-module
+overview: 为 LibreTV 新增 /live 直播模块:M3U 订阅解析(支持用户订阅 + 环境变量预置 + 导出)、HLS/HTTP-FLV 站内播放、XMLTV 节目单(EPG),并改造代理以适配直播长连接。
+design:
+ architecture:
+ framework: react
+ styleKeywords:
+ - 深色直播控制台
+ - 暗亮双主题
+ - 毛玻璃导航
+ - 分组标签条
+ - LIVE 呼吸红点
+ - 卡片圆角
+ - 微交互动效
+ fontSystem:
+ fontFamily: Noto Sans
+ heading:
+ size: 20px
+ weight: 600
+ subheading:
+ size: 15px
+ weight: 500
+ body:
+ size: 13px
+ weight: 400
+ colorSystem:
+ primary:
+ - "#2563EB"
+ - "#3B82F6"
+ - "#1D4ED8"
+ background:
+ - "#0B0F1A"
+ - "#121826"
+ - "#FFFFFF"
+ text:
+ - "#E5E7EB"
+ - "#9CA3AF"
+ - "#111827"
+ functional:
+ - "#EF4444"
+ - "#10B981"
+ - "#F59E0B"
+todos:
+ - id: live-parsers
+ content: 实现 m3u-parser.ts 与 xmltv.ts 并补齐 vitest 单测
+ status: completed
+ - id: live-api
+ content: 新增 /api/live 的 playlist、epg、stream 三个路由与 live-cache
+ status: completed
+ dependencies:
+ - live-parsers
+ - id: live-config
+ content: 新增 DEFAULT_LIVE_SOURCES 解析、status 下发与 types 扩展
+ status: completed
+ dependencies:
+ - live-api
+ - id: live-store
+ content: 扩展 store 直播订阅/收藏/最近观看与 client-api 方法
+ status: completed
+ dependencies:
+ - live-config
+ - id: live-page
+ content: 实现 /live 页面、live-player 与频道列表达
+ status: completed
+ dependencies:
+ - live-store
+---
+
+## 产品概述
+
+在 LibreTV 现有影视点播能力之外,新增一个独立的「直播 / IPTV」模块。用户(或部署者)提供 M3U 直播订阅地址后,可在站内 `/live` 页面按分组浏览频道、搜索频道、查看节目单,并直接在站内播放;不改动、不影响现有点播链路。项目本身不内置任何具体频道源,仅提供解析与播放能力。
+
+## 核心功能
+
+- **直播源管理**:支持用户粘贴 M3U/M3U8 订阅地址(订阅、手动同步、移除)与部署者环境变量预置两种方式;预置源开箱可见,用户取消后不再自动勾回。
+- **频道列表**:按 `group-title` 分组展示频道卡片(台标、频道名、分组标签),支持关键字搜索、分组筛选、收藏与最近观看。
+- **站内播放**:点击频道即在页面内播放,支持 HLS(m3u8)与 HTTP-FLV 两种直播流;播放失败时自动从直连切换到代理通道重试;直播态隐藏进度条、倍速、连播、截图等点播专属控件。
+- **节目单(EPG)**:解析 XMLTV(含 gzip 压缩)并按 `tvg-id` 匹配频道,侧栏展示「正在播出 / 即将播出」与时间轴,点击节目可查看简介。
+- **视觉效果**:沿用站点亮暗双主题与半透明导航风格;播放器区为 16:9 黑色画布,右侧为频道侧栏(分组折叠 + 频道项),底部为当前频道信息条与 EPG 时间轴;LIVE 状态以红色呼吸点标识,分组筛选为横向可滑动标签条。
+
+## 技术栈
+
+沿用项目现有技术栈,仅新增一个前端播放依赖:
+
+- Next.js 15(App Router)+ TypeScript + Tailwind CSS 3 + React 19
+- 播放:ArtPlayer 5 + hls.js 1.5(现有)+ **mpegts.js**(新增,仅直播页动态加载)
+- 状态:zustand + persist(现有 `libretv-settings`);数据获取:@tanstack/react-query
+- 测试:vitest(对齐 `cms-parser.test.ts` 风格)
+- 服务端:Node runtime 路由 + 项目现有 `fetchUpstream()` / `checkUpstreamAllowed()` / 内存 TTL 缓存
+
+## 实现方案
+
+### 整体架构
+
+```mermaid
+flowchart TB
+ subgraph 客户端
+ A[/live 页面] --> B[LivePlayer 协议分发]
+ B -->|m3u8| C[hls.js]
+ B -->|flv| D[mpegts.js 动态 import]
+ A --> E[频道列表 / 分组 / 搜索]
+ A --> F[EPG 时间轴]
+ A --> G[直播源管理抽屉]
+ end
+ subgraph 服务端 Next.js API
+ H[/api/live/playlist] -->|拉取+解析| I[m3u-parser]
+ J[/api/live/epg] -->|拉取+解压+解析| K[xmltv]
+ L[/api/live/stream/[url]] -->|长连接流式透传| M[上游直播源]
+ N[/api/status] --> O[env-live-sources]
+ end
+ H -.复用.-> P[fetchUpstream + checkUpstreamAllowed]
+ J -.复用.-> P
+ L -.复用.-> P
+ I -.写入.-> Q[live-cache 大对象 TTL 缓存]
+ K -.写入.-> Q
+```
+
+### 关键技术决策
+
+**1. 直播流不能复用 `/api/proxy`(必须新建专用通道)**
+现有 `src/app/api/proxy/[url]/route.ts` 使用 `signal: AbortSignal.timeout(TIMEOUT_MS)`(默认 8000ms),该超时作用于**整个响应流**;且 M3U 不重写、非 m3u8 响应统一加 `Cache-Control: public, max-age=3600`,并且失败会重试。HTTP-FLV 是单一长连接,走该代理会在 8 秒后被切断。因此新建 `/api/live/stream/[url]`:
+
+- 只对「收到响应头」设超时(约 15s),拿到响应后立即释放超时信号,之后不限总时长;
+- 不重试、不读取 body 到内存(直接 `new NextResponse(response.body)`);
+- 响应头 `Cache-Control: no-store, no-transform`、`Connection: keep-alive`、透传 `content-type`;
+- 客户端断开(`req.signal`)时主动 `abort` 上游,防止连接泄漏;
+- 每次请求仍强制过 `checkUpstreamAllowed()`(不信任解析阶段的校验结果)。
+
+**2. 直播播放器独立组件,不污染点播播放器**
+新建 `src/components/live-player.tsx`,而非在 `player-shell.tsx` 的 `customType` 里加 flv 分支。理由:点播播放器耦合了进度恢复、IndexedDB 写入、自动连播、集数切换、广告过滤(剔除 `#EXT-X-DISCONTINUITY`,对直播有误伤风险),参数(backBufferLength/maxBufferLength)也是点播调优值。直播需要 `liveSyncDurationCount`、`lowLatencyMode`、直播态 UI。独立组件可将改动限制在新文件,点播链路零风险。
+
+**3. mpegts.js 动态导入**
+仅在检测到 flv 源时 `await import('mpegts.js')`,避免点播首屏为此多下载约 150KB。
+
+**4. 频道源两种来源并存**
+
+- 用户订阅:复用现有订阅心智(订阅 URL、手动同步、按前缀整体替换),但**独立于采集站订阅模型**存于 `liveSubscriptions`,避免与 `customAPIs` 的 `subKeyPrefix` 命名空间冲突;
+- 部署者预置:新增 `DEFAULT_LIVE_SOURCES` 环境变量,解析逻辑对齐 `src/lib/env-sources.ts`(JSON 数组、解析失败仅告警忽略),经 `/api/status` 下发,沿用 `envKeysSeen` 的「首次自动勾选」策略。
+
+**5. EPG 解析与大对象缓存**
+XMLTV 文件常达数十 MB,不可每次请求拉取:服务端按 `tvg-id` 建立 `Map<channelId, 节目[]>` 后**只保留所需窗口**(当前及未来 24 小时)并丢弃原始文本,写入独立缓存(`src/lib/live-cache.ts`,独立 LRU/TTL 上限)。刻意不复用 `fetch-utils.ts` 的 `getCache/setCache`:其条目超 500 会 `cache.clear()`,EPG 大对象会连带清掉豆瓣等热点数据。M3U 列表用较短 TTL(10 分钟)走通用缓存即可。
+
+**6. 安全与合规**
+
+- 所有直播源 URL 播放前必须过 `checkUpstreamAllowed()`(M3U 内容远程可控,解析期校验不可信);
+- 频道名/logo 由 React 文本渲染天然转义;logo URL 仅放行 http(s),渲染走现有图片代理模式;
+- 不内置任何公共 IPTV 源列表;README 沿用「不存储不制作内容,合法性由数据源负责」声明;
+- 内网自建源(`http://192.168.x.x`)默认仍被 SSRF 拦截,提供显式环境变量 `LIVE_ALLOW_PRIVATE=1` 供自部署者按需开启(默认关闭)。
+
+### 性能要点
+
+- M3U 解析为单趟扫描(O(n)),频道去重按 `url` + `tvg-id`;大列表(数千频道)在服务端裁剪后返回,前端分组用 `useMemo`;
+- EPG 只在用户展开某频道时按需查询该 `tvg-id`,不做全量下发;
+- 频道列表与 EPG 查询接入 react-query(`staleTime` 缓存),避免切台重复请求;
+- 直播流代理为纯流式管道,无内存缓冲累积。
+
+## 目录结构
+
+```
+src/
+├── lib/
+│ ├── m3u-parser.ts # [NEW] M3U/M3U8 播放列表解析:#EXTM3U 校验、#EXTINF 行与 tvg-id/tvg-name/tvg-logo/group-title 属性提取、频道去重、URL 标准化(相对地址按订阅 URL 解析)。导出 parseM3u() 返回 LiveChannel[]。
+│ ├── m3u-parser.test.ts # [NEW] 单测:标准 M3U、无属性简写、相对路径、重复频道去重、异常输入不抛错。对齐 cms-parser.test.ts 风格。
+│ ├── xmltv.ts # [NEW] XMLTV 解析:gzip 解压(zlib.gunzipSync)、<channel id>/<programme channel start stop> 提取、YYYYMMDDHHmmss +0800 时间解析、按 tvg-id 索引、时间窗裁剪(当前至 +24h)。导出 parseXmltv()/pickPrograms()。
+│ ├── xmltv.test.ts # [NEW] 单测:gz 与明文、偏移时区、节目排序、当前/后续节目定位。
+│ ├── live-cache.ts # [NEW] 大对象专用 TTL 缓存(EPG),带条目数与内存上限的自清理,与 fetch-utils 通用缓存隔离。
+│ ├── env-live-sources.ts # [NEW] 解析 DEFAULT_LIVE_SOURCES 环境变量(JSON 数组:name/url/epg),失败仅 console.warn 并忽略,模式对齐 env-sources.ts。
+│ ├── types.ts # [MODIFY] 新增 LiveSourceConfig / LiveChannel / EpgProgram / LivePlaylistResponse / LiveEpgResponse 类型;AuthStatusResponse 增加 defaultLiveSources 字段。
+│ ├── store.ts # [MODIFY] 新增 liveSubscriptions、liveEnvSources、liveFavorites、liveRecent;对应 actions(订阅/同步/移除/整体替换、收藏切换、最近观看记录上限 20);partialize 持久化白名单同步扩展(注意 skipHydration 的 SSR 一致性)。
+│ └── client-api.ts # [MODIFY] 新增 api.livePlaylist(url, force)、api.liveEpg(epgUrl, tvgId)、api.liveTest(url),沿用 request() 的 401/503 处理。
+├── app/
+│ ├── api/
+│ │ ├── live/
+│ │ │ ├── playlist/route.ts # [NEW] 拉取并解析 M3U 订阅 → 分组后的频道 JSON;SSRF 校验 + 通用缓存(TTL 10min)+ force 参数跳过缓存;支持 format=m3u 导出订阅文件。
+│ │ │ ├── epg/route.ts # [NEW] 拉取 XMLTV(含 .gz)→ 解析并按 tvg-id(批量)返回节目窗口;写入 live-cache(TTL 6h)。
+│ │ │ └── stream/[url]/route.ts # [NEW] 直播流专用长连接代理:首字节超时、无总时长限制、no-store、客户端断开即 abort 上游、强制 SSRF 校验、可选 LIVE_ALLOW_PRIVATE 放行内网。
+│ │ └── status/route.ts # [MODIFY] 下发 defaultLiveSources(由 env-live-sources 提供)。
+│ └── live/page.tsx # [NEW] 直播页:左侧播放器 + 右侧频道侧栏(分组筛选/搜索/收藏/最近),底部 EPG 时间轴;URL 参数 ?src=&ch= 支持频道深链与刷新保持。
+├── components/
+│ ├── live-player.tsx # [NEW] 直播播放器:ArtPlayer 直播态配置(隐藏进度/连播/截图/倍速)、扩展名→协议分发(m3u8→hls.js;flv→动态 import mpegts.js)、直连失败自动切 /api/live/stream 重试、错误提示与重载。
+│ ├── live-channel-list.tsx # [NEW] 频道侧栏:分组横向标签条 + 搜索框 + 频道项(台标走现有图片代理、名称、LIVE/收藏标记)、虚拟滚动或分页以应对大列表。
+│ ├── live-epg-panel.tsx # [NEW] EPG 面板:当前节目高亮、进度条、后续节目列表、点击展开简介;无数据时优雅降级。
+│ ├── live-source-manager.tsx # [NEW] 直播源管理(嵌入现有设置抽屉):添加/同步/移除订阅、显示预置源、探活耗时、导出 .m3u。
+│ ├── source-manager.tsx # [MODIFY] 在设置抽屉中新增「直播源」分区并挂载 LiveSourceManager。
+│ └── header.tsx # [MODIFY] 顶部导航新增「直播」HeaderLink(复用现有 HeaderLink 组件与高亮逻辑)。
+├── package.json # [MODIFY] 新增依赖 mpegts.js。
+└── README.md # [MODIFY] 环境变量表格补充 DEFAULT_LIVE_SOURCES / LIVE_ALLOW_PRIVATE;核心特性与免责声明补充直播说明。
+```
+
+## 关键代码结构
+
+```ts
+// src/lib/types.ts 新增(示意)
+export interface LiveSourceConfig {
+ key: string;
+ name: string;
+ url: string; // M3U 订阅地址
+ epg?: string; // XMLTV 地址,可选
+ builtin?: boolean; // 来自 DEFAULT_LIVE_SOURCES
+}
+
+export interface LiveChannel {
+ id: string; // tvg-id 或由 url 生成的稳定 id
+ name: string;
+ url: string;
+ logo?: string;
+ group?: string;
+ tvgId?: string;
+ rawName?: string;
+}
+
+export interface EpgProgram {
+ channelId: string;
+ start: number; // epoch ms
+ stop: number;
+ title: string;
+ desc?: string;
+}
+```
+
+```ts
+// src/lib/m3u-parser.ts
+export function parseM3u(content: string, baseUrl?: string): LiveChannel[];
+
+// src/lib/xmltv.ts
+export function parseXmltv(content: string | Buffer, windowMs?: number): Map<string, EpgProgram[]>;
+export function currentAndNext(programs: EpgProgram[], at?: number): { current?: EpgProgram; next?: EpgProgram };
+```
+
+## 实施注意事项
+
+- **不改动** `src/app/api/proxy/[url]/route.ts` 与 `src/components/player-shell.tsx` 的点播行为,直播全部走新增文件,blast radius 可控;
+- 直播路由需显式 `export const runtime = 'nodejs'` 与 `export const dynamic = 'force-dynamic'`,避免被静态化或缓存;
+- 流式响应禁用 Next.js 缓冲:不要 `await response.text()`,且勿设置 `content-length`;
+- 新解析器必须补 vitest 单测,`npm test` 是 CI 门禁;
+- 交付前需全部通过:`npm run typecheck`、`npm test`、`npm run lint`、`npm run build`。
+
+## 设计风格
+
+沿用 LibreTV 现有视觉语言(亮暗双主题、半透明毛玻璃导航、蓝色强调色 #2563eb),新增直播模块仅在既有设计系统内扩展,不引入新组件库:全部使用 Tailwind 工具类,复用项目现成的 `Drawer`、`HeaderLink`、`btn / btn-ghost / btn-primary`、`input`、`bg-surface / bg-surface-raised`、`text-content / text-muted / text-faint`、`border-line`、`bg-hover`、`accent` 等既有 class,保证与点播页视觉完全一致。
+
+## 页面:/live(单页,桌面为主、移动端单列自适应)
+
+1. **顶部导航条(复用全局 Header)**:Logo、搜索框(首页外可见)、新增「直播」入口高亮、主题切换、历史、设置;sticky + backdrop-blur。
+2. **主播放区(左侧主栏)**:16:9 纯黑画布,圆角卡片;右下角红色圆点 + "LIVE" 呼吸动效;播放失败时黑色遮罩 + 重试按钮;加载中显示旋转指示器。
+3. **频道信息条(播放器下方)**:当前频道台标(40px 圆角)、频道名、分组标签、EPG 当前节目名与进度条、收藏星标、复制/外部打开按钮。
+4. **频道侧栏(右侧 300px,移动端下移到底部)**:分组横向可滑动标签条(全部 / 央视 / 卫视 / 地方 / 体育...)+ 搜索输入框 + 频道列表项(台标 28px、名称单行截断、LIVE 红点、收藏星);当前播放项左侧蓝色竖条高亮并自动滚动进视区;支持「收藏 / 最近观看」切换 tab。
+5. **EPG 时间轴(侧栏底部或主栏下方)**:当前节目卡片(标题 + 时间 + 简介折叠)+ 「接下来」列表(时间 + 标题),时间轴用细横线 + 已播进度条表示;无 EPG 数据时显示占位文案。
+
+## 交互与动效
+
+- 切台:频道项点击即播,播放器淡入切换,列表高亮平滑过渡;
+- 分组切换:标签条滑动 + 下划线指示器动画;
+- LIVE 标识:红色圆点 2s 周期呼吸;
+- 收藏:星标填充时 0.2s 缩放弹跳;
+- 全部动效时长控制在 150-300ms,与现有 `animate-fade-in` / `animate-slide-up` 保持一致。
\ No newline at end of file
diff --git a/README.md b/README.md
index 63aa2a3..722db40 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,7 @@ LibreTV Next.js 迁移版:免费在线视频聚合搜索与观看平台。基
- **聚合搜索**:多采集站服务端并行搜索
- **跨源同名聚合**:同名影片合并为一张卡片,展开即可比较和选择各来源
- **HLS 播放**:ArtPlayer + hls.js,广告分片过滤、自动连播、倍速、快捷键、移动端长按 3 倍速
+- **直播 / IPTV**:M3U 订阅解析,`/live` 页面按分组浏览、搜索频道并站内播放(HLS + HTTP-FLV),支持 XMLTV 节目单(EPG)与频道收藏;直播流经专用长连接代理(`/api/live/stream`)转发
- **进度同步**:播放进度与观看历史存于本机 IndexedDB,精确到秒的续播
- **换源测速**:跨源搜索同名资源并测速排序,一键切换保留集数位置
- **源测试与订阅**:一键探活数据源;订阅远程源列表(LibreTV-SourceList JSON),可导出分享
@@ -76,6 +77,8 @@ PASSWORD=your-password npm start # 监听 8080
| `MAX_RETRIES` | 否 | 代理请求重试次数,默认 1 |
| `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 节目单地址 |
+| `LIVE_ALLOW_PRIVATE` | 否 | 设为 `1` 时允许直播流代理访问内网/保留地址(自建 IPTV 场景),默认关闭以维持 SSRF 防护 |
| `DEBUG` | 否 | 调试日志 |
## 使用说明
@@ -86,6 +89,15 @@ PASSWORD=your-password npm start # 监听 8080
4. **进度与历史**:自动保存在本设备 IndexedDB,仅定位信息入库,播放时自动同步最新剧集。
5. **配置迁移**:设置 → 导出/导入配置(兼容旧版 LibreTV-Settings JSON 的历史记录迁移)。
+## 直播 / IPTV
+
+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 订阅**。
diff --git a/package-lock.json b/package-lock.json
index ef89296..10ff96f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -14,6 +14,7 @@
"dexie": "^4.0.8",
"dexie-react-hooks": "^1.1.7",
"hls.js": "^1.5.17",
+ "mpegts.js": "^1.8.2",
"next": "^15.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
@@ -3797,6 +3798,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/es6-promise": {
+ "version": "4.2.8",
+ "resolved": "https://registry.npmmirror.com/es6-promise/-/es6-promise-4.2.8.tgz",
+ "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==",
+ "license": "MIT"
+ },
"node_modules/esbuild": {
"version": "0.21.5",
"resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.21.5.tgz",
@@ -4324,6 +4331,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmmirror.com/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.x"
+ }
+ },
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmmirror.com/expect-type/-/expect-type-1.4.0.tgz",
@@ -5572,6 +5588,19 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/mpegts.js": {
+ "version": "1.8.2",
+ "resolved": "https://registry.npmmirror.com/mpegts.js/-/mpegts.js-1.8.2.tgz",
+ "integrity": "sha512-cZYMa5muASH55wrS6JK5IGkUqnCA96c0f+WdnW91jIK9s/N6NzjmTQDJNYg9A5u/G2Q5nj2b3w1Zwzze/9guxA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "es6-promise": "^4.2.8",
+ "events": "^3.3.0"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ }
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
diff --git a/package.json b/package.json
index c27e6ed..8e632ee 100644
--- a/package.json
+++ b/package.json
@@ -18,6 +18,7 @@
"dexie": "^4.0.8",
"dexie-react-hooks": "^1.1.7",
"hls.js": "^1.5.17",
+ "mpegts.js": "^1.8.2",
"next": "^15.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
diff --git a/src/app/api/live/epg/route.ts b/src/app/api/live/epg/route.ts
new file mode 100644
index 0000000..c6edc33
--- /dev/null
+++ b/src/app/api/live/epg/route.ts
@@ -0,0 +1,59 @@
+import { NextResponse } from 'next/server';
+import { guardRequest, jsonError } from '@/lib/api-guard';
+import { checkUpstreamAllowed } from '@/lib/ssrf';
+import { fetchUpstream } from '@/lib/fetch-utils';
+import { getLiveCache, setLiveCache } from '@/lib/live-cache';
+import { currentAndNext, parseXmltv } from '@/lib/xmltv';
+import type { EpgProgram } from '@/lib/types';
+
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
+/** XMLTV 文件较大,放宽抓取超时 */
+const FETCH_TIMEOUT_MS = 30_000;
+const WINDOW_MS = 24 * 60 * 60 * 1000;
+
+/**
+ * 拉取并解析 XMLTV 节目单(支持 gzip)。
+ * GET /api/live/epg?url=<xmltv>&channel=<tvgId>&force=1
+ * 解析结果(按频道索引、24h 时间窗裁剪)整体缓存 6 小时;单频道按需查询。
+ */
+export async function GET(req: Request) {
+ const guarded = guardRequest(req);
+ if (guarded) return guarded;
+
+ const sp = new URL(req.url).searchParams;
+ const url = sp.get('url')?.trim();
+ const channel = sp.get('channel')?.trim();
+ if (!url || !channel) return jsonError('缺少 url 或 channel 参数', 400);
+ const force = sp.get('force') === '1';
+
+ const verdict = await checkUpstreamAllowed(url);
+ if (!verdict.ok) return jsonError(verdict.reason, 403);
+
+ const key = `live:epg:${url}`;
+ let programMap: Map<string, EpgProgram[]> | undefined = force ? undefined : getLiveCache(key);
+ if (!programMap) {
+ try {
+ const res = await fetchUpstream(url, { timeoutMs: FETCH_TIMEOUT_MS, retries: 0 });
+ if (!res.ok) {
+ return jsonError(`节目单地址请求失败: ${res.status}`, 502);
+ }
+ // gzip 由 parseXmltv 内识别(fetch 对 .gz 不会自动解压)
+ const buf = Buffer.from(await res.arrayBuffer());
+ programMap = parseXmltv(buf, WINDOW_MS);
+ setLiveCache(key, programMap, CACHE_TTL_MS, buf.byteLength * 2);
+ } catch (err) {
+ return jsonError(`节目单地址请求失败: ${err instanceof Error ? err.message : '未知错误'}`, 502);
+ }
+ }
+
+ const programs = programMap.get(channel) ?? [];
+ const { current, next } = currentAndNext(programs);
+
+ return NextResponse.json(
+ { channelId: channel, current, next, programs },
+ { headers: { 'Cache-Control': 'no-store' } }
+ );
+}
diff --git a/src/app/api/live/playlist/route.ts b/src/app/api/live/playlist/route.ts
new file mode 100644
index 0000000..5bbff83
--- /dev/null
+++ b/src/app/api/live/playlist/route.ts
@@ -0,0 +1,95 @@
+import { NextResponse } from 'next/server';
+import { guardRequest, jsonError } from '@/lib/api-guard';
+import { checkUpstreamAllowed } from '@/lib/ssrf';
+import { fetchUpstream, getCache, setCache } from '@/lib/fetch-utils';
+import { parseM3u } from '@/lib/m3u-parser';
+import type { LivePlaylistResponse } from '@/lib/types';
+
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+const CACHE_TTL_MS = 10 * 60 * 1000;
+
+function cacheKey(url: string): string {
+ return `live:playlist:${url}`;
+}
+
+function extractPlaylistName(content: string): string | undefined {
+ const m = content.match(/^#PLAYLIST:(.+)$/m);
+ const name = m?.[1]?.trim();
+ return name || undefined;
+}
+
+/** 反序列化为 M3U 文本(订阅导出用) */
+function toM3uText(playlist: LivePlaylistResponse): string {
+ const esc = (s: string) => s.replace(/"/g, "'");
+ const lines = ['#EXTM3U'];
+ if (playlist.name) lines.push(`#PLAYLIST:${playlist.name}`);
+ for (const c of playlist.channels) {
+ const attrs = [
+ `tvg-id="${esc(c.tvgId || c.id)}"`,
+ c.rawName ? `tvg-name="${esc(c.rawName)}"` : '',
+ c.logo ? `tvg-logo="${esc(c.logo)}"` : '',
+ `group-title="${esc(c.group || '')}"`,
+ ]
+ .filter(Boolean)
+ .join(' ');
+ lines.push(`#EXTINF:-1 ${attrs},${c.name}`);
+ lines.push(c.url);
+ }
+ return lines.join('\n');
+}
+
+/**
+ * 拉取并解析 M3U 直播订阅。
+ * GET /api/live/playlist?url=<m3u>&force=1&format=json|m3u
+ * - 服务端缓存 10 分钟,force=1 跳过缓存强制刷新;
+ * - format=m3u 返回解析后的标准 M3U 文本(订阅导出)。
+ */
+export async function GET(req: Request) {
+ const guarded = guardRequest(req);
+ if (guarded) return guarded;
+
+ const sp = new URL(req.url).searchParams;
+ const url = sp.get('url')?.trim();
+ if (!url) return jsonError('缺少 url 参数', 400);
+ const format = sp.get('format') || 'json';
+ const force = sp.get('force') === '1';
+
+ const verdict = await checkUpstreamAllowed(url);
+ if (!verdict.ok) return jsonError(verdict.reason, 403);
+
+ let playlist: LivePlaylistResponse | undefined = force ? undefined : getCache(cacheKey(url));
+ if (!playlist) {
+ let text: string;
+ try {
+ const res = await fetchUpstream(url, { timeoutMs: 15000, retries: 1 });
+ if (!res.ok) {
+ return jsonError(`订阅地址请求失败: ${res.status}`, 502);
+ }
+ text = await res.text();
+ } catch (err) {
+ return jsonError(`订阅地址请求失败: ${err instanceof Error ? err.message : '未知错误'}`, 502);
+ }
+
+ const channels = parseM3u(text, url);
+ const groups = [...new Set(channels.map((c) => c.group).filter((g): g is string => Boolean(g)))].sort(
+ (a, b) => a.localeCompare(b, 'zh')
+ );
+ playlist = { name: extractPlaylistName(text), channels, groups };
+ setCache(cacheKey(url), playlist, CACHE_TTL_MS);
+ }
+
+ if (format === 'm3u') {
+ return new NextResponse(toM3uText(playlist), {
+ headers: {
+ 'Content-Type': 'audio/x-mpegurl; charset=utf-8',
+ 'Cache-Control': 'no-store',
+ },
+ });
+ }
+
+ return NextResponse.json(playlist, {
+ headers: { 'Cache-Control': 'no-store' },
+ });
+}
diff --git a/src/app/api/live/probe/route.ts b/src/app/api/live/probe/route.ts
new file mode 100644
index 0000000..2fea197
--- /dev/null
+++ b/src/app/api/live/probe/route.ts
@@ -0,0 +1,92 @@
+import { NextResponse } from 'next/server';
+import { guardRequest, jsonError } from '@/lib/api-guard';
+import { checkUpstreamAllowed } from '@/lib/ssrf';
+import { fetchUpstream } from '@/lib/fetch-utils';
+
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+/**
+ * 直播频道批量测活。
+ * POST /api/live/probe body: { urls: string[] }
+ *
+ * 以带 Range 的 GET 轻量探测(部分源不支持 HEAD 且会忽略 Range),
+ * 收到响应头即 cancel body 终止连接,不下载任何媒体数据;
+ * 返回 2xx 视为可用(206 同样算通)。单次最多 50 条,服务端并发 8。
+ * 结果为 best-effort:200 响应不保证编码可解码(H.265 等),仅代表网络可达。
+ */
+
+const MAX_URLS = 50;
+const CONCURRENCY = 8;
+const TIMEOUT_MS = 5000;
+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';
+
+interface ProbeOutcome {
+ url: string;
+ ok: boolean;
+ status?: number;
+ ms?: number;
+ error?: string;
+}
+
+async function probeOne(url: string): Promise<ProbeOutcome> {
+ const start = performance.now();
+ const verdict = await checkUpstreamAllowed(url);
+ if (!verdict.ok) return { url, ok: false, error: verdict.reason };
+ try {
+ const res = await fetchUpstream(url, {
+ timeoutMs: TIMEOUT_MS,
+ retries: 0,
+ headers: { 'User-Agent': UA, Accept: '*/*', Range: 'bytes=0-1' },
+ });
+ const ms = Math.round(performance.now() - start);
+ // 拿到响应头即断开,避免直播流持续下载
+ if (res.body) {
+ try { await res.body.cancel(); } catch { /* 忽略 */ }
+ }
+ return { url, ok: res.ok, status: res.status, ms };
+ } catch (err) {
+ return {
+ url,
+ ok: false,
+ ms: Math.round(performance.now() - start),
+ error: err instanceof Error ? err.message : '探测失败',
+ };
+ }
+}
+
+export async function POST(req: Request) {
+ const guarded = guardRequest(req);
+ if (guarded) return guarded;
+
+ let body: { urls?: unknown };
+ try {
+ body = (await req.json()) as { urls?: unknown };
+ } catch {
+ return jsonError('无效请求体', 400);
+ }
+ if (!Array.isArray(body.urls)) return jsonError('urls 必须为字符串数组', 400);
+
+ const urls = [...new Set(
+ body.urls.filter((u): u is string => typeof u === 'string' && /^https?:\/\//.test(u))
+ )].slice(0, MAX_URLS);
+ if (urls.length === 0) return NextResponse.json({ results: [] });
+
+ // 简单并发池:固定 worker 数从游标取任务
+ const outcomes = new Map<string, ProbeOutcome>();
+ let cursor = 0;
+ const worker = async () => {
+ while (cursor < urls.length) {
+ const url = urls[cursor++];
+ outcomes.set(url, await probeOne(url));
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, urls.length) }, worker));
+
+ return NextResponse.json(
+ { results: urls.map((u) => outcomes.get(u)!) },
+ { headers: { 'Cache-Control': 'no-store' } }
+ );
+}
diff --git a/src/app/api/live/stream/[url]/route.ts b/src/app/api/live/stream/[url]/route.ts
new file mode 100644
index 0000000..1df3241
--- /dev/null
+++ b/src/app/api/live/stream/[url]/route.ts
@@ -0,0 +1,147 @@
+import { NextResponse } from 'next/server';
+import { guardRequest, jsonError } from '@/lib/api-guard';
+import { checkUpstreamAllowed, type UpstreamVerdict } from '@/lib/ssrf';
+import { rewriteM3u8 } from '@/lib/m3u8';
+
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+/**
+ * 直播流专用长连接代理(不复用 /api/proxy):
+ *
+ * /api/proxy 的 AbortSignal.timeout(TIMEOUT_MS) 作用于整个响应流,
+ * 8 秒后即切断长连接——对 HTTP-FLV(单一无限长连接)是致命的。
+ * 本路由改为「仅对响应头等待设超时」:fetch 拿到响应头后立即清除计时器,
+ * 之后 body 无限时长流式透传,直到客户端断开。
+ *
+ * - 不重试(重试对直播无意义);
+ * - m3u8 manifest 仍需重写(变体/分片地址改指本路由),FLV 等纯透传;
+ * - 每一跳都强制 SSRF 校验(不信任解析阶段的校验结果);
+ * - 部署者可设 LIVE_ALLOW_PRIVATE=1 显式放行内网自建源(默认拒绝)。
+ */
+
+const HEADER_TIMEOUT_MS = 15_000;
+const LIVE_PREFIX = '/api/live/stream/';
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+const MAX_REDIRECT_HOPS = 5;
+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 流不再受限。手动逐跳跟随重定向,
+ * 每一跳重新执行 SSRF 校验(302 跳内网是经典绕过手法)。
+ */
+async function fetchLiveUpstream(
+ targetUrl: string,
+ headers: Record<string, string>,
+ controller: AbortController
+): Promise<Response> {
+ let current = targetUrl;
+ for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop++) {
+ const verdict = await checkStreamAllowed(current);
+ if (!verdict.ok) throw new Error(`跳转目标被拒绝: ${verdict.reason}`);
+
+ const timer = setTimeout(() => controller.abort(), HEADER_TIMEOUT_MS);
+ let res: Response;
+ try {
+ res = await fetch(current, {
+ headers,
+ redirect: 'manual',
+ signal: controller.signal,
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+
+ if (!REDIRECT_STATUSES.has(res.status)) return res;
+ const location = res.headers.get('location');
+ if (!location) return res;
+ current = new URL(location, current).href;
+ }
+ throw new Error('重定向次数过多');
+}
+
+export async function GET(req: Request, ctx: { params: Promise<{ url: string }> }) {
+ const { url: encodedUrl } = await ctx.params;
+ const targetUrl = (() => {
+ try { return decodeURIComponent(encodedUrl); } catch { return encodedUrl; }
+ })();
+
+ const guarded = guardRequest(req);
+ if (guarded) return guarded;
+
+ const verdict = await checkStreamAllowed(targetUrl);
+ if (!verdict.ok) return jsonError(verdict.reason, 403);
+
+ const controller = new AbortController();
+ // 客户端断开(切台/关页)时终止上游连接,防止连接泄漏
+ const onClientAbort = () => controller.abort();
+ req.signal.addEventListener('abort', onClientAbort, { once: true });
+
+ const headers: Record<string, string> = { 'User-Agent': UA, Accept: '*/*' };
+
+ let response: Response;
+ try {
+ response = await fetchLiveUpstream(targetUrl, headers, controller);
+ } catch (err) {
+ return jsonError(
+ `直播流连接失败: ${err instanceof Error ? err.message : '未知错误'}`,
+ 502
+ );
+ }
+
+ if (!response.ok && response.body) {
+ // 非直播正常响应(403/404 等):丢弃 body 连接
+ try { await response.body.cancel(); } catch { /* 忽略 */ }
+ return jsonError(`直播流上游返回 ${response.status}`, 502);
+ }
+
+ const contentType = response.headers.get('content-type') || '';
+ const isM3u8 =
+ contentType.includes('mpegurl') || contentType.includes('x-mpegurl') ||
+ targetUrl.toLowerCase().split('?')[0].endsWith('.m3u8');
+
+ // HLS manifest:重写变体/分片地址指向本路由,保证后续请求同源同鉴权
+ if (isM3u8) {
+ const text = await response.text();
+ return new NextResponse(rewriteM3u8(text, targetUrl, 0, LIVE_PREFIX), {
+ status: response.status,
+ headers: {
+ 'Content-Type': 'application/vnd.apple.mpegurl',
+ 'Cache-Control': 'no-store',
+ },
+ });
+ }
+
+ // FLV / TS 等流媒体:纯流式透传(禁止缓冲与缓存)
+ const outHeaders = new Headers();
+ const ct = contentType || 'video/mp2t';
+ outHeaders.set('Content-Type', ct);
+ outHeaders.set('Cache-Control', 'no-store, no-transform');
+ outHeaders.set('X-Accel-Buffering', 'no');
+
+ return new NextResponse(response.body, {
+ status: response.status,
+ headers: outHeaders,
+ });
+}
diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.ts
index 6173632..99aedc0 100644
--- a/src/app/api/status/route.ts
+++ b/src/app/api/status/route.ts
@@ -1,10 +1,11 @@
import { NextResponse } from 'next/server';
import { isPasswordConfigured, sessionFromCookieHeader } from '@/lib/auth';
import { getEnvSources } from '@/lib/env-sources';
+import { getEnvLiveSources } from '@/lib/env-live-sources';
export const runtime = 'nodejs';
-/** 站点状态:客户端据此决定是否弹出登录框 / 提示管理员配置密码,并获取预置采集站 */
+/** 站点状态:客户端据此决定是否弹出登录框 / 提示管理员配置密码,并获取预置采集站与预置直播源 */
export async function GET(req: Request) {
const passwordRequired = isPasswordConfigured();
const verified = passwordRequired && sessionFromCookieHeader(req.headers.get('cookie'));
@@ -15,5 +16,7 @@ export async function GET(req: Request) {
version: process.env.APP_VERSION || 'dev',
// 部署者通过 DEFAULT_SOURCES 预置的采集站
defaultSources: getEnvSources(),
+ // 部署者通过 DEFAULT_LIVE_SOURCES 预置的直播源(M3U 订阅)
+ defaultLiveSources: getEnvLiveSources(),
});
}
diff --git a/src/app/globals.css b/src/app/globals.css
index 9ba6ee5..065e8b7 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -96,3 +96,16 @@ body {
-webkit-text-fill-color: transparent;
color: transparent;
}
+
+/* LIVE 呼吸红点(直播页标识) */
+.live-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 9999px;
+ background: #ef4444;
+ animation: live-breathe 2s ease-in-out infinite;
+}
+@keyframes live-breathe {
+ 0%, 100% { opacity: 1; box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.5); }
+ 50% { opacity: 0.55; box-shadow: 0 0 0 4px rgba(239, 68, 68, 0); }
+}
diff --git a/src/app/live/page.tsx b/src/app/live/page.tsx
new file mode 100644
index 0000000..2e4a465
--- /dev/null
+++ b/src/app/live/page.tsx
@@ -0,0 +1,253 @@
+'use client';
+
+import { Suspense, useCallback, useMemo, useState } from 'react';
+import { useRouter, useSearchParams } from 'next/navigation';
+import { useQuery } from '@tanstack/react-query';
+import { api } from '@/lib/client-api';
+import { Header } from '@/components/header';
+import { LivePlayer } from '@/components/live-player';
+import { LiveChannelList, type LiveChannelItem } from '@/components/live-channel-list';
+import { LiveEpgPanel } from '@/components/live-epg-panel';
+import { useAuth } from '@/components/auth';
+import { allLiveSources, useAppStore } from '@/lib/store';
+import { buildImageUrl, cn } from '@/lib/utils';
+
+/**
+ * 直播页:左侧播放器 + 频道信息 + 节目单;右侧频道侧栏。
+ * 状态由 URL 驱动(?url=&name=&group=&tvgId=&epg=),支持频道深链与刷新保持。
+ */
+export default function LivePage() {
+ return (
+ <Suspense>
+ <LiveContent />
+ </Suspense>
+ );
+}
+
+function LiveContent() {
+ const searchParams = useSearchParams();
+ const router = useRouter();
+ const store = useAppStore();
+ const imageProxyMode = useAppStore((s) => s.imageProxyMode);
+ const customImageProxy = useAppStore((s) => s.customImageProxy);
+ const { verified } = useAuth();
+ const [copied, setCopied] = useState(false);
+
+ const sources = useMemo(() => allLiveSources(store), [store]);
+
+ // 聚合全部直播源的 M3U 解析结果(单源失败不影响整体)
+ const playlistsQuery = useQuery({
+ queryKey: ['livePlaylists', sources.map((s) => s.url).join('|')],
+ queryFn: async () => {
+ const results = await Promise.allSettled(sources.map((s) => api.livePlaylist(s.url)));
+ return sources.map((source, i) => ({ source, result: results[i] }));
+ },
+ enabled: verified && sources.length > 0,
+ staleTime: 10 * 60_000,
+ });
+
+ const { channels, groups, failedCount } = useMemo(() => {
+ const list: LiveChannelItem[] = [];
+ const seen = new Set<string>();
+ let failed = 0;
+ for (const { source, result } of playlistsQuery.data ?? []) {
+ if (result.status !== 'fulfilled') {
+ failed++;
+ continue;
+ }
+ for (const c of result.value.channels) {
+ if (seen.has(c.url)) continue;
+ seen.add(c.url);
+ list.push({ ...c, epg: source.epg });
+ }
+ }
+ const groups = [...new Set(list.map((c) => c.group).filter((g): g is string => Boolean(g)))].sort(
+ (a, b) => a.localeCompare(b, 'zh')
+ );
+ return { channels: list, groups, failedCount: failed };
+ }, [playlistsQuery.data]);
+
+ // 当前频道:优先取列表内完整对象(含台标),否则由 URL 参数重建
+ const currentUrl = searchParams.get('url') || '';
+ const currentChannel = useMemo(() => {
+ const found = channels.find((c) => c.url === currentUrl);
+ if (found) return found;
+ if (!currentUrl) return undefined;
+ return {
+ id: searchParams.get('tvgId') || currentUrl,
+ url: currentUrl,
+ name: searchParams.get('name') || '未知频道',
+ group: searchParams.get('group') || undefined,
+ tvgId: searchParams.get('tvgId') || undefined,
+ epg: searchParams.get('epg') || undefined,
+ } as LiveChannelItem;
+ }, [channels, currentUrl, searchParams]);
+
+ const selectChannel = useCallback(
+ (c: LiveChannelItem) => {
+ const sp = new URLSearchParams({ url: c.url, name: c.name });
+ if (c.group) sp.set('group', c.group);
+ if (c.tvgId) sp.set('tvgId', c.tvgId);
+ if (c.epg) sp.set('epg', c.epg);
+ router.replace(`/live?${sp.toString()}`, { scroll: false });
+ store.addLiveRecent({
+ url: c.url,
+ name: c.name,
+ logo: c.logo,
+ group: c.group,
+ tvgId: c.tvgId,
+ epg: c.epg,
+ });
+ },
+ [router, store]
+ );
+
+ if (!verified) {
+ return (
+ <div className="min-h-screen flex flex-col">
+ <Header />
+ <div className="flex-1 flex items-center justify-center">
+ <p className="text-faint text-sm">等待访问验证...</p>
+ </div>
+ </div>
+ );
+ }
+
+ const logo = buildImageUrl(currentChannel?.logo, imageProxyMode, customImageProxy);
+
+ return (
+ <div className="min-h-screen flex flex-col">
+ <Header showSearch />
+ <main className="flex-1 max-w-7xl w-full mx-auto px-4 py-4">
+ <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-4">
+ {/* 主栏:播放器 + 信息条 + 节目单 */}
+ <div className="min-w-0">
+ <div className="aspect-video bg-black rounded-lg overflow-hidden">
+ {currentUrl ? (
+ <LivePlayer url={currentUrl} title={currentChannel?.name || '直播'} />
+ ) : (
+ <div className="w-full h-full flex flex-col items-center justify-center gap-2 bg-black">
+ <span className="live-dot" />
+ <p className="text-white/60 text-sm">
+ {sources.length === 0
+ ? '请先在设置中添加直播源(M3U 订阅)'
+ : playlistsQuery.isLoading
+ ? '频道列表加载中...'
+ : '从右侧选择一个频道开始观看'}
+ </p>
+ </div>
+ )}
+ </div>
+
+ {/* 频道信息条 */}
+ {currentChannel && (
+ <div className="bg-surface-raised border border-line rounded-lg p-3 mt-3 flex items-center gap-3">
+ <div className="w-10 h-10 shrink-0 rounded bg-chip flex items-center justify-center overflow-hidden">
+ {logo ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={logo} alt="" className="w-full h-full object-contain" />
+ ) : (
+ <span className="text-xs text-faint">{currentChannel.name.slice(0, 1)}</span>
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="live-dot shrink-0" />
+ <h1 className="text-sm font-semibold text-content truncate">{currentChannel.name}</h1>
+ {currentChannel.group && (
+ <span className="tag bg-chip text-faint shrink-0">{currentChannel.group}</span>
+ )}
+ </div>
+ <p className="text-xs text-faint truncate mt-0.5">{currentChannel.url}</p>
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ <button
+ className={cn(
+ 'rounded-md p-2 transition-colors',
+ store.liveFavorites.includes(currentChannel.url)
+ ? 'text-amber-400'
+ : 'text-muted hover:text-amber-400 hover:bg-hover'
+ )}
+ aria-label="收藏"
+ title="收藏"
+ onClick={() => store.toggleLiveFavorite(currentChannel.url)}
+ >
+ <svg
+ className="w-4 h-4"
+ fill={store.liveFavorites.includes(currentChannel.url) ? 'currentColor' : 'none'}
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.196-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.783-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"
+ />
+ </svg>
+ </button>
+ <button
+ className="rounded-md p-2 text-muted hover:text-accent hover:bg-hover transition-colors"
+ aria-label="复制播放地址"
+ title="复制播放地址"
+ onClick={async () => {
+ try {
+ await navigator.clipboard.writeText(currentChannel.url);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ } catch { /* 忽略 */ }
+ }}
+ >
+ {copied ? (
+ <span className="text-[10px] text-green-500">已复制</span>
+ ) : (
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3"
+ />
+ </svg>
+ )}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* 节目单 */}
+ {currentChannel && (
+ <section className="bg-surface-raised border border-line rounded-lg p-3 mt-3">
+ <h2 className="text-sm font-semibold text-content mb-2.5">节目单</h2>
+ <LiveEpgPanel epgUrl={currentChannel.epg} tvgId={currentChannel.tvgId} />
+ </section>
+ )}
+ </div>
+
+ {/* 侧栏:频道列表 */}
+ <aside className="bg-surface-raised border border-line rounded-lg flex flex-col lg:sticky lg:top-20 h-[70vh] lg:h-[calc(100vh-6.5rem)] overflow-hidden">
+ {playlistsQuery.isLoading && channels.length === 0 ? (
+ <div className="flex-1 flex items-center justify-center">
+ <div className="h-9 w-9 rounded-full border-4 border-line border-t-accent animate-spin" />
+ </div>
+ ) : (
+ <LiveChannelList
+ channels={channels}
+ groups={groups}
+ currentUrl={currentUrl}
+ onSelect={selectChannel}
+ />
+ )}
+ {(failedCount > 0 || sources.length === 0) && (
+ <p className="text-[10px] text-faint px-3 py-1.5 border-t border-line shrink-0">
+ {sources.length === 0
+ ? '暂无直播源,请在设置 → 直播源中添加'
+ : `${failedCount} 个订阅拉取失败(共 ${sources.length} 个)`}
+ </p>
+ )}
+ </aside>
+ </div>
+ </main>
+ </div>
+ );
+}
diff --git a/src/components/header.tsx b/src/components/header.tsx
index e97791f..376d7a8 100644
--- a/src/components/header.tsx
+++ b/src/components/header.tsx
@@ -46,6 +46,9 @@ export function Header({ showSearch = false }: { showSearch?: boolean }) {
<div className="flex-1 sm:hidden" />
<nav className="flex items-center gap-1 ml-auto">
+ <HeaderLink href="/live" active={pathname === '/live'}>
+ 直播
+ </HeaderLink>
<HeaderLink href="/about" active={pathname === '/about'}>
关于
</HeaderLink>
diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsx
new file mode 100644
index 0000000..a37fd7d
--- /dev/null
+++ b/src/components/live-channel-list.tsx
@@ -0,0 +1,335 @@
+'use client';
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { buildImageUrl, cn } from '@/lib/utils';
+import { useAppStore } from '@/lib/store';
+import { useLiveProbe, type ProbeResult } from './use-live-probe';
+import type { LiveChannel } from '@/lib/types';
+
+/**
+ * 直播频道侧栏:全部/收藏/最近三个视图 + 分组横向标签条 + 关键字搜索。
+ * 支持批量测活:频道名前显示可达性状态点,可筛选「仅可用」。
+ * 大列表渐进渲染(每次 300,点「加载更多」递增),避免数千频道一次性 DOM。
+ */
+
+const PAGE_SIZE = 300;
+
+export interface LiveChannelItem extends LiveChannel {
+ /** 来源订阅的 EPG 地址(用于节目单查询) */
+ epg?: string;
+}
+
+interface ChannelListProps {
+ channels: LiveChannelItem[];
+ groups: string[];
+ currentUrl: string;
+ onSelect: (channel: LiveChannelItem) => void;
+}
+
+type View = 'all' | 'fav' | 'recent';
+
+export function LiveChannelList({ channels, groups, currentUrl, onSelect }: ChannelListProps) {
+ const store = useAppStore();
+ const imageProxyMode = useAppStore((s) => s.imageProxyMode);
+ const customImageProxy = useAppStore((s) => s.customImageProxy);
+ const [view, setView] = useState<View>('all');
+ const [group, setGroup] = useState<string>('');
+ const [keyword, setKeyword] = useState('');
+ const [limit, setLimit] = useState(PAGE_SIZE);
+ const [onlyAlive, setOnlyAlive] = useState(false);
+ const { results: probeResults, progress: probeProgress, probe, clear: clearProbe, isProbing } = useLiveProbe();
+
+ const favSet = useMemo(() => new Set(store.liveFavorites), [store.liveFavorites]);
+
+ const filtered = useMemo(() => {
+ const kw = keyword.trim().toLowerCase();
+ let list: LiveChannelItem[];
+ if (view === 'fav') {
+ list = channels.filter((c) => favSet.has(c.url));
+ } else if (view === 'recent') {
+ // 按最近观看时间倒序
+ list = store.liveRecent
+ .map((r) => channels.find((c) => c.url === r.url))
+ .filter((c): c is LiveChannelItem => Boolean(c));
+ } else {
+ list = channels;
+ }
+ if (view !== 'recent') {
+ if (group) list = list.filter((c) => c.group === group);
+ }
+ if (kw) {
+ list = list.filter(
+ (c) => c.name.toLowerCase().includes(kw) || (c.tvgId || '').toLowerCase().includes(kw)
+ );
+ }
+ if (onlyAlive && probeResults.size > 0) {
+ list = list.filter((c) => probeResults.get(c.url)?.ok === true);
+ }
+ return list;
+ }, [channels, favSet, store.liveRecent, view, group, keyword, onlyAlive, probeResults]);
+
+ const aliveCount = useMemo(
+ () => (probeResults.size > 0 ? filtered.filter((c) => probeResults.get(c.url)?.ok === true).length : 0),
+ [filtered, probeResults]
+ );
+
+ // 切换视图/分组/搜索时重置渐进渲染
+ useEffect(() => setLimit(PAGE_SIZE), [view, group, keyword]);
+
+ const visible = filtered.slice(0, limit);
+
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ {/* 视图 tab */}
+ <div className="flex items-center gap-1 px-3 pt-2.5 pb-2 border-b border-line shrink-0">
+ {(
+ [
+ ['all', `全部${channels.length ? ` ${channels.length}` : ''}`],
+ ['fav', `收藏${store.liveFavorites.length ? ` ${store.liveFavorites.length}` : ''}`],
+ ['recent', '最近'],
+ ] as [View, string][]
+ ).map(([v, label]) => (
+ <button
+ key={v}
+ className={cn(
+ 'px-2.5 py-1 rounded-md text-xs transition-colors',
+ view === v ? 'bg-accent/10 text-accent font-medium' : 'text-muted hover:text-content hover:bg-hover'
+ )}
+ onClick={() => setView(v)}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {/* 搜索框 */}
+ <div className="px-3 py-2 shrink-0">
+ <input
+ className="input w-full !py-1.5 text-xs"
+ placeholder="搜索频道名称或 tvg-id..."
+ value={keyword}
+ maxLength={60}
+ onChange={(e) => setKeyword(e.target.value)}
+ />
+ </div>
+
+ {/* 测活工具条 */}
+ <div className="flex items-center gap-1.5 px-3 pb-2 shrink-0 flex-wrap">
+ <button
+ className="btn-ghost !py-1 !px-2 text-xs"
+ disabled={isProbing || filtered.length === 0}
+ onClick={() => void probe(filtered)}
+ title="轻量探测当前列表频道的可达性与延迟(每批 10 条并发探测)"
+ >
+ ⚡ 测活
+ </button>
+ {isProbing && probeProgress && (
+ <span className="text-[10px] text-faint">
+ 探测中 {probeProgress.done}/{probeProgress.total}
+ </span>
+ )}
+ {probeResults.size > 0 && !isProbing && (
+ <>
+ <button
+ className={cn(
+ 'shrink-0 px-2 py-0.5 rounded-full text-[10px] whitespace-nowrap transition-colors border',
+ onlyAlive
+ ? 'bg-accent text-white border-accent'
+ : 'bg-chip text-muted border-line hover:text-content hover:bg-hover'
+ )}
+ onClick={() => setOnlyAlive((v) => !v)}
+ >
+ 仅可用 {aliveCount}
+ </button>
+ <button
+ className="text-[10px] text-faint hover:text-content transition-colors"
+ onClick={() => {
+ clearProbe();
+ setOnlyAlive(false);
+ }}
+ >
+ 清除结果
+ </button>
+ </>
+ )}
+ </div>
+
+ {/* 分组标签条(横向可滑动) */}
+ {view === 'all' && groups.length > 0 && (
+ <div className="px-3 pb-2 shrink-0">
+ <div className="flex gap-1.5 overflow-x-auto scrollbar-thin pb-1">
+ <GroupChip active={!group} label="全部分组" onClick={() => setGroup('')} />
+ {groups.map((g) => (
+ <GroupChip key={g} active={group === g} label={g} onClick={() => setGroup(g === group ? '' : g)} />
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* 频道列表 */}
+ <div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-2 pb-2">
+ {visible.length === 0 ? (
+ <p className="text-center text-xs text-faint py-10">
+ {view === 'fav'
+ ? '暂无收藏频道,点击频道右侧星标即可收藏'
+ : view === 'recent'
+ ? '暂无观看记录'
+ : channels.length === 0
+ ? '暂无频道,请先在设置中添加直播源'
+ : onlyAlive && probeResults.size > 0
+ ? '没有探测到可用频道,可清除结果后重试'
+ : '没有匹配的频道'}
+ </p>
+ ) : (
+ <ul className="space-y-1">
+ {visible.map((c) => (
+ <ChannelRow
+ key={c.url}
+ channel={c}
+ active={c.url === currentUrl}
+ isFav={favSet.has(c.url)}
+ probe={probeResults.get(c.url)}
+ logoUrl={buildImageUrl(c.logo, imageProxyMode, customImageProxy)}
+ onSelect={() => onSelect(c)}
+ />
+ ))}
+ </ul>
+ )}
+ {filtered.length > limit && (
+ <button
+ className="btn-ghost w-full mt-2 !py-1.5 text-xs"
+ onClick={() => setLimit((l) => l + PAGE_SIZE)}
+ >
+ 加载更多(剩余 {filtered.length - limit})
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function GroupChip({ label, active, onClick }: { label: string; active: boolean; onClick: () => void }) {
+ return (
+ <button
+ className={cn(
+ 'shrink-0 px-2.5 py-1 rounded-full text-xs whitespace-nowrap transition-colors border',
+ active
+ ? 'bg-accent text-white border-accent'
+ : 'bg-chip text-muted border-line hover:text-content hover:bg-hover'
+ )}
+ onClick={onClick}
+ >
+ {label}
+ </button>
+ );
+}
+
+function ChannelRow({
+ channel,
+ active,
+ isFav,
+ probe,
+ logoUrl,
+ onSelect,
+}: {
+ channel: LiveChannelItem;
+ active: boolean;
+ isFav: boolean;
+ probe?: ProbeResult;
+ logoUrl?: string;
+ onSelect: () => void;
+}) {
+ const store = useAppStore();
+ const ref = useRef<HTMLLIElement>(null);
+
+ // 当前播放项自动滚入视区
+ useEffect(() => {
+ if (active) ref.current?.scrollIntoView({ block: 'nearest' });
+ }, [active]);
+
+ return (
+ <li ref={ref}>
+ <div
+ role="button"
+ tabIndex={0}
+ className={cn(
+ 'group flex items-center gap-2.5 px-2 py-2 rounded-md cursor-pointer transition-colors relative',
+ active ? 'bg-accent/10' : 'hover:bg-hover'
+ )}
+ onClick={onSelect}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onSelect();
+ }
+ }}
+ >
+ {/* 当前播放高亮竖条 */}
+ <span
+ className={cn(
+ 'absolute left-0 top-1/2 -translate-y-1/2 w-[3px] rounded-full bg-accent transition-all duration-200',
+ active ? 'h-5 opacity-100' : 'h-0 opacity-0'
+ )}
+ />
+ {/* 台标 */}
+ <div className="w-7 h-7 shrink-0 rounded bg-chip flex items-center justify-center overflow-hidden">
+ {logoUrl ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={logoUrl}
+ alt=""
+ className="w-full h-full object-contain"
+ loading="lazy"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.visibility = 'hidden';
+ }}
+ />
+ ) : (
+ <span className="text-[10px] text-faint">{channel.name.slice(0, 1)}</span>
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-1.5 min-w-0">
+ {probe && (
+ <span
+ className={cn(
+ 'w-1.5 h-1.5 rounded-full shrink-0',
+ probe.ok ? 'bg-green-500' : 'bg-red-400'
+ )}
+ title={probe.ok ? `可用 · ${probe.ms}ms` : probe.error || '不可用'}
+ />
+ )}
+ <span className={cn('text-xs truncate', active ? 'text-accent font-medium' : 'text-content')}>
+ {channel.name}
+ </span>
+ </div>
+ {channel.group && (
+ <div className="text-[10px] text-faint truncate">{channel.group}</div>
+ )}
+ </div>
+ {/* 收藏星标 */}
+ <button
+ className={cn(
+ 'shrink-0 p-1 rounded transition-transform active:scale-125',
+ isFav ? 'text-amber-400' : 'text-faint/50 opacity-0 group-hover:opacity-100 hover:text-amber-400'
+ )}
+ aria-label={isFav ? '取消收藏' : '收藏'}
+ title={isFav ? '取消收藏' : '收藏'}
+ onClick={(e) => {
+ e.stopPropagation();
+ store.toggleLiveFavorite(channel.url);
+ }}
+ >
+ <svg className="w-3.5 h-3.5" fill={isFav ? 'currentColor' : 'none'} stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.196-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.783-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"
+ />
+ </svg>
+ </button>
+ </div>
+ </li>
+ );
+}
diff --git a/src/components/live-epg-panel.tsx b/src/components/live-epg-panel.tsx
new file mode 100644
index 0000000..1a2e8ba
--- /dev/null
+++ b/src/components/live-epg-panel.tsx
@@ -0,0 +1,132 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { api } from '@/lib/client-api';
+import { cn } from '@/lib/utils';
+import type { EpgProgram } from '@/lib/types';
+
+/**
+ * EPG 节目单面板:当前节目(含播放进度条)+ 接下来节目列表 + 简介展开。
+ * 仅在频道带 tvg-id 且来源订阅配置了 EPG 地址时查询;无数据优雅降级。
+ */
+
+function fmtTime(ms: number): string {
+ const d = new Date(ms);
+ const hh = String(d.getHours()).padStart(2, '0');
+ const mm = String(d.getMinutes()).padStart(2, '0');
+ return `${hh}:${mm}`;
+}
+
+export function LiveEpgPanel({ epgUrl, tvgId }: { epgUrl?: string; tvgId?: string }) {
+ const [now, setNow] = useState(() => Date.now());
+ const [expandedDesc, setExpandedDesc] = useState(false);
+
+ // 30s 心跳刷新进度
+ useEffect(() => {
+ const timer = setInterval(() => setNow(Date.now()), 30_000);
+ return () => clearInterval(timer);
+ }, []);
+
+ const enabled = Boolean(epgUrl && tvgId);
+ const epgQuery = useQuery({
+ queryKey: ['liveEpg', epgUrl, tvgId],
+ queryFn: ({ signal }) => api.liveEpg(epgUrl!, tvgId!, false, signal),
+ enabled,
+ staleTime: 10 * 60_000,
+ });
+
+ if (!enabled) {
+ return (
+ <p className="text-center text-xs text-faint py-4">
+ 该频道未配置节目单数据(需来源订阅提供 EPG 地址且频道带 tvg-id)
+ </p>
+ );
+ }
+
+ if (epgQuery.isLoading) {
+ return (
+ <div className="flex items-center justify-center py-6">
+ <div className="h-5 w-5 rounded-full border-[3px] border-line border-t-accent animate-spin" />
+ </div>
+ );
+ }
+
+ if (epgQuery.isError) {
+ return (
+ <div className="text-center py-4">
+ <p className="text-xs text-faint mb-1.5">节目单加载失败</p>
+ <button className="btn-ghost !py-1 text-xs" onClick={() => epgQuery.refetch()}>
+ 重试
+ </button>
+ </div>
+ );
+ }
+
+ const data = epgQuery.data;
+ const current = data?.current;
+ const upcoming: EpgProgram[] = (data?.programs ?? []).filter((p) => p.start > now).slice(0, 5);
+
+ const progress = current ? Math.min(100, Math.max(0, ((now - current.start) / (current.stop - current.start)) * 100)) : 0;
+
+ return (
+ <div className="space-y-3">
+ {current ? (
+ <div className="bg-card border border-line rounded-lg p-3">
+ <div className="flex items-center gap-2 mb-1.5">
+ <span className="text-[10px] font-semibold text-red-500 bg-red-500/10 px-1.5 py-0.5 rounded">
+ 正在播出
+ </span>
+ <span className="text-[10px] text-faint">
+ {fmtTime(current.start)} - {fmtTime(current.stop)}
+ </span>
+ </div>
+ <button
+ className="text-sm font-medium text-content text-left w-full text-left"
+ onClick={() => setExpandedDesc((v) => !v)}
+ >
+ {current.title}
+ </button>
+ {current.desc && expandedDesc && (
+ <p className="text-xs text-muted mt-1.5 leading-relaxed animate-fade-in">{current.desc}</p>
+ )}
+ {/* 已播进度条 */}
+ <div className="mt-2.5 h-1 rounded-full bg-chip overflow-hidden">
+ <div
+ className="h-full bg-accent rounded-full transition-all duration-500"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ <div className="flex justify-between text-[10px] text-faint mt-1">
+ <span>{fmtTime(current.start)}</span>
+ <span>{Math.round(progress)}%</span>
+ <span>{fmtTime(current.stop)}</span>
+ </div>
+ </div>
+ ) : (
+ <p className="text-xs text-faint text-center py-2">当前时段暂无节目数据</p>
+ )}
+
+ {upcoming.length > 0 && (
+ <div>
+ <h4 className="text-xs font-semibold text-content mb-1.5">接下来</h4>
+ <ul className="space-y-1">
+ {upcoming.map((p) => (
+ <li
+ key={`${p.start}-${p.title}`}
+ className={cn(
+ 'flex items-center gap-2 text-xs px-2 py-1.5 rounded-md',
+ 'text-muted hover:bg-hover transition-colors'
+ )}
+ title={p.desc || p.title}
+ >
+ <span className="text-faint tabular-nums shrink-0">{fmtTime(p.start)}</span>
+ <span className="text-content truncate">{p.title}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/live-player.tsx b/src/components/live-player.tsx
new file mode 100644
index 0000000..ede107b
--- /dev/null
+++ b/src/components/live-player.tsx
@@ -0,0 +1,268 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import Artplayer from 'artplayer';
+import Hls, { type HlsConfig } from 'hls.js';
+
+/**
+ * 直播播放器:与点播 player-shell 完全独立。
+ * - 协议分发:.m3u8 → hls.js(直播参数);.flv → mpegts.js(动态加载,按需 ~150KB);
+ * - 直连失败自动切换到 /api/live/stream/ 代理通道重试一次;
+ * - 直播态 UI:无进度条、无倍速、无截图、无连播。
+ */
+
+const STREAM_PROXY_PREFIX = '/api/live/stream/';
+
+export function isFlvUrl(url: string): boolean {
+ return /\.flv(\?|$)/i.test(url);
+}
+
+function proxyUrl(url: string): string {
+ return STREAM_PROXY_PREFIX + encodeURIComponent(url);
+}
+
+interface LivePlayerProps {
+ /** 上游直播流地址(直连优先,失败自动走代理) */
+ url: string;
+ title: string;
+}
+
+export function LivePlayer({ url, title }: LivePlayerProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const artRef = useRef<any>(null);
+ const hlsRef = useRef<Hls | null>(null);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const mpegtsRef = useRef<any>(null);
+ const [error, setError] = useState('');
+ const [hint, setHint] = useState('');
+ const [loading, setLoading] = useState(true);
+ const hintTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const showHint = (text: string) => {
+ setHint(text);
+ if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
+ hintTimerRef.current = setTimeout(() => setHint(''), 2500);
+ };
+
+ useEffect(() => {
+ if (!containerRef.current || !url) return;
+ setError('');
+ setLoading(true);
+
+ let playbackStarted = false;
+ let disposed = false;
+ let destroyed = false;
+
+ const cleanupEngines = () => {
+ hlsRef.current?.destroy();
+ hlsRef.current = null;
+ if (mpegtsRef.current) {
+ try { mpegtsRef.current.pause(); } catch { /* 忽略 */ }
+ try { mpegtsRef.current.destroy(); } catch { /* 忽略 */ }
+ mpegtsRef.current = null;
+ }
+ };
+
+ /** HLS 直播参数:小缓冲、快速追帧;与点播(大缓冲、进度恢复)刻意区分 */
+ const setupHls = (video: HTMLVideoElement, mediaUrl: string, allowProxyFallback: boolean) => {
+ cleanupEngines();
+ const hlsConfig: Partial<HlsConfig> = {
+ debug: false,
+ enableWorker: true,
+ liveSyncDurationCount: 3,
+ lowLatencyMode: false,
+ backBufferLength: 30,
+ maxBufferLength: 20,
+ maxMaxBufferLength: 40,
+ manifestLoadingMaxRetry: 2,
+ manifestLoadingRetryDelay: 1000,
+ fragLoadingMaxRetry: 4,
+ fragLoadingRetryDelay: 800,
+ };
+ const hls = new Hls(hlsConfig);
+ hlsRef.current = hls;
+ hls.loadSource(mediaUrl);
+ hls.attachMedia(video);
+ hls.on(Hls.Events.MANIFEST_PARSED, () => {
+ video.play().catch(() => {});
+ });
+ hls.on(Hls.Events.ERROR, (_evt, data) => {
+ if (disposed || destroyed) return;
+ if (data.fatal && !playbackStarted) {
+ if (
+ allowProxyFallback &&
+ !mediaUrl.startsWith(STREAM_PROXY_PREFIX) &&
+ (data.details === 'manifestLoadError' || data.type === Hls.ErrorTypes.NETWORK_ERROR)
+ ) {
+ showHint('直连失败,改用代理重试...');
+ // 直播 manifest 重写需要本站前缀,交给代理通道
+ setupHls(video, proxyUrl(url), false);
+ return;
+ }
+ if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
+ hls.recoverMediaError();
+ return;
+ }
+ setError('直播流加载失败,可能该频道已失效,请尝试其他频道');
+ } else if (data.fatal && data.type === Hls.ErrorTypes.NETWORK_ERROR) {
+ // 播放中网络抖动:尝试恢复拉流
+ hls.startLoad();
+ }
+ });
+ };
+
+ const setupFlv = async (
+ video: HTMLVideoElement,
+ mediaUrl: string,
+ allowProxyFallback: boolean
+ ) => {
+ cleanupEngines();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ let Mpegts: any;
+ try {
+ Mpegts = (await import('mpegts.js')).default;
+ } catch {
+ setError('FLV 播放模块加载失败,请检查网络后重试');
+ return;
+ }
+ if (disposed || destroyed) return;
+ if (!Mpegts.getFeatureList().mseLivePlayback) {
+ setError('当前浏览器不支持 FLV 直播播放');
+ return;
+ }
+ const player = Mpegts.createPlayer(
+ {
+ type: 'flv',
+ isLive: true,
+ url: mediaUrl,
+ },
+ {
+ enableWorker: false,
+ enableStashBuffer: false,
+ stashInitialSize: 128,
+ liveBufferLatencyChasing: true,
+ lazyLoad: false,
+ }
+ );
+ mpegtsRef.current = player;
+ player.attachMediaElement(video);
+ player.load();
+ player.on(Mpegts.Events.ERROR, (errType: string) => {
+ if (disposed || destroyed) return;
+ if (!playbackStarted && allowProxyFallback && !mediaUrl.startsWith(STREAM_PROXY_PREFIX)) {
+ showHint('直连失败,改用代理重试...');
+ void setupFlv(video, proxyUrl(url), false);
+ return;
+ }
+ setError(`直播流加载失败(${errType}),请尝试其他频道`);
+ });
+ player.play().catch(() => {});
+ };
+
+ const art = new Artplayer({
+ container: containerRef.current,
+ url,
+ type: isFlvUrl(url) ? 'flv' : 'm3u8',
+ volume: 0.9,
+ autoplay: true,
+ // —— 直播态:关闭点播专属能力 ——
+ pip: true,
+ screenshot: false,
+ setting: false,
+ playbackRate: false,
+ aspectRatio: false,
+ fullscreen: true,
+ fullscreenWeb: true,
+ miniProgressBar: false,
+ hotkey: false,
+ mutex: true,
+ backdrop: true,
+ playsInline: true,
+ airplay: true,
+ theme: '#2563eb',
+ lang: navigator.language.toLowerCase().startsWith('zh') ? 'zh-cn' : 'en',
+ moreVideoAttr: { playsInline: true },
+ customType: {
+ m3u8: (video: HTMLVideoElement) => {
+ setupHls(video, url, true);
+ },
+ flv: (video: HTMLVideoElement) => {
+ void setupFlv(video, url, true);
+ },
+ },
+ });
+ artRef.current = art;
+ art.on('video:loadedmetadata', () => {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (art as any).title = title;
+ } catch { /* 忽略 */ }
+ });
+ art.on('video:playing', () => {
+ playbackStarted = true;
+ setLoading(false);
+ setError('');
+ });
+ art.on('video:error', () => {
+ // mpegts 走自身 ERROR 事件;这里兜底其它未知错误
+ if (!mpegtsRef.current) setError('视频播放失败,请尝试其他频道');
+ });
+ art.on('ready', () => {
+ // 直播隐藏进度条(ArtPlayer 无原生 isLive 开关)
+ try {
+ const progress = art.controls?.progress as HTMLElement | undefined;
+ if (progress) progress.style.display = 'none';
+ } catch { /* 忽略 */ }
+ });
+
+ // 15s 内未起播则提示
+ const startTimer = setTimeout(() => {
+ if (!playbackStarted && !disposed && !destroyed) {
+ setError('频道加载超时,可能该源已失效,请尝试其他频道');
+ }
+ }, 15000);
+
+ return () => {
+ disposed = true;
+ clearTimeout(startTimer);
+ if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
+ cleanupEngines();
+ art.destroy();
+ artRef.current = null;
+ destroyed = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [url]);
+
+ return (
+ <div className="relative w-full h-full">
+ <div ref={containerRef} className="w-full h-full" />
+ {/* LIVE 呼吸标识 */}
+ {!error && (
+ <div className="absolute top-3 right-3 flex items-center gap-1.5 bg-black/60 px-2 py-1 rounded-full pointer-events-none">
+ <span className="live-dot" />
+ <span className="text-[10px] font-semibold text-white tracking-wider">LIVE</span>
+ </div>
+ )}
+ {loading && !error && (
+ <div className="absolute inset-0 flex items-center justify-center bg-black/40 pointer-events-none">
+ <div className="h-9 w-9 rounded-full border-4 border-white/20 border-t-white animate-spin" />
+ </div>
+ )}
+ {error && (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/80">
+ <p className="text-red-400 text-sm px-4 text-center">{error}</p>
+ <button className="btn-ghost text-xs !bg-white/10 !text-white !border-white/20" onClick={() => location.reload()}>
+ 重新加载
+ </button>
+ </div>
+ )}
+ {hint && (
+ <div className="absolute top-4 left-1/2 -translate-x-1/2 bg-black/70 text-white text-sm px-3 py-1.5 rounded-full pointer-events-none animate-fade-in">
+ {hint}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/live-source-manager.tsx b/src/components/live-source-manager.tsx
new file mode 100644
index 0000000..b68c736
--- /dev/null
+++ b/src/components/live-source-manager.tsx
@@ -0,0 +1,176 @@
+'use client';
+
+import { useState } from 'react';
+import { useAppStore } from '@/lib/store';
+import { useToast } from './toast';
+import { api } from '@/lib/client-api';
+import { formatRelativeTime, validateSourceUrl, cn } from '@/lib/utils';
+
+/**
+ * 直播源管理(嵌入设置抽屉):M3U 订阅的添加 / 探活 / 同步 / 移除 / 导出,
+ * 以及部署者预置源展示。模式对齐采集站的 SourceSubscriptions。
+ */
+
+type TestState =
+ | { status: 'loading' }
+ | { status: 'done'; ok: boolean; ms?: number; count?: number; error?: string };
+
+export function LiveSourceManager() {
+ const store = useAppStore();
+ const { toast } = useToast();
+ const [name, setName] = useState('');
+ const [subUrl, setSubUrl] = useState('');
+ const [epg, setEpg] = useState('');
+ const [tests, setTests] = useState<Record<string, TestState>>({});
+
+ const addAndTest = () => {
+ const url = subUrl.trim();
+ if (!validateSourceUrl(url)) {
+ toast('订阅地址需以 http:// 或 https:// 开头', 'warning');
+ return;
+ }
+ store.addLiveSubscription(url, name.trim() || undefined, epg.trim() || undefined);
+ void runTest(url, url);
+ setSubUrl('');
+ setName('');
+ setEpg('');
+ };
+
+ const runTest = async (key: string, url: string) => {
+ setTests((prev) => ({ ...prev, [key]: { status: 'loading' } }));
+ const r = await api.liveTest(url);
+ setTests((prev) => ({
+ ...prev,
+ [key]: r.ok
+ ? { status: 'done', ok: true, ms: r.ms, count: r.count }
+ : { status: 'done', ok: false, error: r.error },
+ }));
+ };
+
+ const exportM3u = (url: string) => {
+ window.open(api.liveExportUrl(url), '_blank', 'noopener');
+ };
+
+ const testBadge = (key: string, url: string) => {
+ const t = tests[key];
+ return (
+ <span className="flex items-center gap-1 shrink-0">
+ {t?.status === 'done' && (
+ <span
+ className={cn(
+ 'text-[10px] px-1.5 py-0.5 rounded',
+ t.ok ? 'bg-green-500/15 text-green-600 dark:text-green-400' : 'bg-red-500/15 text-red-500'
+ )}
+ title={t.ok ? `解析 ${t.ms}ms,共 ${t.count ?? 0} 个频道` : t.error}
+ >
+ {t.ok ? `✓ ${t.count ?? 0} 频道` : `✗ ${t.error?.slice(0, 12) || '失败'}`}
+ </span>
+ )}
+ <button
+ className={cn(
+ 'rounded-md p-1.5 transition-colors disabled:opacity-40',
+ t?.status === 'done' && !t.ok ? 'text-red-400' : 'text-muted hover:text-accent hover:bg-hover'
+ )}
+ disabled={t?.status === 'loading'}
+ onClick={() => runTest(key, url)}
+ aria-label="测试此直播源"
+ title="拉取解析并测速(频道数量与耗时)"
+ >
+ {t?.status === 'loading' ? '…' : '⚡'}
+ </button>
+ </span>
+ );
+ };
+
+ const renderRow = (url: string, label: string, epgUrl?: string, preset = false, lastSync?: number) => (
+ <li 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">
+ {label}
+ {preset && (
+ <span className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-chip text-faint align-middle">
+ 部署者预置
+ </span>
+ )}
+ </div>
+ <div className="text-xs text-faint truncate">
+ {url}
+ {epgUrl && ' · 已配置节目单'}
+ {lastSync && ` · 同步于 ${formatRelativeTime(lastSync)}`}
+ </div>
+ </div>
+ {testBadge(url, url)}
+ <button
+ className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-accent"
+ onClick={() => exportM3u(url)}
+ aria-label="导出 M3U"
+ title="导出为标准 M3U 文件"
+ >
+ ⇩
+ </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>
+ );
+
+ return (
+ <section className="mb-6 border-t border-line pt-5">
+ <div className="flex items-center justify-between mb-2.5">
+ <h3 className="text-sm font-semibold text-content">直播源</h3>
+ <span className="text-[10px] text-faint">M3U 订阅 · /live 页面播放</span>
+ </div>
+ <div className="space-y-2 mb-2.5">
+ <input
+ className="input w-full"
+ placeholder="M3U 订阅地址,如 https://example.com/list.m3u"
+ value={subUrl}
+ maxLength={500}
+ onChange={(e) => setSubUrl(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') addAndTest();
+ }}
+ />
+ {(subUrl.trim() || name.trim() || epg.trim()) && (
+ <>
+ <input
+ className="input w-full"
+ placeholder="名称(可选),如 我的频道列表"
+ value={name}
+ maxLength={50}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <input
+ className="input w-full"
+ placeholder="EPG 节目单地址(可选,XMLTV xml/xml.gz)"
+ value={epg}
+ maxLength={500}
+ onChange={(e) => setEpg(e.target.value)}
+ />
+ </>
+ )}
+ <button className="btn-primary !py-1.5 text-xs w-full" disabled={!subUrl.trim()} onClick={addAndTest}>
+ 添加直播源
+ </button>
+ </div>
+ {store.liveEnvSources.length === 0 && store.liveSubscriptions.length === 0 ? (
+ <p className="text-xs text-faint">
+ 添加 M3U 订阅后即可在「直播」页按分组浏览与播放频道;部署者也可通过 DEFAULT_LIVE_SOURCES 环境变量预置。
+ </p>
+ ) : (
+ <ul className="space-y-2">
+ {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))}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/src/components/providers.tsx b/src/components/providers.tsx
index 2506561..af0f5d8 100644
--- a/src/components/providers.tsx
+++ b/src/components/providers.tsx
@@ -28,6 +28,9 @@ export function Providers({ children }: { children: ReactNode }) {
if (d && Array.isArray(d.defaultSources)) {
useAppStore.getState().setEnvSources(d.defaultSources);
}
+ if (d && Array.isArray(d.defaultLiveSources)) {
+ useAppStore.getState().setLiveEnvSources(d.defaultLiveSources);
+ }
})
.catch(() => {});
}, []);
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index 03eb6f8..646e043 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -8,6 +8,7 @@ import { formatRelativeTime, validateSourceUrl, cn } from '@/lib/utils';
import { exportConfig, importConfig } from '@/lib/db';
import { useAuth } from './auth';
import { api } from '@/lib/client-api';
+import { LiveSourceManager } from './live-source-manager';
/**
* 设置抽屉:数据源管理 + 源订阅 + 播放/过滤选项 + 配置导入导出。
@@ -226,6 +227,8 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
<SourceSubscriptions />
+ <LiveSourceManager />
+
<section className="mb-6 border-t border-line pt-5">
<SectionTitle title="播放与过滤" />
<div className="space-y-3">
diff --git a/src/components/use-live-probe.ts b/src/components/use-live-probe.ts
new file mode 100644
index 0000000..16bf8bf
--- /dev/null
+++ b/src/components/use-live-probe.ts
@@ -0,0 +1,66 @@
+'use client';
+
+import { useCallback, useRef, useState } from 'react';
+import { api } from '@/lib/client-api';
+
+/**
+ * 直播频道批量测活 hook:
+ * - 目标列表分批(每批 10 条)顺序发给 /api/live/probe,服务端批内并发 8;
+ * - 结果渐进写入 Map,列表可实时显示状态点;
+ * - 再次调用自动作废上一轮(runId 比对),clear 重置。
+ */
+
+export interface ProbeResult {
+ ok: boolean;
+ ms?: number;
+ error?: string;
+}
+
+const CHUNK_SIZE = 10;
+const MAX_TARGETS = 400;
+
+export function useLiveProbe() {
+ const [results, setResults] = useState<Map<string, ProbeResult>>(new Map());
+ const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
+ const runIdRef = useRef(0);
+
+ const clear = useCallback(() => {
+ runIdRef.current++;
+ setResults(new Map());
+ setProgress(null);
+ }, []);
+
+ const probe = useCallback(async (targets: { url: string }[]) => {
+ const urls = [...new Set(targets.map((t) => t.url))].slice(0, MAX_TARGETS);
+ if (urls.length === 0) return;
+ const runId = ++runIdRef.current;
+ setProgress({ done: 0, total: urls.length });
+
+ for (let i = 0; i < urls.length; i += CHUNK_SIZE) {
+ if (runIdRef.current !== runId) return;
+ const chunk = urls.slice(i, i + CHUNK_SIZE);
+ try {
+ const { results: list } = await api.liveProbe(chunk);
+ setResults((prev) => {
+ const next = new Map(prev);
+ for (const r of list) next.set(r.url, { ok: r.ok, ms: r.ms, error: r.error });
+ return next;
+ });
+ } catch (err) {
+ // 整批请求失败(网络断开等):标记为不可达而非静默丢弃
+ const msg = err instanceof Error ? err.message : '探测失败';
+ setResults((prev) => {
+ const next = new Map(prev);
+ for (const u of chunk) if (!next.has(u)) next.set(u, { ok: false, error: msg });
+ return next;
+ });
+ }
+ if (runIdRef.current !== runId) return;
+ setProgress({ done: Math.min(i + CHUNK_SIZE, urls.length), total: urls.length });
+ }
+ if (runIdRef.current !== runId) return;
+ setProgress(null);
+ }, []);
+
+ return { results, progress, probe, clear, isProbing: progress !== null };
+}
diff --git a/src/lib/client-api.ts b/src/lib/client-api.ts
index 7ab34fa..fc9fb4a 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 } from './types';
+import type { SearchResponse, VideoDetail, DoubanResponse, BangumiCalendarResponse, AuthStatusResponse, SourceConfig, SearchResultItem, LivePlaylistResponse, LiveEpgResponse } from './types';
/**
* 客户端 API 封装。401 时触发全局事件打开登录框,
@@ -113,6 +113,50 @@ export const api = {
const sp = new URLSearchParams({ url });
return request<{ name?: string; sources: SourceConfig[] }>(`/api/source-list?${sp.toString()}`);
},
+
+ /** —— 直播 / IPTV —— */
+
+ /** 拉取并解析 M3U 订阅;force=1 跳过服务端缓存 */
+ livePlaylist: (url: string, force = false, signal?: AbortSignal) => {
+ const sp = new URLSearchParams({ url });
+ if (force) sp.set('force', '1');
+ return request<LivePlaylistResponse>(`/api/live/playlist?${sp.toString()}`, { signal });
+ },
+
+ /** 查询某频道的节目单(服务端缓存 6h) */
+ liveEpg: (epgUrl: string, tvgId: string, force = false, signal?: AbortSignal) => {
+ const sp = new URLSearchParams({ url: epgUrl, channel: tvgId });
+ if (force) sp.set('force', '1');
+ return request<LiveEpgResponse>(`/api/live/epg?${sp.toString()}`, { signal });
+ },
+
+ /** 直播订阅探活:以拉取解析耗时与频道数衡量可用性 */
+ liveTest: async (url: string) => {
+ const start = performance.now();
+ try {
+ const playlist = await api.livePlaylist(url, true);
+ return { ok: true, ms: Math.round(performance.now() - start), count: playlist.channels.length, error: undefined as string | undefined };
+ } catch (err) {
+ return { ok: false, ms: Math.round(performance.now() - start), count: 0, error: err instanceof Error ? err.message : '失败' };
+ }
+ },
+
+ /** 订阅导出(.m3u)下载地址 */
+ liveExportUrl: (url: string) => {
+ const sp = new URLSearchParams({ url, format: 'm3u' });
+ return `/api/live/playlist?${sp.toString()}`;
+ },
+
+ /** 批量测活:轻量探测频道可达性与延迟(单批最多 50 条) */
+ liveProbe: (urls: string[]) =>
+ request<{ results: { url: string; ok: boolean; status?: number; ms?: number; error?: string }[] }>(
+ '/api/live/probe',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ urls }),
+ }
+ ),
};
export interface SearchFailure {
diff --git a/src/lib/env-live-sources.ts b/src/lib/env-live-sources.ts
new file mode 100644
index 0000000..ccb76cc
--- /dev/null
+++ b/src/lib/env-live-sources.ts
@@ -0,0 +1,37 @@
+import type { LiveSourceConfig } from './types';
+
+/**
+ * 部署者通过 DEFAULT_LIVE_SOURCES 环境变量预置的直播源(M3U 订阅)。
+ * 格式为 JSON 数组:[{"name":"源名","url":"https://.../list.m3u","epg":"https://.../epg.xml.gz"}]
+ * 解析失败时告警并整体忽略,不影响站点运行。模式与 env-sources.ts 对齐。
+ */
+export function getEnvLiveSources(): LiveSourceConfig[] {
+ const raw = process.env.DEFAULT_LIVE_SOURCES;
+ if (!raw || !raw.trim()) return [];
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) throw new Error('必须是 JSON 数组');
+ const list: LiveSourceConfig[] = parsed.map((item, i) => {
+ if (typeof item !== 'object' || item === null) {
+ throw new Error(`第 ${i + 1} 项不是对象`);
+ }
+ const { name, url, epg } = item as Record<string, unknown>;
+ if (typeof name !== 'string' || !name.trim()) {
+ throw new Error(`第 ${i + 1} 项缺少 name`);
+ }
+ if (typeof url !== 'string' || !/^https?:\/\//.test(url.trim())) {
+ throw new Error(`第 ${i + 1} 项的 url 必须以 http:// 或 https:// 开头`);
+ }
+ return {
+ key: `envlive_${i}`,
+ name: name.trim(),
+ url: url.trim().replace(/\/+$/, ''),
+ epg: typeof epg === 'string' && epg.trim() ? epg.trim() : undefined,
+ };
+ });
+ return list;
+ } catch (err) {
+ console.warn('[LibreTV] DEFAULT_LIVE_SOURCES 解析失败,已忽略:', err instanceof Error ? err.message : err);
+ return [];
+ }
+}
diff --git a/src/lib/live-cache.ts b/src/lib/live-cache.ts
new file mode 100644
index 0000000..8efa10f
--- /dev/null
+++ b/src/lib/live-cache.ts
@@ -0,0 +1,56 @@
+/**
+ * 直播模块专用的大对象 TTL 缓存(EPG 节目单等)。
+ *
+ * 刻意不复用 fetch-utils.ts 的通用缓存:其条目数超限时会整体 clear(),
+ * 一个几十 MB 的 EPG 条目即可连带清掉豆瓣推荐等热点数据。
+ * 这里独立实例 + 按字节数与条目数双重上限,超限逐出最旧条目。
+ */
+
+interface Entry {
+ value: unknown;
+ expiresAt: number;
+ /** 估算字节数(sizeHint 或保守估计) */
+ bytes: number;
+}
+
+const MAX_ENTRIES = 10;
+const MAX_TOTAL_BYTES = 256 * 1024 * 1024; // 256MB
+
+const store = new Map<string, Entry>();
+
+export function getLiveCache<T>(key: string): T | undefined {
+ const entry = store.get(key);
+ if (!entry) return undefined;
+ if (Date.now() > entry.expiresAt) {
+ store.delete(key);
+ return undefined;
+ }
+ return entry.value as T;
+}
+
+export function setLiveCache(key: string, value: unknown, ttlMs: number, sizeHint?: number): void {
+ const now = Date.now();
+ const bytes = Math.max(sizeHint ?? 0, 64 * 1024);
+
+ // 先清理已过期条目
+ for (const [k, v] of store) {
+ if (now > v.expiresAt) store.delete(k);
+ }
+
+ // 容量上限:逐出最旧写入的条目(Map 迭代序即插入序)
+ while (store.size >= MAX_ENTRIES) {
+ const oldest = store.keys().next().value;
+ if (oldest === undefined) break;
+ store.delete(oldest);
+ }
+ let total = 0;
+ for (const v of store.values()) total += v.bytes;
+ while (total + bytes > MAX_TOTAL_BYTES && store.size > 0) {
+ const oldest = store.keys().next().value;
+ if (oldest === undefined) break;
+ total -= store.get(oldest)!.bytes;
+ store.delete(oldest);
+ }
+
+ store.set(key, { value, expiresAt: now + ttlMs, bytes });
+}
diff --git a/src/lib/m3u-parser.test.ts b/src/lib/m3u-parser.test.ts
new file mode 100644
index 0000000..a95a730
--- /dev/null
+++ b/src/lib/m3u-parser.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+import { normalizeStreamUrl, parseM3u } from './m3u-parser';
+
+describe('normalizeStreamUrl', () => {
+ it('相对地址按 base 解析', () => {
+ expect(normalizeStreamUrl('/live/cctv1.m3u8', 'https://sub.example.com/playlist')).toBe(
+ 'https://sub.example.com/live/cctv1.m3u8'
+ );
+ });
+
+ it('拒绝非 http(s) 协议', () => {
+ expect(normalizeStreamUrl('rtp://239.1.1.1:5000')).toBeUndefined();
+ expect(normalizeStreamUrl('udp://@239.1.1.1:5000')).toBeUndefined();
+ expect(normalizeStreamUrl('rtsp://cam.local/stream')).toBeUndefined();
+ });
+
+ it('空串与非法地址返回 undefined', () => {
+ expect(normalizeStreamUrl('')).toBeUndefined();
+ expect(normalizeStreamUrl(' ')).toBeUndefined();
+ expect(normalizeStreamUrl('not a url')).toBeUndefined();
+ });
+});
+
+describe('parseM3u', () => {
+ it('解析标准 M3U 属性', () => {
+ const m3u = `#EXTM3U
+#EXTINF:-1 tvg-id="cctv1" tvg-name="CCTV1" tvg-logo="https://img/logo1.png" group-title="央视",CCTV-1 综合
+https://stream.example.com/cctv1.m3u8
+#EXTINF:-1 tvg-id="cctv5" group-title="体育",CCTV-5 体育
+https://stream.example.com/cctv5.m3u8`;
+ const channels = parseM3u(m3u);
+ expect(channels).toHaveLength(2);
+ expect(channels[0]).toMatchObject({
+ id: 'cctv1',
+ name: 'CCTV-1 综合',
+ url: 'https://stream.example.com/cctv1.m3u8',
+ logo: 'https://img/logo1.png',
+ group: '央视',
+ tvgId: 'cctv1',
+ rawName: 'CCTV1',
+ });
+ expect(channels[1].group).toBe('体育');
+ });
+
+ it('兼容属性写在标题后的非标准写法', () => {
+ const m3u = `#EXTM3U
+#EXTINF:-1,广东卫视 tvg-id="gdtv" group-title="卫视"
+https://stream.example.com/gd.flv`;
+ const channels = parseM3u(m3u);
+ expect(channels).toHaveLength(1);
+ expect(channels[0]).toMatchObject({
+ id: 'gdtv',
+ name: '广东卫视',
+ group: '卫视',
+ url: 'https://stream.example.com/gd.flv',
+ });
+ });
+
+ it('EXTGRP 补充分组', () => {
+ const m3u = `#EXTM3U
+#EXTINF:-1,新闻频道
+#EXTGRP:资讯
+https://stream.example.com/news.m3u8`;
+ expect(parseM3u(m3u)[0].group).toBe('资讯');
+ });
+
+ it('相对流地址按订阅 URL 解析', () => {
+ const channels = parseM3u(
+ '#EXTINF:-1,测试\nlive/a.m3u8',
+ 'https://cdn.example.com/list/index.m3u'
+ );
+ expect(channels[0].url).toBe('https://cdn.example.com/list/live/a.m3u8');
+ });
+
+ it('相对 logo 同样解析为绝对地址', () => {
+ const channels = parseM3u(
+ '#EXTINF:-1 tvg-logo="/logos/a.png",A\nhttps://x.example.com/a.m3u8',
+ 'https://cdn.example.com/'
+ );
+ expect(channels[0].logo).toBe('https://cdn.example.com/logos/a.png');
+ });
+
+ it('按 URL 去重,保留首个', () => {
+ const m3u = `#EXTM3U
+#EXTINF:-1,频道A
+https://s.example.com/same.m3u8
+#EXTINF:-1,频道A 高清
+https://s.example.com/same.m3u8`;
+ const channels = parseM3u(m3u);
+ expect(channels).toHaveLength(1);
+ expect(channels[0].name).toBe('频道A');
+ });
+
+ it('丢弃非 http(s) 流与无地址行', () => {
+ const m3u = `#EXTM3U
+#EXTINF:-1,组播源
+rtp://239.3.1.1:5000
+#EXTINF:-1,正常源
+https://s.example.com/ok.m3u8`;
+ const channels = parseM3u(m3u);
+ expect(channels).toHaveLength(1);
+ expect(channels[0].name).toBe('正常源');
+ });
+
+ it('无 EXTINF 的裸地址也能解析并生成兜底名称', () => {
+ const channels = parseM3u('https://s.example.com/feeds/news.m3u8');
+ expect(channels).toHaveLength(1);
+ expect(channels[0].name).toBe('news');
+ expect(channels[0].id).not.toBe('');
+ });
+
+ it('无 tvg-id 时由 URL 生成稳定 id', () => {
+ const a = parseM3u('#EXTINF:-1,X\nhttps://s.example.com/x.m3u8');
+ const b = parseM3u('#EXTINF:-1,X\nhttps://s.example.com/x.m3u8');
+ expect(a[0].id).toBe(b[0].id);
+ });
+
+ it('空输入与异常输入不抛错', () => {
+ expect(parseM3u('')).toEqual([]);
+ expect(parseM3u('随便一段文本\n没有地址')).toEqual([]);
+ expect(parseM3u('#EXTINF:-1,孤儿频道')).toEqual([]);
+ });
+});
diff --git a/src/lib/m3u-parser.ts b/src/lib/m3u-parser.ts
new file mode 100644
index 0000000..cbcabe2
--- /dev/null
+++ b/src/lib/m3u-parser.ts
@@ -0,0 +1,119 @@
+import type { LiveChannel } from './types';
+
+/**
+ * M3U / M3U8 直播播放列表解析。
+ *
+ * 兼容两种常见写法:
+ * - 标准:`#EXTINF:-1 tvg-id="cctv1" tvg-logo="..." group-title="央视",CCTV-1`
+ * - 非标准(属性写在标题后):`#EXTINF:-1,CCTV-1 tvg-id="cctv1"`
+ * 另支持 `#EXTGRP:分组名` 补充分组(属性缺失时的常见替代写法)。
+ *
+ * 解析为单趟扫描(O(n)),频道按 URL 去重,仅保留 http(s) 流地址
+ * (rtp:// udp:// rtsp:// 等浏览器无法播放的协议直接丢弃)。
+ */
+
+const ATTR_RE = /([a-zA-Z0-9_-]+)="([^"]*)"/g;
+const ATTR_STRIP_RE = /[a-zA-Z0-9_-]+="[^"]*"/g;
+
+/** 由任意字符串生成稳定的短 id(djb2 变体,与 store.ts subKeyPrefix 同风格) */
+function stableId(input: string): string {
+ let h = 5381;
+ for (let i = 0; i < input.length; i++) h = ((h << 5) + h + input.charCodeAt(i)) >>> 0;
+ return h.toString(36);
+}
+
+/** 相对地址按订阅 URL 解析为绝对地址;仅放行 http(s) */
+export function normalizeStreamUrl(raw: string, baseUrl?: string): string | undefined {
+ const trimmed = raw.trim();
+ if (!trimmed) return undefined;
+ try {
+ const resolved = new URL(trimmed, baseUrl);
+ if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') return undefined;
+ return resolved.href;
+ } catch {
+ return undefined;
+ }
+}
+
+/** URL 无名时的兜底名称:取路径末段,decode 后仍空则用主机名 */
+function nameFromUrl(url: string): string {
+ try {
+ const u = new URL(url);
+ const last = u.pathname.split('/').filter(Boolean).pop();
+ if (last) {
+ const decoded = decodeURIComponent(last).replace(/\.(m3u8?|flv|ts|mp4)$/i, '');
+ if (decoded) return decoded;
+ }
+ return u.hostname;
+ } catch {
+ return '未命名频道';
+ }
+}
+
+interface ExtinfContext {
+ attrs: Record<string, string>;
+ title: string;
+ /** #EXTGRP 补充的分组(EXTINF 自身带 group-title 时忽略) */
+ extGroup: string;
+}
+
+export function parseM3u(content: string, baseUrl?: string): LiveChannel[] {
+ const channels: LiveChannel[] = [];
+ if (!content) return channels;
+
+ const seen = new Set<string>();
+ let ctx: ExtinfContext | null = null;
+
+ for (const rawLine of content.split(/\r?\n/)) {
+ const line = rawLine.trim();
+ if (!line) continue;
+
+ if (line.toUpperCase().startsWith('#EXTINF')) {
+ const attrs: Record<string, string> = {};
+ ATTR_RE.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = ATTR_RE.exec(line))) attrs[m[1].toLowerCase()] = m[2].trim();
+
+ // 移除属性片段后取首个逗号之后的文本为显示名
+ const stripped = line.replace(ATTR_STRIP_RE, '').replace(/^#EXTINF\s*:\s*/i, '');
+ const commaIdx = stripped.indexOf(',');
+ const title = (commaIdx >= 0 ? stripped.slice(commaIdx + 1) : stripped)
+ .trim()
+ .replace(/^"+|"+$/g, '');
+
+ ctx = { attrs, title, extGroup: '' };
+ continue;
+ }
+
+ if (line.toUpperCase().startsWith('#EXTGRP:')) {
+ const g = line.slice('#EXTGRP:'.length).trim();
+ if (ctx && g && !ctx.attrs['group-title']) ctx.extGroup = g;
+ continue;
+ }
+
+ if (line.startsWith('#')) continue; // 其余指令(#EXTVLCOPT 等)忽略
+
+ // 非注释行即流地址
+ const url = normalizeStreamUrl(line, baseUrl);
+ const cur = ctx;
+ ctx = null;
+ if (!url || seen.has(url)) continue;
+ seen.add(url);
+
+ const attrs = cur?.attrs ?? {};
+ const tvgId = attrs['tvg-id'] || undefined;
+ const logo = attrs['tvg-logo'] ? normalizeStreamUrl(attrs['tvg-logo'], baseUrl) : undefined;
+ const name = cur?.title || nameFromUrl(url);
+ channels.push({
+ id: tvgId || stableId(url),
+ name,
+ url,
+ logo,
+ group: attrs['group-title'] || cur?.extGroup || undefined,
+ tvgId,
+ rawName: attrs['tvg-name'] || undefined,
+ });
+ }
+
+ return channels;
+}
diff --git a/src/lib/m3u8.ts b/src/lib/m3u8.ts
index 1bf8cf7..1304711 100644
--- a/src/lib/m3u8.ts
+++ b/src/lib/m3u8.ts
@@ -16,20 +16,26 @@ export function makeAbsolute(url: string, base: string): string {
}
}
-/** 将 m3u8 中的地址改写为经过本站代理的地址(分片/key/map 同样改写) */
-export function rewriteM3u8(content: string, baseUrl: string, depth = 0): string {
+/** 将 m3u8 中的地址改写为经过本站代理的地址(分片/key/map 同样改写)。
+ * prefix 可指定代理前缀(直播流走 /api/live/stream/,点播默认 /api/proxy/) */
+export function rewriteM3u8(
+ content: string,
+ baseUrl: string,
+ depth = 0,
+ prefix: string = PROXY_PREFIX
+): string {
if (depth > 5) return content;
const lines = content.split('\n');
const out = lines.map((line) => {
if (line.startsWith('#EXT-X-KEY') || line.startsWith('#EXT-X-MAP')) {
return line.replace(/(URI=")([^"]+)(")/g, (m, p1: string, uri: string, p2: string) => {
- if (uri.startsWith(PROXY_PREFIX)) return m;
- return p1 + PROXY_PREFIX + encodeURIComponent(makeAbsolute(uri, baseUrl)) + p2;
+ if (uri.startsWith(prefix)) return m;
+ return p1 + prefix + encodeURIComponent(makeAbsolute(uri, baseUrl)) + p2;
});
}
if (line.startsWith('#') || line.trim() === '') return line;
- if (line.startsWith(PROXY_PREFIX)) return line;
- return PROXY_PREFIX + encodeURIComponent(makeAbsolute(line, baseUrl));
+ if (line.startsWith(prefix)) return line;
+ return prefix + encodeURIComponent(makeAbsolute(line, baseUrl));
});
return out.join('\n');
}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index a7d0969..e2ee1fc 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -2,7 +2,7 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
-import type { SourceConfig } from './types';
+import type { SourceConfig, LiveSourceConfig } from './types';
/**
* 全局设置(zustand + localStorage 持久化)。
@@ -31,6 +31,28 @@ export interface SourceSubscription {
lastSync?: number;
}
+/** 直播订阅:远程 M3U 播放列表(独立于采集站订阅模型,避免 key 前缀冲突) */
+export interface LiveSubscription {
+ url: string;
+ name?: string;
+ /** 该订阅关联的 XMLTV 节目单地址 */
+ epg?: string;
+ /** 上次同步成功时间 */
+ lastSync?: number;
+}
+
+/** 直播最近观看条目(上限 20 条,按 url 去重) */
+export interface LiveRecentEntry {
+ url: string;
+ name: string;
+ logo?: string;
+ group?: string;
+ tvgId?: string;
+ /** 来源订阅地址(用于回查 EPG) */
+ epg?: string;
+ timestamp: number;
+}
+
/** 订阅导入的源 key 前缀:sub_<hash8(url)>_<i>,同步时按前缀整体替换 */
export function subKeyPrefix(url: string): string {
let h = 5381;
@@ -44,6 +66,17 @@ interface AppState extends AppSettings {
/** 已向用户展示过并自动勾选过的预置源 key(持久化:用户取消勾选后不再反复勾上) */
envKeysSeen: string[];
subscriptions: SourceSubscription[];
+ /** —— 直播模块 —— */
+ /** 部署者通过 DEFAULT_LIVE_SOURCES 预置的直播源(服务端下发,不持久化) */
+ liveEnvSources: LiveSourceConfig[];
+ /** 已出现过的预置直播源 key(持久化:用于「首次自动可见」去重) */
+ liveEnvKeysSeen: string[];
+ /** 用户添加的 M3U 订阅 */
+ liveSubscriptions: LiveSubscription[];
+ /** 收藏频道(按流 URL 唯一标识) */
+ liveFavorites: string[];
+ /** 最近观看频道(上限 20) */
+ liveRecent: LiveRecentEntry[];
addCustomApi: (api: Omit<SourceConfig, 'key'> & { key?: string }) => void;
updateCustomApi: (key: string, patch: Partial<SourceConfig>) => void;
removeCustomApi: (key: string) => void;
@@ -55,9 +88,20 @@ interface AppState extends AppSettings {
markSubscriptionSynced: (url: string, name?: string) => void;
/** 用订阅内容整体替换该订阅名下的源,返回新增数量 */
applySubscriptionSources: (subUrl: string, list: Omit<SourceConfig, 'key'>[]) => number;
+ setLiveEnvSources: (list: LiveSourceConfig[]) => void;
+ addLiveSubscription: (url: string, name?: string, epg?: string) => void;
+ removeLiveSubscription: (url: string) => void;
+ markLiveSynced: (url: string, name?: string, epg?: string) => void;
+ toggleLiveFavorite: (channelUrl: string) => void;
+ addLiveRecent: (entry: Omit<LiveRecentEntry, 'timestamp'>) => void;
updateSettings: (patch: Partial<Omit<AppSettings, 'customAPIs' | 'selectedKeys'>>) => void;
}
+/** 全部可用直播源(预置 + 用户订阅)合并视图 */
+export function allLiveSources(state: Pick<AppState, 'liveEnvSources' | 'liveSubscriptions'>): LiveSourceConfig[] {
+ return [...state.liveEnvSources, ...state.liveSubscriptions.map((s) => ({ key: `sub_${s.url}`, name: s.name || s.url, url: s.url, epg: s.epg }))];
+}
+
function nextCustomKey(apiList: SourceConfig[]): string {
let i = 0;
const used = new Set(apiList.map((a) => a.key));
@@ -72,6 +116,11 @@ export const useAppStore = create<AppState>()(
envSources: [],
envKeysSeen: [],
subscriptions: [],
+ liveEnvSources: [],
+ liveEnvKeysSeen: [],
+ liveSubscriptions: [],
+ liveFavorites: [],
+ liveRecent: [],
selectedKeys: [],
yellowFilter: true,
adFilter: true,
@@ -182,6 +231,54 @@ export const useAppStore = create<AppState>()(
return incoming.length;
},
+ setLiveEnvSources: (list) => {
+ // 预置直播源记下已见 key(用户在设置中不可移除预置项,仅作来源去重展示)
+ const seen = new Set(get().liveEnvKeysSeen);
+ const freshKeys = list.map((s) => s.key).filter((k) => !seen.has(k));
+ set({
+ liveEnvSources: list,
+ liveEnvKeysSeen: [...get().liveEnvKeysSeen, ...freshKeys],
+ });
+ },
+
+ addLiveSubscription: (url, name, epg) => {
+ const trimmed = url.trim();
+ if (!trimmed || get().liveSubscriptions.some((s) => s.url === trimmed)) return;
+ set({
+ liveSubscriptions: [...get().liveSubscriptions, { url: trimmed, name, epg }],
+ });
+ },
+
+ removeLiveSubscription: (url) => {
+ set({
+ liveSubscriptions: get().liveSubscriptions.filter((s) => s.url !== url),
+ });
+ },
+
+ markLiveSynced: (url, name, epg) => {
+ set({
+ liveSubscriptions: get().liveSubscriptions.map((s) =>
+ s.url === url
+ ? { ...s, lastSync: Date.now(), name: name ?? s.name, epg: epg ?? s.epg }
+ : s
+ ),
+ });
+ },
+
+ toggleLiveFavorite: (channelUrl) => {
+ const cur = get().liveFavorites;
+ set({
+ liveFavorites: cur.includes(channelUrl)
+ ? cur.filter((u) => u !== channelUrl)
+ : [...cur, channelUrl],
+ });
+ },
+
+ addLiveRecent: (entry) => {
+ const rest = get().liveRecent.filter((r) => r.url !== entry.url);
+ set({ liveRecent: [{ ...entry, timestamp: Date.now() }, ...rest].slice(0, 20) });
+ },
+
updateSettings: (patch) => {
// 打开成人内容过滤时,同步取消勾选所有成人源,避免两者并存
if (patch.yellowFilter === true) {
@@ -207,6 +304,10 @@ export const useAppStore = create<AppState>()(
selectedKeys: s.selectedKeys,
envKeysSeen: s.envKeysSeen,
subscriptions: s.subscriptions,
+ liveEnvKeysSeen: s.liveEnvKeysSeen,
+ liveSubscriptions: s.liveSubscriptions,
+ liveFavorites: s.liveFavorites,
+ liveRecent: s.liveRecent,
yellowFilter: s.yellowFilter,
adFilter: s.adFilter,
doubanEnabled: s.doubanEnabled,
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 565853b..608cc04 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -89,4 +89,56 @@ export interface AuthStatusResponse {
version: string;
/** 部署者通过 DEFAULT_SOURCES 环境变量预置的采集站(未配置时为空数组) */
defaultSources: SourceConfig[];
+ /** 部署者通过 DEFAULT_LIVE_SOURCES 环境变量预置的直播源(未配置时为空数组) */
+ defaultLiveSources: LiveSourceConfig[];
+}
+
+// —— 直播 / IPTV ——
+
+/** 直播源(M3U 订阅)配置 */
+export interface LiveSourceConfig {
+ key: string;
+ name: string;
+ /** M3U 订阅地址 */
+ url: string;
+ /** 可选:XMLTV 节目单地址 */
+ epg?: string;
+}
+
+/** 单个直播频道(由 M3U 解析得到) */
+export interface LiveChannel {
+ /** tvg-id 优先,缺失时由 URL 生成的稳定短 id */
+ id: string;
+ name: string;
+ url: string;
+ logo?: string;
+ group?: string;
+ tvgId?: string;
+ /** M3U 的 tvg-name 属性(原始台名) */
+ rawName?: string;
+}
+
+export interface LivePlaylistResponse {
+ /** 订阅名(M3U 无名时为空) */
+ name?: string;
+ channels: LiveChannel[];
+ groups: string[];
+}
+
+/** 单条节目单条目(XMLTV programme) */
+export interface EpgProgram {
+ channelId: string;
+ /** epoch ms */
+ start: number;
+ /** epoch ms */
+ stop: number;
+ title: string;
+ desc?: string;
+}
+
+export interface LiveEpgResponse {
+ channelId: string;
+ current?: EpgProgram;
+ next?: EpgProgram;
+ programs: EpgProgram[];
}
diff --git a/src/lib/xmltv.test.ts b/src/lib/xmltv.test.ts
new file mode 100644
index 0000000..fdb6e85
--- /dev/null
+++ b/src/lib/xmltv.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it } from 'vitest';
+import { gzipSync } from 'node:zlib';
+import { currentAndNext, parseXmltv, parseXmltvTime } from './xmltv';
+
+// 固定「当前时间」:2024-06-01T12:00:00Z
+const NOW = Date.UTC(2024, 5, 1, 12, 0, 0);
+
+const SAMPLE = `<?xml version="1.0" encoding="UTF-8"?>
+<tv>
+ <channel id="cctv1"><display-name>CCTV-1</display-name></channel>
+ <channel id="cctv5"><display-name>CCTV-5</display-name></channel>
+ <programme start="20240601100000 +0000" stop="20240601113000 +0000" channel="cctv1">
+ <title lang="zh">朝闻天下</title>
+ <desc lang="zh">早间新闻节目</desc>
+ </programme>
+ <programme start="20240601113000 +0000" stop="20240601140000 +0000" channel="cctv1">
+ <title lang="zh">新闻30分</title>
+ <desc lang="zh">午间新闻</desc>
+ </programme>
+ <programme start="20240601140000 +0000" stop="20240601150000 +0000" channel="cctv1">
+ <title lang="zh"><![CDATA[电视剧: 焦点访谈]]></title>
+ </programme>
+ <programme start="20240601123000 +0000" stop="20240601133000 +0000" channel="cctv5">
+ <title lang="zh">体育新闻</title>
+ </programme>
+ <programme start="20230531235959 +0000" stop="20240531235959 +0000" channel="cctv1">
+ <title>早已播完</title>
+ </programme>
+ <programme start="20240602000000 +0000" stop="20240602010000 +0000" channel="cctv1">
+ <title>午夜场</title>
+ </programme>
+</tv>`;
+
+describe('parseXmltvTime', () => {
+ it('解析带时区偏移的时间', () => {
+ // +0800 即东八区:UTC 时间减 8 小时
+ expect(parseXmltvTime('20240601200000 +0800')).toBe(Date.UTC(2024, 5, 1, 12, 0, 0));
+ expect(parseXmltvTime('20240601040000 -0500')).toBe(Date.UTC(2024, 5, 1, 9, 0, 0));
+ });
+
+ it('解析 Z 后缀与无时区时间', () => {
+ expect(parseXmltvTime('20240601120000Z')).toBe(Date.UTC(2024, 5, 1, 12, 0, 0));
+ expect(parseXmltvTime('20240601120000')).toBe(Date.UTC(2024, 5, 1, 12, 0, 0));
+ });
+
+ it('支持毫秒小数', () => {
+ expect(parseXmltvTime('20240601120000.500 +0000')).toBe(Date.UTC(2024, 5, 1, 12, 0, 0, 500));
+ });
+
+ it('非法输入返回 NaN', () => {
+ expect(Number.isNaN(parseXmltvTime('not-a-time'))).toBe(true);
+ expect(Number.isNaN(parseXmltvTime(''))).toBe(true);
+ });
+});
+
+describe('parseXmltv', () => {
+ it('解析明文 XML 并按频道索引、排序、裁剪窗口', () => {
+ const map = parseXmltv(SAMPLE, 24 * 60 * 60 * 1000, NOW);
+ const cctv1 = map.get('cctv1')!;
+ expect(cctv1).toHaveLength(3); // 已播完的被裁剪;午夜场在 24h 窗口内保留
+ expect(cctv1.map((p) => p.title)).toEqual(['新闻30分', '电视剧: 焦点访谈', '午夜场']);
+ // 排序正确
+ for (let i = 1; i < cctv1.length; i++) {
+ expect(cctv1[i].start).toBeGreaterThanOrEqual(cctv1[i - 1].start);
+ }
+ });
+
+ it('CDATA 与描述解析', () => {
+ const map = parseXmltv(SAMPLE, undefined, NOW);
+ expect(map.get('cctv1')![1].title).toBe('电视剧: 焦点访谈');
+ expect(map.get('cctv1')![0].desc).toBe('午间新闻');
+ });
+
+ it('窗口外的未来节目被裁剪', () => {
+ const map = parseXmltv(SAMPLE, 60 * 60 * 1000, NOW); // 只看 [12:00, 13:00)
+ const cctv1 = map.get('cctv1')!;
+ // 焦点访谈 14:00 开始,在窗口外
+ expect(cctv1.map((p) => p.title)).toEqual(['新闻30分']);
+ });
+
+ it('解析 gzip 压缩内容', () => {
+ const compressed = gzipSync(Buffer.from(SAMPLE, 'utf8'));
+ expect(compressed[0]).toBe(0x1f);
+ expect(compressed[1]).toBe(0x8b);
+ const map = parseXmltv(compressed, undefined, NOW);
+ expect(map.get('cctv1')).toHaveLength(3);
+ expect(map.get('cctv5')).toHaveLength(1);
+ });
+
+ it('Buffer 明文输入同样可解析', () => {
+ const map = parseXmltv(Buffer.from(SAMPLE, 'utf8'), undefined, NOW);
+ expect(map.size).toBe(2);
+ });
+
+ it('空输入与畸形内容不抛错', () => {
+ expect(parseXmltv('', undefined, NOW).size).toBe(0);
+ expect(parseXmltv('<tv><programme channel="x" start="bad" stop="bad"><title>t</title></programme></tv>', undefined, NOW).size).toBe(0);
+ });
+});
+
+describe('currentAndNext', () => {
+ const programs = parseXmltv(SAMPLE, undefined, NOW).get('cctv1')!;
+
+ it('正确定位当前与下一个节目', () => {
+ const { current, next } = currentAndNext(programs, NOW);
+ expect(current?.title).toBe('新闻30分');
+ expect(next?.title).toBe('电视剧: 焦点访谈');
+ });
+
+ it('节目间隙时 current 为空、next 为下一档', () => {
+ const gap = Date.UTC(2024, 5, 1, 14, 30, 0); // 焦点访谈(14:00-15:00) 实际覆盖该点;改用末尾之后
+ const { current, next } = currentAndNext(programs, gap);
+ expect(current?.title).toBe('电视剧: 焦点访谈');
+ expect(next?.title).toBe('午夜场');
+ });
+
+ it('空列表返回空对象', () => {
+ expect(currentAndNext([], NOW)).toEqual({ current: undefined, next: undefined });
+ });
+});
diff --git a/src/lib/xmltv.ts b/src/lib/xmltv.ts
new file mode 100644
index 0000000..bc6b0ea
--- /dev/null
+++ b/src/lib/xmltv.ts
@@ -0,0 +1,141 @@
+import { gunzipSync } from 'node:zlib';
+import type { EpgProgram } from './types';
+
+/**
+ * XMLTV 节目单解析。
+ *
+ * XMLTV 文件常达数十 MB,这里不做完整 DOM 解析,而是单趟正则扫描
+ * `<programme ...>` 节点,解析后按频道索引、按时间窗裁剪并丢弃原始文本,
+ * 避免内存中同时持有原始 XML 与解析结果。
+ *
+ * 时间格式:`20240101120000 +0800`(秒可带毫秒小数,时区可省略或为 Z / ±hhmm)。
+ */
+
+const PROGRAMME_RE = /<programme\s+([^>]*?)\/>|<programme\s+([^>]*?)>([\s\S]*?)<\/programme>/g;
+const ATTR_RE = /([a-zA-Z0-9_-]+)="([^"]*)"/g;
+const TITLE_RE = /<title(?:\s[^>]*)?>([\s\S]*?)<\/title>/i;
+const DESC_RE = /<desc(?:\s[^>]*)?>([\s\S]*?)<\/desc>/i;
+
+const DEFAULT_WINDOW_MS = 24 * 60 * 60 * 1000;
+
+/** 解析 XMLTV 实体(含 CDATA 与数字实体) */
+function decodeXmlText(raw: string): string {
+ let text = raw.trim();
+ const cdata = text.match(/^<!\[CDATA\[([\s\S]*)\]\]>$/);
+ if (cdata) text = cdata[1];
+ return text
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex: string) => String.fromCodePoint(parseInt(hex, 16)))
+ .replace(/&#(\d+);/g, (_, dec: string) => String.fromCodePoint(parseInt(dec, 10)))
+ .replace(/&quot;/g, '"')
+ .replace(/&apos;/g, "'")
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&amp;/g, '&');
+}
+
+/** 解析 `YYYYMMDDHHmmss(.fff)?( +hhmm | Z)?` 为 epoch ms;无法解析返回 NaN */
+export function parseXmltvTime(raw: string): number {
+ const m = raw
+ .trim()
+ .match(/^(\d{4})(\d{2})(\d{2})(\d{2})?(\d{2})?(\d{2})?(?:\.(\d{1,3}))?(?:\s*([+-])(\d{2})(\d{2})|Z)?$/);
+ if (!m) return NaN;
+ const [, y, mo, d, h, mi, s, frac, sign, tzh, tzm] = m;
+ const utcMs = Date.UTC(
+ +y,
+ +mo - 1,
+ +d,
+ +(h || 0),
+ +(mi || 0),
+ +(s || 0),
+ frac ? +(frac.padEnd(3, '0')) : 0
+ );
+ if (!sign) return utcMs; // 无时区按 UTC 处理
+ const offsetMin = (+tzh) * 60 + (+tzm);
+ const offsetMs = offsetMin * 60 * 1000 * (sign === '-' ? -1 : 1);
+ return utcMs - offsetMs;
+}
+
+function extractAttrs(attrText: string): Record<string, string> {
+ const attrs: Record<string, string> = {};
+ ATTR_RE.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = ATTR_RE.exec(attrText))) attrs[m[1].toLowerCase()] = m[2];
+ return attrs;
+}
+
+/**
+ * 解析 XMLTV 内容。string 直接入扫描;Buffer 自动识别 gzip(1f 8b 魔数)解压。
+ * 只保留 `[now, now + windowMs]` 窗口内的节目,按频道分组并按开播时间排序。
+ */
+export function parseXmltv(
+ content: string | Buffer,
+ windowMs: number = DEFAULT_WINDOW_MS,
+ now: number = Date.now()
+): Map<string, EpgProgram[]> {
+ let text: string;
+ if (Buffer.isBuffer(content)) {
+ text =
+ content.length >= 2 && content[0] === 0x1f && content[1] === 0x8b
+ ? gunzipSync(content).toString('utf8')
+ : content.toString('utf8');
+ } else {
+ text = content;
+ }
+
+ const result = new Map<string, EpgProgram[]>();
+ const windowEnd = now + windowMs;
+
+ PROGRAMME_RE.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = PROGRAMME_RE.exec(text))) {
+ const attrText = m[1] ?? m[2] ?? '';
+ const inner = m[3] ?? '';
+ const attrs = extractAttrs(attrText);
+ const channelId = attrs['channel']?.trim();
+ if (!channelId) continue;
+ const start = parseXmltvTime(attrs['start'] || '');
+ const stop = parseXmltvTime(attrs['stop'] || '');
+ if (!Number.isFinite(start) || !Number.isFinite(stop)) continue;
+ // 窗口裁剪:节目已完全播完或完全在未来窗口之外则丢弃
+ if (stop <= now || start >= windowEnd) continue;
+
+ const titleMatch = inner.match(TITLE_RE);
+ const descMatch = inner.match(DESC_RE);
+ const program: EpgProgram = {
+ channelId,
+ start,
+ stop,
+ title: titleMatch ? decodeXmlText(titleMatch[1]) : '',
+ };
+ if (descMatch) program.desc = decodeXmlText(descMatch[1]);
+ if (!program.title) continue;
+
+ const list = result.get(channelId);
+ if (list) list.push(program);
+ else result.set(channelId, [program]);
+ }
+
+ // 按开播时间排序(XMLTV 不保证顺序)
+ for (const list of result.values()) list.sort((a, b) => a.start - b.start);
+ return result;
+}
+
+/** 取某频道当前正在播出的节目与下一个节目 */
+export function currentAndNext(
+ programs: EpgProgram[],
+ at: number = Date.now()
+): { current?: EpgProgram; next?: EpgProgram } {
+ let current: EpgProgram | undefined;
+ let next: EpgProgram | undefined;
+ for (const p of programs) {
+ if (p.start <= at && p.stop > at) {
+ current = p;
+ continue; // 同一时刻可能有重叠节目,取最后一个命中者
+ }
+ if (p.start > at) {
+ next = p;
+ break;
+ }
+ }
+ return { current, next };
+}