Compare commits

..
22 Commits
Author SHA1 Message Date
jinghui 3b9f3bbf5d perf: 最新港剧聚合秒开——/api/tvbox/all SWR + fetchClass端点竞速 (fixed133)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
- 接口 stale-while-revalidate: 过期先秒回旧数据(STALE)后台刷新, 60s内HIT
- fetchClass 三端点串行逐试改并发竞速: 冷启动 60s+ -> 22.3s
- 失败分类缓存 30s->2min; 宿主 cron 每分钟保活
- Dockerfile NEXT_PUBLIC_SITE_VERSION=fixed133
2026-11-16 15:42:13 +08:00
jinghui 5d58eee4c7 docs: README 更新日志+当前版本对齐 v-fixed132 2026-11-16 15:01:31 +08:00
jinghui 6bc58e33cd docs: CHANGELOG fixed132 全新浏览器标签页图标
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-16 14:58:16 +08:00
jinghui e086667927 feat: 全新浏览器标签页图标 深蓝圆角底+天蓝播放三角+星光 (16px专用优化版, fixed132) 2026-11-16 14:46:47 +08:00
jinghui a74a82b5d1 fix: 存储模式烤入Dockerfile+README部署铁则+CHANGELOG事故记录 (2026-11-15观看记录丢失)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-15 12:04:44 +08:00
jinghui 4ba6bc2339 feat: 相关推荐改本站片源按主演/导演/语言/地区/类型匹配 点击source+id直达片源 (fixed131)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-15 02:34:21 +08:00
jinghui dfc1d87a54 feat: 相关推荐标题旁显示推荐规则说明 豆瓣相似影片推荐·取前10 (fixed130)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-15 01:34:07 +08:00
jinghui 4c4d065951 fix: 详情页相关推荐点击直达播放页 播放页标题匹配加放宽兜底 (fixed129)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-15 01:24:48 +08:00
jinghui 3362970fff fix: 恢复TVBox旧版配置结构+逐站代理路由 修9xx分类0条/搜索/base64 (fixed128)
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-13 14:51:05 +08:00
3970260761 6cbf7859f0 fix: 最新港剧偶发整栏消失 — 空结果不进60s缓存/客户端重试3次+localStorage持久缓存+失败重试入口 (fixed127)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-12 13:07:11 +08:00
3970260761 1e32753397 feat: TVBox直播txt接口默认首频道改为TVB翡翠台 (fixed126)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-11 11:24:02 +08:00
jinghui d0a2041d9a feat: 首页最新港剧区块加上一页/下一页翻页按钮 (fixed125)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-10 18:13:42 +08:00
jinghui aee4b48995 fix: 管理页每次打开即自动测速所有资源站(测速提升到页面级) (fixed124)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-10 17:46:38 +08:00
jinghui dc7787a5ab feat: 管理页视频源状态列自动显示响应耗时 (fixed123)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-10 17:15:48 +08:00
jinghui 41fe467e63 feat: /filter 资源站测速(响应秒) + 移除失效彗星资源 (fixed122)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-10 16:58:16 +08:00
jinghui 40473955d8 fix: /filter 每页最多50条 (fixed121)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-10 16:18:09 +08:00
jinghui 9d765b9f49 feat: 首页港剧区块 5分钟缓存+超时/失败兜底 (fixed120)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-10 16:12:52 +08:00
jinghui 7c1fae8dcc perf: /filter 聚合源站数 100->8 (fixed119)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-10 16:10:23 +08:00
jinghui 3cc8d957a5 feat: /filter 显示已加载条数 (fixed118)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
2026-11-10 16:05:12 +08:00
jinghui 18953ebc9a fix: /filter 页数据不显示(reset时未追加arr) (fixed117)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-10 15:56:52 +08:00
jinghui 566ee297d9 perf: /api/tvbox/all 增加60s进程内响应缓存,栏目秒开 (fixed110)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-10 14:57:12 +08:00
jinghui b734661e47 fix: 管理员(owner)最后登录时间显示 (fixed109)
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-10 14:52:16 +08:00
23 changed files with 1468 additions and 446 deletions

No files matched your search

+131
View File
@@ -2,6 +2,137 @@
本文档记录 KatelyaTV 项目的重要更新和功能变更。
## [fixed133] - 2026-11-16
### ⚡ 性能:最新港剧等聚合板块秒开(对齐热门电影的加载体验)
- **接口层 stale-while-revalidate**:`/api/tvbox/all` 缓存过期后先立即返回旧数据(`X-Cache: STALE`,实测 0.02s),同时在后台重新聚合——多源聚合实测 8~22s,用户请求从此零等待;60s 内 `X-Cache: HIT`(0.03s)
- **分类端点并发竞速**:`fetchClass` 三个候选端点由「串行逐试、每端点等满 8s」改为「并发竞速、首个成功即用」(半死源最坏 3×8s=24s → 8s);容器重启后的冷启动全量聚合从 **60s+ 降到 22.3s**(前端 25s 超时内可通过)
- **失败分类表缓存 30s → 2min**:避免每分钟刷新反复踩满超时拖慢整体
- **保活**:模块级预热定时器(edge 隔离下不保证存活)+ 宿主 crontab 每分钟保活请求——无用户流量时聚合结果也持续续期,数据最多旧约 2 分钟
- **根因说明**:热门电影走豆瓣单接口(1~2s 即回),最新港剧走全片源站聚合(分类表映射 + 列表拉取 + 硬过滤去重),慢在聚合本身与 60s 缓存过期后的同步等待;本版以 SWR + 端点竞速消灭「等待」,数据源保持片源直达不降级(不换豆瓣源,避免点击后退化为标题搜索)
- Dockerfile `ENV NEXT_PUBLIC_SITE_VERSION` 同步 fixed133(客户端编译期常量)
### 🧪 验证(2026-11-16 实测)
- tsc / next build 通过;冷启动聚合 22.3s(list=70)、第 2 发 HIT 0.031s、过期后 STALE 0.024s(list=65)
- 站点 307→login 200、Redis 67 键完好、容器 `SITE_VERSION=fixed133`
## [fixed132] - 2026-11-16
### ✨ 全新浏览器标签页图标(favicon)
- **重新设计网站图标**:替换原来「暗黑肖像插画缩略图」的旧 favicon(16px 下糊成一团黑、不可辨识)。
新图标为 **深蓝渐变圆角底 + 天蓝播放三角 + 右上角星光点缀**,与站点暗色主题/天蓝主色一致,
影视播放属性一眼可辨。
- **小尺寸专门优化**:favicon.ico 内含 4 个尺寸——**16px 用专用优化版**(三角放大至 72%、去星光、
加粗边线,保证标签页最小尺寸下清晰可辨为播放三角),32/48/64px 用标准版(4K 超采样渲染 + LANCZOS 缩放抗锯齿)。
- **同步更新 PWA 图标**:`public/icons/icon-{192,256,384,512}.png` 全部换成新版设计,
`manifest.json` 图标路径不变,浏览器安装/书签场景同步生效。
- 图标由代码渲染生成(Pillow,脚本存 scratch),无需外部素材;16/32/48/64 四尺寸经视觉逐级核验。
### 验证
- 线上 `/favicon.ico`(32038 字节)与源文件 **sha256 逐字节一致**;浏览器实际加载的 favicon hash 同为 `960d4431c7c88996…`,MATCH。
- 首页 307→登录页正常、登录探针 401、`/icons/icon-512x512.png` 200、Redis 65 键数据完好。
- 镜像 `katelyatv:fixed132` 双推内网 Gitea + 腾讯 TCR(`fixed132` 与 `latest` tag,双仓 digest 一致 `7648449d…`)。
### 🔄 保持不变
- 站点功能、登录鉴权、观看记录(Redis)、相关推荐(fixed131)、TVBox 配置等全部无改动;
仅替换图标资源文件。
## [fixed131] - 2026-11-14
### ✨ 重做(相关推荐:本站片源按元数据匹配,点击直达实际片源)
- **数据源换成本站已有片源,不再走豆瓣推荐接口**:新增 `/api/related` 接口
(`src/app/api/related/route.ts`),用当前片的 **主演 / 导演** 名称全站搜索本站资源站拿到候选池,
再对前 12 个候选取详情,按 **主演、导演、语言、地区、类型** 五项元数据重合度打分,
排除自己/同名/豆瓣同 ID,同名跨源去重后取前 10 返回(`score` + `reasons` 标注重合依据)。
- **点击直达实际片源**:相关推荐卡片 `href` 改为 `/play?source=<源>&id=<条目ID>&title=...`
(`src/components/VideoMetaExtra.tsx`),带 source+id 进播放页后 **直接取该条详情开播,
不再做标题搜索**(`src/app/play/page.tsx` 直达模式)——彻底解决「按 title 找片对不上」的问题;
同名源随后台补搜填充「换源」面板,不阻塞开播;该 id 失效时自动回退标题搜索。
- **推荐规则显示在「相关推荐」旁**:标题右侧常驻说明「按主演 / 导演 / 语言 / 地区 / 类型匹配 · 本站片源直达」,
每张卡片下方还显示年份 · 源站与重合依据(如「导演:叶伟信 · 主演:甄子丹」,悬停看全量)。
- `/api/related` 加入 middleware 白名单(与 `/api/search`、`/api/detail` 同级),接口 10 分钟内存缓存。
### 验证
- 《叶问》(甄子丹/叶伟信/香港/剧情,动作) → 10 条全部同导演同主演:叶问2/叶问4、杀破狼、龙虎门、导火线、叶问3 等,耗时 12.7s。
- 返回条目逐条 `source+id` 直取 `/api/detail` 均返回可播 m3u8(如叶问2 → c1.rrcdnbf2.com/.../index.m3u8);`/play?source=&id=` HTTP 200。
- 构建产物确认播放页 chunk 含「本站片源直达」文案与 `/api/related` 调用。
### 🔄 保持不变
- 登录/注册鉴权、豆瓣评分/短评(仅推荐改成本站数据)、TVBox 配置(fixed128)、首页最新港剧(fixed127)、首访 IPv6 线路门。
### 🐛 修复(2026-11-15 追加:观看记录"消失"事故)
- **根因**:某次 `docker run` 重建容器时漏带 `--env-file .env`,`NEXT_PUBLIC_STORAGE_TYPE=redis`
环境变量丢失 → 站点退回 `localstorage` 模式:服务端 Redis 里的 24 个账号、全部观看记录/收藏/
管理配置瞬间不可读(用户表现为"观看记录都没了"),且登录接口在该模式下未配置 `AUTH_PASSWORD`
直接放行(站内登录形同虚设;外层 Basic Auth 仍在)。**数据本身未丢失**,Redis 中 13 条记录完好。
- **修复**:① `Dockerfile` builder/runner 两阶段 `ENV NEXT_PUBLIC_STORAGE_TYPE=redis` 烤进镜像,
彻底杜绝再丢;② 容器重建改用 `--env-file /vol3/1000/HD3/docker/katelyatv/.env` 全量环境 +
显式 `-e NEXT_PUBLIC_STORAGE_TYPE=redis` 兜底;③ README 新增「方式二 docker run(必须带
`--env-file`)」与部署铁则警示;④ compose `image` 对齐 `katelyatv:fixed131`。
- **验证**:`RUNTIME_CONFIG.STORAGE_TYPE=redis`;`/api/playrecords`(合法签名 cookie)200 返回
13 条记录;登录探针 `__probe__` 401「用户名或密码错误」(修复前为 `ok:true` 直接放行);
登录态首页 200、`/login` 200、公网 `tv.88531.cn` 跳转链正常。
- **注**:故障窗口内在浏览器新看的片记录留在本地 localStorage,不会自动同步回服务端。
### 镜像
- katelyatv:fixed131(内网 + 腾讯云双推,latest 同步)
## [fixed130] - 2026-11-14
### ✨ 优化(相关推荐)
- **标题旁显示推荐规则**:「相关推荐」右侧新增说明「豆瓣相似影片推荐 · 取前10」——
数据来自豆瓣官方推荐接口 `m.douban.com/rexxar/api/v2/{tv|movie}/{豆瓣ID}/recommendations`(取前 10 条),
让用户知道这一栏是按什么规则出的数据(`src/components/VideoMetaExtra.tsx`)。
### 🔄 保持不变
- 相关推荐卡片点击直达播放页(fixed129)、登录/注册鉴权、TVBox 配置(fixed128)、首页最新港剧(fixed127)。
### 镜像
- katelyatv:fixed130(内网 + 腾讯云双推,latest 同步)
## [fixed129] - 2026-11-14
### 🐛 修复(详情页「相关推荐」点了跳到搜索页)
- **相关推荐卡片改为直接进播放页**:`href` 由 `/search?q=<片名>` 改为 `/play?title=<片名>`,
点击即打开对应影片详情并开始播放,不再跳转到搜索页(`src/components/VideoMetaExtra.tsx`)。
- **播放页标题匹配加兜底**:精确匹配不到时(相关推荐/豆瓣标题与源站标题常有差异,如「无惧」vs「无惧神明」、
「大医凌然 第二季」vs「大医凌然」)自动放宽到双向包含匹配,再找不到才走「未找到匹配结果」页
(`src/app/play/page.tsx` 的 fetchSourcesData)。原先这类点击必然落到未找到页。
### 验证
- 构建产物确认:相关推荐卡片 `href:"/play?title="`;播放页 bundle 含「严格→放宽→未找到」三级匹配逻辑。
- 接口级复现(按播放页同款匹配逻辑跑 `/api/search`):「无惧」严格 0 → 放宽命中《无惧神明》;
「大医凌然 第二季」严格 0 → 放宽命中《大医凌然》;「无名英雄」严格命中 9 条。
「模范律师团」「去远方 第二季」源站确实无此片(返回的都是模糊无关结果),仍走未找到页(属数据缺失,非跳转 bug)。
### 🔄 保持不变
- 登录/注册鉴权、首访 IPv6 线路门(`__v6dest`)、TVBox 配置(fixed128)、首页最新港剧(fixed127)。
### 镜像
- katelyatv:fixed129(内网 + 腾讯云双推,latest 同步)
## [fixed128] - 2026-11-13
### 🐛 修复(TVBox 接口“用不了/没数据/功能和之前不一样”)
- **恢复 TVBox 旧版配置结构**:站点列表改回「全部资源」(`/api/tvbox/all`) + 各源逐站代理 `/api/tvbox/<key>`。
源码化(fixed68)时该结构被替换成直连第三方源,旧配置里的 `/api/tvbox/<key>` 路径直接 404,
电视/手机端点播因此拿不到数据;现在全部经本站域名转发,只需能访问 tv.88531.cn 即可点播。
- **新增 `/api/tvbox/[site]` 逐站代理**(旧补丁 P() 的源码化恢复):9xx 顶层分类 → 该源自身分类 id、
agg 分类逐子分类聚合(去重+更新时间排序+10 分钟缓存)、AI短剧搜索(kwPat 过滤)、st/area/year/by 筛选与兜底重查。
- **裸 `/api/tvbox` 的 9xx 分类全部返回 0 条**:agg 分支没把 903/904/905/907 换成源站真实 type_id,
现统一走 `@/lib/tvboxagg` 的逐源映射。
- **`/api/tvbox?wd=` 搜索返回成配置 JSON**:补上 wd 分支(聚合搜索)。
- **配置页「Base64 格式」实际返回 JSON**:`format=base64` 现在真正返回 base64。
- **配置响应 Cache-Control 改 no-store**(旧版语义,改完立即生效);88531 域名下接口地址强制 https(v-fixed43 需求回归)。
- `/api/tvbox/all` 的 agg 分类恢复逐子分类聚合(更全,300 条封顶);分类表缓存统一为非空 10 分钟 / 空 30 秒。
- 分类视图统一 TOP7:AI短剧/香港电影/香港剧/电影/电视剧/综艺/动画片/动漫(含每站 filters 筛选器)。
### 🔄 保持不变
- 直播 `live=txt` 首频道 TVB翡翠台(fixed126);公告/版本 hub 字段;parses/flags/ads;首页最新港剧逻辑。
### 镜像
- katelyatv:fixed128(内网 + 腾讯云双推,latest 同步)
## [fixed96] - 2026-11-09
### ✨ 新增
+8 -2
View File
@@ -35,8 +35,11 @@ RUN find ./src -type f -name "route.ts" -print0 \
ENV DOCKER_ENV=true
# 海报走站内 /api/image-proxy(浏览器直连豆瓣图被拦导致全裂)
ENV NEXT_PUBLIC_IMAGE_PROXY=/api/image-proxy
ENV NEXT_PUBLIC_SITE_VERSION=fixed108
ENV NEXT_PUBLIC_SITE_VERSION=fixed133
ENV NEXT_PUBLIC_ENABLE_REGISTER=true
# 存储模式必须烤进镜像:丢失会导致服务端数据(观看记录/账号/收藏)全部不可读,
# 且登录接口走 localstorage 分支无 AUTH_PASSWORD 直接放行(2026-11-15 事故)
ENV NEXT_PUBLIC_STORAGE_TYPE=redis
# For Docker builds, force dynamic rendering to read runtime environment variables.
RUN sed -i "/const inter = Inter({ subsets: \['latin'] });/a export const dynamic = 'force-dynamic';" src/app/layout.tsx
@@ -56,8 +59,11 @@ ENV HOSTNAME=0.0.0.0
ENV PORT=3000
ENV DOCKER_ENV=true
ENV NEXT_PUBLIC_IMAGE_PROXY=/api/image-proxy
ENV NEXT_PUBLIC_SITE_VERSION=fixed108
ENV NEXT_PUBLIC_SITE_VERSION=fixed133
ENV NEXT_PUBLIC_ENABLE_REGISTER=true
# 存储模式必须烤进镜像:丢失会导致服务端数据(观看记录/账号/收藏)全部不可读,
# 且登录接口走 localstorage 分支无 AUTH_PASSWORD 直接放行(2026-11-15 事故)
ENV NEXT_PUBLIC_STORAGE_TYPE=redis
# 从构建器中复制 standalone 输出
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
+30 -2
View File
@@ -133,6 +133,25 @@ cp .env.redis.example .env
docker compose -f docker-compose.redis.yml up -d
```
#### ⚠️ `docker run` + Redis 模式(生产部署方式,必须带 `--env-file`)
```bash
docker run -d --name katelyatv \
--network katelyatv_katelyatv-network \
-p 3030:3000 \
--restart always \
--env-file .env \
-e NEXT_PUBLIC_STORAGE_TYPE=redis \
--add-host host.docker.internal:host-gateway \
gitea.88531.cn/jinghui/katelyatv:latest
```
> **部署铁则**:`NEXT_PUBLIC_STORAGE_TYPE=redis` 决定观看记录/账号/收藏/管理配置读哪套存储。
> 重建容器时漏带 `--env-file` 或漏掉该变量,站点会退回 `localstorage` 模式——服务端全部账号与
> 观看记录瞬间"不可读"(数据未丢但在页面上表现为全部消失),且登录接口会绕过密码校验直接放行。
> 2026-11-15 生产事故即由此引起。自 fixed131 起该变量已烤进镜像(Dockerfile ENV),
> `docker run` 仍建议显式带 `--env-file .env` 兜底。
### 方式二:Docker Compose部署
上面「Docker + Redis」用到的 `docker-compose.redis.yml` 完整内容(与仓库文件一致,含全部 ports / volumes / environment):
@@ -228,6 +247,15 @@ docker compose -f docker-compose.redis.yml down
## 📋 更新日志
- **v-fixed133**:**最新港剧加载提速(对齐热门电影)**——`/api/tvbox/all` 聚合接口改 stale-while-revalidate:过期先秒回旧数据(STALE 实测 0.02s)后台再刷新,60s 内 HIT 0.03s;分类端点由串行逐试改并发竞速,**冷启动聚合 60s+ → 22.3s**;失败分类缓存 30s→2min + 宿主 cron 每分钟保活;热门电影仍走豆瓣单接口(数据源不变,点击仍直达片源)
- **v-fixed132**:全新浏览器标签页图标——替换旧「暗黑肖像缩略图」favicon(16px 下糊成黑团),新图标为**深蓝渐变圆角底 + 天蓝播放三角 + 右上角星光**,与暗色主题/天蓝主色一致;16px 用专用优化版(三角放大加粗),32/48/64 为标准版(4K 超采样抗锯齿);同步更新 PWA 图标 `icons/icon-{192,256,384,512}.png`
- **v-fixed131**:相关推荐重做——数据改为**本站已有片源**,新增 `/api/related` 按 **主演/导演/语言/地区/类型** 五项元数据匹配打分(豆瓣推荐接口不再用于推荐);卡片点击带 `source+id` **直达实际片源开播**(播放页直达模式不再按标题搜索,杜绝片源对不上);「相关推荐」标题旁常驻显示匹配规则「按主演 / 导演 / 语言 / 地区 / 类型匹配 · 本站片源直达」,卡片下标注重合依据
- **v-fixed130**:详情页「相关推荐」标题旁显示推荐规则说明「豆瓣相似影片推荐 · 取前10」(数据来自豆瓣官方推荐接口,取前 10 条相似影片)
- **v-fixed129**:详情页「相关推荐」点击改为直接打开影片详情并播放(`/play?title=`,原为跳搜索页 `/search?q=`);播放页标题匹配加兜底(精确匹配不到时放宽到双向包含,避免点进去报「未找到匹配结果」)
- **v-fixed128**:恢复 TVBox 旧版配置结构(「全部资源」站点 + 逐站代理 `/api/tvbox/<key>` + TOP7 分类视图,源码化时丢失);新增 `/api/tvbox/[site]` 逐站代理(9xx 分类→该源真实分类 id、逐子分类聚合、AI短剧搜索、筛选兜底);修复裸 `/api/tvbox` 的 9xx 分类全部 0 条、`wd` 搜索返回成配置 JSON、配置页 Base64 格式实际返回 JSON;配置响应改 no-store,88531 域名强制 https
- **v-fixed96**:新增动漫独立页 `/anime`(多源聚合+地区切换+更新排序+分页)与 `/api/browse` 第三方分类浏览接口;电影/剧集/综艺分类全量切第三方分类;修复动漫页首次进入空列表(`reset` 丢数据)
- **v-fixed43**:IPv6 探测改 4443 端口(家宽封 443 导致误判),双端口探测 + 强制使用 IPv6 按钮;恢复右上角按钮断点;chunk 按内容改名防陈旧缓存;源码迁移开始
- **v-fixed42**:IPv6 检测改严格模式(cors + 校验 JSON),缓存 2 分钟,新增重新检测按钮
@@ -244,13 +272,13 @@ docker compose -f docker-compose.redis.yml down
```bash
# 公网可拉(匿名)
docker pull gitea.88531.cn/jinghui/katelyatv:latest # 固定版本
docker pull gitea.88531.cn/jinghui/katelyatv:fixed96
docker pull gitea.88531.cn/jinghui/katelyatv:fixed133
# 腾讯云 TCR(东京,公网匿名)
docker pull jpccr.ccs.tencentyun.com/jinghui/katelyatv:latest
```
当前版本:**v-fixed96**
当前版本:**v-fixed133**
## 🔗 源码
-5
View File
@@ -6,11 +6,6 @@
"name": "无尽资源",
"is_adult": false
},
"hhzy": {
"api": "https://hhzyapi.com/api.php/provide/vod",
"name": "彗星资源",
"is_adult": false
},
"bfzy": {
"api": "https://bfzyapi.com/api.php/provide/vod",
"name": "暴风资源",
+4 -1
View File
@@ -352,8 +352,11 @@ const fu=await liveResolve(id,p);
const loc=(e.headers.get("x-forwarded-proto")||"http")+"://"+(e.headers.get("host")||"localhost:3000")+"/api/tvbox?live=ts&b="+liveB64e(fu);
return new Response(null,{status:302,headers:{"Location":loc,"Cache-Control":"no-store"}})}
if(action==="txt"){const origin=(e.headers.get("x-forwarded-proto")||"http")+"://"+(e.headers.get("host")||"localhost:3000");const chs=await liveChannels();
// TVBox 客户端默认播放列表第一条, 把 TVB翡翠台 排到最前
const rank=function(c){const n=String(c&&c.name||"");return n.indexOf("翡翠")>=0?0:(String(c&&c.id||"")==="5"?0:1)};
const sorted=chs.slice().sort(function(a,b){return rank(a)-rank(b)});
const out=["港澳台直播,#genre#"];
for(const c of chs){out.push(c.name+","+origin+"/api/tvbox?live=ch&id="+c.id+"&p=0");
for(const c of sorted){out.push(c.name+","+origin+"/api/tvbox?live=ch&id="+c.id+"&p=0");
out.push(c.name+","+origin+"/api/tvbox?live=ch&id="+c.id+"&p=1");
out.push(c.name+","+origin+"/api/tvbox?live=ch&id="+c.id+"&p=2")}
return new Response(out.join("\n")+"\n",{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}})}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 162 KiB

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 296 KiB

After

Width:  |  Height:  |  Size: 86 KiB

+42 -1
View File
@@ -650,9 +650,11 @@ const UserConfig = ({ config, role, refreshConfig }: UserConfigProps) => {
const VideoSourceConfig = ({
config,
refreshConfig,
speeds,
}: {
config: AdminConfig | null;
refreshConfig: () => Promise<void>;
speeds: Record<string, { ms: number; ok: boolean }>;
}) => {
const [sources, setSources] = useState<DataSource[]>([]);
const [showAddForm, setShowAddForm] = useState(false);
@@ -1120,6 +1122,21 @@ const VideoSourceConfig = ({
>
{!source.disabled ? '启用中' : '已禁用'}
</span>
{!source.disabled && (
<div className='mt-1 text-xs'>
{speeds[source.key] ? (
speeds[source.key].ok ? (
<span className='text-green-600 dark:text-green-400'>
{(speeds[source.key].ms / 1000).toFixed(2)}s
</span>
) : (
<span className='text-red-600 dark:text-red-400'>超时</span>
)
) : (
<span className='text-gray-400 dark:text-gray-500'>测速中…</span>
)}
</div>
)}
</td>
<td className='px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2'>
<button
@@ -1665,6 +1682,7 @@ const SiteConfigComponent = ({ config }: { config: AdminConfig | null }) => {
function AdminPageClient() {
const router = useRouter();
const [speeds, setSpeeds] = useState<Record<string, { ms: number; ok: boolean }>>({});
const [config, setConfig] = useState<AdminConfig | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -1675,6 +1693,29 @@ function AdminPageClient() {
siteConfig: false,
});
// 每次打开管理页自动并发测速所有资源站一次
useEffect(() => {
let alive = true;
const run = async () => {
try {
const r = await fetch('/api/filter?action=probe');
const j = await r.json().catch(() => null);
if (!alive) return;
const map: Record<string, { ms: number; ok: boolean }> = {};
(j?.results || []).forEach((x: any) => {
map[x.key] = { ms: x.ms, ok: x.ok };
});
setSpeeds(map);
} catch {
/* 测速失败不阻塞页面 */
}
};
run();
return () => {
alive = false;
};
}, []);
// 获取管理员配置
// showLoading 用于控制是否在请求期间显示整体加载骨架。
const fetchConfig = useCallback(async (showLoading = false) => {
@@ -1834,7 +1875,7 @@ function AdminPageClient() {
isExpanded={expandedTabs.videoSource}
onToggle={() => toggleTab('videoSource')}
>
<VideoSourceConfig config={config} refreshConfig={fetchConfig} />
<VideoSourceConfig config={config} refreshConfig={fetchConfig} speeds={speeds} />
</CollapsibleTab>
</div>
</div>
+29 -3
View File
@@ -22,7 +22,7 @@ interface Site {
}
const BATCH_DEFAULT = 5;
const ALL_MAX_SITES = 100;
const ALL_MAX_SITES = 8;
// 源站 class 缓存:有数据 10min / 空 30s(原补丁逻辑)
const classCache = new Map<string, [number, any[], boolean]>();
@@ -166,7 +166,7 @@ async function browseSite(
const batch = Math.min(Math.max(opts.batch || BATCH_DEFAULT, 1), 6);
const want = 24;
const maxPages = 30;
const list: any[] = [];
let list: any[] = [];
let hasMore = true;
let fetched = 0;
while (hasMore && fetched < maxPages) {
@@ -191,6 +191,7 @@ async function browseSite(
});
if (list.length >= want || !hasMore) break;
}
list = list.slice(0, 50);
return { list, next_pg: pg, has_more: hasMore };
}
@@ -222,7 +223,7 @@ async function browseAll(
)
);
const seen = new Set<string>();
const list: any[] = [];
let list: any[] = [];
let hasMore = false;
let nextPg = Infinity;
per.forEach((r) => {
@@ -236,6 +237,7 @@ async function browseAll(
}
});
});
list = list.slice(0, 50);
return { list, next_pg: nextPg === Infinity ? pg + 1 : nextPg, has_more: hasMore };
}
@@ -257,6 +259,30 @@ export async function GET(request: NextRequest) {
{ headers }
);
}
if (action === 'probe') {
const results = await Promise.all(
sites.map(async (st) => {
const base = st.api + (st.api.includes('?') ? '&' : '?');
const t0 = Date.now();
let ok = false;
try {
const ctrl = new AbortController();
const tm = setTimeout(() => ctrl.abort(), 6000);
const r = await fetch(base + 'ac=list', {
headers: { 'User-Agent': UA, Accept: 'application/json' },
signal: ctrl.signal,
});
clearTimeout(tm);
if (r.ok) {
const j = await r.json().catch(() => null);
ok = !!(j && (Array.isArray(j.list) || Array.isArray(j.class)));
}
} catch {}
return { key: st.key, name: st.name, ms: Date.now() - t0, ok };
})
);
return NextResponse.json({ results }, { headers });
}
if (source === 'all') {
if (action === 'classes') {
return NextResponse.json(
+268
View File
@@ -0,0 +1,268 @@
import { NextResponse } from 'next/server';
import { getAvailableApiSites, getCacheTime, type ApiSite } from '@/lib/config';
import { addCorsHeaders, handleOptionsRequest } from '@/lib/cors';
import { searchFromApi, getDetailFromApi } from '@/lib/downstream';
import type { SearchResult } from '@/lib/types';
export const runtime = 'edge';
// 处理OPTIONS预检请求
export async function OPTIONS() {
return handleOptionsRequest();
}
// ---------------------------------------------------------------------------
// 相关推荐:只在本站已有片源里找,按「主演 / 导演 / 语言 / 地区 / 类型」匹配,
// 返回可直接播放的 source+id(点击进 /play?source=&id= 直达,不走标题搜索)。
// ---------------------------------------------------------------------------
interface RelatedItem {
source: string;
source_name: string;
id: string;
title: string;
poster: string;
year: string;
score: number;
reasons: string[];
}
// edge 实例内的短 TTL 缓存,避免同一部片反复全站搜索
const cache = new Map<string, { ts: number; items: RelatedItem[] }>();
const CACHE_TTL = 10 * 60 * 1000;
// 拆分人名/地区/语言/类型串(、,,/;| 和空白分隔)
function splitNames(raw: string, max: number): string[] {
if (!raw) return [];
const parts = raw
.split(/[、,,/;;|]+|\s+/)
.map((x) => x.trim())
.filter((x) => x.length >= 2);
const seen = new Set<string>();
const out: string[] = [];
for (const p of parts) {
if (!seen.has(p)) {
seen.add(p);
out.push(p);
}
if (out.length >= max) break;
}
return out;
}
function normTitle(x: string): string {
return x
.replace(/[\s·::\-—\[\]【]()()、\/]/g, '')
.toLowerCase();
}
// 双向包含式重叠("中国香港" 与 "香港" 互认)
function overlap(self: string[], cand: string[]): string[] {
return self.filter(
(a) => a.length >= 2 && cand.some((b) => b.includes(a) || a.includes(b))
);
}
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const title = searchParams.get('title') || '';
const actor = searchParams.get('actor') || '';
const director = searchParams.get('director') || '';
const area = searchParams.get('area') || '';
const lang = searchParams.get('lang') || '';
const genre = searchParams.get('genre') || '';
const isTvRaw = searchParams.get('isTv'); // '1' | '0' | null
const doubanId = searchParams.get('doubanId') || '';
const selfSource = searchParams.get('selfSource') || '';
const selfId = searchParams.get('selfId') || '';
const respond = async (items: RelatedItem[]) => {
const cacheTime = await getCacheTime();
const response = NextResponse.json(
{ items },
{
headers: {
'Cache-Control': `public, max-age=${cacheTime}, s-maxage=${cacheTime}`,
'CDN-Cache-Control': `public, s-maxage=${cacheTime}`,
'Vercel-CDN-Cache-Control': `public, s-maxage=${cacheTime}`,
},
}
);
return addCorsHeaders(response);
};
const dirs = splitNames(director, 2);
const acts = splitNames(actor, 3);
// 没有主演/导演就没有匹配依据 → 不出相关推荐
if (!title || (dirs.length === 0 && acts.length === 0)) {
return respond([]);
}
const cacheKey = [
title, actor, director, area, lang, genre, isTvRaw, doubanId, selfSource, selfId,
].join('|');
const hit = cache.get(cacheKey);
if (hit && Date.now() - hit.ts < CACHE_TTL) {
return respond(hit.items);
}
try {
const sites = await getAvailableApiSites(true); // 与搜索一致:过滤成人源
if (!sites || sites.length === 0) return respond([]);
// 1) 按 导演名/演员名 全站搜索,得到「本站已有」的候选池(带来源强度)
const keywords: { kw: string; dir: boolean }[] = [
...dirs.map((k) => ({ kw: k, dir: true })),
...acts.map((k) => ({ kw: k, dir: false })),
];
const prov = new Map<
string,
{ dir: number; act: number; sample: SearchResult }
>();
await Promise.all(
keywords.map(async ({ kw, dir }) => {
const batches = await Promise.all(
sites.map((site) =>
searchFromApi(site, kw).catch(() => [] as SearchResult[])
)
);
for (const r of batches.flat()) {
if (!r || !r.id || !r.source) continue;
const key = `${r.source}:${r.id}`;
const cur = prov.get(key) || { dir: 0, act: 0, sample: r };
if (dir) cur.dir += 1;
else cur.act += 1;
if (!cur.sample.episodes?.length && r.episodes?.length) {
cur.sample = r;
}
prov.set(key, cur);
}
})
);
const selfTitle = normTitle(title);
const selfKey = selfSource && selfId ? `${selfSource}:${selfId}` : '';
const doubanNum = parseInt(doubanId, 10);
// 2) 初筛:必须可播放、不是本条目、不是同名
const pool: { r: SearchResult; dir: number; act: number }[] = [];
prov.forEach((v, key) => {
const r = v.sample;
if (key === selfKey) return;
if (!r.episodes || r.episodes.length === 0) return;
if (selfTitle && normTitle(r.title) === selfTitle) return;
if (doubanNum && r.douban_id === doubanNum) return;
pool.push({ r, dir: v.dir, act: v.act });
});
if (pool.length === 0) return respond([]);
// 3) 按来源强度排序,取前 12 补全元数据(主演/导演/地区/语言 只在详情里有)
pool.sort((a, b) => b.dir * 2 + b.act - (a.dir * 2 + a.act));
const top = pool.slice(0, 12);
const siteMap = new Map<string, ApiSite>(
sites.map((s) => [s.key, s] as [string, ApiSite])
);
const enriched = await Promise.all(
top.map(async (c) => {
const site = siteMap.get(c.r.source);
if (!site) return { ...c, detail: null as SearchResult | null };
try {
const d = await getDetailFromApi(site, c.r.id);
return { ...c, detail: d || null };
} catch {
return { ...c, detail: null };
}
})
);
// 4) 打分:主演/导演/地区/语言/类型 越多重合分越高
const selfActs = splitNames(actor, 12);
const selfDirs = splitNames(director, 6);
const selfArea = splitNames(area, 4);
const selfLang = splitNames(lang, 4);
const selfGenre = splitNames(genre, 8);
const isTv = isTvRaw === '1' || isTvRaw === '0' ? isTvRaw === '1' : null;
const items: RelatedItem[] = [];
const seenTitles = new Set<string>();
for (const c of enriched) {
const meta = c.detail || c.r;
const candActs = splitNames(meta.actor || c.r.actor || '', 12);
const candDirs = splitNames(meta.director || c.r.director || '', 8);
const candArea = splitNames(meta.area || '', 4);
const candLang = splitNames(meta.lang || '', 4);
const candGenre = splitNames(meta.class || c.r.class || '', 8);
const sharedActor = overlap(selfActs, candActs);
const sharedDir = overlap(selfDirs, candDirs);
const areaHit = overlap(selfArea, candArea);
const langHit = overlap(selfLang, candLang);
const genreHit = overlap(selfGenre, candGenre);
const hasMeta =
candActs.length + candDirs.length + candArea.length + candLang.length > 0;
const kindHit =
isTv === null
? 0
: (isTv && c.r.episodes.length > 1) ||
(!isTv && c.r.episodes.length <= 1)
? 1
: 0;
const score =
sharedDir.length * 5 +
Math.min(sharedActor.length, 3) * 3 +
Math.min(areaHit.length, 2) * 2 +
Math.min(langHit.length, 2) * 2 +
Math.min(genreHit.length, 3) +
Math.min(c.dir, 2) * 2 +
Math.min(c.act, 3) +
(isTv === null ? 0 : kindHit * 2);
// 证据:有任一元数据重合,或该候选本来就是按导演/演员名搜出来的
const evidence = hasMeta
? sharedDir.length > 0 ||
sharedActor.length > 0 ||
areaHit.length > 0 ||
langHit.length > 0 ||
genreHit.length > 0 ||
c.dir > 0
: c.dir > 0 || c.act > 0;
if (!evidence || score < 3) continue;
const reasons: string[] = [];
if (sharedDir.length) reasons.push(`导演:${sharedDir[0]}`);
sharedActor.slice(0, 2).forEach((a) => reasons.push(`主演:${a}`));
if (areaHit.length) reasons.push(`地区:${areaHit[0]}`);
if (langHit.length) reasons.push(`语言:${langHit[0]}`);
if (genreHit.length) reasons.push(`类型:${genreHit.slice(0, 2).join('/')}`);
const nt = normTitle(c.r.title);
if (seenTitles.has(nt)) continue; // 同名去重(跨源只留分数最高的一条)
seenTitles.add(nt);
items.push({
source: c.r.source,
source_name: c.r.source_name || '',
id: c.r.id,
title: c.r.title,
poster: c.r.poster || '',
year: c.r.year || '',
score,
reasons: reasons.slice(0, 4),
});
}
items.sort((a, b) => b.score - a.score);
const finalItems = items.slice(0, 10);
if (cache.size > 100) cache.clear();
cache.set(cacheKey, { ts: Date.now(), items: finalItems });
return respond(finalItems);
} catch {
return respond([]);
}
}
+216
View File
@@ -0,0 +1,216 @@
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { SrcCfg, aggregateAll, fetchClass, mkTransform, subFetch } from '@/lib/tvboxagg';
// 强制使用 Edge Runtime 以支持 Cloudflare Pages
export const runtime = 'edge';
// ---------- 逐站代理 /api/tvbox/<site> ----------
// 恢复旧运行时补丁 app-api-tvbox-route.js 的 P() 能力(源码化重构时该能力被整体丢失):
// TVBox 配置里每个资源站都指向本站域名,电视/手机端只需要能访问 tv.88531.cn 就能点播,
// 请求经本站转发到真实源站,并做 9xx 顶层分类 → 该源自身分类 id 的映射。
function json(d: any) {
return NextResponse.json(d, { headers: { 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
// 上游异常/站不存在时的空骨架(旧补丁 VB)
function VB(cls: any[]) {
return { code: 1, msg: '数据列表', page: 1, pagecount: 1, limit: 20, total: 0, list: [], class: Array.isArray(cls) ? cls : [] };
}
// 直连某源取一条查询(旧补丁 doF):10s 超时,文本解析容错
async function doF(base: string, q: string): Promise<any> {
const r = await subFetch(base, q, 10000);
return r;
}
// 逐子分类聚合(旧补丁 AGG):每个子分类取一页,vod_id 去重,按更新时间排序,10 分钟缓存
const aggC = new Map<string, [number, any[]]>();
async function AGG(base: string, tids: string[], extra: string, pg: string): Promise<any[]> {
const key = base + '|' + tids.join(',') + '|' + extra + '|' + pg;
const ent = aggC.get(key);
if (ent && Date.now() - ent[0] < 600000) return ent[1];
const start = Date.now();
const pool: any[] = [];
const seen: Record<string, number> = {};
for (let i = 0; i < tids.length; i++) {
if (Date.now() - start > 25000) break; // 兜底:不让逐子分类聚合拖过 TVBox 的超时
let r: any = null;
for (let a = 0; a < 2; a++) {
r = await subFetch(base, 'ac=videolist&pg=' + pg + '&t=' + encodeURIComponent(tids[i]) + extra, 6000);
if (r && Array.isArray(r.list) && r.list.length) break;
if (a === 0) await new Promise((z) => setTimeout(z, 700));
}
if (r && Array.isArray(r.list)) {
for (const it of r.list) {
const v = it.vod_id;
if (v != null && !seen[v]) {
seen[v] = 1;
pool.push(it);
}
}
}
if (i < tids.length - 1) await new Promise((z) => setTimeout(z, 250));
}
pool.sort((a: any, b: any) => String(b.vod_time == null ? '' : b.vod_time).localeCompare(String(a.vod_time == null ? '' : a.vod_time)));
aggC.set(key, [Date.now(), pool]);
if (aggC.size > 100) aggC.clear();
return pool;
}
export async function GET(request: NextRequest, { params }: { params: { site: string } }) {
try {
let site = '';
try {
site = decodeURIComponent(params.site || '').trim();
} catch {
site = String(params.site || '').trim();
}
const config = await getConfig();
const cfg: SrcCfg[] = (config.SourceConfig || []) as SrcCfg[];
// 全部资源 → 直接走 /api/tvbox/all 同一套全源聚合
if (site === 'all') {
const r = await aggregateAll(cfg.filter((s) => !s.disabled), new URL(request.url).searchParams);
return json(r);
}
const sc = cfg.find((x) => (x.key || x.name) === site) || cfg.find((x) => x.key === site) || cfg.find((x) => x.name === site);
if (!sc || !sc.api) {
return json(VB([]));
}
const base = String(sc.api).replace(/[?&]+$/, '');
const sp = new URLSearchParams(new URL(request.url).search);
// 该源自身分类表 + 本站统一的 9xx 分类视图
const cls = await fetchClass(base);
const mk = mkTransform(cls);
const t = sp.get('t') || '';
const st = sp.get('st') || '';
let stv = st;
if (st && !/^\d+$/.test(st)) {
const hit = (cls || []).find((c: any) => c && String(c.type_name).trim() === st);
if (hit) stv = String(hit.type_id);
}
let area = '';
let aggTids: string[] | null = null;
let kwPat = '';
const top = mk.tops[t];
if (top) {
area = top.area || '';
if (st) {
sp.set('t', stv);
} else if (top.kind === 'agg') {
const kids: string[] = (top.ch || []).map((c: any) => String(c.type_id));
aggTids = kids.length ? kids : top.native ? [String(top.native)] : null;
} else if (top.kind === 'search') {
sp.set('wd', top.wd || 'AI短剧');
sp.delete('t');
kwPat = top.kwPat || '';
} else {
sp.set('t', String(top.native));
}
} else if (st) {
sp.set('t', stv);
}
sp.delete('st');
if (area && !sp.get('area')) sp.set('area', area);
let extra = '';
['year', 'area', 'by'].forEach((k) => {
const v = sp.get(k);
if (v) extra += '&' + k + '=' + encodeURIComponent(v);
});
const pg = sp.get('pg') || '1';
let d: any = null;
let aggRan = false;
if (aggTids && aggTids.length) {
const pool = await AGG(base, aggTids, extra, pg);
d = { code: 1, msg: '数据列表', page: Number(pg) || 1, pagecount: 1, limit: pool.length, total: pool.length, list: pool };
aggRan = true;
} else {
d = await doF(base, sp.toString());
}
// agg 结果太少(上游抖动)→ 再补一次聚合兜底(旧补丁逻辑)
if (aggTids && aggTids.length && (!d || !Array.isArray(d.list) || d.list.length < 10)) {
const pool = await AGG(base, aggTids, extra, pg);
if (pool.length) {
d = { code: 1, msg: '数据列表', page: Number(pg) || 1, pagecount: 1, limit: pool.length, total: pool.length, list: pool };
aggRan = true;
}
}
if (!d) return json(VB(cls));
if (!Array.isArray(d.class) || !d.class.length) d.class = cls;
if (!Array.isArray(d.list)) d.list = [];
// 数字 t 在该站结果里对不上号 → 退回用分类名重查一次(旧补丁兜底)
const tid = sp.get('t') || '';
if (!aggRan && !kwPat && tid && /^\d+$/.test(tid)) {
const hitSome = d.list.some((x: any) => String(x.type_id) === tid);
if (!hitSome) {
const nm = (d.class || []).find((x: any) => String(x.type_id) === tid);
if (nm) {
const alt = sp.toString().replace(/(^|&)t=[^&]*/, '$1t=' + encodeURIComponent(String(nm.type_name)));
const d2 = await doF(base, alt);
if (d2 && Array.isArray(d2.list) && d2.list.length) {
if (!Array.isArray(d2.class) || !d2.class.length) d2.class = d.class;
d = d2;
}
}
}
}
const yr = sp.get('year') || '';
const ar = sp.get('area') || '';
const by = sp.get('by') || '';
// 年份筛选拿不到数据 → 去掉分类再查一次,再由下面的年份过滤收敛(旧补丁兜底)
if (yr && !d.list.length) {
const f2 = sp.toString().split('&').filter((p) => p.indexOf('t=') !== 0 && p.indexOf('year=') !== 0).concat('year=' + encodeURIComponent(yr)).join('&');
const d2 = await doF(base, f2);
if (d2 && Array.isArray(d2.list)) {
if (!Array.isArray(d2.class) || !d2.class.length) d2.class = d.class;
d = d2;
if (!Array.isArray(d.list)) d.list = [];
}
}
if (!Array.isArray(d.list)) d.list = [];
const apply = (arr: any[], keep: any[]) => (keep.length ? keep : arr);
if (yr && tid && /^\d+$/.test(tid)) d.list = apply(d.list, d.list.filter((x: any) => String(x.type_id) === tid));
if (yr) d.list = apply(d.list, d.list.filter((x: any) => String(x.vod_year == null ? '' : x.vod_year).indexOf(yr) >= 0));
if (ar) d.list = apply(d.list, d.list.filter((x: any) => String(x.vod_area == null ? '' : x.vod_area).indexOf(ar) >= 0));
if (kwPat) {
const re = new RegExp(kwPat, 'i');
d.list = apply(d.list, d.list.filter((x: any) => re.test(String(x.vod_name == null ? '' : x.vod_name))));
d.list.sort((a: any, b: any) => String(b.vod_time == null ? '' : b.vod_time).localeCompare(String(a.vod_time == null ? '' : a.vod_time)));
}
if (by && d.list.length) {
const gs = (x: any, k: string) => String(x[k] == null ? '' : x[k]);
const gn = (x: any) => { const v = parseFloat(x); return isNaN(v) ? 0 : v; };
d.list.sort((a: any, b: any) => {
if (by === 'time') return gs(b, 'vod_time').localeCompare(gs(a, 'vod_time'));
if (by === 'hits') return (gn(b.vod_hits) - gn(a.vod_hits)) || (gn(b.vod_score) - gn(a.vod_score)) || gs(b, 'vod_time').localeCompare(gs(a, 'vod_time'));
if (by === 'score') return gn(b.vod_score) - gn(a.vod_score);
return 0;
});
}
// TVBox 端统一展示本站的 7+1 分类视图与筛选器(旧补丁:d.class=mk.class / d.filters=mk.filters)
d.class = mk.class;
d.filters = mk.filters;
// 只有走了本站的聚合/筛选才改 total(直连透传时保留上游分页信息)
if (aggRan || kwPat || yr || ar) {
d.total = d.list.length;
d.limit = d.list.length;
}
return json(d);
} catch {
return json(VB([]));
}
}
+72 -143
View File
@@ -1,161 +1,90 @@
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { SrcCfg, aggregateAll } from '@/lib/tvboxagg';
// 强制使用 Edge Runtime 以支持 Cloudflare Pages
export const runtime = 'edge';
// ---------- /api/tvbox/all 全源聚合(源码化,原运行时补丁 app-api-tvbox-route.js 的 ALL) ----------
// ---------- /api/tvbox/all 全源聚合 ----------
// 聚合/class/9xx 映射逻辑已收拢到 @/lib/tvboxagg(旧补丁 ALL 逻辑的源码化实现),
// 本文件只负责:进程内缓存 + 出口。
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36';
// 进程内响应缓存(stale-while-revalidate):
// - HIT:有数据 60s 内直接返回(浏览器同样 max-age=60);
// - STALE:过期后 10 分钟内先立刻返回旧数据,同时后台重新聚合——
// 多源聚合实测 8~18s,用户请求永远零等待(最新港剧与热门电影一样秒开);
// - 完全冷(容器刚重启、无任何旧数据)才同步等一次聚合。
const respCache = new Map<string, [number, any]>();
const refreshing = new Set<string>();
const FRESH_MS = 60000; // 有数据的强新鲜窗口
const FRESH_EMPTY_MS = 5000; // 空结果只短缓存 5s:上游偶发超时不能把空列表当正常数据缓存
const STALE_MS = 10 * 60 * 1000; // stale 窗口:旧数据最多用 10 分钟,期间后台必然已刷新
interface SrcCfg { key: string; name: string; api: string; detail?: string; disabled?: boolean }
async function subFetch(api: string, query: string): Promise<any> {
async function aggregateNow(cacheKey: string, sp: URLSearchParams): Promise<any | null> {
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 8000);
const r = await fetch(api + (api.includes('?') ? '&' : '?') + query, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: ctrl.signal });
clearTimeout(t);
if (!r.ok) return null;
return await r.json();
} catch { return null; }
}
function ns(x: any, key: string) { return Object.assign({}, x, { vod_id: String(key) + ':' + String(x.vod_id) }); }
// 源站 class 缓存:顶层 9xx → 源站真实 type_id(旧补丁 P() 的 tops 映射逻辑)
const classCache = new Map<string, [number, any[]]>();
async function fetchClass(api: string): Promise<any[]> {
const now = Date.now();
const c = classCache.get(api);
if (c && now - c[0] < 600000) return c[1];
for (const ep of [api, api + (api.includes('?') ? '&' : '?') + 'ac=list']) {
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 8000);
const r = await fetch(ep, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: ctrl.signal });
clearTimeout(t);
if (!r.ok) continue;
const j = await r.json();
if (Array.isArray(j?.class) && j.class.length) {
classCache.set(api, [now, j.class]);
return j.class;
}
} catch {}
}
classCache.set(api, [now, []]);
return [];
}
// t=901-907(顶层分类)→ 每个源各自的真实 type_id(各源分类表不同,不能拿第一个源的 id 发给全源)
// t=902(香港剧):源站有“香港剧”类目则直取;没有则取电视剧类目 + area=香港 过滤,保证只出香港剧
async function resolveTopPerSource(sources: SrcCfg[], sp: URLSearchParams): Promise<{ extraArea: string; nativeByApi: Map<string, string> }> {
const t = sp.get('t');
const nativeByApi = new Map<string, string>();
if (!t || !/^90[1-9]$/.test(t) || sp.get('wd') || sp.get('ids')) return { extraArea: '', nativeByApi };
const classes = await Promise.all(sources.map((s) => fetchClass(s.api)));
sources.forEach((s, i) => {
const byN: Record<string, any> = {};
(classes[i] || []).forEach((c) => { if (c && c.type_name != null) byN[String(c.type_name).trim()] = c; });
const fd = (...names: string[]) => { for (const n of names) if (byN[n]) return byN[n]; return null; };
const mv = fd('电影', '电影片');
const tv = fd('连续剧', '电视剧', '剧集');
const vy = fd('综艺', '综艺片');
const an = fd('动漫', '动漫片');
const to = fd('动画片', '动画电影', '动漫电影');
const hk = fd('香港剧', '港澳剧', '港台剧', '港剧');
let hit = null;
if (t === '901') hit = mv;
else if (t === '902') hit = hk || tv;
else if (t === '903') hit = mv;
else if (t === '904') hit = tv;
else if (t === '905') hit = vy;
else if (t === '906') hit = to;
else if (t === '907') hit = an;
if (hit) nativeByApi.set(s.api, String(hit.type_id));
});
if (t === '901' || t === '902') return { extraArea: '香港', nativeByApi };
return { extraArea: '', nativeByApi };
}
async function aggregateAll(sources: SrcCfg[], sp: URLSearchParams) {
const srcs = sources.filter((s) => !s.disabled);
const out: any = { code: 1, msg: '数据列表', page: 1, pagecount: 1, limit: 0, total: 0, list: [] };
const ids = sp.get('ids');
const wd = sp.get('wd');
const t = sp.get('t');
const pg = sp.get('pg') || '1';
if (ids) {
const byK: Record<string, string[]> = {};
ids.split(',').forEach((p) => {
const i = p.indexOf(':');
if (i > 0) { const k = p.slice(0, i); const id = p.slice(i + 1); (byK[k] = byK[k] || []).push(id); }
});
for (const k in byK) {
const d = await subFetch(srcs.find((s) => s.key === k)?.api || '', 'ac=videolist&ids=' + byK[k].map(encodeURIComponent).join(','));
if (d && Array.isArray(d.list)) d.list.forEach((x: any) => out.list.push(ns(x, k)));
const config = await getConfig();
const sourceConfigs: SrcCfg[] = (config.SourceConfig || []).filter((s: any) => !s.disabled);
const r = await aggregateAll(sourceConfigs, sp);
// 只缓存有数据的结果;空结果不驻留(下次请求立即重试)
if (r && Array.isArray(r.list) && r.list.length) {
respCache.set(cacheKey, [Date.now(), r]);
if (respCache.size > 200) respCache.clear();
return r;
}
out.total = out.list.length; out.limit = out.list.length;
return out;
} catch {
// 聚合失败静默:stale 数据继续可用,下次请求/预热会再试
}
return null;
}
// 顶层 9xx 分类:每个源用自己的真实 type_id 查询(旧补丁 P() tops 逻辑,源码化时按源分别映射)
const topT = sp.get('t');
const isTop = topT && /^90[1-9]$/.test(topT) && !wd && !ids;
const { extraArea, nativeByApi } = isTop
? await resolveTopPerSource(srcs, sp)
: { extraArea: '', nativeByApi: new Map<string, string>() };
const baseExtra = ['st', 'year', 'area', 'by'].map((k) => { const v = sp.get(k); return v ? '&' + k + '=' + encodeURIComponent(v) : ''; }).join('');
const queries = srcs.map((s) => {
let q = 'ac=videolist&pg=' + pg;
if (wd) q += '&wd=' + encodeURIComponent(wd);
const nt = isTop ? nativeByApi.get(s.api) : topT;
if (nt) q += '&t=' + encodeURIComponent(nt);
q += baseExtra;
return q;
});
const results = await Promise.all(srcs.map((s, i) => subFetch(s.api, queries[i])));
const seen: Record<string, number> = {};
let list: any[] = [];
results.forEach((d, i) => {
if (d && Array.isArray(d.list)) {
const key = srcs[i].key;
d.list.forEach((x: any) => {
const nm = String(x.vod_name || '').trim();
if (nm && !seen[nm]) { seen[nm] = 1; list.push(ns(x, key)); }
});
}
});
list.sort((a, b) => String(b.vod_time == null ? '' : b.vod_time).localeCompare(String(a.vod_time == null ? '' : a.vod_time)));
// 902 香港剧硬性过滤:只保留地区含“香港”的条目(兜底:无地区但名字命中的保留,避免误杀)
if (topT === '902') {
const hkPat = /港剧|粤语|TVB|邵氏|香港/i;
list = list.filter((x) => {
const area = String(x.vod_area || '');
if (area.indexOf('香港') >= 0 || area === '香港') return true;
if (!area && hkPat.test(String(x.vod_name || ''))) return true;
return false;
});
}
const fy = sp.get('year');
const fa = sp.get('area') || extraArea;
if (fy) list = list.filter((x) => String(x.vod_year || '').indexOf(fy) >= 0);
if (fa && topT !== '902') list = list.filter((x) => String(x.vod_area || '').indexOf(fa) >= 0);
list = list.slice(0, 300);
out.list = list; out.total = list.length; out.limit = list.length;
const rep = results.find((d) => d && Array.isArray(d.class) && d.class.length);
if (rep) { out.class = rep.class; out.filters = rep.filters; }
return out;
// 后台刷新(同一 key 并发去重,避免多个过期请求同时打上游)
function refreshInBackground(cacheKey: string, sp: URLSearchParams) {
if (refreshing.has(cacheKey)) return;
refreshing.add(cacheKey);
aggregateNow(cacheKey, sp).finally(() => refreshing.delete(cacheKey));
}
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const config = await getConfig();
const sourceConfigs: SrcCfg[] = (config.SourceConfig || []).filter((s: any) => !s.disabled);
const r = await aggregateAll(sourceConfigs, searchParams);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
const cacheKey = searchParams.toString();
const now = Date.now();
const c = respCache.get(cacheKey);
const hasList = !!(c && c[1] && Array.isArray(c[1].list) && c[1].list.length);
const freshTTL = hasList ? FRESH_MS : FRESH_EMPTY_MS;
if (c && now - c[0] < freshTTL) {
return NextResponse.json(c[1], { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60', 'X-Cache': 'HIT' } });
}
// stale:先给旧数据、后台刷新——用户零等待
if (hasList && now - c[0] < STALE_MS) {
refreshInBackground(cacheKey, searchParams);
return NextResponse.json(c[1], { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60', 'X-Cache': 'STALE' } });
}
// 完全冷:没人有数据可给,只能同步聚合一等(配合下方启动预热 + 宿主保活 cron,正常用户几乎碰不到)
const r = await aggregateNow(cacheKey, searchParams);
return NextResponse.json(
r || { code: 1, msg: '数据列表', page: 1, pagecount: 1, limit: 0, total: 0, list: [] },
{ headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } },
);
}
// ---------- 启动预热 + 周期保活 ----------
// 模块被首个请求加载后:3s 后预热首页聚合键(最新港剧),此后每 55s 续一次
// (接在 60s fresh 窗口前),用户请求几乎永远命中 HIT/STALE。
// edge isolate 若不保留定时器则自然退化为"过期请求触发后台刷新",无副作用。
const WARM_KEYS = ['ac=videolist&t=902&pg=1&by=time'];
function scheduleWarm() {
const g = globalThis as any;
if (g.__tvboxAllWarm) return;
g.__tvboxAllWarm = true;
const run = () => {
for (const q of WARM_KEYS) {
const ent = respCache.get(q);
if (!ent || Date.now() - ent[0] > FRESH_MS - 5000) refreshInBackground(q, new URLSearchParams(q));
}
};
setTimeout(run, 3000);
setInterval(run, 55000);
}
scheduleWarm();
+34 -214
View File
@@ -1,158 +1,11 @@
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { SrcCfg, aggregateAll, fetchClass, mkTransform } from '@/lib/tvboxagg';
// 强制使用 Edge Runtime 以支持 Cloudflare Pages
export const runtime = 'edge';
// ---------- TVBox 聚合层(源码化,替代 patches/app-api-tvbox-route.js) ----------
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36';
interface SrcCfg { key: string; name: string; api: string; detail?: string; disabled?: boolean }
// 缓存源站 class 列表:30s 正常 / 10min 空
const classCache = new Map<string, [number, any[], boolean]>();
async function fetchClass(api: string): Promise<any[]> {
const now = Date.now();
const c = classCache.get(api);
if (c && (c[2] ? now - c[0] < 30000 : now - c[0] < 600000)) return c[1];
for (const ep of [api, api + (api.includes('?') ? '&' : '?') + 'ac=list', api + (api.includes('?') ? '&' : '?') + 'ac=class']) {
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 8000);
const r = await fetch(ep, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: ctrl.signal });
clearTimeout(t);
if (!r.ok) continue;
const j = await r.json();
if (Array.isArray(j?.class) && j.class.length) {
classCache.set(api, [now, j.class, false]);
return j.class;
}
} catch {}
}
classCache.set(api, [now, [], true]);
return [];
}
function mkTransform(cls: any[]) {
const byN: Record<string, any> = {};
(cls || []).forEach((c) => { if (c && c.type_name != null) byN[String(c.type_name).trim()] = c; });
const fd = (...names: string[]) => { for (const n of names) if (byN[n]) return byN[n]; return null; };
const kd = (r: any) => r ? (cls || []).filter((c) => c && String(c.type_pid) === String(r.type_id) && String(c.type_id) !== String(r.type_id)) : [];
const mv = fd('电影', '电影片');
const tv = fd('连续剧', '电视剧', '剧集');
const vy = fd('综艺', '综艺片');
const an = fd('动漫', '动漫片');
const to = fd('动画片', '动画电影', '动漫电影');
const hk = fd('香港剧', '港澳剧', '港台剧', '港剧');
const T: any[] = [];
if (mv) T.push({ tid: '901', name: '香港电影', kind: 'agg', native: String(mv.type_id), ch: kd(mv), area: '香港' });
if (hk) T.push({ tid: '902', name: '香港剧', kind: 'direct', native: String(hk.type_id), ch: [], area: '' });
if (mv) T.push({ tid: '903', name: '电影', kind: 'agg', native: String(mv.type_id), ch: kd(mv), area: '' });
if (tv) T.push({ tid: '904', name: '电视剧', kind: 'agg', native: String(tv.type_id), ch: kd(tv), area: '' });
if (vy) T.push({ tid: '905', name: '综艺', kind: 'agg', native: String(vy.type_id), ch: kd(vy), area: '' });
if (to) T.push({ tid: '906', name: '动画片', kind: 'direct', native: String(to.type_id), ch: [], area: '' });
if (an) T.push({ tid: '907', name: '动漫', kind: 'agg', native: String(an.type_id), ch: kd(an), area: '' });
T.push({ tid: '909', name: 'AI短剧', kind: 'search', native: '', wd: 'AI短剧', kwPat: 'AI|短剧|微短剧', ch: [], area: '' });
const Y = [{ n: '全部', v: '' }]; for (let y = 2026; y >= 2010; y--) Y.push({ n: String(y), v: String(y) });
const AR = [{ n: '全部', v: '' }, { n: '中国大陆', v: '中国大陆' }, { n: '中国香港', v: '中国香港' }, { n: '中国台湾', v: '中国台湾' }, { n: '美国', v: '美国' }, { n: '韩国', v: '韩国' }, { n: '日本', v: '日本' }, { n: '英国', v: '英国' }, { n: '法国', v: '法国' }, { n: '德国', v: '德国' }, { n: '泰国', v: '泰国' }, { n: '印度', v: '印度' }, { n: '加拿大', v: '加拿大' }, { n: '其他', v: '其他' }];
const BY = [{ n: '最新', v: 'time' }, { n: '最热', v: 'hits' }, { n: '评分', v: 'score' }];
const cls7: any[] = [];
const tops: Record<string, any> = {};
const filters: Record<string, any[]> = {};
T.forEach((t) => {
cls7.push({ type_id: t.tid, type_name: t.name, type_pid: 0 });
tops[t.tid] = { kind: t.kind, native: t.native, wd: t.wd || '', kwPat: t.kwPat || '', ch: t.ch, area: t.area || '' };
const g: any[] = [];
if (t.ch && t.ch.length) g.push({ key: 'st', name: '分类', value: [{ n: '全部', v: '' }].concat(t.ch.map((c: any) => ({ n: String(c.type_name), v: String(c.type_name) }))) });
if (t.tid !== '901') g.push({ key: 'area', name: '地区', value: AR });
g.push({ key: 'year', name: '年份', value: Y });
g.push({ key: 'by', name: '排序', value: BY });
filters[t.tid] = g;
});
if (!cls7.length) (cls || []).forEach((c) => cls7.push({ type_id: String(c.type_id), type_name: c.type_name, type_pid: c.type_pid }));
return { class: cls7, tops, filters };
}
async function subFetch(api: string, query: string): Promise<any> {
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 8000);
const r = await fetch(api + (api.includes('?') ? '&' : '?') + query, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: ctrl.signal });
clearTimeout(t);
if (!r.ok) return null;
return await r.json();
} catch { return null; }
}
function ns(x: any, key: string) { return Object.assign({}, x, { vod_id: String(key) + ':' + String(x.vod_id) }); }
async function aggregate(sources: SrcCfg[], sp: URLSearchParams) {
const out: any = { code: 1, msg: '数据列表', page: 1, pagecount: 1, limit: 0, total: 0, list: [] };
const ids = sp.get('ids');
const wd = sp.get('wd');
const t = sp.get('t');
const pg = sp.get('pg') || '1';
const st = sp.get('st');
const year = sp.get('year');
const area = sp.get('area');
if (ids) {
const byK: Record<string, string[]> = {};
ids.split(',').forEach((p) => {
const i = p.indexOf(':');
if (i > 0) { const k = p.slice(0, i); const id = p.slice(i + 1); (byK[k] = byK[k] || []).push(id); }
});
for (const k in byK) {
const d = await subFetch(sources.find((s) => s.key === k)?.api || '', 'ac=videolist&ids=' + byK[k].map(encodeURIComponent).join(','));
if (d && Array.isArray(d.list)) d.list.forEach((x: any) => out.list.push(ns(x, k)));
}
out.total = out.list.length; out.limit = out.list.length;
return out;
}
let q = 'ac=videolist&pg=' + pg;
if (wd) q += '&wd=' + encodeURIComponent(wd);
if (t) q += '&t=' + encodeURIComponent(t);
['st', 'year', 'area', 'by'].forEach((k) => { const v = sp.get(k); if (v) q += '&' + k + '=' + encodeURIComponent(v); });
const results = await Promise.all(sources.map((s) => subFetch(s.api, q)));
const seen: Record<string, number> = {};
let list: any[] = [];
results.forEach((d, i) => {
if (d && Array.isArray(d.list)) {
const key = sources[i].key;
d.list.forEach((x: any) => {
const nm = String(x.vod_name || '').trim();
if (nm && !seen[nm]) { seen[nm] = 1; list.push(ns(x, key)); }
});
}
});
// 排序
const by = sp.get('by') || 'time';
if (by === 'hits') list.sort((a, b) => (b.vod_hits || 0) - (a.vod_hits || 0));
else if (by === 'score') list.sort((a, b) => (b.vod_score || 0) - (a.vod_score || 0));
else list.sort((a, b) => String(b.vod_time || '').localeCompare(String(a.vod_time || '')));
// 过滤
list = list.filter((x) => {
if (st && String(x.type_name) !== st && String(x.vod_class) !== st) return false;
if (year && String(x.vod_year) !== year) return false;
if (area && String(x.vod_area) !== area) return false;
return true;
});
out.list = list;
out.total = list.length;
out.limit = list.length;
out.page = Number(pg) || 1;
return out;
}
// ---------- 原有 TVBox 配置生成 ----------
interface TVBoxSource { key: string; name: string; type: number; api: string; searchable?: number; quickSearch?: number; filterable?: number; ext?: string; jar?: string; playUrl?: string; categories?: string[]; timeout?: number }
@@ -198,7 +51,7 @@ export async function GET(request: NextRequest) {
} catch { /* fallback 正常 tvbox 逻辑 */ }
const format = searchParams.get('format') || 'json';
const host = request.headers.get('host') || 'localhost:3000';
const protocol = request.headers.get('x-forwarded-proto') || 'http';
const protocol = request.headers.get('x-forwarded-proto') || (host.includes('88531') ? 'https' : (/^(localhost|127\.|0\.0\.0\.0)/.test(host) ? 'http' : 'https'));
const baseUrl = `${protocol}://${host}`;
const config = await getConfig();
@@ -213,51 +66,10 @@ export async function GET(request: NextRequest) {
const transformed = mkTransform(cls);
return NextResponse.json({ code: 1, msg: '数据列表', ...transformed }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
if (ac === 'videolist' || searchParams.get('ids')) {
// 顶层分类 9xx 处理:映射到源站 class + 过滤
const t = searchParams.get('t') || '';
const tops: Record<string, any> = {};
// 重新计算 tops 以获取 kind
if (sourceConfigs[0]) {
const cls = await fetchClass(sourceConfigs[0].api);
const tr = mkTransform(cls);
Object.assign(tops, tr.tops);
}
const top = tops[t];
if (top && top.kind === 'search') {
// AI短剧:走搜索
const sp = new URLSearchParams(searchParams);
sp.set('wd', top.wd || 'AI短剧');
const r = await aggregate(sourceConfigs, sp);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
if (top && top.kind === 'direct') {
const sp = new URLSearchParams(searchParams);
sp.set('t', top.native);
const r = await aggregate(sourceConfigs, sp);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
if (top && top.kind === 'agg') {
// 聚合:native class + 子分类 st 过滤
const sp = new URLSearchParams(searchParams);
if (!sp.get('t')) sp.set('t', top.native);
const st = sp.get('st');
if (st && top.ch) {
const ch = top.ch.find((c: any) => String(c.type_name) === st);
if (ch) sp.set('t', String(ch.type_id));
}
// area=香港 特殊:过滤 vod_area
if (top.area === '香港') {
const r = await aggregate(sourceConfigs, sp);
r.list = (r.list || []).filter((x: any) => String(x.vod_area || '').includes('香港'));
r.total = r.list.length; r.limit = r.list.length;
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
const r = await aggregate(sourceConfigs, sp);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
// 普通 t(源站 class id)直接聚合
const r = await aggregate(sourceConfigs, searchParams);
// vod 请求(分类 t=9xx / 搜索 wd / 详情 ids)→ 全源聚合
// 旧版:agg 分类没把 9xx 换成源站真实 type_id,导致 电影/电视剧 等分类全部返回 0 条
if (ac === 'videolist' || searchParams.get('ids') || searchParams.get('wd')) {
const r = await aggregateAll(sourceConfigs, searchParams);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
@@ -266,6 +78,8 @@ export async function GET(request: NextRequest) {
}
const hub = getHubFields();
// TVBox 端统一分类视图(旧补丁 TOP7)
const TOP7 = ['AI短剧', '香港电影', '香港剧', '电影', '电视剧', '综艺', '动画片', '动漫'];
const tvboxConfig: TVBoxConfig = {
spider: '',
wallpaper: `${baseUrl}/screenshot1.png`,
@@ -273,23 +87,29 @@ export async function GET(request: NextRequest) {
warning: hub.warning,
version: hub.version,
update_url: hub.update_url,
sites: sourceConfigs.map((source) => {
let type = 1;
const apiLower = source.api.toLowerCase();
if (apiLower.includes('at/xml') || apiLower.endsWith('.xml')) type = 0;
return {
key: source.key || source.name,
name: source.name,
type,
api: source.api,
searchable: 1,
quickSearch: 1,
filterable: 1,
ext: source.detail || '',
timeout: 30,
categories: ['电影', '电视剧', '综艺', '动漫', '纪录片', '短剧'],
};
}),
sites: [
// 「全部资源」:本站全源聚合(旧补丁 TOP7 结构)
{ key: 'all', name: '全部资源', type: 1, api: `${baseUrl}/api/tvbox/all`, searchable: 1, quickSearch: 1, filterable: 1, ext: '', timeout: 60, categories: TOP7 },
// 各资源站走本站逐站代理 /api/tvbox/<key>:电视/手机端只要能访问本站域名就能点播,
// 9xx 分类在代理里映射成该源自己的分类 id(旧补丁 P() 能力,源码化时丢失,本次恢复)
...sourceConfigs.map((source) => {
let type = 1;
const apiLower = source.api.toLowerCase();
if (apiLower.includes('at/xml') || apiLower.endsWith('.xml')) type = 0;
return {
key: source.key || source.name,
name: source.name,
type,
api: `${baseUrl}/api/tvbox/${encodeURIComponent(source.key || source.name)}`,
searchable: 1,
quickSearch: 1,
filterable: 1,
ext: source.detail || '',
timeout: 30,
categories: TOP7,
};
}),
],
parses: [
{ name: 'Json并发', type: 2, url: 'Parallel' },
{ name: 'Json轮询', type: 2, url: 'Sequence' },
@@ -300,12 +120,12 @@ export async function GET(request: NextRequest) {
ads: ['mimg.0c1q0l.cn', 'www.googletagmanager.com', 'www.google-analytics.com', 'mc.usihnbcq.cn', 'mg.g1mm3d.cn', 'mscs.svaeuzh.cn', 'cnzz.hhurm.com', 'tp.vinuxhome.com', 'cnzz.mmstat.com', 'www.baihuillq.com', 's23.cnzz.com', 'z3.cnzz.com', 'c.cnzz.com', 'stj.v1vo.top', 'z12.cnzz.com', 'img.mosflower.cn', 'tips.gamevvip.com', 'ehwe.yhdtns.com', 'xdn.cqqc3.com', 'www.jixunkyy.cn', 'sp.chemacid.cn', 'hm.baidu.com', 's9.cnzz.com', 'z6.cnzz.com', 'um.cavuc.com', 'mav.mavuz.com', 'wofwk.aoidf3.com', 'z5.cnzz.com', 'xc.hubeijieshikj.cn', 'tj.tianwenhu.com', 'xg.gars57.cn', 'k.jinxiuzhilv.com', 'cdn.bootcss.com', 'ppl.xunzhuo123.com', 'xomk.jiangjunmh.top', 'img.xunzhuo123.com', 'z1.cnzz.com', 's13.cnzz.com', 'xg.huataisangao.cn', 'z7.cnzz.com', 'xg.huataisangao.cn', 'z2.cnzz.com', 's96.cnzz.com', 'q11.cnzz.com', 'thy.dacedsfa.cn', 'xg.whsbpw.cn', 's19.cnzz.com', 'z8.cnzz.com', 's4.cnzz.com', 'f5w.as12df.top', 'ae01.alicdn.com', 'www.92424.cn', 'k.wudejia.com', 'vivovip.mmszxc.top', 'qiu.xixiqiu.com', 'cdnjs.hnfenxun.com', 'cms.qdwght.com'],
};
if (format === 'txt') {
if (format === 'txt' || format === 'base64') {
const configStr = JSON.stringify(tvboxConfig, null, 2);
const base64Config = Buffer.from(configStr).toString('base64');
return new NextResponse(base64Config, { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Cache-Control': 'public, max-age=3600' } });
return new NextResponse(base64Config, { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Cache-Control': 'no-store' } });
}
return NextResponse.json(tvboxConfig, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Cache-Control': 'public, max-age=3600' } });
return NextResponse.json(tvboxConfig, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Cache-Control': 'no-store' } });
} catch (error) {
return NextResponse.json({ error: 'TVBox配置生成失败', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
+36 -7
View File
@@ -127,6 +127,19 @@ function Pills({
function FilterClient() {
const searchParams = useSearchParams();
const [sources, setSources] = useState<Src[]>([]);
const runProbe = async () => {
setProbing(true);
try {
const r = await fetch('/api/filter?action=probe');
const j = await r.json().catch(() => null);
const map: Record<string, { ms: number; ok: boolean }> = {};
(j?.results || []).forEach((x: any) => { map[x.key] = { ms: x.ms, ok: x.ok }; });
setProbe(map);
} catch { setErr('测速失败'); }
finally { setProbing(false); }
};
const [probe, setProbe] = useState<Record<string, { ms: number; ok: boolean }>>({});
const [probing, setProbing] = useState(false);
const [source, setSource] = useState('all');
const [classes, setClasses] = useState<Cls[]>([]);
const [cat, setCat] = useState(() => searchParams.get('t') || searchParams.get('cat') || '');
@@ -200,7 +213,7 @@ function FilterClient() {
}
const arr: Item[] = Array.isArray(j?.list) ? j.list : [];
setItems((prev) => {
const base = reset ? [] : [...prev, ...arr];
const base = reset ? [...arr] : [...prev, ...arr];
const seen = new Set<string>();
return base.filter((x) => {
const k = x.title + '|' + x.year;
@@ -231,6 +244,12 @@ function FilterClient() {
load(1, true);
}, [source, cat, area, year]);
// 兜底:首次挂载确保加载一次(避免条件 effect 漏触发)
useEffect(() => {
load(1, true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// 分页:上一页/下一页
const goPage = (pg: number) => {
if (pg < 1) return;
@@ -265,12 +284,22 @@ function FilterClient() {
className='px-3 py-1.5 text-xs sm:text-sm rounded-full bg-gray-200/60 dark:bg-gray-700/60 text-gray-700 dark:text-gray-300 max-w-full'
>
<option value='all'>全部资源站</option>
{sources.map((s) => (
<option key={s.key} value={s.key}>
{s.name}
</option>
))}
{sources
.filter((s) => !probe[s.key] || probe[s.key].ok)
.map((s) => (
<option key={s.key} value={s.key}>
{s.name}
{probe[s.key] ? `(${(probe[s.key].ms / 1000).toFixed(2)}s)` : ''}
</option>
))}
</select>
<button
onClick={runProbe}
disabled={probing}
className='px-2.5 py-1.5 text-xs rounded-full bg-blue-500/90 text-white disabled:opacity-50'
>
{probing ? '测速中…' : '测速'}
</button>
</div>
<Pills
label='分类'
@@ -321,7 +350,7 @@ function FilterClient() {
)}
<div className='py-6 flex items-center justify-center gap-3 text-sm'>
<button onClick={() => goPage(nextPg - 2)} disabled={nextPg <= 2} className='px-3 py-1.5 rounded bg-gray-200/60 dark:bg-gray-700/60 disabled:opacity-40'>上一页</button>
<span className='text-gray-500 dark:text-gray-400'>第 {Math.max(1, nextPg - 1)} 页</span>
<span className='text-gray-500 dark:text-gray-400'>第 {Math.max(1, nextPg - 1)} 页 · 已加载 {items.length} 条</span>
<button onClick={() => goPage(nextPg)} disabled={!hasMore} className='px-3 py-1.5 rounded bg-gray-200/60 dark:bg-gray-700/60 disabled:opacity-40'>下一页</button>
</div>
</div>
+79 -13
View File
@@ -520,19 +520,41 @@ function PlayPageClient() {
allResults = data.results;
}
// 处理搜索结果,根据规则过滤
const results = allResults.filter(
(result: SearchResult) =>
result.title.replaceAll(' ', '').toLowerCase() ===
videoTitleRef.current.replaceAll(' ', '').toLowerCase() &&
(videoYearRef.current
? result.year.toLowerCase() === videoYearRef.current.toLowerCase()
: true) &&
(searchType
? (searchType === 'tv' && result.episodes.length > 1) ||
// 处理搜索结果,根据规则过滤(精确匹配优先)
const strict = (result: SearchResult) =>
result.title.replaceAll(' ', '').toLowerCase() ===
videoTitleRef.current.replaceAll(' ', '').toLowerCase() &&
(videoYearRef.current
? result.year.toLowerCase() === videoYearRef.current.toLowerCase()
: true) &&
(searchType
? (searchType === 'tv' && result.episodes.length > 1) ||
(searchType === 'movie' && result.episodes.length === 1)
: true);
let results = allResults.filter(strict);
// 精确匹配不到(相关推荐/豆瓣标题与源站标题常有差异)→ 放宽到双向包含;
// 仍要求满足 searchType 语义;再找不到才走「未找到匹配结果」
if (!results.length && videoTitleRef.current) {
const norm = (x: string) =>
x.replaceAll(' ', '')
.replaceAll('·', '')
.replaceAll(':', '')
.replaceAll(':', '')
.toLowerCase();
const q = norm(videoTitleRef.current);
results = allResults.filter((result: SearchResult) => {
const tt = norm(result.title);
if (!tt || !q) return false;
if (!(tt.includes(q) || q.includes(tt))) return false;
if (searchType) {
return (
(searchType === 'tv' && result.episodes.length > 1) ||
(searchType === 'movie' && result.episodes.length === 1)
: true)
);
);
}
return true;
});
}
setAvailableSources(results);
return results;
} catch (err) {
@@ -558,7 +580,27 @@ function PlayPageClient() {
: '🔍 正在搜索播放源...'
);
let sourcesInfo = await fetchSourcesData(searchTitle || videoTitle);
// 直达模式:带 source+id 且无搜索词、无优选要求 → 直接取该条详情开播,
// 不做标题搜索(按标题找片容易对错片);同名源随后台补搜,供「换源」面板使用
const directMode =
!!currentSource && !!currentId && !searchTitle && !needPrefer;
let directSucceeded = false;
let sourcesInfo: SearchResult[] = [];
if (directMode) {
const direct = await fetchSourceDetail(
currentSource as string,
currentId as string
);
if (direct.length) {
sourcesInfo = direct;
directSucceeded = true;
} else {
// 该 source+id 已失效 → 回退标题搜索
sourcesInfo = await fetchSourcesData(searchTitle || videoTitle);
}
} else {
sourcesInfo = await fetchSourcesData(searchTitle || videoTitle);
}
if (
currentSource &&
currentId &&
@@ -622,6 +664,26 @@ function PlayPageClient() {
newUrl.searchParams.delete('prefer');
window.history.replaceState({}, '', newUrl.toString());
// 直达模式:后台补搜同名源填充「换源」面板(不阻塞开播,不做标题匹配)
if (directSucceeded && videoTitleRef.current) {
const directItem = sourcesInfo[0];
fetchSourcesData(videoTitleRef.current)
.then((rest) => {
setAvailableSources((prev) => {
const list = prev.length ? prev : rest;
const seen = new Set(list.map((x) => `${x.source}:${x.id}`));
const extras = rest.filter((x) => !seen.has(`${x.source}:${x.id}`));
const hasDirect = list.some(
(x) => x.source === directItem.source && x.id === directItem.id
);
return hasDirect
? [...list, ...extras]
: [directItem, ...list, ...extras];
});
})
.catch(() => {});
}
setLoadingStage('ready');
setLoadingMessage('✨ 准备就绪,即将开始播放...');
@@ -1725,7 +1787,11 @@ function PlayPageClient() {
doubanId={detail.douban_id}
area={detail.area}
lang={detail.lang}
genre={detail.class}
isTv={(detail.episodes?.length || 0) > 1}
desc={detail.desc}
selfSource={currentSource}
selfId={currentId}
/>
)}
</div>
+95 -23
View File
@@ -3,6 +3,7 @@
import Link from 'next/link';
import { useEffect, useState } from 'react';
import PaginatedRow from './PaginatedRow';
import VideoCard from './VideoCard';
type VodItem = {
@@ -16,33 +17,104 @@ type VodItem = {
vod_area?: string;
};
const SHOW_COUNT = 10;
const PAGE_SIZE = 10; // 每页条数,与热门电影一致
const LOAD_COUNT = 60; // 一次性多取,支持上一页/下一页翻页
export default function HkDramaRow() {
const [items, setItems] = useState<VodItem[]>([]);
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [tick, setTick] = useState(0);
useEffect(() => {
fetch('/api/tvbox/all?ac=videolist&t=902&pg=1&by=time')
.then((r) => r.json())
.then((j) => {
const arr = (((j && j.list) as VodItem[]) || []).slice();
arr.sort((a, b) => {
const ya = parseInt(a.vod_year || '', 10) || 0;
const yb = parseInt(b.vod_year || '', 10) || 0;
if (yb !== ya) return yb - ya;
return String(b.vod_time || '').localeCompare(
String(a.vod_time || '')
);
});
setItems(arr.slice(0, SHOW_COUNT));
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
const CACHE_KEY = 'hkDramaRow:v3'; // v3: localStorage 持久缓存 + 重试,修复偶发整栏消失
const LEGACY_KEY = 'hkDramaRow:v2';
const TTL = 5 * 60 * 1000;
let dead = false;
// 加载失败且无数据时不占位;加载中显示骨架占位,与其它栏目同时出现
if (!loading && !items.length) return null;
const readCache = (): { ts: number; data: VodItem[] } | null => {
try {
const raw = localStorage.getItem(CACHE_KEY) || sessionStorage.getItem(LEGACY_KEY);
if (raw) {
const o = JSON.parse(raw);
if (o && typeof o.ts === 'number' && Array.isArray(o.data) && o.data.length) return o;
}
} catch {}
return null;
};
const writeCache = (data: VodItem[]) => {
try { localStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), data })); } catch {}
};
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
(async () => {
const cached = readCache();
if (cached && Date.now() - cached.ts < TTL) {
if (dead) return;
setItems(cached.data); setFailed(false); setLoading(false); return;
}
// 上游聚合偶发超时(冷缓存时可达 16s+):最多重试 3 次,每次 25s
for (let n = 1; n <= 3; n++) {
if (dead) return;
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 25000);
try {
const r = await fetch('/api/tvbox/all?ac=videolist&t=902&pg=1&by=time', { signal: ctrl.signal });
const j = await r.json();
const arr = (((j && j.list) as VodItem[]) || []).slice();
if (!arr.length) throw new Error('empty-list');
arr.sort((a, b) => {
const ya = parseInt(a.vod_year || '', 10) || 0;
const yb = parseInt(b.vod_year || '', 10) || 0;
if (yb !== ya) return yb - ya;
return String(b.vod_time || '').localeCompare(String(a.vod_time || ''));
});
const out = arr.slice(0, LOAD_COUNT);
clearTimeout(timer);
if (dead) return;
setItems(out); setFailed(false); setLoading(false); writeCache(out);
return;
} catch {
clearTimeout(timer);
if (dead) return;
if (n < 3) { await sleep(1500); continue; }
const stale = readCache();
if (dead) return;
if (stale) setItems(stale.data);
setFailed(!stale);
setLoading(false);
return;
}
}
if (!dead) setLoading(false);
})();
return () => { dead = true; };
}, [tick]);
// 加载失败且完全没有数据(含过期兜底)时,给重试入口而不是整栏无故消失
if (!loading && !items.length && !failed) return null;
if (failed && !items.length) {
return (
<section className='mb-8'>
<div className='mb-4 flex items-center justify-between'>
<h2 className='text-xl font-bold text-gray-800 dark:text-gray-200'>
最新港剧
</h2>
</div>
<div className='flex items-center justify-center rounded-lg border border-dashed border-gray-300 py-10 text-sm text-gray-500 dark:border-gray-600 dark:text-gray-400'>
港剧数据加载失败
<button
onClick={() => { setFailed(false); setLoading(true); setTick((t) => t + 1); }}
className='ml-3 rounded-md bg-purple-600 px-3 py-1.5 text-white transition-colors hover:bg-purple-700'
>
重新加载
</button>
</div>
</section>
);
}
return (
<section className='mb-8'>
@@ -57,10 +129,10 @@ export default function HkDramaRow() {
查看更多
</Link>
</div>
<div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 relative'>
<PaginatedRow itemsPerPage={PAGE_SIZE}>
{loading
? // 加载中显示10个占位,与热门电影/剧集同时出现,避免后半拍跳动
Array.from({ length: SHOW_COUNT }).map((_, index) => (
Array.from({ length: PAGE_SIZE }).map((_, index) => (
<div key={index} className='w-full'>
<div className='relative aspect-[2/3] w-full overflow-hidden rounded-lg bg-purple-200 animate-pulse dark:bg-purple-800'>
<div className='absolute inset-0 bg-purple-300 dark:bg-purple-700'></div>
@@ -92,7 +164,7 @@ export default function HkDramaRow() {
/>
);
})}
</div>
</PaginatedRow>
</section>
);
}
+96 -31
View File
@@ -24,8 +24,11 @@ export default function VideoMetaExtra({
doubanId,
area,
lang,
genre,
isTv,
desc,
selfSource,
selfId,
}: {
title: string;
actor?: string;
@@ -36,13 +39,18 @@ export default function VideoMetaExtra({
doubanId?: number;
area?: string;
lang?: string;
genre?: string;
isTv?: boolean;
desc?: string;
/** 当前条目所属源与 id,用于相关推荐排除自己 */
selfSource?: string;
selfId?: string;
}) {
const [comments, setComments] = useState<DoubanComment[]>([]);
const [loading, setLoading] = useState(false);
const [dbDetail, setDbDetail] = useState<any>(null);
const [related, setRelated] = useState<any[]>([]);
const [relatedLoading, setRelatedLoading] = useState(false);
useEffect(() => {
if (!doubanId) return;
@@ -64,18 +72,47 @@ export default function VideoMetaExtra({
if (alive && d?.code === 1) setDbDetail(d);
})
.catch(() => {});
// 相关推荐
fetch(`/api/douban-related?id=${encodeURIComponent(String(doubanId))}&type=${isTv ? 'tv' : 'movie'}`)
.then((r) => r.json())
.then((d) => {
if (alive && d?.code === 1) setRelated(d.list || []);
})
.catch(() => {});
return () => {
alive = false;
};
}, [doubanId]);
// 相关推荐:本站片源,按 主演/导演/语言/地区/类型 匹配(不走豆瓣推荐接口)
useEffect(() => {
if (!title || (!actor && !director)) {
setRelated([]);
return;
}
let alive = true;
setRelatedLoading(true);
const params = new URLSearchParams({
title,
actor: actor || '',
director: director || '',
area: area || '',
lang: lang || '',
genre: genre || '',
doubanId: String(doubanId || ''),
selfSource: selfSource || '',
selfId: selfId || '',
});
if (isTv !== undefined) params.set('isTv', isTv ? '1' : '0');
fetch(`/api/related?${params.toString()}`)
.then((r) => r.json())
.then((d) => {
if (alive) setRelated(Array.isArray(d?.items) ? d.items : []);
})
.catch(() => {
if (alive) setRelated([]);
})
.finally(() => {
if (alive) setRelatedLoading(false);
});
return () => {
alive = false;
};
}, [title, actor, director, area, lang, genre, isTv, doubanId, selfSource, selfId]);
const actors = (actor || (dbDetail?.actors || []).join(','))
.split(/[,,、\/|]/)
.map((s: string) => s.trim())
@@ -208,32 +245,60 @@ export default function VideoMetaExtra({
))}
</div>
</div>
{related.length > 0 && (
{/* 相关推荐:本站片源按元数据匹配,点击直达该条片源 */}
{(related.length > 0 || relatedLoading) && (
<div className='mt-4'>
<div className='text-sm font-semibold mb-2 opacity-80'>相关推荐</div>
<div className='grid grid-cols-5 gap-3'>
{related.map((r: any) => (
<a
key={r.id}
href={`/search?q=${encodeURIComponent(r.title)}`}
target='_self'
rel='noreferrer'
className='group block'
>
{r.poster ? (
<img
src={`/api/image-proxy?url=${encodeURIComponent(r.poster)}`}
alt={r.title}
className='w-full aspect-[2/3] object-cover rounded-md mb-1'
/>
) : null}
<div className='text-xs truncate group-hover:text-blue-500'>{r.title}</div>
{r.rating > 0 && (
<div className='text-xs text-amber-500'>{r.rating.toFixed(1)}</div>
)}
</a>
))}
<div className='flex items-baseline gap-2 flex-wrap text-sm font-semibold mb-2 opacity-80'>
<span>相关推荐</span>
<span className='text-[11px] font-normal opacity-60'>
按主演 / 导演 / 语言 / 地区 / 类型匹配 · 本站片源直达
</span>
</div>
{relatedLoading && related.length === 0 && (
<div className='grid grid-cols-5 gap-3'>
{[0, 1, 2, 3, 4].map((i) => (
<div
key={i}
className='animate-pulse aspect-[2/3] rounded-md bg-gray-200/70 dark:bg-gray-700/50'
/>
))}
</div>
)}
{related.length > 0 && (
<div className='grid grid-cols-5 gap-3'>
{related.map((r: any) => (
<a
key={`${r.source}-${r.id}`}
href={`/play?source=${encodeURIComponent(r.source)}&id=${encodeURIComponent(r.id)}&title=${encodeURIComponent(r.title)}${r.year ? `&year=${encodeURIComponent(r.year)}` : ''}`}
target='_self'
rel='noreferrer'
className='group block'
>
{r.poster ? (
<img
src={`/api/image-proxy?url=${encodeURIComponent(r.poster)}`}
alt={r.title}
className='w-full aspect-[2/3] object-cover rounded-md mb-1'
/>
) : null}
<div className='text-xs truncate group-hover:text-blue-500' title={r.title}>
{r.title}
</div>
<div className='text-[10px] opacity-50 truncate'>
{[r.year, r.source_name].filter(Boolean).join(' · ')}
</div>
{r.reasons?.length > 0 && (
<div
className='text-[10px] text-green-600/80 truncate'
title={r.reasons.join('、')}
>
{r.reasons.slice(0, 2).join(' · ')}
</div>
)}
</a>
))}
</div>
)}
</div>
)}
</div>
+4
View File
@@ -349,6 +349,10 @@ export class RedisStorage implements IStorage {
return match ? ensureString(match[1]) : undefined;
})
.filter((u): u is string => typeof u === 'string');
// 站长(owner)不一定有密码记录,但需显示其最后登录时间
if (!usernames.includes(ownerUsername)) {
usernames.push(ownerUsername);
}
// 获取用户创建时间、最后登录时间并构造 User 对象
const users = await Promise.all(
+322
View File
@@ -0,0 +1,322 @@
// TVBox 聚合共享库:/api/tvbox、/api/tvbox/all、/api/tvbox/[site] 三处共用。
// 源码化重构时把三份 class/聚合逻辑收拢到这里,避免各自漂移
// (旧运行时补丁 app-api-tvbox-route.js 的 MK / CL / P / ALL 逻辑迁入本文件)。
export const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36';
export interface SrcCfg {
key: string;
name: string;
api: string;
detail?: string;
disabled?: boolean;
}
export async function subFetch(api: string, query: string, timeoutMs = 8000): Promise<any> {
if (!api) return null;
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
const r = await fetch(api + (api.includes('?') ? '&' : '?') + query, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: ctrl.signal });
clearTimeout(t);
if (!r.ok) return null;
const tx = await r.text();
try {
const j = JSON.parse(tx);
return j && typeof j === 'object' && !Array.isArray(j) ? j : null;
} catch {
return null;
}
} catch {
return null;
}
}
export function ns(x: any, key: string) {
return Object.assign({}, x, { vod_id: String(key) + ':' + String(x.vod_id) });
}
// 源站分类表缓存:非空 10 分钟(分类表很稳定),空 2 分钟(失败过 2 分钟再试,
// 30s 太短会让每分钟的刷新都重新踩满超时拖慢整体聚合)
const classCache = new Map<string, [number, any[], boolean]>();
export async function fetchClass(api: string): Promise<any[]> {
const now = Date.now();
const c = classCache.get(api);
if (c && (c[2] ? now - c[0] < 120000 : now - c[0] < 600000)) return c[1];
// 三个候选端点并发竞速(旧行为是串行逐试:半死源每端点都等满 8s 超时,
// 最坏 3×8s=24s 拖死整体聚合——冷启动 60s 的主要来源);首个返回非空分类的端点即胜,
// 全部失败/超时(单端点 8s)才缓存空结果 → 冷启动最坏 8s 而非 24s
const eps = [api, api + (api.includes('?') ? '&' : '?') + 'ac=list', api + (api.includes('?') ? '&' : '?') + 'ac=class'];
const attempt = async (ep: string): Promise<any[]> => {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 8000);
try {
const r = await fetch(ep, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: ctrl.signal });
if (!r.ok) throw new Error('http ' + r.status);
const j = await r.json();
if (Array.isArray(j?.class) && j.class.length) return j.class;
throw new Error('no class');
} finally {
clearTimeout(t);
}
};
try {
const classes = await Promise.any(eps.map(attempt));
classCache.set(api, [now, classes, false]);
return classes;
} catch {
classCache.set(api, [now, [], true]);
return [];
}
}
// 顶层 9xx 分类表 + 筛选器(旧补丁 MK):TVBox 端每个站点看到的就是这 7+1 个分类
export function mkTransform(cls: any[]) {
const byN: Record<string, any> = {};
(cls || []).forEach((c) => { if (c && c.type_name != null) byN[String(c.type_name).trim()] = c; });
const fd = (...names: string[]) => { for (const n of names) if (byN[n]) return byN[n]; return null; };
const kd = (r: any) => (r ? (cls || []).filter((c: any) => c && String(c.type_pid) === String(r.type_id) && String(c.type_id) !== String(r.type_id)) : []);
const mv = fd('电影', '电影片');
const tv = fd('连续剧', '电视剧', '剧集');
const vy = fd('综艺', '综艺片');
const an = fd('动漫', '动漫片');
const to = fd('动画片', '动画电影', '动漫电影');
const hk = fd('香港剧', '港澳剧', '港台剧', '港剧');
const T: any[] = [];
if (mv) T.push({ tid: '901', name: '香港电影', kind: 'agg', native: String(mv.type_id), ch: kd(mv), area: '香港' });
if (hk) T.push({ tid: '902', name: '香港剧', kind: 'direct', native: String(hk.type_id), ch: [], area: '' });
if (mv) T.push({ tid: '903', name: '电影', kind: 'agg', native: String(mv.type_id), ch: kd(mv), area: '' });
if (tv) T.push({ tid: '904', name: '电视剧', kind: 'agg', native: String(tv.type_id), ch: kd(tv), area: '' });
if (vy) T.push({ tid: '905', name: '综艺', kind: 'agg', native: String(vy.type_id), ch: kd(vy), area: '' });
if (to) T.push({ tid: '906', name: '动画片', kind: 'direct', native: String(to.type_id), ch: [], area: '' });
if (an) T.push({ tid: '907', name: '动漫', kind: 'agg', native: String(an.type_id), ch: kd(an), area: '' });
T.push({ tid: '909', name: 'AI短剧', kind: 'search', native: '', wd: 'AI短剧', kwPat: 'AI|短剧|微短剧', ch: [], area: '' });
const Y = [{ n: '全部', v: '' }]; for (let y = 2026; y >= 2010; y--) Y.push({ n: String(y), v: String(y) });
const AR = [{ n: '全部', v: '' }, { n: '中国大陆', v: '中国大陆' }, { n: '中国香港', v: '中国香港' }, { n: '中国台湾', v: '中国台湾' }, { n: '美国', v: '美国' }, { n: '韩国', v: '韩国' }, { n: '日本', v: '日本' }, { n: '英国', v: '英国' }, { n: '法国', v: '法国' }, { n: '德国', v: '德国' }, { n: '泰国', v: '泰国' }, { n: '印度', v: '印度' }, { n: '加拿大', v: '加拿大' }, { n: '其他', v: '其他' }];
const BY = [{ n: '最新', v: 'time' }, { n: '最热', v: 'hits' }, { n: '评分', v: 'score' }];
const cls7: any[] = [];
const tops: Record<string, any> = {};
const filters: Record<string, any[]> = {};
T.forEach((t) => {
cls7.push({ type_id: t.tid, type_name: t.name, type_pid: 0 });
tops[t.tid] = { kind: t.kind, native: t.native, wd: t.wd || '', kwPat: t.kwPat || '', ch: t.ch, area: t.area || '' };
const g: any[] = [];
if (t.ch && t.ch.length) g.push({ key: 'st', name: '分类', value: [{ n: '全部', v: '' }].concat(t.ch.map((c: any) => ({ n: String(c.type_name), v: String(c.type_name) }))) });
if (t.tid !== '901') g.push({ key: 'area', name: '地区', value: AR });
g.push({ key: 'year', name: '年份', value: Y });
g.push({ key: 'by', name: '排序', value: BY });
filters[t.tid] = g;
});
if (!cls7.length) (cls || []).forEach((c) => cls7.push({ type_id: String(c.type_id), type_name: c.type_name, type_pid: c.type_pid }));
return { class: cls7, tops, filters };
}
interface TopMap {
isTop: boolean;
extraArea: string;
wd: string;
kwPat: string;
tidsByApi: Map<string, string[]>;
}
// 顶层 9xx → 每个源自己的真实分类 id 列表(各源分类表不同,不能拿一个源的 id 发给全源)。
// agg 类分类返回「子分类 id 列表」,供 aggChildren 逐子分类聚合(旧补丁 P() 的 _aggTids 逻辑)。
export async function resolveTopTids(sources: SrcCfg[], sp: URLSearchParams): Promise<TopMap> {
const t = sp.get('t') || '';
const out: TopMap = { isTop: false, extraArea: '', wd: '', kwPat: '', tidsByApi: new Map() };
if (!/^90[1-9]$/.test(t) || sp.get('wd') || sp.get('ids')) return out;
out.isTop = true;
if (t === '909') {
out.wd = 'AI短剧';
out.kwPat = 'AI|短剧|微短剧';
return out;
}
const classes = await Promise.all(sources.map((s) => fetchClass(s.api)));
sources.forEach((s, i) => {
const cl = classes[i] || [];
const byN: Record<string, any> = {};
cl.forEach((c) => { if (c && c.type_name != null) byN[String(c.type_name).trim()] = c; });
const fd = (...names: string[]) => { for (const n of names) if (byN[n]) return byN[n]; return null; };
const kids = (r: any) => cl.filter((c: any) => c && String(c.type_pid) === String(r.type_id) && String(c.type_id) !== String(r.type_id));
const mv = fd('电影', '电影片');
const tv = fd('连续剧', '电视剧', '剧集');
const vy = fd('综艺', '综艺片');
const an = fd('动漫', '动漫片');
const to = fd('动画片', '动画电影', '动漫电影');
const hk = fd('香港剧', '港澳剧', '港台剧', '港剧');
const withKids = (r: any) => { const k = kids(r); return k.length ? k.map((c: any) => String(c.type_id)) : [String(r.type_id)]; };
let tids: string[] = [];
if (t === '901') tids = mv ? withKids(mv) : [];
else if (t === '902') tids = hk ? [String(hk.type_id)] : tv ? [String(tv.type_id)] : [];
else if (t === '903') tids = mv ? withKids(mv) : [];
else if (t === '904') tids = tv ? withKids(tv) : [];
else if (t === '905') tids = vy ? withKids(vy) : [];
else if (t === '906') tids = to ? [String(to.type_id)] : [];
else if (t === '907') tids = an ? withKids(an) : [];
if (tids.length) out.tidsByApi.set(s.api, tids);
});
if (t === '901' || t === '902') out.extraArea = '香港';
return out;
}
// 逐子分类聚合(旧补丁 P() 的 AGG):每个子分类取一页,按 vod_id 去重,按更新时间排序
const aggC = new Map<string, [number, any[]]>();
export async function aggChildren(api: string, tids: string[], extra: string, pg: string): Promise<any[]> {
const key = api + '|' + tids.join(',') + '|' + extra + '|' + pg;
const ent = aggC.get(key);
if (ent && Date.now() - ent[0] < 600000) return ent[1];
const start = Date.now();
const pool: any[] = [];
const seen: Record<string, number> = {};
for (let i = 0; i < tids.length; i++) {
if (Date.now() - start > 25000) break; // 兜底:不让逐子分类聚合拖过 TVBox 的超时
let r: any = null;
for (let a = 0; a < 2; a++) {
r = await subFetch(api, 'ac=videolist&pg=' + pg + '&t=' + encodeURIComponent(tids[i]) + extra, 6000);
if (r && Array.isArray(r.list) && r.list.length) break;
if (a === 0) await new Promise((z) => setTimeout(z, 700));
}
if (r && Array.isArray(r.list)) {
for (const it of r.list) {
const v = it.vod_id;
if (v != null && !seen[v]) {
seen[v] = 1;
pool.push(it);
}
}
}
if (i < tids.length - 1) await new Promise((z) => setTimeout(z, 250));
}
pool.sort((a, b) => String(b.vod_time == null ? '' : b.vod_time).localeCompare(String(a.vod_time == null ? '' : a.vod_time)));
aggC.set(key, [Date.now(), pool]);
if (aggC.size > 120) aggC.clear();
return pool;
}
// 全源聚合(/api/tvbox/all 与裸 /api/tvbox 的 vod 请求共用)
export async function aggregateAll(sources: SrcCfg[], sp: URLSearchParams) {
const srcs = sources.filter((s) => !s.disabled);
const out: any = { code: 1, msg: '数据列表', page: 1, pagecount: 1, limit: 0, total: 0, list: [] };
const ids = sp.get('ids');
const pg = sp.get('pg') || '1';
if (ids) {
const byK: Record<string, string[]> = {};
ids.split(',').forEach((p) => {
const i = p.indexOf(':');
if (i > 0) {
const k = p.slice(0, i);
const id = p.slice(i + 1);
(byK[k] = byK[k] || []).push(id);
}
});
for (const k in byK) {
const d = await subFetch(srcs.find((s) => s.key === k)?.api || '', 'ac=videolist&ids=' + byK[k].map(encodeURIComponent).join(','));
if (d && Array.isArray(d.list)) d.list.forEach((x: any) => out.list.push(ns(x, k)));
}
out.total = out.list.length;
out.limit = out.list.length;
return out;
}
let wd = sp.get('wd');
const topT = sp.get('t') || '';
const st = sp.get('st') || '';
const { isTop, extraArea, wd: wdOv, kwPat, tidsByApi } = await resolveTopTids(srcs, sp);
if (isTop && wdOv) wd = wdOv;
// st(子分类筛选,值为分类名)→ 每个源自己的 type_id
const stTid = new Map<string, string>();
if (st) {
if (/^\d+$/.test(st)) {
srcs.forEach((s) => stTid.set(s.api, st));
} else {
const classes = await Promise.all(srcs.map((s) => fetchClass(s.api)));
srcs.forEach((s, i) => {
const hit = (classes[i] || []).find((c: any) => c && String(c.type_name).trim() === st);
if (hit) stTid.set(s.api, String(hit.type_id));
});
}
}
const baseExtra = ['year', 'area', 'by'].map((k) => {
const v = sp.get(k);
return v ? '&' + k + '=' + encodeURIComponent(v) : '';
}).join('');
const results = await Promise.all(
srcs.map((s) => {
if (wd) return subFetch(s.api, 'ac=videolist&pg=' + pg + '&wd=' + encodeURIComponent(wd));
if (st && !stTid.has(s.api)) return subFetch(s.api, 'ac=videolist&pg=' + pg + '&t=' + encodeURIComponent(st) + baseExtra);
if (stTid.has(s.api)) return subFetch(s.api, 'ac=videolist&pg=' + pg + '&t=' + encodeURIComponent(stTid.get(s.api) as string) + baseExtra);
if (isTop) {
const tids = tidsByApi.get(s.api) || [];
if (!tids.length) return Promise.resolve(null); // 该源没有对应分类,跳过(不发无分类的最新列表污染结果)
if (tids.length === 1) return subFetch(s.api, 'ac=videolist&pg=' + pg + '&t=' + encodeURIComponent(tids[0]) + baseExtra);
return aggChildren(s.api, tids, baseExtra, pg).then((pool) => ({
code: 1, msg: '数据列表', page: Number(pg) || 1, pagecount: 1, limit: pool.length, total: pool.length, list: pool,
}));
}
let q = 'ac=videolist&pg=' + pg;
if (topT) q += '&t=' + encodeURIComponent(topT);
q += baseExtra;
return subFetch(s.api, q);
})
);
const seen: Record<string, number> = {};
let list: any[] = [];
results.forEach((d, i) => {
if (d && Array.isArray(d.list)) {
const key = srcs[i].key;
d.list.forEach((x: any) => {
const nm = String(x.vod_name || '').trim();
if (nm && !seen[nm]) {
seen[nm] = 1;
list.push(ns(x, key));
}
});
}
});
list.sort((a, b) => String(b.vod_time == null ? '' : b.vod_time).localeCompare(String(a.vod_time == null ? '' : a.vod_time)));
// 902 香港剧硬过滤:只保留地区含“香港”的条目(兜底:无地区但名字命中的保留,避免误杀)
if (topT === '902') {
const hkPat = /港剧|粤语|TVB|邵氏|香港/i;
list = list.filter((x) => {
const area = String(x.vod_area || '');
if (area.indexOf('香港') >= 0 || area === '香港') return true;
if (!area && hkPat.test(String(x.vod_name || ''))) return true;
return false;
});
}
// AI短剧(909):搜索结果按关键词兜底过滤
if (kwPat) {
const re = new RegExp(kwPat, 'i');
const k2 = list.filter((x: any) => re.test(String(x.vod_name || '')));
if (k2.length) list = k2;
}
// st 兜底按名称过滤(上游没认 t=分类名 时保证筛选语义)
if (st && !/^\d+$/.test(st)) {
const s2 = list.filter((x: any) => String(x.type_name) === st || String(x.vod_class || '').indexOf(st) >= 0);
if (s2.length) list = s2;
}
const fy = sp.get('year');
const fa = sp.get('area') || extraArea;
if (fy) list = list.filter((x) => String(x.vod_year || '').indexOf(fy) >= 0);
if (fa && topT !== '902') list = list.filter((x) => String(x.vod_area || '').indexOf(fa) >= 0);
list = list.slice(0, 300);
out.list = list;
out.total = list.length;
out.limit = list.length;
const rep = results.find((d) => d && Array.isArray(d.class) && d.class.length);
if (rep) {
out.class = rep.class;
out.filters = rep.filters;
}
return out;
}
+2 -1
View File
@@ -174,6 +174,7 @@ function shouldSkipAuth(pathname: string): boolean {
'/api/douban-comments',
'/api/douban-detail',
'/api/douban-related',
'/api/related',
];
return skipPaths.some((path) => pathname.startsWith(path));
@@ -182,6 +183,6 @@ function shouldSkipAuth(pathname: string): boolean {
// 配置middleware匹配规则
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|login|warning|hls.min.js|mpegts.min.js|api/login|api/register|api/logout|api/cron|api/server-config|api/search|api/detail|api/image-proxy|api/license-config|api/douban-comments|api/douban-detail|api/douban-related).*)',
'/((?!_next/static|_next/image|favicon.ico|login|warning|hls.min.js|mpegts.min.js|api/login|api/register|api/logout|api/cron|api/server-config|api/search|api/detail|api/image-proxy|api/license-config|api/douban-comments|api/douban-detail|api/douban-related|api/related).*)',
],
};