Update app.py
Browse files12345678 unmodified lines161718192021222324252627282930312 unmodified lines34353637383940414243444546474849505152535455565758594 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051065 unmodified lines112113114115116117118119120121import osimport reimport httpxfrom fastapi import FastAPI, HTTPException, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse8 unmodified lines)HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36","Accept": "*/*","Accept-Language": "en-US,en;q=0.9",}@app.get("/embed/{channel_id}", response_class=HTMLResponse)async def serve_player_page(channel_id: str):space_id = os.getenv("SPACE_ID", "futbolx-live")space_domain = f"https://{space_id}.hf.space"manifest_proxy_url = f"{space_domain}/stream-data/{channel_id}"html_content = f"""<!DOCTYPE html>2 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{channel_id.upper()}</title><script src="https://cdn.jsdelivr.net/npm/clappr@latest/dist/clappr.min.js"></script><style>* {{ margin: 0; padding: 0; box-sizing: border-box; }}html, body, #player-container {{ width: 100%; height: 100%; background: #000; overflow: hidden; }}</style></head><body><div id="player-container"></div><script>var player = new Clappr.Player({{source: "{manifest_proxy_url}",parentId: "#player-container",autoPlay: true,mimeType: "application/x-mpegURL",width: "100%",height: "100%",crossOrigin: "anonymous",mediacontrol: {{ seekbar: "#00ffcc", buttons: "#00ffcc" }}}});</script></body>4 unmodified lines@app.get("/stream-data/{channel_id}")async def get_manifest_stream(channel_id: str):target_base = os.getenv("TARGET_DOMAIN", "https://wc.ppvtv.top")embed_url = f"{target_base}/embed/{channel_id}"request_headers = HEADERS.copy()request_headers["Referer"] = f"{target_base}/"async with httpx.AsyncClient(follow_redirects=True) as client:try:# 1. Fetch source page layoutresponse = await client.get(embed_url, headers=request_headers, timeout=10.0)if response.status_code != 200:fallback_base = "https://ppvtv.top"embed_url = f"{fallback_base}/embed/{channel_id}"request_headers["Referer"] = f"{fallback_base}/"response = await client.get(embed_url, headers=request_headers, timeout=10.0)html = response.text# 2. Extract current streaming token arraymatch = re.search(r'var\s+STREAMS\s*=\s*\["([^"]+)"\]', html)if not match:raise HTTPException(status_code=404, detail="Stream token pattern not found.")relative_stream_path = match.group(1)absolute_stream_url = f"{target_base}{relative_stream_path}"# 3. Request the stream from media serversstream_response = await client.get(absolute_stream_url, headers=request_headers, timeout=12.0)manifest_content = stream_response.text# 4. Handle relative paths inside the manifest text filebase_stream_dir = absolute_stream_url.rsplit('/', 1)[0] + '/'fixed_manifest = []for line in manifest_content.splitlines():if line.rstrip() and not line.startswith("#") and not line.startswith("http"):fixed_manifest.append(f"{base_stream_dir}{line}")else:fixed_manifest.append(line)5 unmodified linesmedia_type="application/vnd.apple.mpegurl",headers={"Access-Control-Allow-Origin": "*","Cache-Control": "no-cache"},status_code=200)except Exception as e:raise HTTPException(status_code=500, detail=f"Proxy error: {str(e)}")12345678 unmodified lines161718192021222324252627282930312 unmodified lines3435363738394041424344454647484950515253545556575859604 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191205 unmodified lines126127128129130131132133134135136137138import osimport reimport httpxfrom fastapi import FastAPI, HTTPException, Response, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse8 unmodified lines)HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8","Accept-Language": "en-US,en;q=0.9",}@app.get("/embed/{channel_id}", response_class=HTMLResponse)async def serve_player_page(channel_id: str, request: Request):# DYNAMIC FIX: Automatically detects the exact URL/domain you are currently visitingbase_url = str(request.base_url).rstrip('/')manifest_proxy_url = f"{base_url}/stream-data/{channel_id}"html_content = f"""<!DOCTYPE html>2 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{channel_id.upper()}</title><script src="https://cdn.jsdelivr.net/npm/@clappr/player@latest/dist/clappr.min.js"></script><style>* {{ margin: 0; padding: 0; box-sizing: border-box; }}html, body, #player-container {{ width: 100%; height: 100%; background: #000; overflow: hidden; }}</style></head><body><div id="player-container"></div><script>document.addEventListener("DOMContentLoaded", function() {{var player = new Clappr.Player({{source: "{manifest_proxy_url}",parentId: "#player-container",autoPlay: true,mimeType: "application/x-mpegURL",width: "100%",height: "100%",crossOrigin: "anonymous",mediacontrol: {{ seekbar: "#00ffcc", buttons: "#00ffcc" }}}});}});</script></body>4 unmodified lines@app.get("/stream-data/{channel_id}")async def get_manifest_stream(channel_id: str):target_base = os.getenv("TARGET_DOMAIN", "https://wc.ppvtv.top").rstrip('/')embed_url = f"{target_base}/embed/{channel_id}"request_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36","Accept": "*/*","Referer": f"{target_base}/","Origin": target_base,"Connection": "keep-alive"}async with httpx.AsyncClient(follow_redirects=True, timeout=15.0) as client:try:# 1. Fetch source pageresponse = await client.get(embed_url, headers=request_headers)# Emergency Backup Fallbackif response.status_code != 200:target_base = "https://ppvtv.top"embed_url = f"{target_base}/embed/{channel_id}"request_headers["Referer"] = f"{target_base}/"request_headers["Origin"] = target_baseresponse = await client.get(embed_url, headers=request_headers)if response.status_code != 200:raise HTTPException(status_code=502, detail=f"Source site down or blocked. Code: {response.status_code}")html = response.text# 2. Extract current streaming playlist token arraymatch = re.search(r'var\s+STREAMS\s*=\s*\[\s*["\']([^"\']+)["\']\s*\]', html)if not match:raise HTTPException(status_code=404, detail="Token signature pattern not found on target host.")relative_stream_path = match.group(1)absolute_stream_url = f"{target_base}{relative_stream_path}"# 3. Pull playlist data from streaming serversstream_response = await client.get(absolute_stream_url, headers=request_headers)if stream_response.status_code != 200:raise HTTPException(status_code=502, detail="Failed to fetch playlist array file from media server.")manifest_content = stream_response.text# 4. Correct relative internal data chunk pathwaysbase_stream_dir = absolute_stream_url.rsplit('/', 1)[0] + '/'fixed_manifest = []for line in manifest_content.splitlines():if line.strip() and not line.startswith("#") and not line.startswith("http"):fixed_manifest.append(f"{base_stream_dir}{line}")else:fixed_manifest.append(line)5 unmodified linesmedia_type="application/vnd.apple.mpegurl",headers={"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "GET, OPTIONS","Cache-Control": "no-cache, no-store, must-revalidate"},status_code=200)except httpx.RequestError as exc:raise HTTPException(status_code=504, detail=f"Target proxy timeout connection error: {str(exc)}")except Exception as e:raise HTTPException(status_code=500, detail=str(e))
app.py+54-37