fixed68: 右上角四件套每一页常驻(TopRightButtons共用组件+独立页悬浮条+PageLayout去首页条件+版本号fixed68+停用cachebust运行时补丁)

This commit is contained in:
3970260761 committed 2026-11-07 15:03:03 +08:00
1 parent 980b559296
commit 8a91143e5c
32 files changed
+2593 -238

No files matched your search

+322
View File
@@ -0,0 +1,322 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAvailableApiSites, getCacheTime } from '@/lib/config';
// ---------- /api/filter 筛选接口(源码化,原运行时补丁 app-api-filter-route.js) ----------
// action=sources | classes | browse(default)
// sources: -> { sources: [{key,name}] }
// source=all + classes: -> { source:'all', classes: [] }
// source=all + browse: -> 全站聚合(cat 按各站 type_name 归一,title|year 去重)
// source=<key> + classes: -> 该站分类 { source, source_name, classes }
// source=<key> + browse: -> 单站分页筛选 { source, source_name, list, next_pg, has_more }
// browse 参数:source, t(type_id,单站) / cat(type_name,全站), area, year, pg
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 Site {
key: string;
name: string;
api: string;
detail?: string;
}
const BATCH_DEFAULT = 5;
const ALL_MAX_SITES = 100;
// 源站 class 缓存:有数据 10min / 空 30s(原补丁逻辑)
const classCache = new Map<string, [number, any[], boolean]>();
async function fetchClass(
site: Site
): Promise<{ type_id: string; type_name: string }[]> {
const now = Date.now();
const c = classCache.get(site.api);
if (c && (c[2] ? now - c[0] < 30000 : now - c[0] < 600000)) 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: 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 = rs.find(Boolean) || [];
classCache.set(site.api, [now, hit, !hit.length]);
return hit;
}
// 集数:vod_play_url 按 $$$ 分组取最大 # 段数
function epCount(playUrl: string): number {
if (!playUrl) return 1;
let max = 0;
playUrl.split('$$$').forEach((g) => {
const n = g.split('#').filter((s) => s.trim()).length;
if (n > max) max = n;
});
return max > 0 ? max : 1;
}
function matchAreaYear(item: any, area?: string, year?: string) {
return (
(!area || (item.vod_area || '').includes(area)) &&
(!year ||
((item.vod_year || '').match(/\d{4}/)?.[0] || '') === year)
);
}
function mapItem(item: any, site: Site) {
return {
id: String(item.vod_id),
title: (item.vod_name || '').trim().replace(/\s+/g, ' '),
poster: item.vod_pic || '',
episodes: epCount(item.vod_play_url),
source: site.key,
source_name: site.name,
class: item.vod_class,
year: (item.vod_year && item.vod_year.match(/\d{4}/)?.[0]) || '',
area: item.vod_area || '',
type_name: item.type_name || '',
desc: '',
douban_id: item.vod_douban_id,
};
}
// 单站取一页(含 type_id 回退:catName 重查 / 去 t 全量按 type_name 过滤)
async function fetchOne(
site: Site,
t: string | undefined,
year: string | undefined,
pg: number,
catName?: string
): Promise<{ items: any[]; hasMore: boolean }> {
const url = (tt?: string) => {
let n = `${site.api}?ac=videolist&pg=${pg}`;
if (tt) n += `&t=${encodeURIComponent(tt)}`;
if (year) n += `&year=${encodeURIComponent(year)}`;
return n;
};
const get = async (n: string) => {
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 10000);
const r = await fetch(n, {
headers: { 'User-Agent': UA, Accept: 'application/json' },
signal: ctrl.signal,
});
clearTimeout(timer);
if (!r.ok) return { items: [], hasMore: false };
const j = await r.json();
const list = Array.isArray(j?.list) ? j.list : [];
return { items: list, hasMore: list.length >= 20 };
} catch {
return { items: [], hasMore: false };
}
};
let cur = await get(url(t));
if (catName && t && String(t) !== String(catName) && cur.items.length < 5) {
const retry = await get(url(catName));
if (retry.items.length > cur.items.length) cur = retry;
}
if (catName && cur.items.length < 5) {
const all = await get(url());
if (all.items.length) {
const f = all.items.filter((x: any) => {
const n = x.type_name || '';
return n && (n === catName || n.includes(catName) || catName.includes(n));
});
if (f.length > cur.items.length) cur = { items: f, hasMore: all.hasMore };
}
}
return cur;
}
// 单站 browse:并发翻页凑齐 24 条
async function browseSite(
site: Site,
opts: {
t?: string;
area?: string;
year?: string;
tn?: string;
pg?: number;
batch?: number;
}
) {
const { t, area, year, tn } = opts;
let pg = Math.max(1, opts.pg || 1);
const batch = Math.min(Math.max(opts.batch || BATCH_DEFAULT, 1), 6);
const want = 24;
const maxPages = 30;
const list: any[] = [];
let hasMore = true;
let fetched = 0;
while (hasMore && fetched < maxPages) {
const n = Math.min(batch, maxPages - fetched);
const jobs: Promise<{ items: any[]; hasMore: boolean }>[] = [];
for (let k = 0; k < n; k++) jobs.push(fetchOne(site, t, year, pg + k, tn));
const ds = await Promise.all(jobs);
fetched += n;
pg += n;
hasMore =
(ds[ds.length - 1]?.hasMore ?? false) &&
!(
ds.length > 1 &&
ds[ds.length - 2].items[0] &&
ds[ds.length - 1].items[0] &&
ds[ds.length - 2].items[0].vod_id === ds[ds.length - 1].items[0].vod_id
);
ds.forEach((d) => {
d.items.forEach((it) => {
if (matchAreaYear(it, area, year)) list.push(mapItem(it, site));
});
});
if (list.length >= want || !hasMore) break;
}
return { list, next_pg: pg, has_more: hasMore };
}
// type_name -> type_id(精确优先,含糊匹配兜底)
function resolveTypeId(classes: { type_id: string; type_name: string }[], cat: string) {
const exact = classes.find((c) => c.type_name === cat);
if (exact) return exact.type_id;
return classes.find((c) => c.type_name.includes(cat) || cat.includes(c.type_name))?.type_id;
}
// 全站聚合 browse
async function browseAll(
sites: Site[],
opts: { cat?: string; area?: string; year?: string; pg?: number }
) {
const { cat, area, year } = opts;
const pg = Math.max(1, opts.pg || 1);
const slice = sites.slice(0, ALL_MAX_SITES);
const per = await Promise.all(
slice.map(async (s) =>
browseSite(s, {
t: cat ? resolveTypeId(await fetchClass(s), cat) || cat : undefined,
tn: cat,
area,
year,
pg,
batch: 4,
})
)
);
const seen = new Set<string>();
const list: any[] = [];
let hasMore = false;
let nextPg = Infinity;
per.forEach((r) => {
if (r.has_more) hasMore = true;
if (r.next_pg < nextPg) nextPg = r.next_pg;
r.list.forEach((it) => {
const k = `${it.title}|${it.year}`;
if (!seen.has(k)) {
seen.add(k);
list.push(it);
}
});
});
return { list, next_pg: nextPg === Infinity ? pg + 1 : nextPg, has_more: hasMore };
}
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const action = searchParams.get('action') || 'browse';
const source = searchParams.get('source');
try {
const sites = await getAvailableApiSites(true);
const cacheTime = await getCacheTime();
const headers = {
'Cache-Control': `public, max-age=${Math.min(cacheTime, 600)}, s-maxage=${Math.min(cacheTime, 600)}`,
'CDN-Cache-Control': `public, s-maxage=${Math.min(cacheTime, 600)}`,
'Vercel-CDN-Cache-Control': `public, s-maxage=${Math.min(cacheTime, 600)}`,
};
if (action === 'sources') {
return NextResponse.json(
{ sources: sites.map((s) => ({ key: s.key, name: s.name })) },
{ headers }
);
}
if (source === 'all') {
if (action === 'classes') {
return NextResponse.json(
{ source: 'all', source_name: '全部资源站', classes: [] },
{ headers }
);
}
const out = await browseAll(sites, {
cat: searchParams.get('cat') || undefined,
area: searchParams.get('area') || undefined,
year: searchParams.get('year') || undefined,
pg: parseInt(searchParams.get('pg') || '1', 10),
});
return NextResponse.json(
{ source: 'all', source_name: '全部资源站', ...out },
{ headers }
);
}
const site = (source ? sites.find((s) => s.key === source) : undefined) || sites[0];
if (!site) {
return NextResponse.json({ error: '未找到指定的资源站' }, { status: 404 });
}
if (action === 'classes') {
const classes = await fetchClass(site);
return NextResponse.json(
{ source: site.key, source_name: site.name, classes },
{ headers }
);
}
const t = searchParams.get('t') || undefined;
const classes = t ? await fetchClass(site) : [];
const tn = t
? (classes.find((c) => String(c.type_id) === String(t)) || {}).type_name
: undefined;
const out = await browseSite(site, {
t,
tn,
area: searchParams.get('area') || undefined,
year: searchParams.get('year') || undefined,
pg: parseInt(searchParams.get('pg') || '1', 10),
});
return NextResponse.json(
{ source: site.key, source_name: site.name, ...out },
{ headers }
);
} 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',
},
});
}
+37
View File
@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
export const runtime = 'nodejs';
export async function GET() {
try {
const hub = (global as any).__licenseHub || eval('require')('/app/license-hub.js');
const st = hub.getStatus();
return NextResponse.json(
{ code: 200, message: 'ok', data: st },
{
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'public, max-age=60',
},
},
);
} catch (x: any) {
console.log('[LICENSE-CFG] ERR', x && x.message);
return NextResponse.json(
{ code: 500, message: String(x && x.message || x), data: null },
{ headers: { 'Access-Control-Allow-Origin': '*' } },
);
}
}
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',
},
});
}
+137
View File
@@ -0,0 +1,137 @@
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
// 强制使用 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=902(香港剧 direct)→ 源站真实 id;t=901(香港电影 agg)→ 源站电影 id + area=香港过滤
async function resolveTop(sources: SrcCfg[], sp: URLSearchParams): Promise<{ extraArea: string }> {
const t = sp.get('t');
if (!t || !/^90[1-9]$/.test(t) || sp.get('wd')) return { extraArea: '' };
const first = sources[0];
if (!first) return { extraArea: '' };
const cls = await fetchClass(first.api);
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 mv = fd('电影', '电影片');
const tv = fd('连续剧', '电视剧', '剧集');
const vy = fd('综艺', '综艺片');
const an = fd('动漫', '动漫片');
const to = fd('动画片', '动画电影', '动漫电影');
const hk = fd('香港剧', '港澳剧', '港台剧', '港剧');
const nat: Record<string, any> = { '901': mv, '902': hk, '903': mv, '904': tv, '905': vy, '906': to, '907': an };
const hit = nat[t];
if (hit) {
sp.set('t', String(hit.type_id));
if (t === '901') { sp.set('area', '香港'); return { extraArea: '香港' }; }
}
return { extraArea: '' };
}
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;
}
let q = 'ac=videolist&pg=' + pg;
if (wd) q += '&wd=' + encodeURIComponent(wd);
// 顶层 9xx 分类先映射到源站真实 type_id(旧补丁 P() tops 逻辑)
const { extraArea } = await resolveTop(srcs, sp);
const t2 = sp.get('t');
if (t2) q += '&t=' + encodeURIComponent(t2);
['st', 'year', 'area', 'by'].forEach((k) => { const v = sp.get(k); if (v) q += '&' + k + '=' + encodeURIComponent(v); });
const results = await Promise.all(srcs.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 = 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)));
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) 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) {
const { searchParams } = new URL(request.url);
const config = await getConfig();
const sourceConfigs: SrcCfg[] = (config.SourceConfig || []).filter((s: any) => !s.disabled);
const r = await aggregateAll(sourceConfigs, searchParams);
return NextResponse.json(r, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=60' } });
}
+270 -202
View File
@@ -5,245 +5,313 @@ import { getConfig } from '@/lib/config';
// 强制使用 Edge Runtime 以支持 Cloudflare Pages
export const runtime = 'edge';
// TVBox源格式接口
interface TVBoxSource {
key: string;
name: string;
type: number; // 0=影视源, 1=直播源, 3=解析源
api: string;
searchable?: number; // 0=不可搜索, 1=可搜索
quickSearch?: number; // 0=不支持快速搜索, 1=支持快速搜索
filterable?: number; // 0=不支持分类筛选, 1=支持分类筛选
ext?: string; // 扩展参数
jar?: string; // jar包地址
playUrl?: string; // 播放解析地址
categories?: string[]; // 分类
timeout?: number; // 超时时间(秒)
// ---------- 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 [];
}
interface TVBoxConfig {
spider?: string; // 爬虫jar包地址
wallpaper?: string; // 壁纸地址
lives?: Array<{
name: string;
type: number;
url: string;
epg?: string;
logo?: string;
}>; // 直播源
sites: TVBoxSource[]; // 影视源
parses?: Array<{
name: string;
type: number;
url: string;
ext?: Record<string, unknown>;
header?: Record<string, string>;
}>; // 解析源
flags?: string[]; // 播放标识
ijk?: Record<string, unknown>; // IJK播放器配置
ads?: string[]; // 广告过滤规则
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);
const format = searchParams.get('format') || 'json'; // 支持json和base64格式
// 直播功能(源码化注入:原 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 = config.SourceConfig || [];
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 });
}
// 转换为TVBox格式
const hub = getHubFields();
const tvboxConfig: TVBoxConfig = {
// 基础配置
spider: '', // 可以根据需要添加爬虫jar包
wallpaper: `${baseUrl}/screenshot1.png`, // 使用项目截图作为壁纸
// 影视源配置
spider: '',
wallpaper: `${baseUrl}/screenshot1.png`,
notice: hub.notice,
warning: hub.warning,
version: hub.version,
update_url: hub.update_url,
sites: sourceConfigs.map((source) => {
// 更智能的type判断逻辑:
// 1. 如果api地址包含 "/provide/vod" 且不包含 "at/xml",则认为是JSON类型 (type=1)
// 2. 如果api地址包含 "at/xml",则认为是XML类型 (type=0)
// 3. 如果api地址以 ".json" 结尾,则认为是JSON类型 (type=1)
// 4. 其他情况默认为JSON类型 (type=1),因为现在大部分都是JSON
let type = 1; // 默认为JSON类型
let type = 1;
const apiLower = source.api.toLowerCase();
if (apiLower.includes('at/xml') || apiLower.endsWith('.xml')) {
type = 0; // XML类型
}
if (apiLower.includes('at/xml') || apiLower.endsWith('.xml')) type = 0;
return {
key: source.key || source.name,
name: source.name,
type: type, // 使用智能判断的type
type,
api: source.api,
searchable: 1, // 可搜索
quickSearch: 1, // 支持快速搜索
filterable: 1, // 支持分类筛选
ext: source.detail || '', // 详情页地址作为扩展参数
timeout: 30, // 30秒超时
categories: [
"电影", "电视剧", "综艺", "动漫", "纪录片", "短剧"
]
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"]
}
}
{ 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: "KatelyaTV直播",
type: 0,
url: `${baseUrl}/api/live/channels`,
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"
]
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'],
};
// 根据format参数返回不同格式
if (format === 'txt') {
// 返回base64编码的配置(TVBox常用格式)
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'
}
});
} else {
// 返回JSON格式
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 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 }
);
return NextResponse.json({ error: 'TVBox配置生成失败', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}
// 支持CORS预检请求
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',
}
});
return new NextResponse(null, { status: 200, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' } });
}