170 lines
12 KiB
JavaScript
170 lines
12 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)}}
|
||
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){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:1100px;margin:0 auto;padding:14px;display:flex;flex-direction:column;gap:14px}
|
||
@media(min-width:820px){.wrap{flex-direction:row}.side{width:300px;flex:none;max-height:78vh;overflow:auto}.main{flex:1}}
|
||
.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)}
|
||
.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:grid;grid-template-columns:repeat(auto-fill,minmax(104px,1fr));gap:8px}
|
||
.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="main">
|
||
<div class="player-box"><video id="v" playsinline></video><div class="tip" id="tip">选择频道开始观看</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 class="side"><div class="sec">频道列表</div><div class="grid" id="grid"><div class="empty">加载中…</div></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');
|
||
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){}}
|
||
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){}}
|
||
v.play().catch(function(){});
|
||
setTimeout(function(){if(v.readyState<2)tip.style.display='flex'},2500);
|
||
v.onplaying=function(){tip.style.display='none'};
|
||
}
|
||
function nextLine(){if(sel.options.length&&+sel.value<sel.options.length-1){sel.value=+sel.value+1;playLine(sel.value)}else{tip.textContent='所有线路暂不可用';tip.style.display='flex'}}
|
||
window.nextLine=nextLine;
|
||
function playLine(p){
|
||
if(!curId)return;
|
||
tip.textContent='加载中…';tip.style.display='flex';
|
||
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){
|
||
curId=id;
|
||
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='';tip.textContent='加载线路…';tip.style.display='flex';
|
||
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{tip.textContent='暂无可用线路'}
|
||
}).catch(function(){tip.textContent='线路解析失败'});
|
||
}
|
||
fetch(API+'channels').then(function(r){return r.json()}).then(function(j){
|
||
chs=j.list||[];
|
||
if(!chs.length){grid.innerHTML='<div class="empty">暂无频道</div>';return}
|
||
grid.innerHTML='';
|
||
chs.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)};grid.appendChild(d)});
|
||
}).catch(function(){grid.innerHTML='<div class="empty">加载失败,请刷新</div>'});
|
||
</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)}}
|
||
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:[]});
|
||
return new Response("error",{status:500})}}
|
||
/* ==== LIVE END ==== */
|