222 lines
16 KiB
JavaScript
222 lines
16 KiB
JavaScript
/* ==== 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();
|
||
async function liveText(u,ms){const c=new AbortController();const t=setTimeout(()=>c.abort(),ms||15000);
|
||
try{const r=await fetch(u,{redirect:"follow",signal:c.signal,headers:{"User-Agent":LIVE_UA,"Referer":LIVE_UP+"/"}});return await r.text()}finally{clearTimeout(t)}}
|
||
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;
|
||
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||[]}
|
||
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<20000)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}
|
||
.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:#6b7280;font-size:14px;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}
|
||
.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></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></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(){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'}});
|
||
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||'';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"}})}
|
||
async function LIVE(action,e){
|
||
try{
|
||
if(action==="page")return livePage();
|
||
if(action==="channels")return liveJ({list:await liveChannels()});
|
||
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==="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 ==== */
|