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

This commit is contained in:
jinghui committed 2026-11-13 14:51:05 +08:00
1 parent 6cbf7859f0
commit 3362970fff
7 files changed
+593 -362

No files matched your search

+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([]));
}
}
+5 -146
View File
@@ -1,159 +1,18 @@
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { SrcCfg, aggregateAll } from '@/lib/tvboxagg';
// 强制使用 Edge Runtime 以支持 Cloudflare Pages
export const runtime = 'edge';
// ---------- /api/tvbox/all 全源聚合(源码化,原运行时补丁 app-api-tvbox-route.js 的 ALL) ----------
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 }
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;
}
// ---------- /api/tvbox/all 全源聚合 ----------
// 聚合/class/9xx 映射逻辑已收拢到 @/lib/tvboxagg(旧补丁 ALL 逻辑的源码化实现),
// 本文件只负责:进程内缓存 + 出口。
// 进程内响应缓存:相同查询 60s 内直接返回,避免每次刷新都重新聚合上游(最新港剧等栏目秒开)
const respCache = new Map<string, [number, any]>();
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const cacheKey = searchParams.toString();
+34 -214
View File
@@ -1,158 +1,11 @@
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { SrcCfg, aggregateAll, fetchClass, mkTransform } from '@/lib/tvboxagg';
// 强制使用 Edge Runtime 以支持 Cloudflare Pages
export const runtime = 'edge';
// ---------- TVBox 聚合层(源码化,替代 patches/app-api-tvbox-route.js) ----------
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36';
interface SrcCfg { key: string; name: string; api: string; detail?: string; disabled?: boolean }
// 缓存源站 class 列表:30s 正常 / 10min 空
const classCache = new Map<string, [number, any[], boolean]>();
async function fetchClass(api: string): Promise<any[]> {
const now = Date.now();
const c = classCache.get(api);
if (c && (c[2] ? now - c[0] < 30000 : now - c[0] < 600000)) return c[1];
for (const ep of [api, api + (api.includes('?') ? '&' : '?') + 'ac=list', api + (api.includes('?') ? '&' : '?') + 'ac=class']) {
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 8000);
const r = await fetch(ep, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: ctrl.signal });
clearTimeout(t);
if (!r.ok) continue;
const j = await r.json();
if (Array.isArray(j?.class) && j.class.length) {
classCache.set(api, [now, j.class, false]);
return j.class;
}
} catch {}
}
classCache.set(api, [now, [], true]);
return [];
}
function mkTransform(cls: any[]) {
const byN: Record<string, any> = {};
(cls || []).forEach((c) => { if (c && c.type_name != null) byN[String(c.type_name).trim()] = c; });
const fd = (...names: string[]) => { for (const n of names) if (byN[n]) return byN[n]; return null; };
const kd = (r: any) => r ? (cls || []).filter((c) => c && String(c.type_pid) === String(r.type_id) && String(c.type_id) !== String(r.type_id)) : [];
const mv = fd('电影', '电影片');
const tv = fd('连续剧', '电视剧', '剧集');
const vy = fd('综艺', '综艺片');
const an = fd('动漫', '动漫片');
const to = fd('动画片', '动画电影', '动漫电影');
const hk = fd('香港剧', '港澳剧', '港台剧', '港剧');
const T: any[] = [];
if (mv) T.push({ tid: '901', name: '香港电影', kind: 'agg', native: String(mv.type_id), ch: kd(mv), area: '香港' });
if (hk) T.push({ tid: '902', name: '香港剧', kind: 'direct', native: String(hk.type_id), ch: [], area: '' });
if (mv) T.push({ tid: '903', name: '电影', kind: 'agg', native: String(mv.type_id), ch: kd(mv), area: '' });
if (tv) T.push({ tid: '904', name: '电视剧', kind: 'agg', native: String(tv.type_id), ch: kd(tv), area: '' });
if (vy) T.push({ tid: '905', name: '综艺', kind: 'agg', native: String(vy.type_id), ch: kd(vy), area: '' });
if (to) T.push({ tid: '906', name: '动画片', kind: 'direct', native: String(to.type_id), ch: [], area: '' });
if (an) T.push({ tid: '907', name: '动漫', kind: 'agg', native: String(an.type_id), ch: kd(an), area: '' });
T.push({ tid: '909', name: 'AI短剧', kind: 'search', native: '', wd: 'AI短剧', kwPat: 'AI|短剧|微短剧', ch: [], area: '' });
const Y = [{ n: '全部', v: '' }]; for (let y = 2026; y >= 2010; y--) Y.push({ n: String(y), v: String(y) });
const AR = [{ n: '全部', v: '' }, { n: '中国大陆', v: '中国大陆' }, { n: '中国香港', v: '中国香港' }, { n: '中国台湾', v: '中国台湾' }, { n: '美国', v: '美国' }, { n: '韩国', v: '韩国' }, { n: '日本', v: '日本' }, { n: '英国', v: '英国' }, { n: '法国', v: '法国' }, { n: '德国', v: '德国' }, { n: '泰国', v: '泰国' }, { n: '印度', v: '印度' }, { n: '加拿大', v: '加拿大' }, { n: '其他', v: '其他' }];
const BY = [{ n: '最新', v: 'time' }, { n: '最热', v: 'hits' }, { n: '评分', v: 'score' }];
const cls7: any[] = [];
const tops: Record<string, any> = {};
const filters: Record<string, any[]> = {};
T.forEach((t) => {
cls7.push({ type_id: t.tid, type_name: t.name, type_pid: 0 });
tops[t.tid] = { kind: t.kind, native: t.native, wd: t.wd || '', kwPat: t.kwPat || '', ch: t.ch, area: t.area || '' };
const g: any[] = [];
if (t.ch && t.ch.length) g.push({ key: 'st', name: '分类', value: [{ n: '全部', v: '' }].concat(t.ch.map((c: any) => ({ n: String(c.type_name), v: String(c.type_name) }))) });
if (t.tid !== '901') g.push({ key: 'area', name: '地区', value: AR });
g.push({ key: 'year', name: '年份', value: Y });
g.push({ key: 'by', name: '排序', value: BY });
filters[t.tid] = g;
});
if (!cls7.length) (cls || []).forEach((c) => cls7.push({ type_id: String(c.type_id), type_name: c.type_name, type_pid: c.type_pid }));
return { class: cls7, tops, filters };
}
async function subFetch(api: string, query: string): Promise<any> {
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 8000);
const r = await fetch(api + (api.includes('?') ? '&' : '?') + query, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: ctrl.signal });
clearTimeout(t);
if (!r.ok) return null;
return await r.json();
} catch { return null; }
}
function ns(x: any, key: string) { return Object.assign({}, x, { vod_id: String(key) + ':' + String(x.vod_id) }); }
async function aggregate(sources: SrcCfg[], sp: URLSearchParams) {
const out: any = { code: 1, msg: '数据列表', page: 1, pagecount: 1, limit: 0, total: 0, list: [] };
const ids = sp.get('ids');
const wd = sp.get('wd');
const t = sp.get('t');
const pg = sp.get('pg') || '1';
const st = sp.get('st');
const year = sp.get('year');
const area = sp.get('area');
if (ids) {
const byK: Record<string, string[]> = {};
ids.split(',').forEach((p) => {
const i = p.indexOf(':');
if (i > 0) { const k = p.slice(0, i); const id = p.slice(i + 1); (byK[k] = byK[k] || []).push(id); }
});
for (const k in byK) {
const d = await subFetch(sources.find((s) => s.key === k)?.api || '', 'ac=videolist&ids=' + byK[k].map(encodeURIComponent).join(','));
if (d && Array.isArray(d.list)) d.list.forEach((x: any) => out.list.push(ns(x, k)));
}
out.total = out.list.length; out.limit = out.list.length;
return out;
}
let q = 'ac=videolist&pg=' + pg;
if (wd) q += '&wd=' + encodeURIComponent(wd);
if (t) q += '&t=' + encodeURIComponent(t);
['st', 'year', 'area', 'by'].forEach((k) => { const v = sp.get(k); if (v) q += '&' + k + '=' + encodeURIComponent(v); });
const results = await Promise.all(sources.map((s) => subFetch(s.api, q)));
const seen: Record<string, number> = {};
let list: any[] = [];
results.forEach((d, i) => {
if (d && Array.isArray(d.list)) {
const key = sources[i].key;
d.list.forEach((x: any) => {
const nm = String(x.vod_name || '').trim();
if (nm && !seen[nm]) { seen[nm] = 1; list.push(ns(x, key)); }
});
}
});
// 排序
const by = sp.get('by') || 'time';
if (by === 'hits') list.sort((a, b) => (b.vod_hits || 0) - (a.vod_hits || 0));
else if (by === 'score') list.sort((a, b) => (b.vod_score || 0) - (a.vod_score || 0));
else list.sort((a, b) => String(b.vod_time || '').localeCompare(String(a.vod_time || '')));
// 过滤
list = list.filter((x) => {
if (st && String(x.type_name) !== st && String(x.vod_class) !== st) return false;
if (year && String(x.vod_year) !== year) return false;
if (area && String(x.vod_area) !== area) return false;
return true;
});
out.list = list;
out.total = list.length;
out.limit = list.length;
out.page = Number(pg) || 1;
return out;
}
// ---------- 原有 TVBox 配置生成 ----------
interface TVBoxSource { key: string; name: string; type: number; api: string; searchable?: number; quickSearch?: number; filterable?: number; ext?: string; jar?: string; playUrl?: string; categories?: string[]; timeout?: number }
@@ -198,7 +51,7 @@ export async function GET(request: NextRequest) {
} catch { /* fallback 正常 tvbox 逻辑 */ }
const format = searchParams.get('format') || 'json';
const host = request.headers.get('host') || 'localhost:3000';
const protocol = request.headers.get('x-forwarded-proto') || 'http';
const protocol = request.headers.get('x-forwarded-proto') || (host.includes('88531') ? 'https' : (/^(localhost|127\.|0\.0\.0\.0)/.test(host) ? 'http' : 'https'));
const baseUrl = `${protocol}://${host}`;
const config = await getConfig();
@@ -213,51 +66,10 @@ export async function GET(request: NextRequest) {
const transformed = mkTransform(cls);
return NextResponse.json({ code: 1, msg: '数据列表', ...transformed }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
if (ac === 'videolist' || searchParams.get('ids')) {
// 顶层分类 9xx 处理:映射到源站 class + 过滤
const t = searchParams.get('t') || '';
const tops: Record<string, any> = {};
// 重新计算 tops 以获取 kind
if (sourceConfigs[0]) {
const cls = await fetchClass(sourceConfigs[0].api);
const tr = mkTransform(cls);
Object.assign(tops, tr.tops);
}
const top = tops[t];
if (top && top.kind === 'search') {
// AI短剧:走搜索
const sp = new URLSearchParams(searchParams);
sp.set('wd', top.wd || 'AI短剧');
const r = await aggregate(sourceConfigs, sp);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
if (top && top.kind === 'direct') {
const sp = new URLSearchParams(searchParams);
sp.set('t', top.native);
const r = await aggregate(sourceConfigs, sp);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
if (top && top.kind === 'agg') {
// 聚合:native class + 子分类 st 过滤
const sp = new URLSearchParams(searchParams);
if (!sp.get('t')) sp.set('t', top.native);
const st = sp.get('st');
if (st && top.ch) {
const ch = top.ch.find((c: any) => String(c.type_name) === st);
if (ch) sp.set('t', String(ch.type_id));
}
// area=香港 特殊:过滤 vod_area
if (top.area === '香港') {
const r = await aggregate(sourceConfigs, sp);
r.list = (r.list || []).filter((x: any) => String(x.vod_area || '').includes('香港'));
r.total = r.list.length; r.limit = r.list.length;
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
const r = await aggregate(sourceConfigs, sp);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
// 普通 t(源站 class id)直接聚合
const r = await aggregate(sourceConfigs, searchParams);
// vod 请求(分类 t=9xx / 搜索 wd / 详情 ids)→ 全源聚合
// 旧版:agg 分类没把 9xx 换成源站真实 type_id,导致 电影/电视剧 等分类全部返回 0 条
if (ac === 'videolist' || searchParams.get('ids') || searchParams.get('wd')) {
const r = await aggregateAll(sourceConfigs, searchParams);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
@@ -266,6 +78,8 @@ export async function GET(request: NextRequest) {
}
const hub = getHubFields();
// TVBox 端统一分类视图(旧补丁 TOP7)
const TOP7 = ['AI短剧', '香港电影', '香港剧', '电影', '电视剧', '综艺', '动画片', '动漫'];
const tvboxConfig: TVBoxConfig = {
spider: '',
wallpaper: `${baseUrl}/screenshot1.png`,
@@ -273,23 +87,29 @@ export async function GET(request: NextRequest) {
warning: hub.warning,
version: hub.version,
update_url: hub.update_url,
sites: sourceConfigs.map((source) => {
let type = 1;
const apiLower = source.api.toLowerCase();
if (apiLower.includes('at/xml') || apiLower.endsWith('.xml')) type = 0;
return {
key: source.key || source.name,
name: source.name,
type,
api: source.api,
searchable: 1,
quickSearch: 1,
filterable: 1,
ext: source.detail || '',
timeout: 30,
categories: ['电影', '电视剧', '综艺', '动漫', '纪录片', '短剧'],
};
}),
sites: [
// 「全部资源」:本站全源聚合(旧补丁 TOP7 结构)
{ key: 'all', name: '全部资源', type: 1, api: `${baseUrl}/api/tvbox/all`, searchable: 1, quickSearch: 1, filterable: 1, ext: '', timeout: 60, categories: TOP7 },
// 各资源站走本站逐站代理 /api/tvbox/<key>:电视/手机端只要能访问本站域名就能点播,
// 9xx 分类在代理里映射成该源自己的分类 id(旧补丁 P() 能力,源码化时丢失,本次恢复)
...sourceConfigs.map((source) => {
let type = 1;
const apiLower = source.api.toLowerCase();
if (apiLower.includes('at/xml') || apiLower.endsWith('.xml')) type = 0;
return {
key: source.key || source.name,
name: source.name,
type,
api: `${baseUrl}/api/tvbox/${encodeURIComponent(source.key || source.name)}`,
searchable: 1,
quickSearch: 1,
filterable: 1,
ext: source.detail || '',
timeout: 30,
categories: TOP7,
};
}),
],
parses: [
{ name: 'Json并发', type: 2, url: 'Parallel' },
{ name: 'Json轮询', type: 2, url: 'Sequence' },
@@ -300,12 +120,12 @@ export async function GET(request: NextRequest) {
ads: ['mimg.0c1q0l.cn', 'www.googletagmanager.com', 'www.google-analytics.com', 'mc.usihnbcq.cn', 'mg.g1mm3d.cn', 'mscs.svaeuzh.cn', 'cnzz.hhurm.com', 'tp.vinuxhome.com', 'cnzz.mmstat.com', 'www.baihuillq.com', 's23.cnzz.com', 'z3.cnzz.com', 'c.cnzz.com', 'stj.v1vo.top', 'z12.cnzz.com', 'img.mosflower.cn', 'tips.gamevvip.com', 'ehwe.yhdtns.com', 'xdn.cqqc3.com', 'www.jixunkyy.cn', 'sp.chemacid.cn', 'hm.baidu.com', 's9.cnzz.com', 'z6.cnzz.com', 'um.cavuc.com', 'mav.mavuz.com', 'wofwk.aoidf3.com', 'z5.cnzz.com', 'xc.hubeijieshikj.cn', 'tj.tianwenhu.com', 'xg.gars57.cn', 'k.jinxiuzhilv.com', 'cdn.bootcss.com', 'ppl.xunzhuo123.com', 'xomk.jiangjunmh.top', 'img.xunzhuo123.com', 'z1.cnzz.com', 's13.cnzz.com', 'xg.huataisangao.cn', 'z7.cnzz.com', 'xg.huataisangao.cn', 'z2.cnzz.com', 's96.cnzz.com', 'q11.cnzz.com', 'thy.dacedsfa.cn', 'xg.whsbpw.cn', 's19.cnzz.com', 'z8.cnzz.com', 's4.cnzz.com', 'f5w.as12df.top', 'ae01.alicdn.com', 'www.92424.cn', 'k.wudejia.com', 'vivovip.mmszxc.top', 'qiu.xixiqiu.com', 'cdnjs.hnfenxun.com', 'cms.qdwght.com'],
};
if (format === 'txt') {
if (format === 'txt' || format === 'base64') {
const configStr = JSON.stringify(tvboxConfig, null, 2);
const base64Config = Buffer.from(configStr).toString('base64');
return new NextResponse(base64Config, { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Cache-Control': 'public, max-age=3600' } });
return new NextResponse(base64Config, { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Cache-Control': 'no-store' } });
}
return NextResponse.json(tvboxConfig, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Cache-Control': 'public, max-age=3600' } });
return NextResponse.json(tvboxConfig, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Cache-Control': 'no-store' } });
} catch (error) {
return NextResponse.json({ error: 'TVBox配置生成失败', details: error instanceof Error ? error.message : String(error) }, { status: 500 });