// 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 { 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(); export async function fetchClass(api: string): Promise { 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 = {}; (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 = {}; const filters: Record = {}; 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; } // 顶层 9xx → 每个源自己的真实分类 id 列表(各源分类表不同,不能拿一个源的 id 发给全源)。 // agg 类分类返回「子分类 id 列表」,供 aggChildren 逐子分类聚合(旧补丁 P() 的 _aggTids 逻辑)。 export async function resolveTopTids(sources: SrcCfg[], sp: URLSearchParams): Promise { 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 = {}; 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(); export async function aggChildren(api: string, tids: string[], extra: string, pg: string): Promise { 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 = {}; 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 = {}; 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(); 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 = {}; 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; }