Compare commits

...
38 Commits
Author SHA1 Message Date
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-10 14:52:16 +08:00
jinghui 9dbe231c79 fix: 启用新用户注册 (redis 存储 + ENABLE_REGISTER) fixed108
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-10 14:17:40 +08:00
jinghui 2b3582b4ff fix: 恢复登录鉴权 + 站名米视TV + 首访 IPv6 跳转 tv6 (fixed107)
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 10:59:15 +08:00
jinghui c29f5395ac fix: 更换失效采集源,恢复最新港剧行 (fixed106)
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
- 5 个旧采集源全部失效(hnzy/liangzizy/yongjiuzy NXDOMAIN,ffzy/1080zyku 连接不通)
- 替换为验证通过的 2 个新源:无尽资源 api.wujinapi.me + 彗星资源 hhzyapi.com
- 实测: /api/tvbox/all?t=902 返回 36 条港剧,m3u8 播放地址 200
- 首页四板块齐全(最新港剧/热门电影/剧集/综艺),海报 40/40 加载
2026-11-10 09:28:15 +08:00
jinghui d5443d97c9 fix: 移除首访强制跳转/ipv6 与图片代理拼接修复 (fixed105)
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
- 删除 Ipv6FirstVisitGate 首访强制跳转(layout.tsx 不再挂载),首页直接加载数据
- 开启 NEXT_PUBLIC_IMAGE_PROXY=/api/image-proxy,海报走站内代理
- 修复 processImageUrl 缺少 ?url= 分隔符导致的非法图片 URL
- 实测: 30/30 海报加载成功, 无跳转, IPv6 推荐浮层正常显示
2026-11-10 02:14:18 +08:00
3970260761 2c8a68b064 feat: middleware 首访未选线路时跳转 /ipv6 选择页 (v-fixed98)
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-09 18:06:17 +08:00
3970260761 9ffb113ca5 feat: 首访自动跳转 IPv4/IPv6 线路选择页 (v-fixed97)
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-09 16:37:12 +08:00
3970260761 e34ec79d5a docs: README 镜像段补公网固定版本与TCR拉取命令, 标注当前 v-fixed96 2026-11-09 03:05:45 +08:00
3970260761 e766391534 fixed96: 新增/动漫页与/api/browse第三方分类浏览,修复动漫页首屏空列表
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
- 新增 src/app/anime + src/app/api/anime: 多源并行抓取、地区归一化、title+year去重、update_time降序、pg分页
- 新增 src/app/api/browse + src/lib/vodcat.ts: kind/cat|area/pg 统一第三方分类浏览接口
- douban 电影/剧集/综艺 选择器改走 /api/browse, 分类全量切第三方分类语义
- PageLayout/MobileBottomNav 增加 动漫 导航入口(源码实现)
- 修复 /anime reset=true 时 base 置空导致新数据被丢弃(接口200页面空)
- 版本 NEXT_PUBLIC_SITE_VERSION=fixed96; README/CHANGELOG 更新
2026-11-09 03:02:13 +08:00
3970260761 776f915db5 fixed95: 去掉多余ENV行
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
2026-11-08 23:27:25 +08:00
3970260761 142cf135a5 fixed95: 动漫页标题显示动漫+修复构建期版本号注入 2026-11-08 23:27:22 +08:00
3970260761 421328c6cb fixed85-94: filter分页/搜索分页/直播页返回与静音/动漫分类入口
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
2026-11-08 23:05:38 +08:00
3970260761 395a8fd3f5 fixed84: 相关推荐海报走image-proxy防豆瓣防盗链
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-08 21:08:20 +08:00
3970260761 53cc479f0f fixed83: 去掉重复剧情简介,仅显示一处
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
2026-11-08 21:00:23 +08:00
3970260761 1df73ed0bf fixed82: 相关推荐改为本站搜索链接
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-08 15:38:11 +08:00
3970260761 eb93b3f062 fixed81: 豆瓣详情补充地区/语言/片长/剧情简介
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
2026-11-08 15:35:49 +08:00
3970260761 7a99890425 fixed80: 相关推荐10部(豆瓣) + 中间件白名单
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
2026-11-08 15:32:27 +08:00
3970260761 574fa99fb4 fixed79: 豆瓣详情兜底评分/演员/导演 + 新增 douban-detail 路由
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
2026-11-08 15:06:53 +08:00
3970260761 428b4b73d0 fixed78: 详情页改为豆瓣短评+豆瓣跳转按钮(演员/评分/演员搜索保留)
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
2026-11-08 14:35:25 +08:00
3970260761 8c0a1e209b fixed77: 首页最新港剧+筛选页统一换VideoCard(豆瓣链+hover收藏对齐热门电影)+VideoCard search豆瓣0值过滤+兜底
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
2026-11-08 13:52:12 +08:00
3970260761 940c34a560 docs: README 增加「方式二:Docker Compose部署」(docker-compose.redis.yml 完整 yaml + up -d) 2026-11-08 01:41:42 +08:00
3970260761 70b2cacc20 fixed76: 管理用户表加注册时间+最后登录两列+TVBox配置页加直播源地址+注册/添加补时间写入
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-08 01:38:08 +08:00
3970260761 7d698273d0 fixed75: TVBOX按钮弹双地址(配置地址+直播源地址各带复制)
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
2026-11-08 00:59:44 +08:00
3970260761 d508f84954 fixed74: 直播抓取加重试+过期缓存兜底
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
- live-inject.js liveText: 15s单次超时改为25s x 3次重试, 失败打[LIVE-FETCH-RETRY]日志
- liveChannels: 失败/空列表时用过期缓存兜底[LIVE-CH-STALE], 避免前端撞上上游抖动显示暂无频道
- 版本号对齐 fixed74
2026-11-08 00:31:18 +08:00
3970260761 54fdea4f84 fixed73: 通知切授权公告+右上角版本号全页显示
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/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Release / docker (push) Canceled after 0s
- 首页旧公告弹窗彻底拆除(page.tsx: 删JSX/useSite/showAnnouncement/handleCloseAnnouncement残留)
- layout授权覆盖顺序修复: 先getConfig再hub.getNotice覆盖, 授权公告优先
- HubBell只发open-hub-notice事件, 不再清hasSeenAnnouncement/跳首页
- HubNotice支持铃铛手动打开: 公告/首条/版本兜底, 空指针修复
- 版本号三处补齐: TopRightButtons bar+float, MobileHeader移动端, 对齐fixed73
2026-11-08 00:19:48 +08:00
52 changed files with 2732 additions and 751 deletions

No files matched your search

+43
View File
@@ -2,6 +2,49 @@
本文档记录 KatelyaTV 项目的重要更新和功能变更。 本文档记录 KatelyaTV 项目的重要更新和功能变更。
## [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
### ✨ 新增
- **动漫独立页 `/anime`(源码化)**
- 聚合各资源站全部动漫内容,地区切换:全部 / 国产 / 日韩 / 欧美 / 港台 / 海外
- 后端 `/api/anime`:多源并行抓取 → 地区归一化(国产剧/港台/韩国/日本/欧美/动漫… → 动漫域分类)
→ 按 title+year 去重 → 按 `update_time` 降序 → 分页 `pg/next_pg/has_more`
- 顶部菜单与移动端底部导航均新增「动漫」入口(源码内 `PageLayout` / `MobileBottomNav`)
- **第三方分类浏览接口 `/api/browse`(源码化)**
- 统一 `kind=tv|movie|show|anime` + `cat`(分类,支持 `|` 多选)+ `area`(地区)+ `pg`
- 新增 `src/lib/vodcat.ts` 集中维护八大分类与地区选项
- 三类页签分类全量切到第三方分类语义(电影/剧集/综艺),不再用豆瓣分类值
### 🐛 修复
- **动漫页首次进入永远空列表**:`reset=true` 时 `base` 被置成空数组,新到的 `arr` 没有拼进去,
导致接口 200、页面却显示「暂无动漫内容」;改为 `base = [...arr]`
### 🔄 变更
- `/douban` 电影/剧集/综艺 三类选择器改走 `/api/browse`,与 `/api/anime` 共用排序去重逻辑
- 版本号 `NEXT_PUBLIC_SITE_VERSION` → `fixed96`(Dockerfile 构建期注入,已验证镜像内 chunk 与页头一致)
## [fixed44] - 2026-11-06 ## [fixed44] - 2026-11-06
### 🐛 修复 ### 🐛 修复
+7 -1
View File
@@ -33,6 +33,10 @@ COPY . .
RUN find ./src -type f -name "route.ts" -print0 \ RUN find ./src -type f -name "route.ts" -print0 \
| xargs -0 sed -i "s/export const runtime = 'edge';/export const runtime = 'nodejs';/g" | xargs -0 sed -i "s/export const runtime = 'edge';/export const runtime = 'nodejs';/g"
ENV DOCKER_ENV=true ENV DOCKER_ENV=true
# 海报走站内 /api/image-proxy(浏览器直连豆瓣图被拦导致全裂)
ENV NEXT_PUBLIC_IMAGE_PROXY=/api/image-proxy
ENV NEXT_PUBLIC_SITE_VERSION=fixed128
ENV NEXT_PUBLIC_ENABLE_REGISTER=true
# For Docker builds, force dynamic rendering to read runtime environment variables. # 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 RUN sed -i "/const inter = Inter({ subsets: \['latin'] });/a export const dynamic = 'force-dynamic';" src/app/layout.tsx
@@ -51,7 +55,9 @@ ENV NODE_ENV=production
ENV HOSTNAME=0.0.0.0 ENV HOSTNAME=0.0.0.0
ENV PORT=3000 ENV PORT=3000
ENV DOCKER_ENV=true ENV DOCKER_ENV=true
ENV NEXT_PUBLIC_SITE_VERSION=fixed71 ENV NEXT_PUBLIC_IMAGE_PROXY=/api/image-proxy
ENV NEXT_PUBLIC_SITE_VERSION=fixed128
ENV NEXT_PUBLIC_ENABLE_REGISTER=true
# 从构建器中复制 standalone 输出 # 从构建器中复制 standalone 输出
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
+115 -1
View File
@@ -80,6 +80,31 @@
- **缓存穿透防护**:chunk 文件按内容 hash 命名,内容变了文件名跟着变,浏览器当新文件拉取,避免陈旧缓存 - **缓存穿透防护**:chunk 文件按内容 hash 命名,内容变了文件名跟着变,浏览器当新文件拉取,避免陈旧缓存
- **Redis 缓存**:支持 Redis/Kvrocks 存储,缓存搜索结果 - **Redis 缓存**:支持 Redis/Kvrocks 存储,缓存搜索结果
### 7. 动漫聚合页
**页面**:`/anime`
聚合各资源站全部动漫内容,无需逐站翻找:
| 功能 | 说明 |
|------|------|
| 地区切换 | 全部 / 国产 / 日韩 / 欧美 / 港台 / 海外 |
| 多源并行 | 一次请求并行抓取多个资源站的 `ac=videaclass t=动漫` |
| 归一去重 | 豆瓣式分类(国产剧/港台/韩国/日本/欧美/动漫)统一映射到动漫域,按 `title+年份` 去重 |
| 更新排序 | 按 `update_time` 降序,最新更新在前 |
| 分页 | `pg/next_pg/has_more`,触底自动加载 |
顶部菜单与移动端底部导航均有「动漫」入口,路由 `/anime`。
### 8. 第三方分类浏览(电影/剧集/综艺)
**页面**:`/douban?type=movie|tv|show` **接口**:`/api/browse`
- 分类全量使用第三方分类语义:电影 8 类、剧集 7 类、综艺 4 类,地区 7 档
- 请求参数 `kind=tv|movie|show|anime` + `cat`(`|` 分隔多选)+ `area` + `pg`
- 与 `/api/anime` 共用同一套归一化、去重、`update_time` 排序、分页逻辑
- 分类选项集中在 `src/lib/vodcat.ts`,改分类只需改这一处
## 🚀 快速安装 ## 🚀 快速安装
### Docker 单容器(最简单) ### Docker 单容器(最简单)
@@ -108,6 +133,85 @@ cp .env.redis.example .env
docker compose -f docker-compose.redis.yml up -d docker compose -f docker-compose.redis.yml up -d
``` ```
### 方式二:Docker Compose部署
上面「Docker + Redis」用到的 `docker-compose.redis.yml` 完整内容(与仓库文件一致,含全部 ports / volumes / environment):
```yaml
version: '3.8'
services:
# KatelyaTV 应用服务
katelyatv:
image: ghcr.io/katelya77/katelyatv:latest
ports:
- "3000:3000"
environment:
# 数据库配置 - 使用 Redis
NEXT_PUBLIC_STORAGE_TYPE: redis
REDIS_URL: redis://katelyatv-redis:6379
REDIS_PASSWORD: ${REDIS_PASSWORD:-}
REDIS_DATABASE: 0
# 站点访问密码配置
PASSWORD: ${PASSWORD:-}
# 其他必要的环境变量
NEXTAUTH_SECRET: ${NEXTAUTH_SECRET}
NEXTAUTH_URL: ${NEXTAUTH_URL:-http://localhost:3000}
depends_on:
- katelyatv-redis
restart: unless-stopped
networks:
- katelyatv-network
# Redis 数据库服务
katelyatv-redis:
image: redis:7-alpine
container_name: katelyatv-redis
command: redis-server --appendonly yes --maxmemory 256mb --maxmemory-policy allkeys-lru
volumes:
# 持久化数据存储
- katelyatv-redis-data:/data
restart: unless-stopped
networks:
- katelyatv-network
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
volumes:
# Redis 数据卷
katelyatv-redis-data:
driver: local
networks:
katelyatv-network:
driver: bridge
```
启动 / 停止:
```bash
# 1. 下载编排文件与环境变量模板
curl -O https://gitea.88531.cn/jinghui/katelyatv/raw/branch/main/docker-compose.redis.yml
curl -O https://gitea.88531.cn/jinghui/katelyatv/raw/branch/main/.env.redis.example
cp .env.redis.example .env
# 编辑 .env,设置 PASSWORD、NEXTAUTH_SECRET 等
# 2. 启动
docker compose -f docker-compose.redis.yml up -d
# 3. 查看状态 / 停止
docker compose -f docker-compose.redis.yml ps
docker compose -f docker-compose.redis.yml down
```
> 不想用 Compose 时,用上面「方式一:Docker 单容器」的 `docker run` 即可(仅省略 Redis,此时把存储类型设为 `localstorage`)。
### 环境变量 ### 环境变量
| 变量 | 必填 | 说明 | | 变量 | 必填 | 说明 |
@@ -124,6 +228,9 @@ docker compose -f docker-compose.redis.yml up -d
## 📋 更新日志 ## 📋 更新日志
- **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-fixed43**:IPv6 探测改 4443 端口(家宽封 443 导致误判),双端口探测 + 强制使用 IPv6 按钮;恢复右上角按钮断点;chunk 按内容改名防陈旧缓存;源码迁移开始
- **v-fixed42**:IPv6 检测改严格模式(cors + 校验 JSON),缓存 2 分钟,新增重新检测按钮 - **v-fixed42**:IPv6 检测改严格模式(cors + 校验 JSON),缓存 2 分钟,新增重新检测按钮
- **v-fixed41**:源码迁移,/ipv6 页面 React 化,中间件白名单 - **v-fixed41**:源码迁移,/ipv6 页面 React 化,中间件白名单
@@ -137,9 +244,16 @@ docker compose -f docker-compose.redis.yml up -d
## 🐳 Docker 镜像 ## 🐳 Docker 镜像
```bash ```bash
docker pull gitea.88531.cn/jinghui/katelyatv:latest # 公网可拉(匿名)
docker pull gitea.88531.cn/jinghui/katelyatv:latest # 固定版本
docker pull gitea.88531.cn/jinghui/katelyatv:fixed96
# 腾讯云 TCR(东京,公网匿名)
docker pull jpccr.ccs.tencentyun.com/jinghui/katelyatv:latest
``` ```
当前版本:**v-fixed96**
## 🔗 源码 ## 🔗 源码
- Gitea:https://gitea.88531.cn/jinghui/katelyatv - Gitea:https://gitea.88531.cn/jinghui/katelyatv
+13 -18
View File
@@ -1,30 +1,25 @@
{ {
"cache_time": 7200, "cache_time": 7200,
"api_site": { "api_site": {
"hnzy": { "wjzy": {
"api": "https://hnzyapi.com/api.php/provide/vod", "api": "https://api.wujinapi.me/api.php/provide/vod",
"name": "火鸟资源", "name": "无尽资源",
"is_adult": false "is_adult": false
}, },
"lzzy": { "bfzy": {
"api": "https://api.liangzizy.com/inc/apijson_vod.php", "api": "https://bfzyapi.com/api.php/provide/vod",
"name": "量子资源", "name": "暴风资源",
"is_adult": false "is_adult": false
}, },
"ffzy": { "jyzy": {
"api": "https://ffzyapi.com/api.php/provide/vod", "api": "https://jyzyapi.com/api.php/provide/vod",
"name": "非凡资源", "name": "极速资源",
"is_adult": false "is_adult": false
}, },
"ykzy": { "bz360": {
"api": "https://api.yongjiuzy.cc/provide/vod", "api": "https://360zy.com/api.php/provide/vod",
"name": "永久资源", "name": "360资源",
"is_adult": false
},
"bdzy": {
"api": "https://api.1080zyku.com/inc/apijson_vod.php",
"name": "百度资源",
"is_adult": false "is_adult": false
} }
} }
} }
+20 -6
View File
@@ -29,17 +29,28 @@ const all=await liveEpgAll();
const key=EPG_MAP[name]||(all[name]?name:null); const key=EPG_MAP[name]||(all[name]?name:null);
if(!key)return{has:false,list:[]}; if(!key)return{has:false,list:[]};
return{has:true,epg_key:key,list:all[key]||[]}} return{has:true,epg_key:key,list:all[key]||[]}}
async function liveText(u,ms){const c=new AbortController();const t=setTimeout(()=>c.abort(),ms||15000); async function liveText(u,ms){const timeout=ms||25000;let lastErr=null;
try{const r=await fetch(u,{redirect:"follow",signal:c.signal,headers:{"User-Agent":LIVE_UA,"Referer":LIVE_UP+"/"}});return await r.text()}finally{clearTimeout(t)}} for(let attempt=1;attempt<=3;attempt++){
const c=new AbortController();const t=setTimeout(()=>c.abort(),timeout);
try{const r=await fetch(u,{redirect:"follow",signal:c.signal,headers:{"User-Agent":LIVE_UA,"Referer":LIVE_UP+"/"}});
if(!r.ok)throw new Error("http "+r.status);
const txt=await r.text();clearTimeout(t);return txt}
catch(e){clearTimeout(t);lastErr=e;console.log("[LIVE-FETCH-RETRY]",attempt+"/3",(u||"").slice(0,60),e&&e.message);
if(attempt<3)await new Promise(r=>setTimeout(r,800*attempt))}}
throw lastErr||new Error("fetch failed")}
function liveRegion(n){if(/澳门|澳門|澳[視视]|澳亚|莲花/.test(n))return"澳门"; function liveRegion(n){if(/澳门|澳門|澳[視视]|澳亚|莲花/.test(n))return"澳门";
if(/凤凰|TVB|有线|有線|NOW|ViuTV|HOY|港台|香港|明珠|HKS/.test(n))return"香港"; if(/凤凰|TVB|有线|有線|NOW|ViuTV|HOY|港台|香港|明珠|HKS/.test(n))return"香港";
if(/中天|东森|東森|中视|中視|台视|台視|三立|非凡|民视|民視|华视|華視|镜电视|鏡電視|寰宇|TVBS|纬来|緯來|ELEVEN|DAZN|爱尔达|愛爾達/.test(n))return"台湾";return"其他"} if(/中天|东森|東森|中视|中視|台视|台視|三立|非凡|民视|民視|华视|華視|镜电视|鏡電視|寰宇|TVBS|纬来|緯來|ELEVEN|DAZN|爱尔达|愛爾達/.test(n))return"台湾";return"其他"}
async function liveChannels(){ async function liveChannels(){
if(liveCh.list&&Date.now()-liveCh.ts<3600e3)return liveCh.list; if(liveCh.list&&Date.now()-liveCh.ts<3600e3)return liveCh.list;
try{
const h=await liveText(LIVE_UP+"/?tid=gt");const seen=new Set(),list=[]; const h=await liveText(LIVE_UP+"/?tid=gt");const seen=new Set(),list=[];
for(const m of h.matchAll(/href="\?act=play&(?:amp;)?tid=gt&(?:amp;)?id=(\d+)"[^>]*>\s*([^<]+?)\s*</g)){ for(const m of h.matchAll(/href="\?act=play&(?:amp;)?tid=gt&(?:amp;)?id=(\d+)"[^>]*>\s*([^<]+?)\s*</g)){
if(!seen.has(m[1])){seen.add(m[1]);list.push({id:m[1],name:m[2]})}} if(!seen.has(m[1])){seen.add(m[1]);list.push({id:m[1],name:m[2]})}}
if(list.length){list.forEach(function(c){c.region=liveRegion(c.name)});liveCh.list=list;liveCh.ts=Date.now()}return list||[]} if(list.length){list.forEach(function(c){c.region=liveRegion(c.name)});liveCh.list=list;liveCh.ts=Date.now();return list}
throw new Error("channels empty")}catch(e){console.log("[LIVE-CH-ERR]",e&&e.message);
if(liveCh.list&&liveCh.list.length){console.log("[LIVE-CH-STALE] use stale list n="+liveCh.list.length);return liveCh.list}
return[]}}
async function liveLines(id){ async function liveLines(id){
const c=liveLn.get(id);if(c&&Date.now()-c.ts<1800e3)return c.lines; const c=liveLn.get(id);if(c&&Date.now()-c.ts<1800e3)return c.lines;
const h=await liveText(LIVE_UP+"/?act=play&tid=gt&id="+encodeURIComponent(id)); const h=await liveText(LIVE_UP+"/?act=play&tid=gt&id="+encodeURIComponent(id));
@@ -152,7 +163,7 @@ select{background:#171b24;color:#e5e7eb;border:1px solid #2a3140;border-radius:6
.sec{font-size:13px;color:#6b7280;margin:2px 0 8px} .sec{font-size:13px;color:#6b7280;margin:2px 0 8px}
.empty{color:#6b7280;font-size:13px;padding:20px 0;text-align:center} .empty{color:#6b7280;font-size:13px;padding:20px 0;text-align:center}
</style></head><body> </style></head><body>
<div class="hd"><a href="/" >‹</a><h1>电视直播 · 港澳台</h1><span style="flex:1"></span><a class="ghLink" href="https://gitea.88531.cn/jinghui/katelyatv" target="_blank" rel="noopener">⭐ 开源地址</a><button class="tvboxBtn" id="tvboxBtn">📺 TVBOX接入</button> <div class="hd"><a href="/" target="_top" >‹</a><h1>电视直播 · 港澳台</h1><span style="flex:1"></span><a class="ghLink" href="https://gitea.88531.cn/jinghui/katelyatv" target="_blank" rel="noopener">⭐ 开源地址</a><button class="tvboxBtn" id="tvboxBtn">📺 TVBOX接入</button>
<div class="tvboxPop" id="tvboxPop"> <div class="tvboxPop" id="tvboxPop">
<div class="tvboxPopTitle">TVBox / 影视仓 · 接入直播</div> <div class="tvboxPopTitle">TVBox / 影视仓 · 接入直播</div>
<div class="tvboxRow"><span class="tvboxLbl">配置地址(含直播,推荐)</span><code id="tbCfg">—</code><button id="tbCfgCopy">复制</button></div> <div class="tvboxRow"><span class="tvboxLbl">配置地址(含直播,推荐)</span><code id="tbCfg">—</code><button id="tbCfgCopy">复制</button></div>
@@ -295,7 +306,7 @@ function loadChs(retry){fetch(API+'channels').then(function(r){return r.json()})
grid.appendChild(h);grid.appendChild(box); grid.appendChild(h);grid.appendChild(box);
}); });
var DEF=chs.find(function(c){return c.id==='5'})||chs.find(function(c){return (c.name||'').indexOf('翡翠')>=0})||chs[0]; var DEF=chs.find(function(c){return c.id==='5'})||chs.find(function(c){return (c.name||'').indexOf('翡翠')>=0})||chs[0];
if(DEF){pick(DEF.id,1)} if(DEF){pick(DEF.id,0)}
}).catch(function(){if(retry<3){grid.innerHTML='<div class="empty">加载中…</div>';setTimeout(function(){loadChs(retry+1)},3000)}else{grid.innerHTML='<div class="empty">加载失败,请刷新</div>'}})} }).catch(function(){if(retry<3){grid.innerHTML='<div class="empty">加载中…</div>';setTimeout(function(){loadChs(retry+1)},3000)}else{grid.innerHTML='<div class="empty">加载失败,请刷新</div>'}})}
loadChs(0); loadChs(0);
</script></body></html>`; </script></body></html>`;
@@ -341,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); 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"}})} 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(); 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#"]; 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=1");
out.push(c.name+","+origin+"/api/tvbox?live=ch&id="+c.id+"&p=2")} 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"}})} return new Response(out.join("\n")+"\n",{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}})}
+1 -1
View File
@@ -1 +1 @@
if(!self.define){let e,s={};const a=(a,n)=>(a=new URL(a+".js",n).href,s[a]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=a,e.onload=s,document.head.appendChild(e)}else e=a,importScripts(a),s()}).then(()=>{let e=s[a];if(!e)throw new Error(`Module ${a} didn’t register its module`);return e}));self.define=(n,i)=>{const c=e||("document"in self?document.currentScript.src:"")||location.href;if(s[c])return;let t={};const r=e=>a(e,c),o={module:{uri:c},exports:t,require:r};s[c]=Promise.all(n.map(e=>o[e]||r(e))).then(e=>(i(...e),t))}}define(["./workbox-e9849328"],function(e){"use strict";importScripts(),self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"/_next/app-build-manifest.json",revision:"d3c25753d011e80b2ccd5a754ac24ed9"},{url:"/_next/static/0MjBArWMO37oCPAjOorM5/_buildManifest.js",revision:"85aecd8a55db42fc901f52386fd2a680"},{url:"/_next/static/0MjBArWMO37oCPAjOorM5/_ssgManifest.js",revision:"b6652df95db52feb4daf4eca35380933"},{url:"/_next/static/chunks/151-8711dd3ec7fbfa61.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/234-b4915b11eb0bb661.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/242-5a0502f47346ed4a.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/273-fffc7e5390a1c642.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/547-65bdb23e16942a03.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/609-46d66c37b95adf6a.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/78-b091442d784a205f.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/866-7f5b3d6941560701.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/_not-found/page-2f2263c5b98c190a.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/admin/page-759806afdd5b7523.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/config/page-228e0af5a31948e0.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/douban/page-72adc56cdd9fa67a.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/filter/page-4cebc2f48c3257a1.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/ipv6/page-8a601c06ae5900e7.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/layout-abad67b72f2d607d.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/live/page-f9e105dfdc52a0d4.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/login/page-b2957b92254ae889.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/page-e5765bbccc00a155.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/play/page-5cfe996f3331a017.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/search/page-62b12f466a432302.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/settings/page-acdcc4f7e3aba36e.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/tvbox/page-b0ddd4e31a961ddc.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/app/warning/page-e6b20b93b37dc516.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/b145b63a-d75d6adf389a7589.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/c72274ce-909438a8a5dd87a5.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/da9543df-c2ce5269243dd748.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/framework-6e06c675866dc992.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/main-8daa958ee4a360c2.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/main-app-734bbab0f54e7373.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/pages/_app-3fcac1a2c632f1ef.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/pages/_error-d3fe151bf402c134.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/chunks/polyfills-42372ed130431b0a.js",revision:"846118c33b2c0e922d7b3a7676f81f6f"},{url:"/_next/static/chunks/webpack-f732225cafd52a05.js",revision:"0MjBArWMO37oCPAjOorM5"},{url:"/_next/static/css/23100062f5d4aac0.css",revision:"23100062f5d4aac0"},{url:"/_next/static/css/da6e9b4a73108890.css",revision:"da6e9b4a73108890"},{url:"/_next/static/css/e93463efba6c08e2.css",revision:"e93463efba6c08e2"},{url:"/_next/static/media/19cfc7226ec3afaa-s.woff2",revision:"9dda5cfc9a46f256d0e131bb535e46f8"},{url:"/_next/static/media/21350d82a1f187e9-s.woff2",revision:"4e2553027f1d60eff32898367dd4d541"},{url:"/_next/static/media/8e9860b6e62d6359-s.woff2",revision:"01ba6c2a184b8cba08b0d57167664d75"},{url:"/_next/static/media/ba9851c3c22cd980-s.woff2",revision:"9e494903d6b0ffec1a1e14d34427d44d"},{url:"/_next/static/media/c5fe6dc8356a8c31-s.woff2",revision:"027a89e9ab733a145db70f09b8a18b42"},{url:"/_next/static/media/df0a9ae256c0569c-s.woff2",revision:"d54db44de5ccb18886ece2fda72bdfe0"},{url:"/_next/static/media/e4af272ccee01ff0-s.p.woff2",revision:"65850a373e258f1c897a2b3d75eb74de"},{url:"/favicon.ico",revision:"c5deLine truncated if(!self.define){let e,s={};const i=(i,a)=>(i=new URL(i+".js",a).href,s[i]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=i,e.onload=s,document.head.appendChild(e)}else e=i,importScripts(i),s()}).then(()=>{let e=s[i];if(!e)throw new Error(`Module ${i} didn’t register its module`);return e}));self.define=(a,n)=>{const c=e||("document"in self?document.currentScript.src:"")||location.href;if(s[c])return;let t={};const u=e=>i(e,c),r={module:{uri:c},exports:t,require:u};s[c]=Promise.all(a.map(e=>r[e]||u(e))).then(e=>(n(...e),t))}}define(["./workbox-e9849328"],function(e){"use strict";importScripts(),self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"/_next/app-build-manifest.json",revision:"25e66d74fe8e173a352f137403fc1b41"},{url:"/_next/static/ZESVig0uAX5meOOL1E-0u/_buildManifest.js",revision:"85aecd8a55db42fc901f52386fd2a680"},{url:"/_next/static/ZESVig0uAX5meOOL1E-0u/_ssgManifest.js",revision:"b6652df95db52feb4daf4eca35380933"},{url:"/_next/static/chunks/234-b108db3d3cb1eaf9.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/242-5a0502f47346ed4a.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/273-fffc7e5390a1c642.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/609-46d66c37b95adf6a.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/732-ccd095260c41a876.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/78-b091442d784a205f.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/866-7f5b3d6941560701.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/_not-found/page-2f2263c5b98c190a.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/admin/page-20830ba52baaf531.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/anime/page-da4e609a40d81799.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/config/page-affbe8c5ef4d1058.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/douban/page-031ac55e075e253c.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/filter/page-4b5af6e51fd51bb5.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/ipv6/page-a35328d302bb65d6.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/layout-abad67b72f2d607d.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/live/page-9ed579d82b48211a.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/login/page-b2957b92254ae889.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/page-1635d434ad57af23.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/play/page-d9e8b68743f4288a.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/search/page-ba0b744cf689fe40.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/settings/page-136d93ac82c90f3c.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/tvbox/page-aee2e8c0cbeb259a.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/app/warning/page-e6b20b93b37dc516.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/b145b63a-d75d6adf389a7589.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/c72274ce-909438a8a5dd87a5.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/da9543df-c2ce5269243dd748.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/framework-6e06c675866dc992.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/main-0d408c4099fe4491.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/main-app-734bbab0f54e7373.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/pages/_app-3fcac1a2c632f1ef.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/pages/_error-d3fe151bf402c134.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/chunks/polyfills-42372ed130431b0a.js",revision:"846118c33b2c0e922d7b3a7676f81f6f"},{url:"/_next/static/chunks/webpack-f732225cafd52a05.js",revision:"ZESVig0uAX5meOOL1E-0u"},{url:"/_next/static/css/23100062f5d4aac0.css",revision:"23100062f5d4aac0"},{url:"/_next/static/css/3b3ab5132de7694d.css",revision:"3b3ab5132de7694d"},{url:"/_next/static/css/da6e9b4a73108890.css",revision:"da6e9b4a73108890"},{url:"/_next/static/media/19cfc7226ec3afaa-s.woff2",revision:"9dda5cfc9a46f256d0e131bb535e46f8"},{url:"/_next/static/media/21350d82a1f187e9-s.woff2",revision:"4e2553027f1d60eff32898367dd4d541"},{url:"/_next/static/media/8e9860b6e62d6359-s.woff2",revision:"01ba6c2a184b8cba08b0d57167664d75"},{url:"/_next/static/media/ba9851c3c22cd980-s.woff2",revision:"9e494903d6b0ffec1a1e14d34427d44d"},{url:"/_next/static/media/c5fe6dc8356a8c31-s.woff2",revision:"027a89e9ab733a145db70f09b8a18b42"},{url:"/_next/static/media/df0a9ae256c0569c-s.woff2",revision:"d54db44de5ccb18886ece2fda72bdfe0"},{url:"/_next/static/media/e4af272ccee01ff0-s.p.woff2",revision:"65850a373e258f1c897a2b3d75eb74de"},{url:"/favicon.ico",revLine truncated
+64 -1
View File
@@ -470,6 +470,18 @@ const UserConfig = ({ config, role, refreshConfig }: UserConfigProps) => {
> >
状态 状态
</th> </th>
<th
scope='col'
className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider'
>
注册时间
</th>
<th
scope='col'
className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider'
>
最后登录
</th>
<th <th
scope='col' scope='col'
className='px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider' className='px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider'
@@ -548,6 +560,16 @@ const UserConfig = ({ config, role, refreshConfig }: UserConfigProps) => {
{!user.banned ? '正常' : '已封禁'} {!user.banned ? '正常' : '已封禁'}
</span> </span>
</td> </td>
<td className='px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400'>
{user.created_at
? `${new Date(user.created_at).toLocaleString('zh-CN', { hour12: false })}${user.created_at_estimated ? '*' : ''}`
: '-'}
</td>
<td className='px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400'>
{user.last_login_at
? `${new Date(user.last_login_at).toLocaleString('zh-CN', { hour12: false })}${user.last_login_estimated ? '*' : ''}`
: '-'}
</td>
<td className='px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2'> <td className='px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2'>
{/* 修改密码按钮 */} {/* 修改密码按钮 */}
{canChangePassword && ( {canChangePassword && (
@@ -628,9 +650,11 @@ const UserConfig = ({ config, role, refreshConfig }: UserConfigProps) => {
const VideoSourceConfig = ({ const VideoSourceConfig = ({
config, config,
refreshConfig, refreshConfig,
speeds,
}: { }: {
config: AdminConfig | null; config: AdminConfig | null;
refreshConfig: () => Promise<void>; refreshConfig: () => Promise<void>;
speeds: Record<string, { ms: number; ok: boolean }>;
}) => { }) => {
const [sources, setSources] = useState<DataSource[]>([]); const [sources, setSources] = useState<DataSource[]>([]);
const [showAddForm, setShowAddForm] = useState(false); const [showAddForm, setShowAddForm] = useState(false);
@@ -1098,6 +1122,21 @@ const VideoSourceConfig = ({
> >
{!source.disabled ? '启用中' : '已禁用'} {!source.disabled ? '启用中' : '已禁用'}
</span> </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>
<td className='px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2'> <td className='px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2'>
<button <button
@@ -1643,6 +1682,7 @@ const SiteConfigComponent = ({ config }: { config: AdminConfig | null }) => {
function AdminPageClient() { function AdminPageClient() {
const router = useRouter(); const router = useRouter();
const [speeds, setSpeeds] = useState<Record<string, { ms: number; ok: boolean }>>({});
const [config, setConfig] = useState<AdminConfig | null>(null); const [config, setConfig] = useState<AdminConfig | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -1653,6 +1693,29 @@ function AdminPageClient() {
siteConfig: false, 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 用于控制是否在请求期间显示整体加载骨架。 // showLoading 用于控制是否在请求期间显示整体加载骨架。
const fetchConfig = useCallback(async (showLoading = false) => { const fetchConfig = useCallback(async (showLoading = false) => {
@@ -1812,7 +1875,7 @@ function AdminPageClient() {
isExpanded={expandedTabs.videoSource} isExpanded={expandedTabs.videoSource}
onToggle={() => toggleTab('videoSource')} onToggle={() => toggleTab('videoSource')}
> >
<VideoSourceConfig config={config} refreshConfig={fetchConfig} /> <VideoSourceConfig config={config} refreshConfig={fetchConfig} speeds={speeds} />
</CollapsibleTab> </CollapsibleTab>
</div> </div>
</div> </div>
+186
View File
@@ -0,0 +1,186 @@
/* eslint-disable react-hooks/exhaustive-deps */
'use client';
import { useSearchParams } from 'next/navigation';
import { Suspense, useCallback, useEffect, useRef, useState } from 'react';
import PageLayout from '@/components/PageLayout';
import VideoCard from '@/components/VideoCard';
// ---------- /anime 动漫频道(数据来自第三方采集站全量动漫分类) ----------
// 后端:src/app/api/anime/route.ts -> { list:[...], next_pg, has_more }
type Item = {
id: string;
title: string;
poster: string;
episodes: number;
source: string;
source_name: string;
year: string;
area: string;
type_name: string;
douban_id?: number | string;
};
const REGION_OPTS = [
{ label: '全部', value: '' },
{ label: '国产', value: '国产' },
{ label: '日韩', value: '日韩' },
{ label: '欧美', value: '欧美' },
{ label: '港台', value: '港台' },
{ label: '海外', value: '海外' },
];
function AnimeClient() {
const searchParams = useSearchParams();
const [region, setRegion] = useState(() => searchParams.get('region') || '');
const [items, setItems] = useState<Item[]>([]);
const [refreshing, setRefreshing] = useState(false);
const [nextPg, setNextPg] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [err, setErr] = useState('');
const reqId = useRef(0);
const load = useCallback(
async (pg: number, reset: boolean) => {
const id = ++reqId.current;
if (reset) {
setRefreshing(true);
setErr('');
}
try {
const q = new URLSearchParams({ pg: String(pg) });
if (region) q.set('region', region);
const r = await fetch('/api/anime?' + q.toString());
const j = await r.json();
if (id !== reqId.current) return;
if (j?.error) {
setErr(j.error);
return;
}
const arr: Item[] = Array.isArray(j?.list) ? j.list : [];
setItems((prev) => {
const base = reset ? [...arr] : [...prev, ...arr];
const seen = new Set<string>();
return base.filter((x) => {
const k = x.title + '|' + x.year;
if (seen.has(k)) return false;
seen.add(k);
return true;
});
});
setNextPg(j?.next_pg || pg + 1);
setHasMore(!!j?.has_more && arr.length > 0);
} catch {
if (id === reqId.current) setErr('加载失败,请稍后重试');
} finally {
if (id === reqId.current) setRefreshing(false);
}
},
[region]
);
useEffect(() => {
setItems([]);
setNextPg(1);
setHasMore(true);
load(1, true);
}, [region]);
const goPage = (pg: number) => {
if (pg < 1) return;
setItems([]);
setNextPg(pg);
load(pg, true);
};
return (
<PageLayout activePath='/anime'>
<div className='px-4 sm:px-8 lg:px-12 py-4 sm:py-8'>
<h1 className='text-xl font-bold text-gray-800 dark:text-gray-200 mb-1'>动漫</h1>
<p className='text-xs text-gray-500 dark:text-gray-400 mb-4'>
聚合各资源站全部动漫内容(国产 / 日韩 / 欧美 / 港台)
</p>
<div className='flex flex-col sm:flex-row sm:items-center gap-2 mb-6'>
<span className='text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400 min-w-[48px]'>
地区
</span>
<div className='flex flex-wrap gap-2'>
{REGION_OPTS.map((o) => {
const on = region === o.value;
return (
<button
key={o.value || 'all'}
onClick={() => setRegion(o.value)}
className={
'px-3 py-1.5 text-xs sm:text-sm font-medium rounded-full transition-all duration-200 whitespace-nowrap ' +
(on
? 'bg-purple-500 text-white shadow-sm'
: 'bg-gray-200/60 text-gray-700 hover:bg-gray-300/60 dark:bg-gray-700/60 dark:text-gray-300 dark:hover:bg-gray-600/60')
}
>
{o.label}
</button>
);
})}
</div>
</div>
{err ? <div className='text-sm text-red-500 mb-4'>{err}</div> : null}
{refreshing && items.length === 0 ? (
<div className='text-sm text-gray-500 dark:text-gray-400'>加载中…</div>
) : items.length === 0 ? (
<div className='text-sm text-gray-500 dark:text-gray-400'>
暂无动漫内容,试试切换地区
</div>
) : (
<div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4'>
{items.map((v) => (
<VideoCard
key={v.source + ':' + v.id}
id={v.id}
source={v.source}
source_name={v.source_name}
title={v.title}
poster={v.poster}
episodes={v.episodes}
year={v.year}
douban_id={v.douban_id ? String(v.douban_id) : ''}
from='search'
type={v.episodes > 1 ? 'tv' : 'movie'}
/>
))}
</div>
)}
<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>
<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>
</PageLayout>
);
}
export default function AnimePage() {
return (
<Suspense>
<AnimeClient />
</Suspense>
);
}
+4 -2
View File
@@ -132,11 +132,13 @@ export async function POST(request: NextRequest) {
); );
} }
await storage.registerUser(targetUsername!, targetPassword); await storage.registerUser(targetUsername!, targetPassword);
// 更新配置 // 更新配置(带注册时间,避免列表显示空白)
adminConfig.UserConfig.Users.push({ adminConfig.UserConfig.Users.push({
username: targetUsername!, username: targetUsername!,
role: 'user', role: 'user',
}); created_at: new Date().toISOString(),
created_at_estimated: false,
} as any);
targetEntry = targetEntry =
adminConfig.UserConfig.Users[ adminConfig.UserConfig.Users[
adminConfig.UserConfig.Users.length - 1 adminConfig.UserConfig.Users.length - 1
+85
View File
@@ -0,0 +1,85 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAvailableApiSites, getCacheTime } from '@/lib/config';
import { fetchSiteKind, mapItem, Site } from '@/lib/vodcat';
// ---------- /api/anime 动漫聚合接口(源码化) ----------
// 数据来源:各第三方采集站(maccms 10 协议),非豆瓣精选
// 逻辑:按「动漫/动画/卡通」分类名跨站筛分类 -> 逐类取分页 -> 合并去重(全量)
// 参数:region('' | 国产 | 日韩 | 欧美 | 港台 | 海外)、pg
const EXCLUDE_SITES = new Set(['xiaojizy', '155api']);
// 地区 -> 各站分类名里的关键词(国产动漫 / 中国动漫 / 国产动漫…)
const REGION_MAP: Record<string, string> = {
国产: '国产',
日韩: '日韩',
欧美: '欧美',
港台: '港台',
海外: '海外',
};
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const region = searchParams.get('region') || '';
const pg = Math.max(1, parseInt(searchParams.get('pg') || '1', 10));
try {
const all = await getAvailableApiSites(true);
const sites = all.filter(
(s) => !EXCLUDE_SITES.has(s.key) && !String(s.name || '').startsWith('AV-')
) as unknown as Site[];
const cacheTime = await getCacheTime();
const cat = REGION_MAP[region] || '';
const settled = await Promise.all(
sites.map(async (s) => {
try {
return await fetchSiteKind(s, 'anime', cat, pg);
} catch {
return { items: [] as any[], hasMore: false };
}
})
);
const seen = new Set<string>();
const list: any[] = [];
let hasMore = false;
settled.forEach((r, i) => {
if (r.hasMore) hasMore = true;
const site = sites[i];
r.items.forEach((it) => {
const m = mapItem(it, site);
if (!m.title) return;
const k = `${m.title}|${m.year}`;
if (seen.has(k)) return;
seen.add(k);
list.push(m);
});
});
return NextResponse.json(
{ source: 'all', region, pg, list, next_pg: pg + 1, has_more: hasMore },
{
headers: {
'Cache-Control': `public, max-age=${Math.min(cacheTime, 300)}, s-maxage=${Math.min(cacheTime, 300)}`,
},
}
);
} catch (e: any) {
return NextResponse.json(
{ error: '动漫聚合请求失败', details: e?.message || String(e) },
{ status: 500 }
);
}
}
export async function OPTIONS() {
return new NextResponse(null, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
},
});
}
+83
View File
@@ -0,0 +1,83 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAvailableApiSites, getCacheTime } from '@/lib/config';
import { fetchSiteKind, mapItem, Site } from '@/lib/vodcat';
// ---------- /api/browse 第三方分类聚合接口(源码化) ----------
// 数据来源:各第三方采集站(maccms 10 协议),按分类名跨站聚合,全部数据而非精选
// 参数:kind=tv|show|movie|anime(剧集/综艺/电影/动漫)、cat=细分分类名(可空)、pg=页码
const EXCLUDE_SITES = new Set(['xiaojizy', '155api']);
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const kind = (searchParams.get('kind') || 'tv') as string;
const cat = searchParams.get('cat') || '';
const area = searchParams.get('area') || '';
const pg = Math.max(1, parseInt(searchParams.get('pg') || '1', 10));
try {
const all = await getAvailableApiSites(true);
const sites = all.filter(
(s) => !EXCLUDE_SITES.has(s.key) && !String(s.name || '').startsWith('AV-')
) as unknown as Site[];
const cacheTime = await getCacheTime();
const settled = await Promise.all(
sites.map(async (s) => {
try {
return await fetchSiteKind(s, kind, cat, pg);
} catch {
return { items: [] as any[], hasMore: false };
}
})
);
// area 支持多选('中国|大陆|香港'),命中任一即保留
const areaKeys = area ? area.split('|').filter(Boolean) : [];
const seen = new Set<string>();
const list: any[] = [];
let hasMore = false;
settled.forEach((r, i) => {
if (r.hasMore) hasMore = true;
const site = sites[i];
r.items.forEach((it) => {
const m = mapItem(it, site);
if (!m.title) return;
if (areaKeys.length) {
const ar = m.area || '';
if (!ar || !areaKeys.some((k) => ar.includes(k))) return;
}
const k = `${m.title}|${m.year}`;
if (seen.has(k)) return;
seen.add(k);
list.push(m);
});
});
return NextResponse.json(
{ kind, cat, area, pg, list, next_pg: pg + 1, has_more: hasMore },
{
headers: {
'Cache-Control': `public, max-age=${Math.min(cacheTime, 300)}, s-maxage=${Math.min(cacheTime, 300)}`,
},
}
);
} catch (e: any) {
return NextResponse.json(
{ error: '分类聚合请求失败', details: e?.message || String(e) },
{ status: 500 }
);
}
}
export async function OPTIONS() {
return new NextResponse(null, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
},
});
}
+54
View File
@@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
interface DoubanComment {
id: string;
user: string;
avatar: string;
rating: number;
content: string;
time: string;
location: string;
}
// 从豆瓣 rexxar 移动 API 获取短评(热门优先)
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const id = (searchParams.get('id') || '').trim();
const sort = (searchParams.get('sort') || 'hot').trim(); // hot | new
const count = Math.min(parseInt(searchParams.get('count') || '10') || 10, 20);
if (!id) return NextResponse.json({ code: 0, msg: '缺少豆瓣ID', list: [] });
const order = sort === 'new' ? 'time' : 'hot';
const url = `https://m.douban.com/rexxar/api/v2/movie/${id}/interests?count=${count}&order_by=${order}&status=done`;
try {
const r = await fetch(url, {
headers: {
'User-Agent':
'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1',
Referer: `https://m.douban.com/movie/subject/${id}/`,
Accept: 'application/json',
},
signal: AbortSignal.timeout(15000),
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const d: any = await r.json();
const list: DoubanComment[] = (Array.isArray(d?.interests) ? d.interests : [])
.map((x: any) => ({
id: String(x?.id || ''),
user: String(x?.user?.name || ''),
avatar: String(x?.user?.avatar || ''),
rating: Number(x?.rating?.value || 0),
content: String(x?.comment || '').trim(),
time: String(x?.create_time || ''),
location: String(x?.ip_location || ''),
}))
.filter((c: DoubanComment) => c.content.length > 0);
return NextResponse.json({ code: 1, msg: 'ok', total: d?.total || list.length, list });
} catch (e: any) {
return NextResponse.json({ code: 0, msg: e?.message || 'fetch fail', list: [] });
}
}
+48
View File
@@ -0,0 +1,48 @@
import { NextRequest, NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
// 从豆瓣 rexxar 获取条目详情(评分/演员/导演等)
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const id = (searchParams.get('id') || '').trim();
if (!id) return NextResponse.json({ code: 0, msg: '缺少豆瓣ID' });
const ua =
'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1';
for (const kind of ['movie', 'tv']) {
try {
const r = await fetch(`https://m.douban.com/rexxar/api/v2/${kind}/${id}`, {
headers: { 'User-Agent': ua, Referer: `https://m.douban.com/${kind}/subject/${id}/`, Accept: 'application/json' },
signal: AbortSignal.timeout(15000),
});
if (!r.ok) continue;
const d: any = await r.json();
if (!d || !d.id) continue;
const actors = (Array.isArray(d.actors) ? d.actors : [])
.map((a: any) => a?.name || a?.title)
.filter(Boolean);
const directors = (Array.isArray(d.directors) ? d.directors : [])
.map((a: any) => a?.name || a?.title)
.filter(Boolean);
return NextResponse.json({
code: 1,
msg: 'ok',
title: d.title || '',
rating: Number(d?.rating?.value || 0),
ratingCount: Number(d?.rating?.count || 0),
actors,
directors,
area: Array.isArray(d.regions) ? d.regions.join(' / ') : d.regions || '',
year: d.year || '',
duration: Array.isArray(d.durations) ? d.durations.join(' / ') : d.durations || '',
languages: Array.isArray(d.languages) ? d.languages.join(' / ') : d.languages || '',
intro: d.intro || '',
});
} catch {
continue;
}
}
return NextResponse.json({ code: 0, msg: '未找到', rating: 0, actors: [], directors: [] });
}
+38
View File
@@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const id = (searchParams.get('id') || '').trim();
const type = (searchParams.get('type') || 'movie').trim();
if (!id) return NextResponse.json({ code: 0, msg: '缺少豆瓣ID' });
const ua =
'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1';
const kind = type === 'tv' ? 'tv' : 'movie';
try {
const r = await fetch(
`https://m.douban.com/rexxar/api/v2/${kind}/${id}/recommendations?count=10&start=0`,
{
headers: { 'User-Agent': ua, Referer: `https://m.douban.com/${kind}/subject/${id}/`, Accept: 'application/json' },
signal: AbortSignal.timeout(15000),
}
);
if (!r.ok) return NextResponse.json({ code: 0, msg: '请求失败' });
const arr: any = await r.json();
if (!Array.isArray(arr)) return NextResponse.json({ code: 0, msg: '无数据' });
const list = arr.slice(0, 10).map((x: any) => ({
id: String(x.id || ''),
title: x.title || '',
poster: x?.pic?.large || x?.pic?.normal || '',
rating: Number(x?.rating?.value || 0),
subtitle: x.card_subtitle || '',
url: x.url || '',
}));
return NextResponse.json({ code: 1, msg: 'ok', list });
} catch (e: any) {
return NextResponse.json({ code: 0, msg: e?.message || 'error' });
}
}
+29 -3
View File
@@ -22,7 +22,7 @@ interface Site {
} }
const BATCH_DEFAULT = 5; const BATCH_DEFAULT = 5;
const ALL_MAX_SITES = 100; const ALL_MAX_SITES = 8;
// 源站 class 缓存:有数据 10min / 空 30s(原补丁逻辑) // 源站 class 缓存:有数据 10min / 空 30s(原补丁逻辑)
const classCache = new Map<string, [number, any[], boolean]>(); 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 batch = Math.min(Math.max(opts.batch || BATCH_DEFAULT, 1), 6);
const want = 24; const want = 24;
const maxPages = 30; const maxPages = 30;
const list: any[] = []; let list: any[] = [];
let hasMore = true; let hasMore = true;
let fetched = 0; let fetched = 0;
while (hasMore && fetched < maxPages) { while (hasMore && fetched < maxPages) {
@@ -191,6 +191,7 @@ async function browseSite(
}); });
if (list.length >= want || !hasMore) break; if (list.length >= want || !hasMore) break;
} }
list = list.slice(0, 50);
return { list, next_pg: pg, has_more: hasMore }; return { list, next_pg: pg, has_more: hasMore };
} }
@@ -222,7 +223,7 @@ async function browseAll(
) )
); );
const seen = new Set<string>(); const seen = new Set<string>();
const list: any[] = []; let list: any[] = [];
let hasMore = false; let hasMore = false;
let nextPg = Infinity; let nextPg = Infinity;
per.forEach((r) => { 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 }; return { list, next_pg: nextPg === Infinity ? pg + 1 : nextPg, has_more: hasMore };
} }
@@ -257,6 +259,30 @@ export async function GET(request: NextRequest) {
{ headers } { 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 (source === 'all') {
if (action === 'classes') { if (action === 'classes') {
return NextResponse.json( return NextResponse.json(
+67
View File
@@ -0,0 +1,67 @@
import { NextRequest, NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
const SEARXNG = process.env.SEARXNG_URL || 'http://192.168.68.19:4000';
interface HotComment {
title: string;
content: string;
url: string;
source: string;
}
// 评论聚合:SearXNG 全网搜“片名+评价/影评/观后感”,正文长的优先,取前 10 条
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const title = (searchParams.get('title') || '').trim();
if (!title) return NextResponse.json({ code: 0, msg: '缺少片名', list: [] });
const queries = [`${title} 评价`, `${title} 影评 观后感`];
const seen = new Set<string>();
const out: HotComment[] = [];
for (const q of queries) {
if (out.length >= 10) break;
let d: any = null;
try {
const r = await fetch(
`${SEARXNG}/search?q=${encodeURIComponent(q)}&format=json&language=zh-CN`,
{ signal: AbortSignal.timeout(15000) }
);
if (!r.ok) continue;
d = await r.json();
} catch {
continue;
}
const results: any[] = Array.isArray(d?.results) ? d.results : [];
// 正文长的优先(一般是真实影评),顺带过滤纯导航/下载站
results.sort(
(a, b) => String(b?.content || '').length - String(a?.content || '').length
);
for (const x of results) {
if (out.length >= 10) break;
const url: string = String(x?.url || '');
const content: string = String(x?.content || '').replace(/\s+/g, ' ').trim();
if (!url || !content || content.length < 40) continue;
if (/rarbg|torrent|magnet|bt\.| JAV|javhd|porn|赌场|博彩|贷款/i.test(url + content)) continue;
let host = '';
try {
host = new URL(url).hostname.replace(/^www\.|^m\.|^wap\./, '');
} catch {
continue;
}
const key = host + '|' + content.slice(0, 60);
if (seen.has(key)) continue;
seen.add(key);
out.push({
title: String(x?.title || host).slice(0, 80),
content: content.slice(0, 600),
url,
source: host,
});
}
}
return NextResponse.json({ code: 1, msg: 'ok', list: out.slice(0, 10) });
}
+4 -2
View File
@@ -97,11 +97,13 @@ export async function POST(req: NextRequest) {
await db.registerUser(username, password); await db.registerUser(username, password);
// 添加到配置中并保存 // 添加到配置中并保存(带注册时间,避免列表显示空白)
config.UserConfig.Users.push({ config.UserConfig.Users.push({
username, username,
role: 'user', role: 'user',
}); created_at: new Date().toISOString(),
created_at_estimated: false,
} as any);
await db.saveAdminConfig(config); await db.saveAdminConfig(config);
// 注册成功,设置认证cookie // 注册成功,设置认证cookie
+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([]));
}
}
+18 -145
View File
@@ -1,161 +1,34 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { SrcCfg, aggregateAll } from '@/lib/tvboxagg';
// 强制使用 Edge Runtime 以支持 Cloudflare Pages // 强制使用 Edge Runtime 以支持 Cloudflare Pages
export const runtime = 'edge'; 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'; // 进程内响应缓存:相同查询 60s 内直接返回,避免每次刷新都重新聚合上游(最新港剧等栏目秒开)
const respCache = new Map<string, [number, any]>();
interface SrcCfg { key: string; name: string; api: string; detail?: string; disabled?: boolean }
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) }); }
// 源站 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)));
}
out.total = out.list.length; out.limit = out.list.length;
return out;
}
// 顶层 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;
}
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url); const { searchParams } = new URL(request.url);
const cacheKey = searchParams.toString();
const now = Date.now();
const c = respCache.get(cacheKey);
// 空结果只缓存 5s:上游偶发超时不能把空列表当 60s 正常数据缓存(最新港剧整栏消失的根因之一)
const cTTL = c && c[1] && Array.isArray(c[1].list) && c[1].list.length ? 60000 : 5000;
if (c && now - c[0] < cTTL) {
return NextResponse.json(c[1], { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60', 'X-Cache': 'HIT' } });
}
const config = await getConfig(); const config = await getConfig();
const sourceConfigs: SrcCfg[] = (config.SourceConfig || []).filter((s: any) => !s.disabled); const sourceConfigs: SrcCfg[] = (config.SourceConfig || []).filter((s: any) => !s.disabled);
const r = await aggregateAll(sourceConfigs, searchParams); const r = await aggregateAll(sourceConfigs, searchParams);
// 只缓存有数据的结果;空结果短缓存(上面 5s TTL)且不长期驻留
if (r && Array.isArray(r.list) && r.list.length) respCache.set(cacheKey, [now, r]);
// 防止缓存无限增长:超过 200 条清空
if (respCache.size > 200) respCache.clear();
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } }); return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
} }
+34 -214
View File
@@ -1,158 +1,11 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { SrcCfg, aggregateAll, fetchClass, mkTransform } from '@/lib/tvboxagg';
// 强制使用 Edge Runtime 以支持 Cloudflare Pages // 强制使用 Edge Runtime 以支持 Cloudflare Pages
export const runtime = 'edge'; 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 配置生成 ---------- // ---------- 原有 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 } 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 逻辑 */ } } catch { /* fallback 正常 tvbox 逻辑 */ }
const format = searchParams.get('format') || 'json'; const format = searchParams.get('format') || 'json';
const host = request.headers.get('host') || 'localhost:3000'; 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 baseUrl = `${protocol}://${host}`;
const config = await getConfig(); const config = await getConfig();
@@ -213,51 +66,10 @@ export async function GET(request: NextRequest) {
const transformed = mkTransform(cls); const transformed = mkTransform(cls);
return NextResponse.json({ code: 1, msg: '数据列表', ...transformed }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } }); return NextResponse.json({ code: 1, msg: '数据列表', ...transformed }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
} }
if (ac === 'videolist' || searchParams.get('ids')) { // vod 请求(分类 t=9xx / 搜索 wd / 详情 ids)→ 全源聚合
// 顶层分类 9xx 处理:映射到源站 class + 过滤 // 旧版:agg 分类没把 9xx 换成源站真实 type_id,导致 电影/电视剧 等分类全部返回 0 条
const t = searchParams.get('t') || ''; if (ac === 'videolist' || searchParams.get('ids') || searchParams.get('wd')) {
const tops: Record<string, any> = {}; const r = await aggregateAll(sourceConfigs, searchParams);
// 重新计算 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);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } }); 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(); const hub = getHubFields();
// TVBox 端统一分类视图(旧补丁 TOP7)
const TOP7 = ['AI短剧', '香港电影', '香港剧', '电影', '电视剧', '综艺', '动画片', '动漫'];
const tvboxConfig: TVBoxConfig = { const tvboxConfig: TVBoxConfig = {
spider: '', spider: '',
wallpaper: `${baseUrl}/screenshot1.png`, wallpaper: `${baseUrl}/screenshot1.png`,
@@ -273,23 +87,29 @@ export async function GET(request: NextRequest) {
warning: hub.warning, warning: hub.warning,
version: hub.version, version: hub.version,
update_url: hub.update_url, update_url: hub.update_url,
sites: sourceConfigs.map((source) => { sites: [
let type = 1; // 「全部资源」:本站全源聚合(旧补丁 TOP7 结构)
const apiLower = source.api.toLowerCase(); { key: 'all', name: '全部资源', type: 1, api: `${baseUrl}/api/tvbox/all`, searchable: 1, quickSearch: 1, filterable: 1, ext: '', timeout: 60, categories: TOP7 },
if (apiLower.includes('at/xml') || apiLower.endsWith('.xml')) type = 0; // 各资源站走本站逐站代理 /api/tvbox/<key>:电视/手机端只要能访问本站域名就能点播,
return { // 9xx 分类在代理里映射成该源自己的分类 id(旧补丁 P() 能力,源码化时丢失,本次恢复)
key: source.key || source.name, ...sourceConfigs.map((source) => {
name: source.name, let type = 1;
type, const apiLower = source.api.toLowerCase();
api: source.api, if (apiLower.includes('at/xml') || apiLower.endsWith('.xml')) type = 0;
searchable: 1, return {
quickSearch: 1, key: source.key || source.name,
filterable: 1, name: source.name,
ext: source.detail || '', type,
timeout: 30, api: `${baseUrl}/api/tvbox/${encodeURIComponent(source.key || source.name)}`,
categories: ['电影', '电视剧', '综艺', '动漫', '纪录片', '短剧'], searchable: 1,
}; quickSearch: 1,
}), filterable: 1,
ext: source.detail || '',
timeout: 30,
categories: TOP7,
};
}),
],
parses: [ parses: [
{ name: 'Json并发', type: 2, url: 'Parallel' }, { name: 'Json并发', type: 2, url: 'Parallel' },
{ name: 'Json轮询', type: 2, url: 'Sequence' }, { 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'], 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 configStr = JSON.stringify(tvboxConfig, null, 2);
const base64Config = Buffer.from(configStr).toString('base64'); 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) { } catch (error) {
return NextResponse.json({ error: 'TVBox配置生成失败', details: error instanceof Error ? error.message : String(error) }, { status: 500 }); return NextResponse.json({ error: 'TVBox配置生成失败', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
+42
View File
@@ -8,6 +8,7 @@ export const dynamic = 'force-dynamic';
export default function ConfigPage() { export default function ConfigPage() {
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
const [copiedLive, setCopiedLive] = useState(false);
const [format, setFormat] = useState<'json' | 'base64'>('json'); const [format, setFormat] = useState<'json' | 'base64'>('json');
const getConfigUrl = useCallback(() => { const getConfigUrl = useCallback(() => {
@@ -16,6 +17,12 @@ export default function ConfigPage() {
return `${baseUrl}/api/tvbox?format=${format}`; return `${baseUrl}/api/tvbox?format=${format}`;
}, [format]); }, [format]);
const getLiveUrl = useCallback(() => {
if (typeof window === 'undefined') return '';
const baseUrl = window.location.origin;
return `${baseUrl}/api/tvbox?live=txt`;
}, []);
const handleCopy = async () => { const handleCopy = async () => {
try { try {
await navigator.clipboard.writeText(getConfigUrl()); await navigator.clipboard.writeText(getConfigUrl());
@@ -26,6 +33,16 @@ export default function ConfigPage() {
} }
}; };
const handleCopyLive = async () => {
try {
await navigator.clipboard.writeText(getLiveUrl());
setCopiedLive(true);
setTimeout(() => setCopiedLive(false), 2000);
} catch {
// Copy failed silently
}
};
return ( return (
<> <>
<TopRightButtons variant='float' /> <TopRightButtons variant='float' />
@@ -72,6 +89,31 @@ export default function ConfigPage() {
{copied ? '已复制' : '复制'} {copied ? '已复制' : '复制'}
</button> </button>
</div> </div>
<h2 className="text-xl font-semibold mt-6 mb-2 text-gray-900 dark:text-white">
直播源地址
</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
仅含电视直播,可单独填入 TVBox 直播源(TXT 格式)。
</p>
<div className="flex items-center space-x-2">
<input
type="text"
readOnly
value={getLiveUrl()}
className="flex-1 p-3 border border-gray-300 dark:border-gray-600 rounded-md bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white font-mono text-sm"
/>
<button
onClick={handleCopyLive}
className={`px-4 py-3 rounded-md font-medium transition-colors ${
copiedLive
? 'bg-green-500 text-white'
: 'bg-blue-500 hover:bg-blue-600 text-white'
}`}
>
{copiedLive ? '已复制' : '复制'}
</button>
</div>
</div> </div>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 mb-6"> <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 mb-6">
+101 -74
View File
@@ -6,17 +6,26 @@ import { useSearchParams } from 'next/navigation';
import { Suspense } from 'react'; import { Suspense } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { getDoubanCategories } from '@/lib/douban.client';
import { DoubanItem } from '@/lib/types';
import DoubanCardSkeleton from '@/components/DoubanCardSkeleton'; import DoubanCardSkeleton from '@/components/DoubanCardSkeleton';
import DoubanSelector from '@/components/DoubanSelector'; import DoubanSelector from '@/components/DoubanSelector';
import PageLayout from '@/components/PageLayout'; import PageLayout from '@/components/PageLayout';
import VideoCard from '@/components/VideoCard'; import VideoCard from '@/components/VideoCard';
// 第三方采集站聚合条目(/api/browse 返回)
type BrowseItem = {
id: string;
title: string;
poster: string;
year: string;
area: string;
episodes: number;
source: string;
source_name: string;
};
function DoubanPageClient() { function DoubanPageClient() {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const [doubanData, setDoubanData] = useState<DoubanItem[]>([]); const [browseData, setBrowseData] = useState<BrowseItem[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(0); const [currentPage, setCurrentPage] = useState(0);
const [hasMore, setHasMore] = useState(true); const [hasMore, setHasMore] = useState(true);
@@ -27,12 +36,14 @@ function DoubanPageClient() {
const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null); const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const type = searchParams.get('type') || 'movie'; const type = searchParams.get('type') || 'movie';
const catParam = searchParams.get('cat') || '';
// 选择器状态 - 完全独立,不依赖URL参数 // 选择器状态 - 完全独立,不依赖URL参数
const [primarySelection, setPrimarySelection] = useState<string>(() => { const [primarySelection, setPrimarySelection] = useState<string>(() => {
return type === 'movie' ? '热门' : ''; return type === 'movie' ? '全部' : '';
}); });
const [secondarySelection, setSecondarySelection] = useState<string>(() => { const [secondarySelection, setSecondarySelection] = useState<string>(() => {
if (catParam) return catParam;
if (type === 'movie') return '全部'; if (type === 'movie') return '全部';
if (type === 'tv') return 'tv'; if (type === 'tv') return 'tv';
if (type === 'show') return 'show'; if (type === 'show') return 'show';
@@ -41,29 +52,27 @@ function DoubanPageClient() {
// 初始化时标记选择器为准备好状态 // 初始化时标记选择器为准备好状态
useEffect(() => { useEffect(() => {
// 短暂延迟确保初始状态设置完成
const timer = setTimeout(() => { const timer = setTimeout(() => {
setSelectorsReady(true); setSelectorsReady(true);
}, 50); }, 50);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, []); // 只在组件挂载时执行一次 }, []);
// type变化时立即重置selectorsReady(最高优先级) // type变化时立即重置selectorsReady(最高优先级)
useEffect(() => { useEffect(() => {
setSelectorsReady(false); setSelectorsReady(false);
setLoading(true); // 立即显示loading状态 setLoading(true); // 立即显示loading状态
}, [type]); }, [type, catParam]);
// 当type变化时重置选择器状态 // 当type变化时重置选择器状态
useEffect(() => { useEffect(() => {
// 批量更新选择器状态
if (type === 'movie') { if (type === 'movie') {
setPrimarySelection('热门'); setPrimarySelection('全部');
setSecondarySelection('全部'); setSecondarySelection(catParam || '全部');
} else if (type === 'tv') { } else if (type === 'tv') {
setPrimarySelection(''); setPrimarySelection('');
setSecondarySelection('tv'); setSecondarySelection(catParam || 'tv');
} else if (type === 'show') { } else if (type === 'show') {
setPrimarySelection(''); setPrimarySelection('');
setSecondarySelection('show'); setSecondarySelection('show');
@@ -72,75 +81,100 @@ function DoubanPageClient() {
setSecondarySelection('全部'); setSecondarySelection('全部');
} }
// 使用短暂延迟确保状态更新完成后标记选择器准备好
const timer = setTimeout(() => { const timer = setTimeout(() => {
setSelectorsReady(true); setSelectorsReady(true);
}, 50); }, 50);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, [type]); }, [type, catParam]);
// 生成骨架屏数据 // 生成骨架屏数据
const skeletonData = Array.from({ length: 25 }, (_, index) => index); const skeletonData = Array.from({ length: 25 }, (_, index) => index);
// 生成API请求参数的辅助函数 // 选择器 -> 第三方聚合接口参数映射
const getRequestParams = useCallback( const getBrowseParams = useCallback((): { kind: string; cat: string; area: string } => {
(pageStart: number) => { if (type === 'movie') {
// 当type为tv或show时,kind统一为'tv',category使用type本身 // 二级为地区,映射到 vod_area 关键词
if (type === 'tv' || type === 'show') { const areaMap: Record<string, string> = {
return { 全部: '',
kind: 'tv' as const, 华语: '中国|大陆|香港|台湾|澳门',
category: type, 欧美: '美国|英国|法国|德国|加拿大|西班牙|意大利|荷兰|俄罗斯',
type: secondarySelection, 韩国: '韩国',
pageLimit: 25, 日本: '日本',
pageStart, 泰国: '泰国',
}; };
}
// 电影类型保持原逻辑
return { return {
kind: type as 'tv' | 'movie', kind: 'movie',
category: primarySelection, cat: primarySelection === '全部' || primarySelection === '热门' ? '' : primarySelection,
type: secondarySelection, area: areaMap[secondarySelection] ?? '',
pageLimit: 25, };
pageStart, }
if (type === 'tv') {
// 二级为剧集地区/类型
const tvMap: Record<string, { kind: string; cat: string }> = {
tv: { kind: 'tv', cat: '' },
tv_domestic: { kind: 'tv', cat: '国产剧' },
tv_american: { kind: 'tv', cat: '欧美剧' },
tv_japanese: { kind: 'tv', cat: '日本剧' },
tv_korean: { kind: 'tv', cat: '韩国剧' },
tv_animation: { kind: 'anime', cat: '' },
tv_documentary: { kind: 'tv', cat: '纪录' },
};
const m = tvMap[secondarySelection] || { kind: 'tv', cat: '' };
return { kind: m.kind, cat: m.cat, area: '' };
}
// 综艺
const showMap: Record<string, string> = {
show: '',
show_domestic: '大陆|国内|港台',
show_foreign: '日韩|欧美|海外|国外',
};
return { kind: 'show', cat: showMap[secondarySelection] ?? '', area: '' };
}, [type, primarySelection, secondarySelection]);
const fetchPage = useCallback(
async (pg: number) => {
const { kind, cat, area } = getBrowseParams();
const params = new URLSearchParams({ kind, pg: String(pg) });
if (cat) params.set('cat', cat);
if (area) params.set('area', area);
const res = await fetch(`/api/browse?${params.toString()}`);
if (!res.ok) throw new Error(`浏览接口请求失败: ${res.status}`);
return (await res.json()) as {
list: BrowseItem[];
has_more: boolean;
}; };
}, },
[type, primarySelection, secondarySelection] [getBrowseParams]
); );
// 防抖的数据加载函数 // 防抖的数据加载函数
const loadInitialData = useCallback(async () => { const loadInitialData = useCallback(async () => {
try { try {
setLoading(true); setLoading(true);
const data = await getDoubanCategories(getRequestParams(0)); const data = await fetchPage(1);
setBrowseData(data.list);
if (data.code === 200) { setHasMore(data.has_more && data.list.length > 0);
setDoubanData(data.list); setLoading(false);
setHasMore(data.list.length === 25);
setLoading(false);
} else {
throw new Error(data.message || '获取数据失败');
}
} catch (err) { } catch (err) {
console.error(err); console.error(err);
setLoading(false);
} }
}, [type, primarySelection, secondarySelection, getRequestParams]); }, [fetchPage]);
// 只在选择器准备好后才加载数据
useEffect(() => { useEffect(() => {
// 只有在选择器准备好时才开始加载
if (!selectorsReady) { if (!selectorsReady) {
return; return;
} }
// 重置页面状态 // 重置页面状态
setDoubanData([]); setBrowseData([]);
setCurrentPage(0); setCurrentPage(0);
setHasMore(true); setHasMore(true);
setIsLoadingMore(false); setIsLoadingMore(false);
// 清除之前的防抖定时器
if (debounceTimeoutRef.current) { if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current); clearTimeout(debounceTimeoutRef.current);
} }
@@ -148,9 +182,8 @@ function DoubanPageClient() {
// 使用防抖机制加载数据,避免连续状态更新触发多次请求 // 使用防抖机制加载数据,避免连续状态更新触发多次请求
debounceTimeoutRef.current = setTimeout(() => { debounceTimeoutRef.current = setTimeout(() => {
loadInitialData(); loadInitialData();
}, 100); // 100ms 防抖延迟 }, 100);
// 清理函数
return () => { return () => {
if (debounceTimeoutRef.current) { if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current); clearTimeout(debounceTimeoutRef.current);
@@ -171,16 +204,9 @@ function DoubanPageClient() {
try { try {
setIsLoadingMore(true); setIsLoadingMore(true);
const data = await getDoubanCategories( const data = await fetchPage(currentPage + 1);
getRequestParams(currentPage * 25) setBrowseData((prev) => [...prev, ...data.list]);
); setHasMore(data.has_more && data.list.length > 0);
if (data.code === 200) {
setDoubanData((prev) => [...prev, ...data.list]);
setHasMore(data.list.length === 25);
} else {
throw new Error(data.message || '获取数据失败');
}
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} finally { } finally {
@@ -194,12 +220,10 @@ function DoubanPageClient() {
// 设置滚动监听 // 设置滚动监听
useEffect(() => { useEffect(() => {
// 如果没有更多数据或正在加载,则不设置监听
if (!hasMore || isLoadingMore || loading) { if (!hasMore || isLoadingMore || loading) {
return; return;
} }
// 确保 loadingRef 存在
if (!loadingRef.current) { if (!loadingRef.current) {
return; return;
} }
@@ -226,7 +250,6 @@ function DoubanPageClient() {
// 处理选择器变化 // 处理选择器变化
const handlePrimaryChange = useCallback( const handlePrimaryChange = useCallback(
(value: string) => { (value: string) => {
// 只有当值真正改变时才设置loading状态
if (value !== primarySelection) { if (value !== primarySelection) {
setLoading(true); setLoading(true);
setPrimarySelection(value); setPrimarySelection(value);
@@ -237,7 +260,6 @@ function DoubanPageClient() {
const handleSecondaryChange = useCallback( const handleSecondaryChange = useCallback(
(value: string) => { (value: string) => {
// 只有当值真正改变时才设置loading状态
if (value !== secondarySelection) { if (value !== secondarySelection) {
setLoading(true); setLoading(true);
setSecondarySelection(value); setSecondarySelection(value);
@@ -247,7 +269,7 @@ function DoubanPageClient() {
); );
const getPageTitle = () => { const getPageTitle = () => {
// 根据 type 生成标题 if (type === 'tv' && catParam === 'tv_animation') return '动漫';
return type === 'movie' ? '电影' : type === 'tv' ? '电视剧' : '综艺'; return type === 'movie' ? '电影' : type === 'tv' ? '电视剧' : '综艺';
}; };
@@ -271,7 +293,7 @@ function DoubanPageClient() {
{getPageTitle()} {getPageTitle()}
</h1> </h1>
<p className='text-sm sm:text-base text-gray-600 dark:text-gray-400'> <p className='text-sm sm:text-base text-gray-600 dark:text-gray-400'>
来自豆瓣的精选内容 全网资源站聚合,按分类实时更新
</p> </p>
</div> </div>
@@ -295,14 +317,19 @@ function DoubanPageClient() {
? // 显示骨架屏 ? // 显示骨架屏
skeletonData.map((index) => <DoubanCardSkeleton key={index} />) skeletonData.map((index) => <DoubanCardSkeleton key={index} />)
: // 显示实际数据 : // 显示实际数据
doubanData.map((item, index) => ( browseData.map((item, index) => (
<div key={`${item.title}-${index}`} className='w-full'> <div
key={`${item.source}-${item.id}-${index}`}
className='w-full'
>
<VideoCard <VideoCard
from='douban' from='search'
id={item.id}
source={item.source}
source_name={item.source_name}
title={item.title} title={item.title}
poster={item.poster} poster={item.poster}
douban_id={item.id} episodes={item.episodes}
rate={item.rate}
year={item.year} year={item.year}
type={type === 'movie' ? 'movie' : ''} // 电影类型严格控制,tv 不控 type={type === 'movie' ? 'movie' : ''} // 电影类型严格控制,tv 不控
/> />
@@ -332,12 +359,12 @@ function DoubanPageClient() {
)} )}
{/* 没有更多数据提示 */} {/* 没有更多数据提示 */}
{!hasMore && doubanData.length > 0 && ( {!hasMore && browseData.length > 0 && (
<div className='text-center text-gray-500 py-8'>已加载全部内容</div> <div className='text-center text-gray-500 py-8'>已加载全部内容</div>
)} )}
{/* 空状态 */} {/* 空状态 */}
{!loading && doubanData.length === 0 && ( {!loading && browseData.length === 0 && (
<div className='text-center text-gray-500 py-8'>暂无相关内容</div> <div className='text-center text-gray-500 py-8'>暂无相关内容</div>
)} )}
</div> </div>
+60 -50
View File
@@ -1,11 +1,11 @@
/* eslint-disable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */
'use client'; 'use client';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation'; import { useSearchParams } from 'next/navigation';
import { Suspense, useCallback, useEffect, useRef, useState } from 'react'; import { Suspense, useCallback, useEffect, useRef, useState } from 'react';
import PageLayout from '@/components/PageLayout'; import PageLayout from '@/components/PageLayout';
import VideoCard from '@/components/VideoCard';
// ---------- /filter 筛选页(源码化,原运行时补丁 filter-page-chunk.js) ---------- // ---------- /filter 筛选页(源码化,原运行时补丁 filter-page-chunk.js) ----------
// 数据约定对应 src/app/api/filter/route.ts: // 数据约定对应 src/app/api/filter/route.ts:
@@ -25,6 +25,7 @@ type Item = {
year: string; year: string;
area: string; area: string;
type_name: string; type_name: string;
douban_id?: number | string;
}; };
const AREA_OPTS = [ const AREA_OPTS = [
@@ -126,6 +127,19 @@ function Pills({
function FilterClient() { function FilterClient() {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const [sources, setSources] = useState<Src[]>([]); 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 [source, setSource] = useState('all');
const [classes, setClasses] = useState<Cls[]>([]); const [classes, setClasses] = useState<Cls[]>([]);
const [cat, setCat] = useState(() => searchParams.get('t') || searchParams.get('cat') || ''); const [cat, setCat] = useState(() => searchParams.get('t') || searchParams.get('cat') || '');
@@ -199,7 +213,7 @@ function FilterClient() {
} }
const arr: Item[] = Array.isArray(j?.list) ? j.list : []; const arr: Item[] = Array.isArray(j?.list) ? j.list : [];
setItems((prev) => { setItems((prev) => {
const base = reset ? [] : [...prev, ...arr]; const base = reset ? [...arr] : [...prev, ...arr];
const seen = new Set<string>(); const seen = new Set<string>();
return base.filter((x) => { return base.filter((x) => {
const k = x.title + '|' + x.year; const k = x.title + '|' + x.year;
@@ -230,21 +244,19 @@ function FilterClient() {
load(1, true); load(1, true);
}, [source, cat, area, year]); }, [source, cat, area, year]);
// 触底加载更多 // 兜底:首次挂载确保加载一次(避免条件 effect 漏触发)
useEffect(() => { useEffect(() => {
const el = loadingRef.current; load(1, true);
if (!el) return; // eslint-disable-next-line react-hooks/exhaustive-deps
const ob = new IntersectionObserver( }, []);
(es) => {
if (es[0]?.isIntersecting && hasMore && !refreshing && !loadingMore) { // 分页:上一页/下一页
load(nextPg, false); const goPage = (pg: number) => {
} if (pg < 1) return;
}, setItems([]);
{ rootMargin: '400px' } setNextPg(pg);
); load(pg, true);
ob.observe(el); };
return () => ob.disconnect();
}, [hasMore, refreshing, loadingMore, nextPg, load]);
const resetAll = () => { const resetAll = () => {
setCat(''); setCat('');
@@ -272,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' 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> <option value='all'>全部资源站</option>
{sources.map((s) => ( {sources
<option key={s.key} value={s.key}> .filter((s) => !probe[s.key] || probe[s.key].ok)
{s.name} .map((s) => (
</option> <option key={s.key} value={s.key}>
))} {s.name}
{probe[s.key] ? `(${(probe[s.key].ms / 1000).toFixed(2)}s)` : ''}
</option>
))}
</select> </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> </div>
<Pills <Pills
label='分类' label='分类'
@@ -307,41 +329,29 @@ function FilterClient() {
) : ( ) : (
<div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4'> <div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4'>
{items.map((v) => { {items.map((v) => {
const pic = v.poster ? '/api/image-proxy?url=' + encodeURIComponent(v.poster) : ''; const dbId = v.douban_id ? String(v.douban_id) : '';
return ( return (
<Link <VideoCard
key={v.source + ':' + v.id} key={v.source + ':' + v.id}
href={`/play?source=${encodeURIComponent(v.source)}&id=${encodeURIComponent(v.id)}&title=${encodeURIComponent(v.title)}${v.year ? '&year=' + encodeURIComponent(v.year) : ''}`} id={v.id}
className='group block' source={v.source}
> source_name={v.source_name}
<div className='relative aspect-[2/3] w-full overflow-hidden rounded-lg bg-gray-200 dark:bg-gray-800'> title={v.title}
{pic ? ( poster={v.poster}
<img episodes={v.episodes}
src={pic} year={v.year}
alt={v.title} douban_id={dbId}
loading='lazy' from='search'
className='absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-300' type={v.episodes > 1 ? 'tv' : 'movie'}
/> />
) : null}
{v.episodes > 1 ? (
<span className='absolute bottom-1 right-1 px-1.5 py-0.5 text-xs bg-black/65 text-white rounded'>
{v.episodes}集
</span>
) : null}
</div>
<div className='mt-2 text-sm font-medium text-gray-800 dark:text-gray-200 truncate'>
{v.title}
</div>
<div className='text-xs text-gray-500 dark:text-gray-400 truncate'>
{[v.year, v.source_name].filter(Boolean).join(' · ')}
</div>
</Link>
); );
})} })}
</div> </div>
)} )}
<div ref={loadingRef} className='py-6 text-center text-sm text-gray-500 dark:text-gray-400'> <div className='py-6 flex items-center justify-center gap-3 text-sm'>
{loadingMore ? '加载中…' : hasMore && items.length > 0 ? '下拉加载更多' : items.length > 0 ? '已加载全部内容' : ''} <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)} 页 · 已加载 {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>
</div> </div>
</PageLayout> </PageLayout>
+117 -34
View File
@@ -8,15 +8,21 @@ const H = {
v6: 'https://tv6.88531.cn:4443', v6: 'https://tv6.88531.cn:4443',
}; };
// 第一步:纯 IPv6 端点(仅 AAAA 记录),用于判断"客户端自己是否有 IPv6 出口"
const IPV6_TEST = 'https://api6.ipify.org?format=json';
// 第二步:我们自己的 IPv6 入口
const URLS = [ const URLS = [
'https://tv6.88531.cn:4443/api/license-config?_=', 'https://tv6.88531.cn:4443/api/license-config?_=',
'https://tv6.88531.cn/api/license-config?_=', 'https://tv6.88531.cn/api/license-config?_=',
]; ];
type ProbeState = 'checking' | 'ok' | 'fail'; type ProbeState = 'checking' | 'ok' | 'fail';
type FailReason = 'no-ipv6' | 'entry' | 'unknown';
export default function IPv6Page() { export default function IPv6Page() {
const [state, setState] = useState<ProbeState>('checking'); const [state, setState] = useState<ProbeState>('checking');
const [reason, setReason] = useState<FailReason>('unknown');
const [detail, setDetail] = useState('');
const [back, setBack] = useState('/'); const [back, setBack] = useState('/');
useEffect(() => { useEffect(() => {
@@ -35,6 +41,8 @@ export default function IPv6Page() {
const cached = JSON.parse(localStorage.getItem('__v6probe') || 'null'); const cached = JSON.parse(localStorage.getItem('__v6probe') || 'null');
if (cached && Date.now() - cached.t < 120000) { if (cached && Date.now() - cached.t < 120000) {
setState(cached.ok ? 'ok' : 'fail'); setState(cached.ok ? 'ok' : 'fail');
setReason(cached.reason || 'unknown');
setDetail(cached.detail || '');
return; return;
} }
} catch (e) { // ignore } catch (e) { // ignore
@@ -42,51 +50,81 @@ export default function IPv6Page() {
} }
let cancelled = false; let cancelled = false;
const fetchJson = (url: string, timeout = 5000) => {
const c = new AbortController();
const ti = setTimeout(() => c.abort(), timeout);
return fetch(url, { mode: 'cors', signal: c.signal, cache: 'no-store', credentials: 'omit' })
.then((r) => { clearTimeout(ti); return r.json(); })
.catch((e) => { clearTimeout(ti); throw e; });
};
const fail = (r: FailReason, d: string) => {
if (cancelled) return;
try { localStorage.setItem('__v6probe', JSON.stringify({ t: Date.now(), ok: false, reason: r, detail: d })); } catch (e) { /* ignore */ }
setReason(r);
setDetail(d);
setState('fail');
};
// 单一检测点:我们自己的 v6 入口(纯 IPv6,AAAA 记录)
// 能通 ⇒ 客户端有 IPv6 出口且 v6 入口可达;不通 ⇒ 其中一方有问题
let i = 0; let i = 0;
const probe = () => { const probeEntry = () => {
if (i >= URLS.length) { if (i >= URLS.length) {
if (!cancelled) { fail('entry', 'v6 入口 ' + URLS.join(' / ') + ' 全部失败:客户端没有可用的 IPv6 出口,或服务端 v6 入口被防火墙/运营商拦截。');
try { localStorage.setItem('__v6probe', JSON.stringify({ t: Date.now(), ok: false })); } catch (e) { // ignore
// ignore
}
setState('fail');
}
return; return;
} }
const c = new AbortController(); fetchJson(URLS[i] + Date.now(), 5000)
const ti = setTimeout(() => c.abort(), 5000); .then((jj) => {
fetch(URLS[i] + Date.now(), { mode: 'cors', signal: c.signal, cache: 'no-store', credentials: 'omit' })
.then((r) => r.json())
.then((j) => {
clearTimeout(ti);
if (cancelled) return; if (cancelled) return;
if (j && j.code === 200 && j.data) { if (jj && jj.code === 200 && jj.data) {
try { localStorage.setItem('__v6probe', JSON.stringify({ t: Date.now(), ok: true })); } catch (e) { // ignore try { localStorage.setItem('__v6probe', JSON.stringify({ t: Date.now(), ok: true })); } catch (e) { /* ignore */ }
// ignore
}
setState('ok'); setState('ok');
} else { } else {
i++; i++;
probe(); probeEntry();
} }
}) })
.catch(() => { .catch((e) => {
clearTimeout(ti);
if (cancelled) return; if (cancelled) return;
i++; i++;
probe(); probeEntry();
}); });
}; };
probe(); probeEntry();
return () => { cancelled = true; }; return () => { cancelled = true; };
}, []); }, []);
const choose = (which: 'v4' | 'v6') => { const choose = (which: 'v4' | 'v6') => {
const dest = which === 'v4' ? H.v4 : H.v6; const dest = which === 'v4' ? H.v4 : H.v6;
let targetBack = back;
try {
const s = sessionStorage.getItem('__v6back');
if (s) { targetBack = s; sessionStorage.removeItem('__v6back'); }
} catch (e) { /* ignore */ }
try { localStorage.setItem('__v6dest', which); } catch (e) { // ignore try { localStorage.setItem('__v6dest', which); } catch (e) { // ignore
// ignore // ignore
} }
window.location.href = dest + back + window.location.search + window.location.hash; document.cookie = `__v6dest=${which}; path=/; max-age=31536000; samesite=lax`;
// 去掉 search 里的 back 参数,避免透传到目标地址
const qs = new URLSearchParams(window.location.search);
qs.delete('back');
const searchStr = qs.toString() ? '?' + qs.toString() : '';
const u = new URL(dest);
const m = /^([^?#]*)(\?[^#]*)?(#.*)?$/.exec(targetBack) || [];
u.pathname = m[1] || '/';
if (m[2]) {
const q2 = new URLSearchParams(m[2].slice(1));
q2.forEach((v, k) => { if (!u.searchParams.has(k)) u.searchParams.set(k, v); });
}
if (searchStr) {
const q3 = new URLSearchParams(searchStr.slice(1));
q3.forEach((v, k) => { if (!u.searchParams.has(k)) u.searchParams.set(k, v); });
}
if (m[3]) u.hash = m[3];
window.location.href = u.toString();
}; };
const reprobe = () => { const reprobe = () => {
@@ -104,7 +142,24 @@ export default function IPv6Page() {
try { localStorage.setItem('__v6dest', 'v6'); } catch (e) { // ignore try { localStorage.setItem('__v6dest', 'v6'); } catch (e) { // ignore
// ignore // ignore
} }
window.location.href = H.v6 + back + window.location.search + window.location.hash; document.cookie = '__v6dest=v6; path=/; max-age=31536000; samesite=lax';
let targetBack = back;
try {
const s = sessionStorage.getItem('__v6back');
if (s) { targetBack = s; sessionStorage.removeItem('__v6back'); }
} catch (e) { /* ignore */ }
const u = new URL(H.v6);
const m = /^([^?#]*)(\?[^#]*)?(#.*)?$/.exec(targetBack) || [];
u.pathname = m[1] || '/';
if (m[2]) {
const q2 = new URLSearchParams(m[2].slice(1));
q2.forEach((v, k) => { if (!u.searchParams.has(k)) u.searchParams.set(k, v); });
}
const qs = new URLSearchParams(window.location.search);
qs.delete('back');
qs.forEach((v, k) => { if (!u.searchParams.has(k)) u.searchParams.set(k, v); });
if (m[3]) u.hash = m[3];
window.location.href = u.toString();
}; };
return ( return (
@@ -125,14 +180,35 @@ export default function IPv6Page() {
<p style={{ color: 'rgba(255,255,255,.5)', marginBottom: 32 }}>选择访问线路</p> <p style={{ color: 'rgba(255,255,255,.5)', marginBottom: 32 }}>选择访问线路</p>
{state === 'checking' && ( {state === 'checking' && (
<p style={{ color: 'rgba(255,255,255,.45)' }}>正在检测 IPv6…</p> <p style={{ color: 'rgba(255,255,255,.45)' }}>正在检测 IPv6(客户端出口 + v6 入口)…</p>
)} )}
{state === 'ok' && ( {state === 'ok' && (
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', justifyContent: 'center' }}> <>
<button onClick={() => choose('v4')} style={btnStyle}>IPv4 线路</button> <div style={{
<button onClick={() => choose('v6')} style={btnStyle}>IPv6 线路</button> background: 'rgba(80,220,120,.10)',
</div> border: '1px solid rgba(80,220,120,.3)',
borderRadius: 12,
padding: '14px 20px',
maxWidth: 520,
textAlign: 'center',
marginBottom: 24,
}}>
<p style={{ margin: 0, fontWeight: 600, color: '#7ef0a0' }}>✅ 检测到你的网络支持 IPv6</p>
<p style={{ margin: '8px 0 0', color: 'rgba(255,255,255,.6)', fontSize: 13, lineHeight: 1.5 }}>
推荐选择「IPv6 线路」,观影更流畅;如遇 IPv6 无法访问再切回 IPv4。
</p>
</div>
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', justifyContent: 'center' }}>
<button onClick={() => choose('v6')} style={{
...btnStyle,
background: 'rgba(80,220,120,.16)',
border: '1px solid rgba(80,220,120,.55)',
fontWeight: 600,
}}>IPv6 线路(推荐)</button>
<button onClick={() => choose('v4')} style={btnStyle}>IPv4 线路</button>
</div>
</>
)} )}
{state === 'fail' && ( {state === 'fail' && (
@@ -142,13 +218,20 @@ export default function IPv6Page() {
border: '1px solid rgba(255,180,0,.3)', border: '1px solid rgba(255,180,0,.3)',
borderRadius: 12, borderRadius: 12,
padding: '16px 20px', padding: '16px 20px',
maxWidth: 480, maxWidth: 520,
textAlign: 'center', textAlign: 'left',
marginBottom: 24, marginBottom: 24,
}}> }}>
<p style={{ margin: 0, fontWeight: 600 }}>⚠️ 检测到你的网络不支持 IPv6 访问</p> <p style={{ margin: 0, fontWeight: 600 }}>
<p style={{ margin: '8px 0 0', color: 'rgba(255,255,255,.6)', fontSize: 14 }}> {reason === 'no-ipv6' ? '⚠️ 你的浏览器/网络没有可用的 IPv6 出口' : '⚠️ 你的网络支持 IPv6,但我们的 v6 入口不可达'}
已隐藏 IPv6 线路。请使用 IPv4 线路访问。 </p>
<p style={{ margin: '8px 0 0', color: 'rgba(255,255,255,.6)', fontSize: 13, lineHeight: 1.5, wordBreak: 'break-word' }}>
{detail}
</p>
<p style={{ margin: '10px 0 0', color: 'rgba(255,255,255,.45)', fontSize: 12 }}>
{reason === 'no-ipv6'
? '常见原因:系统代理/VPN 只走 IPv4;路由器未分配 IPv6;浏览器禁用 IPv6。'
: '常见原因:路由器/光猫 IPv6 防火墙拦截入向 4443;运营商阻断;或服务端 IPv6 地址已变更。'}
</p> </p>
</div> </div>
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}> <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
+10 -8
View File
@@ -7,13 +7,14 @@ import 'sweetalert2/dist/sweetalert2.min.css';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { SiteProvider } from '../components/SiteProvider'; import { SiteProvider } from '../components/SiteProvider';
import Ipv6FirstVisitGate from '../components/Ipv6FirstVisitGate';
import { ThemeProvider } from '../components/ThemeProvider'; import { ThemeProvider } from '../components/ThemeProvider';
const inter = Inter({ subsets: ['latin'] }); const inter = Inter({ subsets: ['latin'] });
// 动态生成 metadata,支持配置更新后的标题变化 // 动态生成 metadata,支持配置更新后的标题变化
export async function generateMetadata(): Promise<Metadata> { export async function generateMetadata(): Promise<Metadata> {
let siteName = process.env.SITE_NAME || 'KatelyaTV'; let siteName = process.env.SITE_NAME || '米视TV';
try { try {
// 只有在非 d1 和 upstash 存储类型时才尝试获取配置 // 只有在非 d1 和 upstash 存储类型时才尝试获取配置
@@ -57,16 +58,10 @@ export default async function RootLayout({
}: { }: {
children: React.ReactNode; children: React.ReactNode;
}) { }) {
let siteName = process.env.SITE_NAME || 'KatelyaTV'; let siteName = process.env.SITE_NAME || '米视TV';
let announcement = let announcement =
process.env.ANNOUNCEMENT || process.env.ANNOUNCEMENT ||
'本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。Link Me TG:@katelya77'; '本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。Link Me TG:@katelya77';
// 授权中心公告优先(CardAuth):有则覆盖默认免责声明,失败开放保留原公告
try {
const hub = (global as any).__licenseHub || eval('require')('/app/license-hub.js');
const n = hub.getNotice ? hub.getNotice() : '';
if (n) announcement = String(n);
} catch {}
let enableRegister = process.env.NEXT_PUBLIC_ENABLE_REGISTER === 'true'; let enableRegister = process.env.NEXT_PUBLIC_ENABLE_REGISTER === 'true';
let imageProxy = process.env.NEXT_PUBLIC_IMAGE_PROXY || ''; let imageProxy = process.env.NEXT_PUBLIC_IMAGE_PROXY || '';
let doubanProxy = process.env.NEXT_PUBLIC_DOUBAN_PROXY || ''; let doubanProxy = process.env.NEXT_PUBLIC_DOUBAN_PROXY || '';
@@ -81,6 +76,12 @@ export default async function RootLayout({
imageProxy = config.SiteConfig.ImageProxy; imageProxy = config.SiteConfig.ImageProxy;
doubanProxy = config.SiteConfig.DoubanProxy; doubanProxy = config.SiteConfig.DoubanProxy;
} }
// 授权中心公告优先(CardAuth):有则覆盖 config 默认免责声明,失败开放保留原公告
try {
const hub = (global as any).__licenseHub || eval('require')('/app/license-hub.js');
const n = hub.getNotice ? hub.getNotice() : '';
if (n) announcement = String(n);
} catch {}
// 将运行时配置注入到全局 window 对象,供客户端在运行时读取 // 将运行时配置注入到全局 window 对象,供客户端在运行时读取
const runtimeConfig = { const runtimeConfig = {
@@ -114,6 +115,7 @@ export default async function RootLayout({
disableTransitionOnChange disableTransitionOnChange
> >
<SiteProvider siteName={siteName} announcement={announcement}> <SiteProvider siteName={siteName} announcement={announcement}>
<Ipv6FirstVisitGate />
{children} {children}
</SiteProvider> </SiteProvider>
</ThemeProvider> </ThemeProvider>
+12 -12
View File
@@ -7,18 +7,18 @@ export default function LivePage() {
<> <>
<TopRightButtons variant='float' /> <TopRightButtons variant='float' />
<iframe <iframe
src='/api/tvbox?live=page' src='/api/tvbox?live=page'
title='港澳台电视直播' title='港澳台电视直播'
allow='autoplay; fullscreen; encrypted-media' allow='autoplay; fullscreen; encrypted-media'
allowFullScreen allowFullScreen
style={{ style={{
width: '100%', width: '100%',
height: 'calc(100vh - 64px)', height: 'calc(100vh - 64px)',
minHeight: 480, minHeight: 480,
border: 'none', border: 'none',
display: 'block', display: 'block',
background: '#0f1115', background: '#0f1115',
}} }}
/> />
</> </>
); );
+7 -60
View File
@@ -20,12 +20,12 @@ import { DoubanItem } from '@/lib/types';
import CapsuleSwitch from '@/components/CapsuleSwitch'; import CapsuleSwitch from '@/components/CapsuleSwitch';
import ContinueWatching from '@/components/ContinueWatching'; import ContinueWatching from '@/components/ContinueWatching';
import HkDramaRow from '@/components/HkDramaRow'; import HkDramaRow from '@/components/HkDramaRow';
import LineRecommender from '@/components/LineRecommender';
import PageLayout from '@/components/PageLayout'; import PageLayout from '@/components/PageLayout';
import PaginatedRow from '@/components/PaginatedRow'; import PaginatedRow from '@/components/PaginatedRow';
import { useSite } from '@/components/SiteProvider';
import VideoCard from '@/components/VideoCard'; import VideoCard from '@/components/VideoCard';
// 主内容区大型 KatelyaTV Logo 组件 // 主内容区大型 米视TV Logo 组件
const MainKatelyaLogo = () => { const MainKatelyaLogo = () => {
return ( return (
<div className='main-logo-container'> <div className='main-logo-container'>
@@ -33,7 +33,7 @@ const MainKatelyaLogo = () => {
<div className='logo-background-glow'></div> <div className='logo-background-glow'></div>
{/* 主 Logo */} {/* 主 Logo */}
<div className='main-katelya-logo'>KatelyaTV</div> <div className='main-katelya-logo'>米视TV</div>
{/* 副标题 */} {/* 副标题 */}
<div className='mt-3 text-center'> <div className='mt-3 text-center'>
@@ -53,7 +53,7 @@ const MainKatelyaLogo = () => {
); );
}; };
// KatelyaTV 底部 Logo 组件 // 米视TV 底部 Logo 组件
const BottomKatelyaLogo = () => { const BottomKatelyaLogo = () => {
return ( return (
<div className='bottom-logo-container'> <div className='bottom-logo-container'>
@@ -66,9 +66,9 @@ const BottomKatelyaLogo = () => {
</div> </div>
<div className='text-center'> <div className='text-center'>
<div className='bottom-logo'>KatelyaTV</div> <div className='bottom-logo'>米视TV</div>
<div className='mt-2 text-sm text-gray-500 dark:text-gray-400 opacity-75'> <div className='mt-2 text-sm text-gray-500 dark:text-gray-400 opacity-75'>
Powered by KatelyaTV Core Powered by 米视TV Core
</div> </div>
</div> </div>
</div> </div>
@@ -81,7 +81,6 @@ function HomeClient() {
const [hotTvShows, setHotTvShows] = useState<DoubanItem[]>([]); const [hotTvShows, setHotTvShows] = useState<DoubanItem[]>([]);
const [hotVarietyShows, setHotVarietyShows] = useState<DoubanItem[]>([]); const [hotVarietyShows, setHotVarietyShows] = useState<DoubanItem[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const { announcement } = useSite();
// 分页状态管理 // 分页状态管理
const [moviePage, setMoviePage] = useState(0); const [moviePage, setMoviePage] = useState(0);
@@ -98,20 +97,6 @@ function HomeClient() {
varietyShows: true, varietyShows: true,
}); });
const [showAnnouncement, setShowAnnouncement] = useState(false);
// 检查公告弹窗状态
useEffect(() => {
if (typeof window !== 'undefined' && announcement) {
const hasSeenAnnouncement = localStorage.getItem('hasSeenAnnouncement');
if (hasSeenAnnouncement !== announcement) {
setShowAnnouncement(true);
} else {
setShowAnnouncement(Boolean(!hasSeenAnnouncement && announcement));
}
}
}, [announcement]);
// 收藏夹数据 // 收藏夹数据
type FavoriteItem = { type FavoriteItem = {
id: string; id: string;
@@ -311,11 +296,6 @@ function HomeClient() {
return unsubscribe; return unsubscribe;
}, [activeTab]); }, [activeTab]);
const handleCloseAnnouncement = (announcement: string) => {
setShowAnnouncement(false);
localStorage.setItem('hasSeenAnnouncement', announcement); // 记录已查看弹窗
};
return ( return (
<PageLayout> <PageLayout>
<div className='px-4 sm:px-8 lg:px-12 py-4 sm:py-8 overflow-visible'> <div className='px-4 sm:px-8 lg:px-12 py-4 sm:py-8 overflow-visible'>
@@ -553,40 +533,6 @@ function HomeClient() {
)} )}
</div> </div>
</div> </div>
{announcement && showAnnouncement && (
<div
className={`fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm dark:bg-black/70 p-4 transition-opacity duration-300 ${
showAnnouncement ? '' : 'opacity-0 pointer-events-none'
}`}
>
<div className='w-full max-w-md rounded-xl bg-white p-6 shadow-xl dark:bg-gray-900 transform transition-all duration-300 hover:shadow-2xl'>
<div className='flex justify-between items-start mb-4'>
<h3 className='text-2xl font-bold tracking-tight text-gray-800 dark:text-white border-b border-purple-500 pb-1'>
提示
</h3>
<button
onClick={() => handleCloseAnnouncement(announcement)}
className='text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-white transition-colors'
aria-label='关闭'
></button>
</div>
<div className='mb-6'>
<div className='relative overflow-hidden rounded-lg mb-4 bg-purple-50 dark:bg-purple-900/20'>
<div className='absolute inset-y-0 left-0 w-1.5 bg-purple-500 dark:bg-purple-400'></div>
<p className='ml-4 text-gray-600 dark:text-gray-300 leading-relaxed'>
{announcement}
</p>
</div>
</div>
<button
onClick={() => handleCloseAnnouncement(announcement)}
className='w-full rounded-lg bg-gradient-to-r from-purple-600 to-purple-700 px-4 py-3 text-white font-medium shadow-md hover:shadow-lg hover:from-purple-700 hover:to-purple-800 dark:from-purple-600 dark:to-purple-700 dark:hover:from-purple-700 dark:hover:to-purple-800 transition-all duration-300 transform hover:-translate-y-0.5'
>
我知道了
</button>
</div>
</div>
)}
</PageLayout> </PageLayout>
); );
} }
@@ -595,6 +541,7 @@ export default function Home() {
return ( return (
<Suspense> <Suspense>
<HomeClient /> <HomeClient />
<LineRecommender />
</Suspense> </Suspense>
); );
} }
+29 -2
View File
@@ -23,6 +23,7 @@ import { getVideoResolutionFromM3u8, processImageUrl } from '@/lib/utils';
import EpisodeSelector from '@/components/EpisodeSelector'; import EpisodeSelector from '@/components/EpisodeSelector';
import PageLayout from '@/components/PageLayout'; import PageLayout from '@/components/PageLayout';
import VideoMetaExtra from '@/components/VideoMetaExtra';
import SkipController, { SkipSettingsButton } from '@/components/SkipController'; import SkipController, { SkipSettingsButton } from '@/components/SkipController';
// 扩展 HTMLVideoElement 类型以支持 hls 属性 // 扩展 HTMLVideoElement 类型以支持 hls 属性
@@ -1499,13 +1500,24 @@ function PlayPageClient() {
<div className='flex flex-col gap-3 py-4 px-5 lg:px-[3rem] 2xl:px-20'> <div className='flex flex-col gap-3 py-4 px-5 lg:px-[3rem] 2xl:px-20'>
{/* 第一行:影片标题和操作按钮 */} {/* 第一行:影片标题和操作按钮 */}
<div className='py-1 flex items-center justify-between'> <div className='py-1 flex items-center justify-between'>
<h1 className='text-xl font-semibold text-gray-900 dark:text-gray-100'> <h1 className='text-xl font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2'>
{videoTitle || '影片标题'} {videoTitle || '影片标题'}
{totalEpisodes > 1 && ( {totalEpisodes > 1 && (
<span className='text-gray-500 dark:text-gray-400'> <span className='text-gray-500 dark:text-gray-400'>
{` > 第 ${currentEpisodeIndex + 1} 集`} {` > 第 ${currentEpisodeIndex + 1} 集`}
</span> </span>
)} )}
{detail?.douban_id && (
<a
href={`https://movie.douban.com/subject/${detail.douban_id}/`}
target='_blank'
rel='noreferrer'
title='跳转到豆瓣'
className='inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-green-600 hover:bg-green-700 text-white text-xs font-medium transition-colors'
>
豆瓣 →
</a>
)}
</h1> </h1>
{/* 跳过设置按钮 */} {/* 跳过设置按钮 */}
@@ -1693,7 +1705,7 @@ function PlayPageClient() {
{detail?.type_name && <span>{detail.type_name}</span>} {detail?.type_name && <span>{detail.type_name}</span>}
</div> </div>
{/* 剧情简介 */} {/* 剧情简介 */}
{detail?.desc && ( {detail?.desc && !detail?.douban_id && (
<div <div
className='mt-0 text-base leading-relaxed opacity-90 overflow-y-auto pr-2 flex-1 min-h-0 scrollbar-hide' className='mt-0 text-base leading-relaxed opacity-90 overflow-y-auto pr-2 flex-1 min-h-0 scrollbar-hide'
style={{ whiteSpace: 'pre-line' }} style={{ whiteSpace: 'pre-line' }}
@@ -1701,6 +1713,21 @@ function PlayPageClient() {
{detail.desc} {detail.desc}
</div> </div>
)} )}
{/* 演员 / 评分 / 全网热评 */}
{detail && (
<VideoMetaExtra
title={detail.title}
actor={detail.actor}
director={detail.director}
score={detail.score}
scoreNum={detail.score_num}
doubanScore={detail.douban_score}
doubanId={detail.douban_id}
area={detail.area}
lang={detail.lang}
desc={detail.desc}
/>
)}
</div> </div>
</div> </div>
+14
View File
@@ -39,6 +39,8 @@ function SearchPageClient() {
// 分组标签页状态 // 分组标签页状态
const [activeTab, setActiveTab] = useState<'regular' | 'adult'>('regular'); const [activeTab, setActiveTab] = useState<'regular' | 'adult'>('regular');
const [searchPage, setSearchPage] = useState(1);
const PAGE_SIZE = 50;
// 获取默认聚合设置:只读取用户本地设置,默认为 true // 获取默认聚合设置:只读取用户本地设置,默认为 true
const getDefaultAggregate = () => { const getDefaultAggregate = () => {
@@ -357,6 +359,11 @@ function SearchPageClient() {
: groupedResults.regular; : groupedResults.regular;
} }
const totalPages = Math.max(1, Math.ceil(displayResults.length / PAGE_SIZE));
const page = Math.min(searchPage, totalPages);
const pagedResults = displayResults.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
displayResults = pagedResults;
// 聚合显示模式 // 聚合显示模式
if (viewMode === 'agg') { if (viewMode === 'agg') {
const aggregated = aggregateResults(displayResults); const aggregated = aggregateResults(displayResults);
@@ -406,6 +413,13 @@ function SearchPageClient() {
未找到相关结果 未找到相关结果
</div> </div>
)} )}
{searchResults.length > 0 && (
<div className='col-span-full flex items-center justify-center gap-3 py-6 text-sm'>
<button onClick={() => setSearchPage((p) => Math.max(1, p - 1))} disabled={searchPage <= 1} 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'>第 {searchPage} / {Math.max(1, Math.ceil(searchResults.length / 50))} 页</span>
<button onClick={() => setSearchPage((p) => p + 1)} disabled={searchPage >= Math.ceil(searchResults.length / 50)} className='px-3 py-1.5 rounded bg-gray-200/60 dark:bg-gray-700/60 disabled:opacity-40'>下一页</button>
</div>
)}
</div> </div>
</section> </section>
) : searchHistory.length > 0 ? ( ) : searchHistory.length > 0 ? (
+12 -6
View File
@@ -39,21 +39,27 @@ const DoubanSelector: React.FC<DoubanSelectorProps> = ({
width: number; width: number;
}>({ left: 0, width: 0 }); }>({ left: 0, width: 0 });
// 电影的一级选择器选项 // 电影的一级选择器选项(第三方采集站分类)
const moviePrimaryOptions: SelectorOption[] = [ const moviePrimaryOptions: SelectorOption[] = [
{ label: '热门电影', value: '热门' }, { label: '全部电影', value: '全部' },
{ label: '最新电影', value: '最新' }, { label: '动作片', value: '动作片' },
{ label: '豆瓣高分', value: '豆瓣高分' }, { label: '喜剧片', value: '喜剧片' },
{ label: '冷门佳片', value: '冷门佳片' }, { label: '爱情片', value: '爱情片' },
{ label: '科幻片', value: '科幻片' },
{ label: '恐怖片', value: '恐怖片' },
{ label: '剧情片', value: '剧情片' },
{ label: '战争片', value: '战争片' },
{ label: '纪录片', value: '纪录' },
]; ];
// 电影的二级选择器选项 // 电影的二级选择器选项(地区)
const movieSecondaryOptions: SelectorOption[] = [ const movieSecondaryOptions: SelectorOption[] = [
{ label: '全部', value: '全部' }, { label: '全部', value: '全部' },
{ label: '华语', value: '华语' }, { label: '华语', value: '华语' },
{ label: '欧美', value: '欧美' }, { label: '欧美', value: '欧美' },
{ label: '韩国', value: '韩国' }, { label: '韩国', value: '韩国' },
{ label: '日本', value: '日本' }, { label: '日本', value: '日本' },
{ label: '泰国', value: '泰国' },
]; ];
// 电视剧选择器选项 // 电视剧选择器选项
+114 -53
View File
@@ -3,6 +3,9 @@
import Link from 'next/link'; import Link from 'next/link';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import PaginatedRow from './PaginatedRow';
import VideoCard from './VideoCard';
type VodItem = { type VodItem = {
vod_id?: string | number; vod_id?: string | number;
vod_name?: string; vod_name?: string;
@@ -10,35 +13,108 @@ type VodItem = {
vod_remarks?: string; vod_remarks?: string;
vod_year?: string; vod_year?: string;
vod_time?: string; vod_time?: string;
vod_douban_id?: number;
vod_area?: string;
}; };
const SHOW_COUNT = 10; const PAGE_SIZE = 10; // 每页条数,与热门电影一致
const LOAD_COUNT = 60; // 一次性多取,支持上一页/下一页翻页
export default function HkDramaRow() { export default function HkDramaRow() {
const [items, setItems] = useState<VodItem[]>([]); const [items, setItems] = useState<VodItem[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [tick, setTick] = useState(0);
useEffect(() => { useEffect(() => {
fetch('/api/tvbox/all?ac=videolist&t=902&pg=1&by=time') const CACHE_KEY = 'hkDramaRow:v3'; // v3: localStorage 持久缓存 + 重试,修复偶发整栏消失
.then((r) => r.json()) const LEGACY_KEY = 'hkDramaRow:v2';
.then((j) => { const TTL = 5 * 60 * 1000;
const arr = (((j && j.list) as VodItem[]) || []).slice(); let dead = false;
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 readCache = (): { ts: number; data: VodItem[] } | null => {
if (!loading && !items.length) return 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 ( return (
<section className='mb-8'> <section className='mb-8'>
@@ -53,10 +129,10 @@ export default function HkDramaRow() {
查看更多 查看更多
</Link> </Link>
</div> </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 {loading
? // 加载中显示10个占位,与热门电影/剧集同时出现,避免后半拍跳动 ? // 加载中显示10个占位,与热门电影/剧集同时出现,避免后半拍跳动
Array.from({ length: SHOW_COUNT }).map((_, index) => ( Array.from({ length: PAGE_SIZE }).map((_, index) => (
<div key={index} className='w-full'> <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='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> <div className='absolute inset-0 bg-purple-300 dark:bg-purple-700'></div>
@@ -69,41 +145,26 @@ export default function HkDramaRow() {
const sep = key.indexOf(':'); const sep = key.indexOf(':');
const ks = sep > 0 ? key.slice(0, sep) : ''; const ks = sep > 0 ? key.slice(0, sep) : '';
const kid = sep > 0 ? key.slice(sep + 1) : key; const kid = sep > 0 ? key.slice(sep + 1) : key;
const pic = v.vod_pic const epMatch = String(v.vod_remarks || '').match(/(\d+)/);
? '/api/image-proxy?url=' + encodeURIComponent(v.vod_pic) const epCount = epMatch ? parseInt(epMatch[1], 10) : 1;
: ''; const dbId = v.vod_douban_id ? String(v.vod_douban_id) : '';
return ( return (
<Link <VideoCard
key={key} key={key}
href={`/play?source=${encodeURIComponent( id={kid}
ks source={ks}
)}&id=${encodeURIComponent(kid)}&stitle=${encodeURIComponent( source_name={ks}
v.vod_name || '' title={v.vod_name || ''}
)}&stype=tv`} poster={v.vod_pic || ''}
className='group block' episodes={epCount}
> year={v.vod_year || ''}
<div className='relative aspect-[2/3] w-full overflow-hidden rounded-lg bg-gray-200 dark:bg-gray-800'> douban_id={dbId}
{pic ? ( from='search'
<img type='tv'
src={pic} />
alt={v.vod_name || ''}
loading='lazy'
className='absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-300'
/>
) : null}
{v.vod_remarks ? (
<span className='absolute bottom-1 right-1 px-1.5 py-0.5 text-xs bg-black/65 text-white rounded'>
{v.vod_remarks}
</span>
) : null}
</div>
<div className='mt-2 text-sm font-medium text-gray-800 dark:text-gray-200 truncate'>
{v.vod_name}
</div>
</Link>
); );
})} })}
</div> </PaginatedRow>
</section> </section>
); );
} }
+1 -3
View File
@@ -29,10 +29,8 @@ export default function HubBell({ forceShow = false }: { forceShow?: boolean })
<button <button
onClick={() => { onClick={() => {
try { try {
localStorage.removeItem('hasSeenAnnouncement'); window.dispatchEvent(new CustomEvent('open-hub-notice'));
} catch {} } catch {}
if (location.pathname === '/') location.reload();
else location.href = '/';
}} }}
title='公告通知' title='公告通知'
className={ className={
+32 -3
View File
@@ -16,6 +16,30 @@ export default function HubNotice() {
const [mode, setMode] = useState<'ann' | 'upd'>('ann'); const [mode, setMode] = useState<'ann' | 'upd'>('ann');
useEffect(() => { useEffect(() => {
const openHandler = () => {
// 铃铛手动打开:有授权公告就显示公告,无公告则显示版本信息兜底
fetch('/api/license-config', { cache: 'no-store' })
.then((r) => r.json())
.then((j) => {
if (!j || j.code !== 200 || !j.data) return;
const d = j.data as LicenseData;
setData(d);
if (d.announcement) {
setMode('ann');
setVisible(true);
} else if (Array.isArray((d as any).announcements) && (d as any).announcements.length) {
const first = (d as any).announcements[0];
setData({ ...d, announcement: first });
setMode('ann');
setVisible(true);
} else {
setMode('upd');
setVisible(true);
}
})
.catch(() => {});
};
window.addEventListener('open-hub-notice', openHandler);
const t = setTimeout(() => { const t = setTimeout(() => {
fetch('/api/license-config', { cache: 'no-store' }) fetch('/api/license-config', { cache: 'no-store' })
.then((r) => r.json()) .then((r) => r.json())
@@ -42,7 +66,10 @@ export default function HubNotice() {
}) })
.catch(() => {}); .catch(() => {});
}, 1500); }, 1500);
return () => clearTimeout(t); return () => {
clearTimeout(t);
window.removeEventListener('open-hub-notice', openHandler);
};
}, []); }, []);
if (!visible || !data) return null; if (!visible || !data) return null;
@@ -50,11 +77,13 @@ export default function HubNotice() {
const title = const title =
mode === 'ann' && data.announcement mode === 'ann' && data.announcement
? String(data.announcement.title || '📢 公告') ? String(data.announcement.title || '📢 公告')
: '发现新版本 v' + String(data.latest || ''); : data.latest
? '发现新版本 v' + String(data.latest || '')
: '米视TV v' + String(data.version || '');
const body = const body =
mode === 'ann' && data.announcement mode === 'ann' && data.announcement
? String(data.announcement.content || '') ? String(data.announcement.content || '')
: String(data.changelog || '').slice(0, 600); : String(data.changelog || '当前已是最新版本,暂无授权中心公告。').slice(0, 600);
const close = (dismissVer = false) => { const close = (dismissVer = false) => {
try { try {
+1
View File
@@ -9,6 +9,7 @@ export default function Ipv6Button({ forceShow = false, compact = false, light =
return ( return (
<button <button
onClick={() => { onClick={() => {
try { sessionStorage.setItem('__v6back', location.pathname + location.search + location.hash); } catch {}
location.href = '/ipv6'; location.href = '/ipv6';
}} }}
title='切换 IPv4 / IPv6 线路' title='切换 IPv4 / IPv6 线路'
+25
View File
@@ -0,0 +1,25 @@
'use client';
// 首次访问公网入口:若用户支持 IPv6,则跳转到 tv6 线路选择页让用户选择
import { useEffect } from 'react';
export default function Ipv6FirstVisitGate() {
useEffect(() => {
try {
if (location.hostname !== 'tv.88531.cn') return;
if (/(^|;\s*)__v6dest=/.test(document.cookie)) return;
if (localStorage.getItem('__v6dest')) return;
// 探测 IPv6 可达性,可达才跳转
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 1500);
fetch('https://tv6.88531.cn:4443/api/license-config?_=', { mode: 'no-cors', signal: ctrl.signal })
.then(() => {
clearTimeout(t);
sessionStorage.setItem('__v6back', location.pathname + location.search + location.hash);
location.replace('https://tv6.88531.cn:4443/ipv6');
})
.catch(() => { clearTimeout(t); });
} catch {}
}, []);
return null;
}
+98
View File
@@ -0,0 +1,98 @@
'use client';
import { useEffect, useState } from 'react';
const V6 = 'https://tv6.88531.cn:4443';
const PROBE_URL = 'https://tv6.88531.cn:4443/api/license-config?_=';
// 首次访问的线路推荐:不阻塞数据加载,检测到支持 IPv6 时浮层提示用户可切换
export default function LineRecommender() {
const [show, setShow] = useState(false);
useEffect(() => {
try {
// 已记住线路 / 不在 v6 入口 / 已提示过 → 不再弹
if (window.location.hostname === 'tv6.88531.cn') return;
if (localStorage.getItem('__v6dest')) return;
if (localStorage.getItem('__v6hint')) return;
const cached = JSON.parse(localStorage.getItem('__v6probe') || 'null');
if (cached && Date.now() - cached.t < 120000) {
if (cached.ok) setShow(true);
return;
}
const c = new AbortController();
const ti = setTimeout(() => c.abort(), 5000);
fetch(PROBE_URL + Date.now(), { mode: 'cors', signal: c.signal, cache: 'no-store', credentials: 'omit' })
.then((r) => { clearTimeout(ti); return r.json(); })
.then((jj) => {
const ok = !!(jj && jj.code === 200 && jj.data);
try { localStorage.setItem('__v6probe', JSON.stringify({ t: Date.now(), ok })); } catch (e) { /* ignore */ }
if (ok) setShow(true);
})
.catch(() => { clearTimeout(ti); });
} catch (e) { /* ignore */ }
}, []);
if (!show) return null;
const dismiss = (pick?: 'v6' | 'v4') => {
try {
localStorage.setItem('__v6hint', '1');
if (pick === 'v6') {
localStorage.setItem('__v6dest', 'v6');
document.cookie = '__v6dest=v6; path=/; max-age=31536000; samesite=lax';
window.location.href = V6 + window.location.pathname + window.location.search;
return;
}
if (pick === 'v4') {
localStorage.setItem('__v6dest', 'v4');
document.cookie = '__v6dest=v4; path=/; max-age=31536000; samesite=lax';
}
} catch (e) { /* ignore */ }
setShow(false);
};
return (
<div style={{
position: 'fixed',
right: 16,
bottom: 16,
zIndex: 9999,
maxWidth: 340,
background: 'rgba(20,24,20,.96)',
border: '1px solid rgba(80,220,120,.45)',
borderRadius: 14,
padding: '14px 16px',
color: '#fff',
fontFamily: 'system-ui, -apple-system, sans-serif',
boxShadow: '0 8px 30px rgba(0,0,0,.45)',
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
<p style={{ margin: 0, fontWeight: 600, color: '#7ef0a0', fontSize: 14 }}>
✅ 检测到你的网络支持 IPv6
</p>
<button onClick={() => dismiss()} aria-label='关闭' style={{
background: 'none', border: 'none', color: 'rgba(255,255,255,.5)',
fontSize: 16, cursor: 'pointer', lineHeight: 1, padding: 0,
}}>×</button>
</div>
<p style={{ margin: '8px 0 12px', color: 'rgba(255,255,255,.65)', fontSize: 13, lineHeight: 1.5 }}>
推荐切换到 IPv6 线路,观影更流畅。
</p>
<div style={{ display: 'flex', gap: 8 }}>
<button onClick={() => dismiss('v6')} style={{
flex: 1, padding: '8px 10px', borderRadius: 9,
border: '1px solid rgba(80,220,120,.55)', background: 'rgba(80,220,120,.18)',
color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
}}>切换 IPv6</button>
<button onClick={() => dismiss('v4')} style={{
flex: 1, padding: '8px 10px', borderRadius: 9,
border: '1px solid rgba(255,255,255,.18)', background: 'rgba(255,255,255,.06)',
color: 'rgba(255,255,255,.8)', fontSize: 13, cursor: 'pointer',
}}>保持 IPv4</button>
</div>
</div>
);
}
+9 -2
View File
@@ -1,6 +1,6 @@
'use client'; 'use client';
import { Clover, Film, Filter, Home, Radio, Search, Tv } from 'lucide-react'; import { Clover, Film, Filter, Home, Radio, Search, Sparkles, Tv } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
@@ -30,6 +30,11 @@ const MobileBottomNav = ({ activePath }: MobileBottomNavProps) => {
label: '剧集', label: '剧集',
href: '/douban?type=tv', href: '/douban?type=tv',
}, },
{
icon: Sparkles,
label: '动漫',
href: '/anime',
},
{ {
icon: Clover, icon: Clover,
label: '综艺', label: '综艺',
@@ -50,6 +55,7 @@ const MobileBottomNav = ({ activePath }: MobileBottomNavProps) => {
const isActive = (href: string) => { const isActive = (href: string) => {
if (href === '/filter') return currentActive.startsWith('/filter'); if (href === '/filter') return currentActive.startsWith('/filter');
const typeMatch = href.match(/type=([^&]+)/)?.[1]; const typeMatch = href.match(/type=([^&]+)/)?.[1];
const catMatch = href.match(/cat=([^&]+)/)?.[1];
// 解码URL以进行正确的比较 // 解码URL以进行正确的比较
const decodedActive = decodeURIComponent(currentActive); const decodedActive = decodeURIComponent(currentActive);
@@ -58,7 +64,8 @@ const MobileBottomNav = ({ activePath }: MobileBottomNavProps) => {
return ( return (
decodedActive === decodedItemHref || decodedActive === decodedItemHref ||
(decodedActive.startsWith('/douban') && (decodedActive.startsWith('/douban') &&
decodedActive.includes(`type=${typeMatch}`)) decodedActive.includes(`type=${typeMatch}`) &&
(catMatch ? decodedActive.includes(`cat=${catMatch}`) : !decodedActive.includes('cat=')))
); );
}; };
+6
View File
@@ -23,6 +23,12 @@ const MobileHeader = ({ showBackButton = false }: MobileHeaderProps) => {
{/* 右侧按钮 */} {/* 右侧按钮 */}
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span
className='shrink-0 select-none rounded-md px-1.5 py-0.5 text-[10px] font-bold tracking-wide text-purple-600 dark:text-purple-400 bg-purple-500/10 border border-purple-500/20'
title='米视TV 当前版本'
>
v{process.env.NEXT_PUBLIC_SITE_VERSION || 'fixed75'}
</span>
<ThemeToggle /> <ThemeToggle />
<UserMenu /> <UserMenu />
</div> </div>
+6 -1
View File
@@ -1,4 +1,4 @@
import { Clover, Film, Filter, Home, Play, Radio, Search, Tv } from 'lucide-react'; import { Clover, Film, Filter, Home, Play, Radio, Search, Sparkles, Tv } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation'; import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
@@ -66,6 +66,11 @@ const TopNavbar = ({ activePath = '/' }: { activePath?: string }) => {
label: '剧集', label: '剧集',
href: '/douban?type=tv', href: '/douban?type=tv',
}, },
{
icon: Sparkles,
label: '动漫',
href: '/anime',
},
{ {
icon: Clover, icon: Clover,
label: '综艺', label: '综艺',
+7 -1
View File
@@ -16,6 +16,12 @@ export default function TopRightButtons({ variant = 'bar' }: TopRightButtonsProp
if (variant === 'float') { if (variant === 'float') {
return ( return (
<div className='fixed top-2 right-2 z-50 flex items-center gap-1.5 rounded-xl bg-black/55 px-2 py-1.5 backdrop-blur-md border border-white/10'> <div className='fixed top-2 right-2 z-50 flex items-center gap-1.5 rounded-xl bg-black/55 px-2 py-1.5 backdrop-blur-md border border-white/10'>
<span
className='shrink-0 select-none rounded-md px-1.5 py-1 text-[10px] font-bold tracking-wide text-purple-300 bg-purple-500/20 border border-purple-400/30'
title='米视TV 当前版本'
>
v{process.env.NEXT_PUBLIC_SITE_VERSION || 'fixed75'}
</span>
<HubBell forceShow /> <HubBell forceShow />
<TvboxButton forceShow compact /> <TvboxButton forceShow compact />
<Ipv6Button forceShow compact /> <Ipv6Button forceShow compact />
@@ -37,7 +43,7 @@ export default function TopRightButtons({ variant = 'bar' }: TopRightButtonsProp
className='hidden lg:inline-flex shrink-0 items-center select-none rounded-lg px-2 py-1.5 text-xs font-bold tracking-wide text-purple-600 dark:text-purple-400 bg-purple-500/10 border border-purple-500/20' className='hidden lg:inline-flex shrink-0 items-center select-none rounded-lg px-2 py-1.5 text-xs font-bold tracking-wide text-purple-600 dark:text-purple-400 bg-purple-500/10 border border-purple-500/20'
title='米视TV 当前版本' title='米视TV 当前版本'
> >
v{process.env.NEXT_PUBLIC_SITE_VERSION || 'fixed71'} v{process.env.NEXT_PUBLIC_SITE_VERSION || 'fixed75'}
</span> </span>
<HubBell /> <HubBell />
<TvboxButton /> <TvboxButton />
+70 -28
View File
@@ -5,7 +5,25 @@ import { useState } from 'react';
export default function TvboxButton({ forceShow = false, compact = false }: { forceShow?: boolean; compact?: boolean }) { export default function TvboxButton({ forceShow = false, compact = false }: { forceShow?: boolean; compact?: boolean }) {
const [label, setLabel] = useState('📺 TVBOX接口'); const [label, setLabel] = useState('📺 TVBOX接口');
const showModal = (title: string, body: string, link?: string) => { const copyText = (t: string, btn?: HTMLButtonElement) => {
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(t).then(() => {
if (btn) { btn.textContent = '✓ 已复制'; setTimeout(() => (btn.textContent = '复制'), 1600); }
}).catch(() => {});
return;
}
} catch {}
const ta = document.createElement('textarea');
ta.value = t;
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); } catch {}
document.body.removeChild(ta);
if (btn) { btn.textContent = '✓ 已复制'; setTimeout(() => (btn.textContent = '复制'), 1600); }
};
const showTvboxModal = (cfg: string, live: string) => {
const ov = document.createElement('div'); const ov = document.createElement('div');
ov.className = ov.className =
'fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4'; 'fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4';
@@ -18,7 +36,7 @@ export default function TvboxButton({ forceShow = false, compact = false }: { fo
const h3 = document.createElement('h3'); const h3 = document.createElement('h3');
h3.className = h3.className =
'text-base font-bold text-gray-900 dark:text-gray-100 truncate mr-2'; 'text-base font-bold text-gray-900 dark:text-gray-100 truncate mr-2';
h3.textContent = title; h3.textContent = '📺 TVBOX 接入';
const xb = document.createElement('button'); const xb = document.createElement('button');
xb.className = xb.className =
'text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 text-lg leading-none flex-shrink-0'; 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 text-lg leading-none flex-shrink-0';
@@ -27,8 +45,51 @@ export default function TvboxButton({ forceShow = false, compact = false }: { fo
head.appendChild(xb); head.appendChild(xb);
const bd = document.createElement('div'); const bd = document.createElement('div');
bd.className = bd.className =
'px-6 pb-4 overflow-y-auto text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap'; 'px-6 pb-4 overflow-y-auto text-sm text-gray-700 dark:text-gray-300';
bd.textContent = body; const mkRow = (label: string, url: string) => {
const wrap = document.createElement('div');
wrap.style.marginBottom = '14px';
const lb = document.createElement('div');
lb.style.fontWeight = '700';
lb.style.marginBottom = '6px';
lb.textContent = label;
const urlDiv = document.createElement('div');
urlDiv.style.wordBreak = 'break-all';
urlDiv.style.background = 'rgba(127,127,127,.12)';
urlDiv.style.borderRadius = '8px';
urlDiv.style.padding = '8px 10px';
urlDiv.style.fontSize = '12px';
urlDiv.textContent = url;
const row = document.createElement('div');
row.style.display = 'flex';
row.style.gap = '8px';
row.style.marginTop = '8px';
const cp = document.createElement('button');
cp.textContent = '复制';
cp.className =
'px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-purple-600 hover:bg-purple-700';
cp.onclick = () => copyText(url, cp);
const op = document.createElement('a');
op.href = url;
op.target = '_blank';
op.rel = 'noopener';
op.textContent = '打开 →';
op.className =
'px-3 py-1.5 rounded-lg text-xs font-medium text-purple-600 dark:text-purple-400 hover:bg-purple-500/10';
row.appendChild(cp);
row.appendChild(op);
wrap.appendChild(lb);
wrap.appendChild(urlDiv);
wrap.appendChild(row);
return wrap;
};
bd.appendChild(mkRow('配置地址(含直播,推荐)', cfg));
bd.appendChild(mkRow('直播源地址(仅直播)', live));
const tip = document.createElement('div');
tip.style.fontSize = '12px';
tip.style.opacity = '0.75';
tip.textContent = '影视仓/TVBox「设置 → 配置地址」粘贴保存即可';
bd.appendChild(tip);
card.appendChild(head); card.appendChild(head);
card.appendChild(bd); card.appendChild(bd);
const foot = document.createElement('div'); const foot = document.createElement('div');
@@ -39,16 +100,6 @@ export default function TvboxButton({ forceShow = false, compact = false }: { fo
'px-3 py-1.5 rounded-lg text-xs font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-600'; 'px-3 py-1.5 rounded-lg text-xs font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-600';
kb.textContent = '我知道了'; kb.textContent = '我知道了';
foot.appendChild(kb); foot.appendChild(kb);
if (link) {
const la = document.createElement('a');
la.href = link;
la.target = '_blank';
la.rel = 'noopener';
la.className =
'px-3 py-1.5 rounded-lg text-xs font-medium text-purple-600 dark:text-purple-400 hover:bg-purple-500/10';
la.textContent = '查看详情 →';
foot.insertBefore(la, kb);
}
card.appendChild(foot); card.appendChild(foot);
const close = () => { const close = () => {
if (ov && ov.parentNode) ov.parentNode.removeChild(ov); if (ov && ov.parentNode) ov.parentNode.removeChild(ov);
@@ -63,25 +114,16 @@ export default function TvboxButton({ forceShow = false, compact = false }: { fo
}; };
const onClick = (ev: React.MouseEvent<HTMLButtonElement>) => { const onClick = (ev: React.MouseEvent<HTMLButtonElement>) => {
const u = location.origin + '/api/tvbox'; const cfg = location.origin + '/api/tvbox';
const live = location.origin + '/api/tvbox?live=txt';
const bt = ev.currentTarget; const bt = ev.currentTarget;
const ok = () => { const ok = () => {
setLabel('✓ 已复制'); setLabel('✓ 已复制');
setTimeout(() => setLabel('📺 TVBOX接口'), 1600); setTimeout(() => setLabel('📺 TVBOX接口'), 1600);
}; };
const tip = '影视仓/TVBox「设置 → 配置地址」粘贴保存即可'; void bt;
try { void ok;
if (navigator.clipboard && navigator.clipboard.writeText) { showTvboxModal(cfg, live);
navigator.clipboard
.writeText(u)
.then(ok)
.catch(() =>
showModal('📺 TVBOX 接入', '配置地址: ' + u + ' —— ' + tip, u)
);
return;
}
} catch {}
showModal('📺 TVBOX 接入', '配置地址: ' + u + ' —— ' + tip, u);
}; };
return ( return (
+3 -3
View File
@@ -100,7 +100,7 @@ export default function VideoCard({
const actualSource = aggregateData?.first.source ?? source; const actualSource = aggregateData?.first.source ?? source;
const actualId = aggregateData?.first.id ?? id; const actualId = aggregateData?.first.id ?? id;
const actualDoubanId = String( const actualDoubanId = String(
aggregateData?.mostFrequentDoubanId ?? douban_id aggregateData?.mostFrequentDoubanId ?? douban_id ?? ''
); );
const actualEpisodes = aggregateData?.mostFrequentEpisodes ?? episodes; const actualEpisodes = aggregateData?.mostFrequentEpisodes ?? episodes;
const actualYear = aggregateData?.first.year ?? year; const actualYear = aggregateData?.first.year ?? year;
@@ -248,9 +248,9 @@ export default function VideoCard({
showSourceName: true, showSourceName: true,
showProgress: false, showProgress: false,
showPlayButton: true, showPlayButton: true,
showHeart: !isAggregate, showHeart: true,
showCheckCircle: false, showCheckCircle: false,
showDoubanLink: !!actualDoubanId, showDoubanLink: !!actualDoubanId && actualDoubanId !== '0',
showRating: false, showRating: false,
}, },
douban: { douban: {
+241
View File
@@ -0,0 +1,241 @@
'use client';
import Link from 'next/link';
import { useEffect, useState } from 'react';
interface DoubanComment {
id: string;
user: string;
avatar: string;
rating: number;
content: string;
time: string;
location: string;
}
// 演员 / 评分 / 全网热评(详情页简介下方)
export default function VideoMetaExtra({
title,
actor,
director,
score,
scoreNum,
doubanScore,
doubanId,
area,
lang,
isTv,
desc,
}: {
title: string;
actor?: string;
director?: string;
score?: string;
scoreNum?: number;
doubanScore?: string;
doubanId?: number;
area?: string;
lang?: string;
isTv?: boolean;
desc?: string;
}) {
const [comments, setComments] = useState<DoubanComment[]>([]);
const [loading, setLoading] = useState(false);
const [dbDetail, setDbDetail] = useState<any>(null);
const [related, setRelated] = useState<any[]>([]);
useEffect(() => {
if (!doubanId) return;
let alive = true;
setLoading(true);
fetch(`/api/douban-comments?id=${encodeURIComponent(String(doubanId))}`)
.then((r) => r.json())
.then((d) => {
if (alive && d?.code === 1) setComments(d.list || []);
})
.catch(() => {})
.finally(() => {
if (alive) setLoading(false);
});
// 豆瓣详情(评分/演员兜底)
fetch(`/api/douban-detail?id=${encodeURIComponent(String(doubanId))}`)
.then((r) => r.json())
.then((d) => {
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]);
const actors = (actor || (dbDetail?.actors || []).join(','))
.split(/[,,、\/|]/)
.map((s: string) => s.trim())
.filter(Boolean)
.slice(0, 20);
const scoreNum1 = parseFloat(score || '') || 0;
const dbNum = parseFloat(doubanScore || '') || dbDetail?.rating || 0;
const showScore = scoreNum1 > 0 ? scoreNum1.toFixed(1) : dbNum > 0 ? dbNum.toFixed(1) : '';
const showDirector = director || (dbDetail?.directors || []).join('、');
const showArea = area || dbDetail?.area || '';
const showLang = lang || dbDetail?.languages || '';
const showDuration = dbDetail?.duration || '';
if (!actors.length && !showDirector && !showScore && !showArea && !loading && !comments.length) return null;
return (
<div className='mt-4 space-y-4'>
{/* 导演 / 地区 / 语言 */}
{(showDirector || showArea || showLang || showDuration) && (
<div className='text-sm opacity-80 space-x-4'>
{showDirector && (
<span>
导演:<span className='font-medium'>{showDirector}</span>
</span>
)}
{showArea && <span>地区:{showArea}</span>}
{showLang && <span>语言:{showLang}</span>}
{showDuration && <span>片长:{showDuration}</span>}
</div>
)}
{/* 评分 */}
{showScore && (
<div className='flex items-center gap-2'>
<span className='text-sm opacity-80'>评分</span>
<span className='text-2xl font-bold text-amber-500'>{showScore}</span>
<span className='flex text-amber-500'>
{[1, 2, 3, 4, 5].map((i) => (
<span key={i} className={i <= Math.round(Number(showScore) / 2) ? '' : 'opacity-30'}>
★
</span>
))}
</span>
{scoreNum && scoreNum > 0 && <span className='text-xs opacity-60'>({scoreNum}人评)</span>}
{doubanId ? (
<a
href={`https://movie.douban.com/subject/${doubanId}/`}
target='_blank'
rel='noreferrer'
className='text-xs text-green-600 hover:underline ml-1'
>
豆瓣详情 →
</a>
) : null}
</div>
)}
{(dbDetail?.intro || desc) && (
<div className='text-sm leading-relaxed opacity-90 whitespace-pre-line'>
<span className='font-semibold'>剧情简介:</span>
{dbDetail?.intro || desc}
</div>
)}
{/* 演员列表 */}
{actors.length > 0 && (
<div>
<div className='text-sm font-semibold mb-2 opacity-80'>演员({actors.length})</div>
<div className='flex flex-wrap gap-2'>
{actors.map((a: string) => (
<Link
key={a}
href={`/search?q=${encodeURIComponent(a)}`}
title={`搜索${a}的全部作品`}
className='px-3 py-1 rounded-full bg-gray-200/70 dark:bg-gray-700/70 text-sm hover:bg-green-500 hover:text-white dark:hover:bg-green-600 transition-colors cursor-pointer'
>
{a}
</Link>
))}
</div>
</div>
)}
{/* 豆瓣短评 */}
<div>
<div className='text-sm font-semibold mb-2 opacity-80 flex items-center gap-2'>
豆瓣短评
{doubanId ? (
<a
href={`https://movie.douban.com/subject/${doubanId}/comments`}
target='_blank'
rel='noreferrer'
className='text-xs text-green-600 hover:underline font-normal'
>
查看全部 →
</a>
) : null}
</div>
{loading && comments.length === 0 && (
<div className='space-y-2'>
{[0, 1, 2].map((i) => (
<div key={i} className='animate-pulse h-14 rounded-lg bg-gray-200/70 dark:bg-gray-700/50' />
))}
</div>
)}
{!loading && comments.length === 0 && (
<div className='text-sm opacity-50'>暂无豆瓣短评。</div>
)}
<div className='space-y-2'>
{comments.map((c) => (
<div
key={c.id}
className='rounded-lg bg-gray-100/80 dark:bg-gray-800/60 p-3'
>
<div className='flex items-center gap-2 mb-1'>
{c.avatar ? (
<img src={c.avatar} alt={c.user} className='w-6 h-6 rounded-full' />
) : null}
<span className='text-sm font-medium truncate flex-1'>{c.user}</span>
{c.rating > 0 && (
<span className='text-xs text-amber-500'>{'★'.repeat(c.rating)}</span>
)}
<span className='text-xs opacity-50 flex-shrink-0'>{c.time.slice(0, 10)}</span>
</div>
<div className='text-sm opacity-80 leading-relaxed'>{c.content}</div>
{c.location ? (
<div className='text-xs opacity-40 mt-1'>{c.location}</div>
) : null}
</div>
))}
</div>
</div>
{related.length > 0 && (
<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>
</div>
)}
</div>
);
}
+4
View File
@@ -13,6 +13,10 @@ export interface AdminConfig {
username: string; username: string;
role: 'user' | 'admin' | 'owner'; role: 'user' | 'admin' | 'owner';
banned?: boolean; banned?: boolean;
created_at?: string;
created_at_estimated?: boolean;
last_login_at?: string;
last_login_estimated?: boolean;
}[]; }[];
}; };
SourceConfig: { SourceConfig: {
+80 -12
View File
@@ -73,16 +73,41 @@ async function initConfig() {
adminConfig = await (storage as any).getAdminConfig(); adminConfig = await (storage as any).getAdminConfig();
} }
// 获取所有用户名,用于补全 Users // 获取所有用户(含注册/最后登录时间),用于补全 Users
let userNames: string[] = []; let userNames: string[] = [];
const userTimeMap = new Map<
string,
{
created_at?: string;
created_at_estimated?: boolean;
last_login_at?: string;
last_login_estimated?: boolean;
}
>();
if (storage && typeof (storage as any).getAllUsers === 'function') { if (storage && typeof (storage as any).getAllUsers === 'function') {
try { try {
const rawUsers = await (storage as any).getAllUsers(); const rawUsers = await (storage as any).getAllUsers();
// getAllUsers 返回的是 User 对象数组,这里统一取用户名字符串, // getAllUsers 返回的是 User 对象数组,这里统一取用户名字符串,
// 否则会把整个对象写入 Users[].username(导致管理页渲染对象报 React #31) // 否则会把整个对象写入 Users[].username(导致管理页渲染对象报 React #31)
userNames = (Array.isArray(rawUsers) ? rawUsers : []) // 同时保留时间字段,供用户列表展示注册/最后登录时间
.map((u: any) => (typeof u === 'string' ? u : u && typeof u.username === 'string' ? u.username : '')) (Array.isArray(rawUsers) ? rawUsers : []).forEach((u: any) => {
.filter((n: string) => !!n); const n =
typeof u === 'string'
? u
: u && typeof u.username === 'string'
? u.username
: '';
if (!n) return;
userNames.push(n);
if (typeof u === 'object' && u) {
userTimeMap.set(n, {
created_at: u.created_at || undefined,
created_at_estimated: !!u.created_at_estimated,
last_login_at: u.last_login_at || undefined,
last_login_estimated: !!u.last_login_estimated,
});
}
});
} catch (e) { } catch (e) {
console.error('获取用户列表失败:', e); console.error('获取用户列表失败:', e);
} }
@@ -132,7 +157,24 @@ async function initConfig() {
adminConfig!.UserConfig.Users.push({ adminConfig!.UserConfig.Users.push({
username: uname, username: uname,
role: 'user', role: 'user',
...(userTimeMap.get(uname) || {}),
}); });
} else {
// 已存在用户也回填时间字段(老配置升级时补上)
const exist = adminConfig!.UserConfig.Users.find(
(u) => u.username === uname
);
const t = userTimeMap.get(uname);
if (exist && t) {
if (!exist.created_at && t.created_at) {
exist.created_at = t.created_at;
exist.created_at_estimated = t.created_at_estimated;
}
if (!exist.last_login_at && t.last_login_at) {
exist.last_login_at = t.last_login_at;
exist.last_login_estimated = t.last_login_estimated;
}
}
} }
}); });
// 站长 // 站长
@@ -151,6 +193,7 @@ async function initConfig() {
let allUsers = userNames.map((uname) => ({ let allUsers = userNames.map((uname) => ({
username: uname, username: uname,
role: 'user', role: 'user',
...(userTimeMap.get(uname) || {}),
})); }));
const ownerUser = process.env.USERNAME; const ownerUser = process.env.USERNAME;
if (ownerUser) { if (ownerUser) {
@@ -162,7 +205,7 @@ async function initConfig() {
} }
adminConfig = { adminConfig = {
SiteConfig: { SiteConfig: {
SiteName: process.env.SITE_NAME || 'KatelyaTV', SiteName: process.env.SITE_NAME || '米视TV',
Announcement: Announcement:
process.env.ANNOUNCEMENT || process.env.ANNOUNCEMENT ||
'本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。', '本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。',
@@ -202,7 +245,7 @@ async function initConfig() {
// 本地存储直接使用文件配置 // 本地存储直接使用文件配置
cachedConfig = { cachedConfig = {
SiteConfig: { SiteConfig: {
SiteName: process.env.SITE_NAME || 'KatelyaTV', SiteName: process.env.SITE_NAME || '米视TV',
Announcement: Announcement:
process.env.ANNOUNCEMENT || process.env.ANNOUNCEMENT ||
'本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。', '本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。',
@@ -247,7 +290,7 @@ export async function getConfig(): Promise<AdminConfig> {
if (adminConfig) { if (adminConfig) {
// 合并一些环境变量配置 // 合并一些环境变量配置
adminConfig.SiteConfig.SiteName = process.env.SITE_NAME || 'KatelyaTV'; adminConfig.SiteConfig.SiteName = process.env.SITE_NAME || '米视TV';
adminConfig.SiteConfig.Announcement = adminConfig.SiteConfig.Announcement =
process.env.ANNOUNCEMENT || process.env.ANNOUNCEMENT ||
'本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。'; '本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。';
@@ -325,14 +368,38 @@ export async function getConfig(): Promise<AdminConfig> {
export async function resetConfig() { export async function resetConfig() {
const storage = getStorage(); const storage = getStorage();
// 获取所有用户名,用于补全 Users // 获取所有用户(含注册/最后登录时间),用于补全 Users
let userNames: string[] = []; let userNames: string[] = [];
const userTimeMap = new Map<
string,
{
created_at?: string;
created_at_estimated?: boolean;
last_login_at?: string;
last_login_estimated?: boolean;
}
>();
if (storage && typeof (storage as any).getAllUsers === 'function') { if (storage && typeof (storage as any).getAllUsers === 'function') {
try { try {
const rawUsers = await (storage as any).getAllUsers(); const rawUsers = await (storage as any).getAllUsers();
userNames = (Array.isArray(rawUsers) ? rawUsers : []) (Array.isArray(rawUsers) ? rawUsers : []).forEach((u: any) => {
.map((u: any) => (typeof u === 'string' ? u : u && typeof u.username === 'string' ? u.username : '')) const n =
.filter((n: string) => !!n); typeof u === 'string'
? u
: u && typeof u.username === 'string'
? u.username
: '';
if (!n) return;
userNames.push(n);
if (typeof u === 'object' && u) {
userTimeMap.set(n, {
created_at: u.created_at || undefined,
created_at_estimated: !!u.created_at_estimated,
last_login_at: u.last_login_at || undefined,
last_login_estimated: !!u.last_login_estimated,
});
}
});
} catch (e) { } catch (e) {
console.error('获取用户列表失败:', e); console.error('获取用户列表失败:', e);
} }
@@ -358,6 +425,7 @@ export async function resetConfig() {
let allUsers = userNames.map((uname) => ({ let allUsers = userNames.map((uname) => ({
username: uname, username: uname,
role: 'user', role: 'user',
...(userTimeMap.get(uname) || {}),
})); }));
const ownerUser = process.env.USERNAME; const ownerUser = process.env.USERNAME;
if (ownerUser) { if (ownerUser) {
@@ -369,7 +437,7 @@ export async function resetConfig() {
} }
const adminConfig = { const adminConfig = {
SiteConfig: { SiteConfig: {
SiteName: process.env.SITE_NAME || 'KatelyaTV', SiteName: process.env.SITE_NAME || '米视TV',
Announcement: Announcement:
process.env.ANNOUNCEMENT || process.env.ANNOUNCEMENT ||
'本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。', '本网站仅提供影视信息搜索服务,所有内容均来自第三方网站。本站不存储任何视频资源,不对任何内容的准确性、合法性、完整性负责。',
+7
View File
@@ -266,6 +266,13 @@ export async function getDetailFromApi(
desc: cleanHtmlTags(videoDetail.vod_content), desc: cleanHtmlTags(videoDetail.vod_content),
type_name: videoDetail.type_name, type_name: videoDetail.type_name,
douban_id: videoDetail.vod_douban_id, douban_id: videoDetail.vod_douban_id,
actor: videoDetail.vod_actor || '',
director: videoDetail.vod_director || '',
score: String(videoDetail.vod_score ?? ''),
score_num: Number(videoDetail.vod_score_num ?? 0) || 0,
douban_score: String(videoDetail.vod_douban_score ?? ''),
area: videoDetail.vod_area || '',
lang: videoDetail.vod_lang || '',
}; };
} }
+4
View File
@@ -349,6 +349,10 @@ export class RedisStorage implements IStorage {
return match ? ensureString(match[1]) : undefined; return match ? ensureString(match[1]) : undefined;
}) })
.filter((u): u is string => typeof u === 'string'); .filter((u): u is string => typeof u === 'string');
// 站长(owner)不一定有密码记录,但需显示其最后登录时间
if (!usernames.includes(ownerUsername)) {
usernames.push(ownerUsername);
}
// 获取用户创建时间、最后登录时间并构造 User 对象 // 获取用户创建时间、最后登录时间并构造 User 对象
const users = await Promise.all( const users = await Promise.all(
+312
View File
@@ -0,0 +1,312 @@
// 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 分钟(分类表很稳定),空 30 秒(失败要尽快重试)
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] < 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 [];
}
// 顶层 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;
}
+7
View File
@@ -120,6 +120,13 @@ export interface SearchResult {
desc?: string; desc?: string;
type_name?: string; type_name?: string;
douban_id?: number; douban_id?: number;
actor?: string;
director?: string;
score?: string;
score_num?: number;
douban_score?: string;
area?: string;
lang?: string;
} }
// 豆瓣数据结构 // 豆瓣数据结构
+4 -1
View File
@@ -37,7 +37,10 @@ export function processImageUrl(originalUrl: string): string {
const proxyUrl = getImageProxyUrl(); const proxyUrl = getImageProxyUrl();
if (!proxyUrl) return originalUrl; if (!proxyUrl) return originalUrl;
return `${proxyUrl}${encodeURIComponent(originalUrl)}`; // 代理地址若未自带查询参数(如 /api/image-proxy),补 ?url=,否则拼出的 URL 非法
if (proxyUrl.includes('url=')) return `${proxyUrl}${encodeURIComponent(originalUrl)}`;
const sep = proxyUrl.includes('?') ? '&' : '?url=';
return `${proxyUrl}${sep}${encodeURIComponent(originalUrl)}`;
} }
/** /**
+160
View File
@@ -0,0 +1,160 @@
// ---------- 第三方采集站分类取数共享模块(源码化) ----------
// 各站 maccms 10 协议:?ac=list 取 class 分类;?ac=videolist&t=<type_id>&pg=<页> 取分类数据
// 注意:各站 type_id 互不相同(360zy 国产剧=13,lziapi=13,hongniuzy3=12…),
// 所以必须先按分类名筛选 type_id,再逐类取数,绝不能写死 ID。
export interface Site {
key: string;
name: string;
api: string;
detail?: string;
}
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 ClassItem {
type_id: string;
type_name: string;
}
// ---------- 分类名归类规则 ----------
export const KIND_RULES: Record<string, { match: string[]; exclude: string[] }> = {
// 剧集:连续剧 + 各地区剧(不含动漫/综艺/伦理/解说)
tv: {
match: ['连续剧', '国产剧', '香港剧', '港澳剧', '韩国剧', '韩剧', '欧美剧', '台湾剧', '日本剧', '日剧', '海外剧', '泰国剧', '短剧', '纪录'],
exclude: ['动漫', '动画', '综艺', '伦理', '解说', '预告片', '赛事'],
},
// 综艺
show: {
match: ['综艺'],
exclude: ['动漫', '动画', '伦理', '解说'],
},
// 电影:电影/电影片 + 各类型片(排除剧集、动漫、综艺)
movie: {
match: ['电影', '动作片', '喜剧片', '爱情片', '科幻片', '恐怖片', '剧情片', '战争片', '悬疑片', '犯罪片', '灾难片', '惊悚片', '古装片', '历史片', '家庭片', '西部片', '纪录', '短片', '预告片'],
exclude: ['动漫', '动画', '伦理', '解说', '剧集', '连续剧', '综艺', '爽文'],
},
// 动漫
anime: {
match: ['动漫', '动画', '卡通'],
exclude: ['动漫解说', '动漫周边'],
},
};
const classCache = new Map<string, [number, ClassItem[], boolean]>();
/** 拉某站的分类列表(带缓存;失败时用空数组缓存 30s 避免反复打超时站) */
export async function fetchClass(site: Site): Promise<ClassItem[]> {
const now = Date.now();
const c = classCache.get(site.api);
if (c && (c[2] ? now - c[0] < 30000 : now - c[0] < 1800000)) return c[1];
const mk = async (u: string) => {
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 8000);
const r = await fetch(u, {
headers: { 'User-Agent': UA, Accept: 'application/json' },
signal: ctrl.signal,
});
clearTimeout(t);
if (!r.ok) return null;
const j = await r.json();
if (j && Array.isArray(j.class) && j.class.length)
return j.class.map((x: any) => ({
type_id: String(x.type_id),
type_name: String(x.type_name || ''),
}));
return null;
} catch {
return null;
}
};
const base = site.api + (site.api.includes('?') ? '&' : '?');
const rs = await Promise.all([mk(site.api), mk(base + 'ac=list'), mk(base + 'ac=videolist&pg=1')]);
const hit: ClassItem[] = rs.find(Boolean) || [];
classCache.set(site.api, [now, hit, !hit.length]);
return hit;
}
/** 按 kind(tv/show/movie/anime)筛出该站对应的分类;cat 为可选的进一步细分(如 '国产剧') */
export function pickClasses(classes: ClassItem[], kind: string, cat = ''): ClassItem[] {
const rule = KIND_RULES[kind] || KIND_RULES.tv;
let out = classes.filter(
(c) =>
rule.match.some((k) => c.type_name.includes(k)) &&
!rule.exclude.some((k) => c.type_name.includes(k))
);
if (cat) {
// 支持多关键词('日韩综艺|欧美综艺'),命中任一即保留
const keys = cat.split('|').filter(Boolean);
const narrowed = out.filter((c) => keys.some((k) => c.type_name.includes(k)));
if (narrowed.length) out = narrowed;
}
return out;
}
/** 取某站某分类的一页数据 */
export async function fetchTypePage(site: Site, tid: string, pg: number): Promise<any[]> {
const base = site.api + (site.api.includes('?') ? '&' : '?');
const u = `${base}ac=videolist&t=${encodeURIComponent(tid)}&pg=${pg}`;
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 12000);
const r = await fetch(u, {
headers: { 'User-Agent': UA, Accept: 'application/json' },
signal: ctrl.signal,
});
clearTimeout(timer);
if (!r.ok) return [];
const j = await r.json();
return Array.isArray(j?.list) ? j.list : [];
} catch {
return [];
}
}
function epCount(playUrl: string): number {
if (!playUrl) return 1;
let max = 0;
String(playUrl)
.split('$$$')
.forEach((g) => {
const n = g.split('#').filter((s) => s.trim()).length;
if (n > max) max = n;
});
return max > 0 ? max : 1;
}
/** 统一映射为前端 VideoCard 可用的结构 */
export function mapItem(item: any, site: Site) {
return {
id: String(item.vod_id),
title: String(item.vod_name || '').trim().replace(/\s+/g, ' '),
poster: item.vod_pic || '',
episodes: epCount(item.vod_play_url),
source: site.key,
source_name: site.name,
year: (item.vod_year && String(item.vod_year).match(/\d{4}/)?.[0]) || '',
area: item.vod_area || '',
type_name: item.type_name || '',
douban_id: item.vod_douban_id,
};
}
/** 单站取数:按 kind/cat 筛分类 -> 逐类取一页 -> 返回条目与是否有下一页 */
export async function fetchSiteKind(site: Site, kind: string, cat: string, pg: number) {
const classes = await fetchClass(site);
const targets = pickClasses(classes, kind, cat);
if (!targets.length) return { items: [] as any[], hasMore: false };
const pages = await Promise.all(targets.map((c) => fetchTypePage(site, c.type_id, pg)));
const items: any[] = [];
let hasMore = false;
pages.forEach((list) => {
if (list.length >= 20) hasMore = true;
list.forEach((it) => items.push(it));
});
return { items, hasMore };
}
+8 -4
View File
@@ -49,12 +49,13 @@ export async function middleware(request: NextRequest) {
return NextResponse.next(); return NextResponse.next();
} }
// 首次访问不再强制跳转 /ipv6 选线路页:首页直接加载数据,线路由顶栏「IPV4/IPV6」切换
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage'; const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (!process.env.AUTH_PASSWORD) { if (!process.env.AUTH_PASSWORD) {
// 如果没有设置密码,重定向到警告页面 // 未配置 AUTH_PASSWORD 时直接放行,不强制访问控制
const warningUrl = new URL('/warning', request.url); return NextResponse.next();
return NextResponse.redirect(warningUrl);
} }
// 从cookie获取认证信息 // 从cookie获取认证信息
@@ -170,6 +171,9 @@ function shouldSkipAuth(pathname: string): boolean {
'/api/tvbox', '/api/tvbox',
'/api/filter', '/api/filter',
'/api/license-config', '/api/license-config',
'/api/douban-comments',
'/api/douban-detail',
'/api/douban-related',
]; ];
return skipPaths.some((path) => pathname.startsWith(path)); return skipPaths.some((path) => pathname.startsWith(path));
@@ -178,6 +182,6 @@ function shouldSkipAuth(pathname: string): boolean {
// 配置middleware匹配规则 // 配置middleware匹配规则
export const config = { export const config = {
matcher: [ 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).*)', '/((?!_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).*)',
], ],
}; };