Files
katelyatv/live-inject.js
T
3970260761 d508f84954
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
fixed74: 直播抓取加重试+过期缓存兜底
- live-inject.js liveText: 15s单次超时改为25s x 3次重试, 失败打[LIVE-FETCH-RETRY]日志
- liveChannels: 失败/空列表时用过期缓存兜底[LIVE-CH-STALE], 避免前端撞上上游抖动显示暂无频道
- 版本号对齐 fixed74
2026-11-08 00:31:18 +08:00

369 lines
28 KiB
JavaScript
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.
/* ==== LIVE: 港澳台电视直播(注入片段,纯函数,无模块依赖) ==== */
const LIVE_UP="https://m.iptv807.com";
let _liveVm=null;try{_liveVm=require("vm")}catch(e){}
const LIVE_UA="Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1";
const LIVE_HOSTS=/(^|\.)(iptv200\.com|2026016\.xyz)$/;
const liveCh={ts:0,list:null},liveLn=new Map(),liveRv=new Map();
const EPG_MAP={"凤凰卫视中文台":"凤凰中文","凤凰卫视资讯台":"凤凰资讯","TVB翡翠台":"翡翠台","TVB无线新闻台":"无线新闻","TVB明珠台":"明珠台","中视新闻台":"中视新闻","中视HD":"中视","台视HD":"台视","民视HD":"民视","华视HD":"华视","华视新闻台":"华视新闻","非凡新闻":"非凡新闻台","寰宇新闻台":"寰宇新闻","寰宇新闻台湾台":"寰宇新闻","TVBS HD":"TVBS","纬来育乐台":"纬来综合台","緯來體育台":"纬来体育台","爱尔达体育1台":"爱尔达体育1","爱尔达体育2台":"爱尔达体育2","ELEVEN 1(DAZN 1)":"ELTV","ELEVEN 2(DAZN 2)":"ELTV","澳視澳門":"澳門","澳門Macau":"澳門"};
const liveEpg={ts:0,map:null};
function liveToday(){const d=new Date(Date.now()+8*3600e3);return d.toISOString().slice(0,10).replace(/-/g,"")}
async function liveEpgAll(){
if(liveEpg.map&&Date.now()-liveEpg.ts<1800e3)return liveEpg.map;
const x=await liveText("http://epg.51zmt.top:8000/e2.xml.gz",25000);
if(!x||x.indexOf("<programme")<0)throw new Error("epg unavailable");
const chm={};let m;
const reC=/<channel id="([^"]+)">\s*<display-name[^>]*>([^<]+)<\/display-name>/g;
while((m=reC.exec(x)))chm[m[1]]=m[2];
const today=liveToday(),map={};
const reP=/<programme start="(\d{14})\s*[^"]*"\s*stop="(\d{14})[^"]*" channel="([^"]+)"[^>]*>\s*(?:<title[^>]*>([\s\S]*?)<\/title>)?/g;
while((m=reP.exec(x))){
if(m[1].slice(0,8)!==today)continue;
const nm=chm[m[3]];if(!nm)continue;
(map[nm]=map[nm]||[]).push({s:m[1].slice(8,12),e:m[2].slice(8,12),t:(m[4]||"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")})}
if(!Object.keys(map).length)throw new Error("epg empty");
liveEpg.map=map;liveEpg.ts=Date.now();
console.log("[LIVE-EPG] loaded channels="+Object.keys(map).length);
return map}
async function liveEpgFor(name){
const all=await liveEpgAll();
const key=EPG_MAP[name]||(all[name]?name:null);
if(!key)return{has:false,list:[]};
return{has:true,epg_key:key,list:all[key]||[]}}
async function liveText(u,ms){const timeout=ms||25000;let lastErr=null;
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"澳门";
if(/凤凰|TVB|有线|有線|NOW|ViuTV|HOY|港台|香港|明珠|HKS/.test(n))return"香港";
if(/中天|东森|東森|中视|中視|台视|台視|三立|非凡|民视|民視|华视|華視|镜电视|鏡電視|寰宇|TVBS|纬来|緯來|ELEVEN|DAZN|爱尔达|愛爾達/.test(n))return"台湾";return"其他"}
async function liveChannels(){
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=[];
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(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){
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 blocks=[...h.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m=>m[1])
.filter(s=>/keyStr|reverse\(\)\.join/.test(s)&&/function|var /.test(s));
let ctx={};
if(_liveVm){
ctx=_liveVm.createContext({});
for(const s of blocks){try{_liveVm.runInContext(s,ctx)}catch(e){console.log("[LIVE-BLK-VM]",e&&e.message)}}
}else{
for(const s of blocks){
try{
const names=[...s.matchAll(/function\s+(\w+)\s*\(/g)].map(m=>m[1]);
const vars=[...s.matchAll(/var\s+(\w+)/g)].map(m=>m[1]);
const uniq=[...new Set(names.concat(vars))];
const fn=new Function(s+"\nvar __o={};"+uniq.map(n=>"try{__o."+n+"="+n+"}catch(e){}").join("")+"\nreturn __o;");
Object.assign(ctx,fn());
}catch(e){console.log("[LIVE-BLK-FN]",e&&e.message)}}
}
const fns=Object.keys(ctx).filter(k=>typeof ctx[k]==="function");
const dec=fns.find(k=>/replace\(["']token=/.test(ctx[k].toString()));
console.log("[LIVE-LINES]",id,"blocks="+blocks.length,"fns="+fns.length,"dec="+dec);
if(!dec)throw new Error("decoder unavailable");
const lines=[...h.matchAll(/<option value="([^"]+)"[^>]*>([^<]+)</g)].map(o=>{let url="";
try{url=ctx[dec](o[1])}catch(e){console.log("[LIVE-DEC-ERR]",e&&e.message)}
return{name:o[2],url}}).filter(l=>/^https?:\/\//.test(l.url));
console.log("[LIVE-LINES]",id,"lines="+lines.length,lines[0]?lines[0].url.slice(0,70):"");
if(lines.length)liveLn.set(id,{ts:Date.now(),lines});return lines}
async function liveResolve(id,p){
const key=id+"|"+p;const c=liveRv.get(key);if(c&&Date.now()-c.ts<300000)return c.finalUrl;
const lines=await liveLines(id);const ln=lines[p]||lines[0];if(!ln)throw new Error("no line");
console.log("[LIVE-RS] fetch",ln.url.slice(0,70));
const ctl=new AbortController();const tm=setTimeout(()=>ctl.abort(),20000);
try{const r=await fetch(ln.url,{redirect:"follow",signal:ctl.signal,headers:{"User-Agent":LIVE_UA,"Referer":LIVE_UP+"/"}});
console.log("[LIVE-RS] final",r.status,r.url.slice(0,70));
if(r.body)try{await r.body.cancel()}catch(e){}
console.log("[LIVE-RS] cancelled");
const uu=new URL(r.url);if(!LIVE_HOSTS.test(uu.hostname))throw new Error("bad host");
liveRv.set(key,{ts:Date.now(),finalUrl:r.url});return r.url}finally{clearTimeout(tm)}}
function liveB64e(s){return Buffer.from(s,"utf8").toString("base64url")}
function liveB64d(s){return Buffer.from(s,"base64url").toString("utf8")}
function liveJ(o){return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}
function livePage(){
const html=`<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>电视直播 · 港澳台</title><style>
:root{color-scheme:dark}*{box-sizing:border-box;margin:0;padding:0}
body{background:#0f1115;color:#e5e7eb;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;min-height:100vh}
.hd{position:sticky;top:0;z-index:9;background:rgba(15,17,21,.92);backdrop-filter:blur(8px);padding:10px 14px;display:flex;align-items:center;gap:10px;border-bottom:1px solid #1f2430}
.hd a{color:#9ca3af;text-decoration:none;font-size:24px;line-height:1}
.hd h1{font-size:17px;font-weight:600}
.tvboxBtn{border:1px solid rgba(59,130,246,.55);background:rgba(37,99,235,.16);color:#bfdbfe;border-radius:8px;padding:7px 12px;font-size:13px;cursor:pointer;white-space:nowrap;transition:.15s}
.tvboxBtn:hover{background:rgba(37,99,235,.32);color:#fff}
.ghLink{display:flex;align-items:center;gap:5px;border:1px solid rgba(255,255,255,.18);background:rgba(255,255,255,.06);color:#c7d2fe;border-radius:8px;padding:7px 11px;font-size:13px;font-weight:600;text-decoration:none;white-space:nowrap;transition:.15s}
.ghLink:hover{background:rgba(255,255,255,.14);color:#fff}
.tvboxPop{position:absolute;right:14px;top:calc(100% + 8px);width:min(400px,94vw);background:#12151c;border:1px solid #2a3143;border-radius:12px;padding:14px;display:none;box-shadow:0 16px 44px rgba(0,0,0,.6);z-index:30}
.tvboxPop.open{display:block}
.tvboxPopTitle{font-size:14px;font-weight:600;color:#e5e7eb;margin-bottom:10px}
.tvboxRow{display:flex;align-items:center;gap:8px;margin-bottom:8px;flex-wrap:wrap}
.tvboxLbl{font-size:12px;color:#9ca3af;width:100%}
.tvboxRow code{flex:1;min-width:0;background:#0b0d12;border:1px solid #232936;border-radius:6px;padding:7px 9px;font-size:12px;color:#93c5fd;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.tvboxRow button{flex:none;border:none;background:#1d4ed8;color:#fff;border-radius:6px;padding:7px 12px;font-size:12px;cursor:pointer;transition:.15s}
.tvboxRow button:hover{background:#2563eb}
.tvboxHint{font-size:12px;color:#6b7280;line-height:1.6;margin-top:4px}
.wrap{max-width:1180px;margin:0 auto;padding:14px;display:flex;flex-direction:column;gap:14px}
.side{max-height:36vh;overflow:auto;padding-right:2px}
video{object-fit:contain}
@media(min-width:820px){
html,body{height:100%;overflow:hidden}
.wrap{position:fixed;top:46px;left:0;right:0;bottom:0;max-width:none;margin:0;padding:10px 12px;gap:12px;flex-direction:row;align-items:stretch}
.side{width:300px;flex:none;max-height:none;height:auto;overflow:auto}
.main{flex:1;min-width:0;display:flex;flex-direction:column}
.player-box{flex:1;min-height:0;aspect-ratio:auto;border-radius:8px}
.bar{flex:none;padding-top:8px}
}
.player-box{background:#000;border-radius:10px;overflow:hidden;aspect-ratio:16/9;position:relative}
video{width:100%;height:100%;display:block;background:#000}
.tip{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#fff;font-size:19px;font-weight:600;text-shadow:0 2px 8px rgba(0,0,0,.8);pointer-events:none;background:rgba(0,0,0,.35)}
.bigplay{position:absolute;inset:0;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,.45);color:#fff;font-size:64px;cursor:pointer;z-index:5;user-select:none}
.pctrl{position:absolute;right:10px;bottom:10px;display:flex;gap:8px;z-index:6}
.epgTab{position:absolute;right:10px;top:10px;z-index:6;border:none;border-radius:8px;background:rgba(0,0,0,.55);color:#fff;font-size:13px;padding:7px 11px;cursor:pointer;backdrop-filter:blur(4px);transition:.15s}
.epgTab:hover{background:rgba(0,0,0,.8)}
.epgPanel{position:absolute;right:0;top:0;bottom:0;width:min(320px,86%);background:rgba(13,16,23,.97);z-index:7;transform:translateX(105%);transition:transform .25s ease;display:flex;flex-direction:column;border-left:1px solid #232936}
.epgPanel.open{transform:translateX(0)}
.epgHead{display:flex;justify-content:space-between;align-items:center;padding:10px 14px;border-bottom:1px solid #1c2230;font-size:14px;font-weight:600;color:#e5e7eb;flex:none}
.epgHead button{background:none;border:none;color:#9ca3af;font-size:20px;cursor:pointer;line-height:1;padding:0 2px}
.epgHead button:hover{color:#fff}
.epgList{flex:1;overflow:auto;padding:4px 0}
.epgRow{display:flex;gap:10px;padding:8px 14px;font-size:13px;color:#9ca3af;border-bottom:1px solid rgba(255,255,255,.03)}
.epgRow .et{flex:none;color:#6b7280;font-variant-numeric:tabular-nums}
.epgRow.now{background:rgba(59,130,246,.14);color:#fff;border-left:3px solid #3b82f6}
.epgRow.now .et{color:#93c5fd}
.epgEmpty{padding:36px 16px;text-align:center;color:#6b7280;font-size:13px}
.bigplay{display:none !important}
.pctrl button{width:36px;height:36px;border:none;border-radius:8px;background:rgba(0,0,0,.55);color:#fff;font-size:16px;cursor:pointer;line-height:1;transition:.15s;backdrop-filter:blur(4px)}
.pctrl button:hover{background:rgba(0,0,0,.8);transform:scale(1.06)}
.pctrl button:active{transform:scale(.95)}
.bar{display:flex;align-items:center;gap:10px;font-size:13px;color:#9ca3af}
.bar .cur{color:#fff;font-weight:600;font-size:15px}
select{background:#171b24;color:#e5e7eb;border:1px solid #2a3140;border-radius:6px;padding:5px 8px;font-size:13px}
.grid{display:block}
.gbox{display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:8px;margin:2px 0 12px}
.ghead{display:flex;justify-content:space-between;align-items:center;padding:7px 2px;font-size:13px;font-weight:600;color:#9ca3af;cursor:pointer;user-select:none}
.ghead:hover{color:#d1d5db}
.ghead .gcount{color:#4b5563;font-weight:400;font-size:12px}
.ghead.closed{opacity:.55}
.ch{background:#171b24;border:1px solid #232936;color:#d1d5db;padding:10px 6px;border-radius:8px;font-size:13px;text-align:center;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;transition:.15s}
.ch:hover{border-color:#3b82f6;color:#fff}
.ch.on{background:#1d4ed8;border-color:#3b82f6;color:#fff}
.sec{font-size:13px;color:#6b7280;margin:2px 0 8px}
.empty{color:#6b7280;font-size:13px;padding:20px 0;text-align:center}
</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="tvboxPop" id="tvboxPop">
<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="tbLive">—</code><button id="tbLiveCopy">复制</button></div>
<div class="tvboxHint">TVBox「设置→配置地址」粘贴上面的配置地址即可,直播已内置;只想加直播时用下面的直播源地址粘贴到「直播」一栏。</div>
</div></div>
<div class="wrap">
<div class="side"><div class="sec">频道列表 <span style="color:#4b5563">点击切换</span></div><div class="grid" id="grid"><div class="empty">加载中…</div></div></div>
<div class="main">
<div class="player-box"><video id="v" playsinline></video><div class="tip" id="tip">选择频道开始观看</div><div class="bigplay" id="bigplay">▶</div><button class="epgTab" id="epgTab">📋 节目单</button><div class="epgPanel" id="epgPanel"><div class="epgHead"><span id="epgTitle">节目单</span><button id="epgClose" title="收起">✕</button></div><div class="epgList" id="epgList"><div class="epgEmpty">选择频道后查看节目单</div></div></div><div class="pctrl"><button id="btnPP" title="暂停/播放">⏸</button><button id="btnMute" title="静音/开启声音">🔊</button></div></div>
<div class="bar" style="margin-top:10px"><span class="cur" id="cur">未选择</span><span style="flex:1"></span>
<label>线路 <select id="lineSel" onchange="playLine(this.value)"></select></label></div>
</div>
</div>
<script src="/hls.min.js"></script><script src="/mpegts.min.js"></script><script>
var hls=null,mp=null,chs=[],curId=null;
var v=document.getElementById('v'),tip=document.getElementById('tip'),
grid=document.getElementById('grid'),sel=document.getElementById('lineSel'),
cur=document.getElementById('cur'),bigplay=document.getElementById('bigplay');
var API='/api/tvbox?live=';
function stopAll(){if(hls){hls.destroy();hls=null}if(mp){mp.destroy();mp=null}try{v.removeAttribute('src');v.load()}catch(e){}}
var loadTimer=null;
function startTick(){if(loadTimer)clearInterval(loadTimer);var t0=Date.now();
tip.style.display='flex';tip.textContent='加载中… 0.0s';
loadTimer=setInterval(function(){tip.textContent='加载中… '+((Date.now()-t0)/1000).toFixed(1)+'s'},100)}
function stopTick(){if(loadTimer){clearInterval(loadTimer);loadTimer=null}}
function playSrc(u,flv){
stopAll();
if(flv&&window.mpegts){try{mp=mpegts.createPlayer({type:'flv',isLive:true,url:u,liveBufferLatencyChasing:true});mp.attachMediaElement(v);mp.load()}catch(e){}}
else if(/\\.m3u8/.test(u)){ if(v.canPlayType('application/vnd.apple.mpegurl')){v.src=u}
else if(window.Hls&&Hls.isSupported()){hls=new Hls({maxBufferLength:10,manifestLoadingMaxRetry:2,levelLoadingMaxRetry:2,fragLoadingMaxRetry:3});
hls.loadSource(u);hls.attachMedia(v);
hls.on(Hls.Events.ERROR,function(e,d){if(d.fatal){if(d.type===Hls.ErrorTypes.NETWORK_ERROR){hls.startLoad()}else if(d.type===Hls.ErrorTypes.MEDIA_ERROR){hls.recoverMediaError()}else{nextLine()}}})}
}else if(/\\.flv/.test(u)&&window.mpegts){try{mp=mpegts.createPlayer({type:'flv',isLive:true,url:u});mp.attachMediaElement(v);mp.load()}catch(e){}}
var pr=v.play();
if(pr&&pr.catch)pr.catch(function(){v.muted=true;var pr2=v.play();if(pr2&&pr2.catch)pr2.catch(function(){bigplay.style.display='flex'})});
setTimeout(function(){if(v.readyState<2&&v.paused)tip.style.display='flex'},2500);
v.onplaying=function(){stopTick();tip.style.display='none'};
}
bigplay.addEventListener('click',function(){v.muted=false;bigplay.style.display='none';v.play().catch(function(){})});
v.addEventListener('click',function(){ if(v.muted){v.muted=false;bigplay.style.display='none'}; if(v.paused){ var pr=v.play(); if(pr&&pr.catch)pr.catch(function(){bigplay.style.display='flex'}) } else { v.pause() } });
var btnPP=document.getElementById('btnPP'),btnMute=document.getElementById('btnMute');
function syncCtrl(){
btnPP.textContent=v.paused?'▶':'⏸';
btnPP.title=v.paused?'播放':'暂停';
btnMute.textContent=v.muted?'🔇':'🔊';
btnMute.title=v.muted?'开启声音':'静音';
bigplay.style.display=v.paused?'flex':'none';
if(!v.paused) tip.style.display='none';
}
btnPP.addEventListener('click',function(e){e.stopPropagation();
if(v.paused){var pr=v.play();if(pr&&pr.catch)pr.catch(function(){})}else{v.pause()}
setTimeout(syncCtrl,60)});
btnMute.addEventListener('click',function(e){e.stopPropagation();
v.muted=!v.muted;syncCtrl()});
v.addEventListener('play',syncCtrl);
v.addEventListener('pause',syncCtrl);
v.addEventListener('volumechange',syncCtrl);
syncCtrl();
var epgTab=document.getElementById('epgTab'),epgPanel=document.getElementById('epgPanel'),
epgTitle=document.getElementById('epgTitle'),epgList=document.getElementById('epgList'),
epgClose=document.getElementById('epgClose');
var epgOpen=false;
function renderEpg(j){
if(!j||!j.has||!j.list||!j.list.length){epgList.innerHTML='<div class="epgEmpty">该台暂无节目单</div>';return}
var d=new Date(),hh=String(d.getHours()).padStart(2,'0'),mm=String(d.getMinutes()).padStart(2,'0'),nowHM=hh+mm;
epgList.innerHTML=j.list.map(function(p){
var isNow=nowHM>=p.s&&nowHM<p.e;
return '<div class="epgRow'+(isNow?' now':'')+'"><span class="et">'+p.s.slice(0,2)+':'+p.s.slice(2)+'</span><span class="et">'+p.e.slice(0,2)+':'+p.e.slice(2)+'</span><span class="etx">'+p.t+'</span></div>'
}).join('');
var nowRow=epgList.querySelector('.epgRow.now');
if(nowRow)nowRow.scrollIntoView({block:'center'});
}
function refreshEpg(){
if(!curId)return;
var nm=(chs.find(function(c){return String(c.id)===String(curId)})||{}).name||'';
epgTitle.textContent=nm+(nm?' · 节目单':'节目单');
epgList.innerHTML='<div class="epgEmpty">加载中…</div>';
fetch(API+'epg&name='+encodeURIComponent(nm)).then(function(r){return r.json()}).then(renderEpg).catch(function(){renderEpg(null)});
}
epgTab.addEventListener('click',function(e){e.stopPropagation();
epgOpen=true;epgPanel.classList.add('open');refreshEpg()});
epgClose.addEventListener('click',function(e){e.stopPropagation();
epgOpen=false;epgPanel.classList.remove('open')});
var tvboxBtn=document.getElementById('tvboxBtn'),tvboxPop=document.getElementById('tvboxPop');
var tbCfg=document.getElementById('tbCfg'),tbLive=document.getElementById('tbLive');
if(tbCfg)tbCfg.textContent=location.origin+'/api/tvbox';
if(tbLive)tbLive.textContent=location.origin+'/api/tvbox?live=txt';
function copyTxt(txt,btn,done){
var ok=function(){btn.textContent='已复制 ✓';setTimeout(function(){btn.textContent=done},1600)};
if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(txt).then(ok,function(){fallback()})}
else fallback();
function fallback(){var ta=document.createElement('textarea');ta.value=txt;ta.style.position='fixed';ta.style.opacity='0';
document.body.appendChild(ta);ta.select();try{document.execCommand('copy');ok()}catch(e){}
document.body.removeChild(ta)}
}
if(tvboxBtn){tvboxBtn.addEventListener('click',function(e){e.stopPropagation();
tvboxPop.classList.toggle('open')});
document.getElementById('tbCfgCopy').addEventListener('click',function(e){e.stopPropagation();copyTxt(tbCfg.textContent,this,'复制')});
document.getElementById('tbLiveCopy').addEventListener('click',function(e){e.stopPropagation();copyTxt(tbLive.textContent,this,'复制')});
tvboxPop.addEventListener('click',function(e){e.stopPropagation()});
document.addEventListener('click',function(){tvboxPop.classList.remove('open')});
}
function nextLine(){if(sel.options.length&&+sel.value<sel.options.length-1){sel.value=+sel.value+1;playLine(sel.value)}else if(sel.options.length){setTimeout(function(){sel.value=0;playLine(0)},2000)}}
window.nextLine=nextLine;
function playLine(p){
if(!curId)return;
fetch(API+'m3u8&id='+curId+'&p='+p).then(function(r){return r.json()}).then(function(j){
if(j.url){cur.textContent=(chs.find(function(c){return c.id==curId})||{}).name||'';if(epgOpen)refreshEpg();playSrc(j.url,!!j.flv)}
else{nextLine()}
}).catch(function(){nextLine()});
}
window.playLine=playLine;
function pick(id,auto){
curId=id;
if(!auto){v.muted=false;bigplay.style.display='none'}
document.querySelectorAll('.ch.on').forEach(function(e){e.classList.remove('on')});
var el=document.querySelector('.ch[data-id="'+id+'"]');if(el)el.classList.add('on');
sel.innerHTML='';startTick();
if(!auto&&window.innerWidth<820){var pb=document.querySelector('.player-box');if(pb)pb.scrollIntoView({behavior:'smooth',block:'center'})}
fetch(API+'lines&id='+id).then(function(r){return r.json()}).then(function(j){
(j.lines||[]).forEach(function(l,i){var o=document.createElement('option');o.value=i;o.textContent=l.name;sel.appendChild(o)});
if((j.lines||[]).length){sel.value=0;playLine(0)}else{setTimeout(function(){pick(curId,1)},3000)}
}).catch(function(){setTimeout(function(){pick(curId,1)},3000)});
}
function loadChs(retry){fetch(API+'channels').then(function(r){return r.json()}).then(function(j){
chs=j.list||[];
if(!chs.length){if(retry<3){grid.innerHTML='<div class="empty">加载中…</div>';setTimeout(function(){loadChs(retry+1)},3000)}else{grid.innerHTML='<div class="empty">暂无频道</div>'}return}
grid.innerHTML='';
var order=['香港','澳门','台湾'],groups={};
chs.forEach(function(c){var r=c.region||'其他';(groups[r]=groups[r]||[]).push(c)});
order.concat(Object.keys(groups).filter(function(k){return order.indexOf(k)<0})).forEach(function(g){
if(!groups[g]||!groups[g].length)return;
var h=document.createElement('div');h.className='ghead';
h.innerHTML='<span>'+g+'</span><span class="gcount">'+groups[g].length+' 个 ▾</span>';
var box=document.createElement('div');box.className='gbox';
groups[g].forEach(function(c){var d=document.createElement('div');d.className='ch';d.dataset.id=c.id;d.textContent=c.name;
d.onclick=function(){pick(c.id)};box.appendChild(d)});
h.onclick=function(){var open=box.style.display!=='none';box.style.display=open?'none':'grid';h.classList.toggle('closed',open)};
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];
if(DEF){pick(DEF.id,1)}
}).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);
</script></body></html>`;
return new Response(html,{headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}
function livePrefetch(list){
try{if(typeof globalThis!=="undefined"&&globalThis.__livePf)return;globalThis.__livePf=1;
const ids=(list||[]).slice(0,10).map(c=>c.id).filter(Boolean);let i=0;
const step=()=>{if(i>=ids.length){console.log("[LIVE-PF] done",i);return}
const id=ids[i++];
liveLines(id).then(ls=>{if(ls&&ls.length)return liveResolve(id,0)}).catch(()=>{})
.finally(()=>setTimeout(step,900))};
setTimeout(step,1200)}catch(e){console.log("[LIVE-PF-ERR]",e&&e.message)}}
async function LIVE(action,e){
try{
if(action==="page")return livePage();
if(action==="channels"){const l=await liveChannels();livePrefetch(l);return liveJ({list:l})}
const q=new URL(e.url).searchParams;
if(action==="lines"){const id=(q.get("id")||"").replace(/[^\d]/g,"");if(!id)return liveJ({lines:[]});
const lines=await liveLines(id);return liveJ({lines:lines.map(l=>({name:l.name}))})}
if(action==="epg"){const nm=q.get("name")||"";
try{return liveJ(await liveEpgFor(nm))}catch(e){console.log("[LIVE-EPG-ERR]",e&&e.message);
return liveJ({has:false,list:[],err:String(e&&e.message||e)})}}
if(action==="m3u8"){const id=(q.get("id")||"").replace(/[^\d]/g,"");const p=Math.max(0,parseInt(q.get("p")||"0",10)||0);
if(!id)return liveJ({url:""});
const fu=await liveResolve(id,p);
if(/\.flv($|\?)/i.test(fu))return liveJ({url:"/api/tvbox?live=ts&b="+liveB64e(fu),flv:1});
const txt=await liveText(fu,10000);
if(!/#EXTM3U/.test(txt))return liveJ({url:""});
const out=txt.split("\\n").map(line=>{const t=line.trim();if(!t||t[0]==="#")return line;
try{const abs=new URL(t,fu);if(!LIVE_HOSTS.test(abs.hostname))return line;
return"/api/tvbox?live=ts&b="+liveB64e(abs.toString())}catch(err){return line}}).join("\\n");
return new Response(out,{headers:{"Content-Type":"application/vnd.apple.mpegurl","Cache-Control":"no-store"}})}
if(action==="ts"){const b=q.get("b")||"";let uu;try{uu=new URL(liveB64d(b))}catch(err){return new Response("bad",{status:400})}
if(!/^https?:$/.test(uu.protocol)||!LIVE_HOSTS.test(uu.hostname))return new Response("forbidden",{status:403});
const isFlv=/\.flv($|\?)/i.test(uu.href);
const ctl=new AbortController();const tm=setTimeout(()=>ctl.abort(),isFlv?3600e3:20000);
try{const r=await fetch(uu.toString(),{redirect:"follow",signal:ctl.signal,headers:{"User-Agent":LIVE_UA}});
const hs={"Content-Type":r.headers.get("content-type")||"video/mp2t","Access-Control-Allow-Origin":"*","Cache-Control":"no-store"};
return new Response(r.body,{status:r.status,headers:hs})}finally{clearTimeout(tm)}}
if(action==="ch"){const id=(q.get("id")||"").replace(/[^\d]/g,"");const p=Math.max(0,parseInt(q.get("p")||"0",10)||0);
if(!id)return new Response("bad",{status:400});
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);
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();
const out=["港澳台直播,#genre#"];
for(const c of chs){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=2")}
return new Response(out.join("\n")+"\n",{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}})}
return new Response("not found",{status:404})
}catch(x){console.log("[LIVE-ERR]",x&&x.message);
if(action==="m3u8")return liveJ({url:"",err:String(x&&x.message||x)});
if(action==="lines"||action==="channels")return liveJ({list:[],lines:[]});
if(action==="ch")return new Response("resolve failed",{status:502});
if(action==="txt")return new Response("港澳台直播,#genre#\n",{headers:{"Content-Type":"text/plain; charset=utf-8"}});
return new Response("error",{status:500})}}
/* ==== LIVE END ==== */
try{if(typeof module!=="undefined"&&module.exports){module.exports={LIVE:LIVE}}}catch(e){}