Update app.py
Browse files6 unmodified lines789101112132 unmodified lines161718192021222324252627282930313233343536372 unmodified lines4041424344454647484950515253545556575859606162633 unmodified lines676869707172735 unmodified lines7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271286 unmodified linesapp = FastAPI()# Enable CORS so your streaming data loads cleanly across different subdomainsapp.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# Standard browser headers to ensure the remote host responds normallyHEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",}@app.get("/embed/{channel_id}", response_class=HTMLResponse)async def serve_player_page(channel_id: str):"""Renders the HTML video player wrapper.Example: Hitting /embed/hd1 dynamically configures Clappr to pull from /stream-data/hd1"""# Auto-detect your Hugging Face Space domain layout dynamicallyspace_id = os.getenv("SPACE_ID", "futbolx-live")space_domain = f"https://{space_id}.hf.space"# Secure stream source url pointing directly to our background parsing agentmanifest_proxy_url = f"{space_domain}/stream-data/{channel_id}"html_content = f"""2 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Futbol-X Live Stream - {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 {{ width: 100%; height: 100%; background: #000; overflow: hidden; font-family: sans-serif; }}#layout-container {{ display: flex; flex-direction: column; width: 100%; height: 100%; }}#my-ad-banner {{ height: 50px; background: #111; color: #00ffcc; display: flex; align-items: center; justify-content: center; font-size: 0.85rem; border-bottom: 1px solid #222; font-weight: bold; }}#player-container {{ flex: 1; background: #000; }}</style></head><body><div id="layout-container"><!-- Replace this placeholder text with your custom ad provider scripts if needed --><div id="my-ad-banner">✨ FUTBOL-X PREMIUM MEDIA PLAYER SLOT ✨</div><!-- Clean Video Canvas --><div id="player-container"></div></div><script>var player = new Clappr.Player({{3 unmodified linesmimeType: "application/x-mpegURL",width: "100%",height: "100%",actualLiveTime: true,mediacontrol: {{ seekbar: "#00ffcc", buttons: "#00ffcc" }}}});</script>5 unmodified lines@app.get("/stream-data/{channel_id}")async def get_manifest_stream(channel_id: str):"""Background proxy worker. Fetches the page, strips tracking pixels and popunders,isolates the streaming path array variable, and serves the underlying stream manifest."""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() as client:try:# 1. Attempt to pull from primary target clusterresponse = await client.get(embed_url, headers=request_headers, timeout=8.0)# 2. Check for emergency domain redirection fallbackif 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=8.0)html = response.text# 3. Match the raw target stream javascript declaration: var STREAMS = ["/stream/..."];match = re.search(r'var\s+STREAMS\s*=\s*\["([^"]+)"\]', html)if not match:raise HTTPException(status_code=404, detail=f"Active stream profile not resolved for channel: {channel_id}")relative_stream_path = match.group(1)absolute_stream_url = f"{target_base}{relative_stream_path}"# 4. Fetch the clean, active stream manifest payloadstream_response = await client.get(absolute_stream_url, headers=request_headers, timeout=10.0)return Response(content=stream_response.content,media_type="application/x-mpegURL",status_code=stream_response.status_code)except Exception as e:raise HTTPException(status_code=500, detail=f"Streaming agent runtime fault: {str(e)}")if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)6 unmodified lines7891011122 unmodified lines151617181920212223242526272829302 unmodified lines333435363738394041424344454647483 unmodified lines525354555657585 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201216 unmodified linesapp = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)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"""2 unmodified lines<head><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({{3 unmodified linesmimeType: "application/x-mpegURL",width: "100%",height: "100%",crossOrigin: "anonymous",mediacontrol: {{ seekbar: "#00ffcc", buttons: "#00ffcc" }}}});</script>5 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)clean_payload = "\n".join(fixed_manifest)return Response(content=clean_payload,media_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)}")
app.py+37-44