Files
katelyatv/src/app/api/tvbox/route.ts
T

318 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
// 强制使用 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 }
interface TVBoxConfig { spider?: string; wallpaper?: string; notice?: string; warning?: string; version?: string; update_url?: string; lives?: any[]; sites: TVBoxSource[]; parses?: any[]; flags?: string[]; ijk?: Record<string, unknown>; ads?: string[] }
function getHubFields() {
try {
const hub = (global as any).__licenseHub || eval('require')('/app/license-hub.js');
const notice = hub.getNotice ? hub.getNotice() : '';
return {
notice,
warning: notice,
version: hub.getVersion ? hub.getVersion() : '',
update_url: hub.getUpdateUrl ? hub.getUpdateUrl() : '',
};
} catch {
return { notice: '', warning: '', version: '', update_url: '' };
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
// 直播功能(源码化注入:原 patches/live-inject.js 27KB,随镜像发布,不再运行时注入)
// 注意:LIVE 返回原生 Response(流/302/文本/m3u8),必须透传,不可包 NextResponse.json
try {
const lv = searchParams.get('live');
if (lv) {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const liveMod = eval('require')('/app/live-inject.js');
const fn = liveMod.LIVE || liveMod;
const out = await fn(lv, {
url: request.url,
headers: {
get: (k: string) =>
request.headers.get(k.toLowerCase()) ?? request.headers.get(k),
},
});
if (out instanceof Response) return out;
return NextResponse.json(out ?? {}, { headers: { 'Access-Control-Allow-Origin': '*' } });
}
} 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 baseUrl = `${protocol}://${host}`;
const config = await getConfig();
const sourceConfigs: SrcCfg[] = (config.SourceConfig || []).filter((s: any) => !s.disabled);
// 聚合分支:ac=class / ac=videolist / ids
const ac = searchParams.get('ac');
if (ac === 'class' || ac === 'list') {
// 取第一个源的 class 作为基准
const first = sourceConfigs[0];
const cls = first ? await fetchClass(first.api) : [];
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);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
if (sourceConfigs.length === 0) {
return NextResponse.json({ error: '没有配置任何视频源' }, { status: 500 });
}
const hub = getHubFields();
const tvboxConfig: TVBoxConfig = {
spider: '',
wallpaper: `${baseUrl}/screenshot1.png`,
notice: hub.notice,
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: ['电影', '电视剧', '综艺', '动漫', '纪录片', '短剧'],
};
}),
parses: [
{ name: 'Json并发', type: 2, url: 'Parallel' },
{ name: 'Json轮询', type: 2, url: 'Sequence' },
{ name: 'KatelyaTV内置解析', type: 1, url: `${baseUrl}/api/parse?url=`, ext: { flag: ['qiyi', 'qq', 'letv', 'sohu', 'youku', 'mgtv', 'bilibili', 'wasu', 'xigua', '1905'] } },
],
flags: ['youku', 'qq', 'iqiyi', 'qiyi', 'letv', 'sohu', 'tudou', 'pptv', 'mgtv', 'wasu', 'bilibili', 'le', 'duoduozy', 'renrenmi', 'xigua', '优酷', '腾讯', '爱奇艺', '奇艺', '乐视', '搜狐', '土豆', 'PPTV', '芒果', '华数', '哔哩', '1905'],
lives: [{ name: '电视直播', type: 0, url: `${baseUrl}/api/tvbox?live=txt`, ua: 'Mozilla/5.0', epg: '', logo: '' }],
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') {
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 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' } });
} catch (error) {
return NextResponse.json({ error: 'TVBox配置生成失败', details: error instanceof Error ? error.message : String(error) }, { 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' } });
}