import asyncio import os import re import urllib.parse from typing import Dict, Optional, Tuple import gradio as gr import httpx from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.cors import CORSMiddleware from starlette.requests import Request from starlette.responses import JSONResponse, Response, StreamingResponse from starlette.routing import Route try: import spaces @spaces.GPU def _sf_gpu_ready(): return "Study Farm Stream Edge Online" except Exception: def _sf_gpu_ready(): return "Study Farm Stream Edge Online" FIXED_UA = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/125.0.0.0 Safari/537.36" ) TESTWAVE_ORIGIN_HOSTS = [ "amorphous-cheetah-ejv65cqsx5x8j7xip061qmst.herokudns.com", "75.2.43.161", "99.83.217.1", "15.197.129.158", "76.223.11.49", ] CORS_HEADERS = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS", "Access-Control-Allow-Headers": "*", "Access-Control-Expose-Headers": "*", } PASS_HEADERS = ( "content-type", "content-length", "content-range", "accept-ranges", "last-modified", "etag", ) def get_public_base_origin(request: Request) -> str: fwd_host = request.headers.get("x-forwarded-host", "").split(",")[0].strip() host = fwd_host or request.headers.get("host", "").split(",")[0].strip() if not host: return "" fwd_proto = request.headers.get("x-forwarded-proto", "").split(",")[0].strip() if not fwd_proto: fwd_proto = ( "http" if host.startswith("localhost") or host.startswith("127.0.0.1") else "https" ) return f"{fwd_proto}://{host}" def is_testwave_host(hostname: str) -> bool: h = (hostname or "").lower() return h == "testwave.cc" or h.endswith(".testwave.cc") def parse_raw_http_headers(header_bytes: bytes) -> Tuple[int, Dict[str, str]]: text = header_bytes.decode("latin-1", errors="replace") lines = text.split("\r\n") status = 502 if lines: m = re.match(r"^HTTP/\d\.\d\s+(\d{3})", lines[0]) if m: status = int(m.group(1)) headers: Dict[str, str] = {} for line in lines[1:]: if ":" in line: k, v = line.split(":", 1) key = k.strip().lower() val = v.strip() if key: headers[key] = val return status, headers async def open_testwave_tcp( raw_url: str, method: str, range_header: Optional[str], redirect_depth: int = 0, ) -> Optional[ Tuple[int, Dict[str, str], bytes, asyncio.StreamReader, asyncio.StreamWriter] ]: parsed = urllib.parse.urlsplit(raw_url) target_host = parsed.netloc path_with_query = (parsed.path or "/") + (f"?{parsed.query}" if parsed.query else "") req_lines = [ f"{'HEAD' if method == 'HEAD' else 'GET'} {path_with_query} HTTP/1.0", f"Host: {target_host}", "Referer: https://stream.aryavidya.cc/", "Connection: close", ] if range_header: req_lines.append(f"Range: {range_header}") raw_req = ("\r\n".join(req_lines) + "\r\n\r\n").encode("latin-1") for origin_host in TESTWAVE_ORIGIN_HOSTS: writer: Optional[asyncio.StreamWriter] = None try: reader, writer = await asyncio.wait_for( asyncio.open_connection(origin_host, 80), timeout=12.0 ) writer.write(raw_req) await writer.drain() buf = bytearray() sep_idx = -1 while sep_idx == -1: chunk = await asyncio.wait_for(reader.read(8192), timeout=15.0) if not chunk: break buf.extend(chunk) sep_idx = buf.find(b"\r\n\r\n") if len(buf) > 32768 and sep_idx == -1: break if sep_idx == -1: writer.close() continue status, headers = parse_raw_http_headers(bytes(buf[:sep_idx])) leftover = bytes(buf[sep_idx + 4 :]) if ( status in (301, 302, 303, 307, 308) and headers.get("location") and redirect_depth < 3 ): next_url = urllib.parse.urljoin(raw_url, headers["location"]) writer.close() return await open_testwave_tcp( next_url, method, range_header, redirect_depth + 1 ) if status in (200, 206): return status, headers, leftover, reader, writer writer.close() except Exception: if writer is not None: try: writer.close() except Exception: pass return None def rewrite_hls_playlist(text: str, raw_url: str, proxy_prefix: str) -> str: parent_parsed = urllib.parse.urlsplit(raw_url) parent_qs = urllib.parse.parse_qsl(parent_parsed.query, keep_blank_values=True) def merge_and_proxy(target_str: str) -> str: try: abs_target = urllib.parse.urljoin(raw_url, target_str) seg_parsed = urllib.parse.urlsplit(abs_target) seg_params = urllib.parse.parse_qsl(seg_parsed.query, keep_blank_values=True) existing_keys = {k for k, _ in seg_params} for pk, pv in parent_qs: if pk.lower() != "start" and pk not in existing_keys: seg_params.append((pk, pv)) new_query = urllib.parse.urlencode(seg_params) final_seg = urllib.parse.urlunsplit( ( seg_parsed.scheme, seg_parsed.netloc, seg_parsed.path, new_query, seg_parsed.fragment, ) ) return f"{proxy_prefix}?url={urllib.parse.quote(final_seg, safe='')}" except Exception: return target_str out_lines = [] for line in text.split("\n"): trimmed = line.strip() if not trimmed: out_lines.append(line) continue if trimmed.startswith("#"): if 'URI="' in trimmed: out_lines.append( re.sub( r'URI="([^"]+)"', lambda m: f'URI="{merge_and_proxy(m.group(1))}"', line, ) ) else: out_lines.append(line) continue out_lines.append(merge_and_proxy(trimmed)) result = "\n".join(out_lines) if "#EXT-X-ENDLIST" not in result: result += "\n#EXT-X-ENDLIST\n" return result async def health_endpoint(request: Request): if request.method == "OPTIONS": return Response(status_code=204, headers=CORS_HEADERS) return JSONResponse( { "status": "ok", "service": "study-farm-stream-edge", "endpoints": ["/api/stream-proxy?url=...", "/proxy?url=..."], }, headers=CORS_HEADERS, ) async def stream_proxy_endpoint(request: Request): if request.method == "OPTIONS": return Response(status_code=204, headers=CORS_HEADERS) raw_url = (request.query_params.get("url") or "").strip() if not raw_url or not ( raw_url.startswith("http://") or raw_url.startswith("https://") ): return Response( content="Invalid or missing target URL", status_code=400, media_type="text/plain", headers=CORS_HEADERS, ) parsed = urllib.parse.urlsplit(raw_url) method = "HEAD" if request.method == "HEAD" else "GET" range_header = request.headers.get("range") lower_url = parsed.path.lower() # 1. Try ultra-fast direct TCP origin socket for *.testwave.cc tcp_conn = None if is_testwave_host(parsed.hostname or ""): tcp_conn = await open_testwave_tcp(raw_url, method, range_header) if tcp_conn is not None: status, up_headers, leftover, reader, writer = tcp_conn content_type = up_headers.get("content-type", "").lower() content_length = int(up_headers.get("content-length", "0") or "0") has_range = ("content-range" in up_headers) or (status == 206) is_binary = ( content_type.startswith(("video/", "audio/", "image/")) or lower_url.endswith( (".mp4", ".jpeg", ".jpg", ".png", ".ts", ".m4s", ".aac") ) ) is_potential_playlist = ( method != "HEAD" and not is_binary and not has_range and ( (0 < content_length < 524288) or ( content_length == 0 and (lower_url.endswith(".m3u8") or lower_url.endswith(".docx")) ) ) and ( lower_url.endswith((".m3u8", ".docx", ".pdf")) or "mpegurl" in content_type ) ) if is_potential_playlist: try: rest = await asyncio.wait_for(reader.read(), timeout=20.0) body = leftover + rest finally: try: writer.close() except Exception: pass if body.lstrip().startswith(b"#EXTM3U"): public_base = get_public_base_origin(request) proxy_prefix = ( f"{public_base}/api/stream-proxy" if public_base else "/api/stream-proxy" ) rewritten = rewrite_hls_playlist( body.decode("utf-8", errors="replace"), raw_url, proxy_prefix ) return Response( content=rewritten, status_code=200, media_type="application/vnd.apple.mpegurl", headers={ **CORS_HEADERS, "Cache-Control": "public, max-age=86400", }, ) out_headers = {h: up_headers[h] for h in PASS_HEADERS if h in up_headers} if lower_url.endswith((".pdf", ".ts", ".m4s")): out_headers["content-type"] = "video/mp2t" out_headers["Cache-Control"] = "public, max-age=604800, immutable" out_headers.update(CORS_HEADERS) return Response(content=body, status_code=status, headers=out_headers) out_headers = {h: up_headers[h] for h in PASS_HEADERS if h in up_headers} if lower_url.endswith((".pdf", ".ts", ".m4s")): out_headers["content-type"] = "video/mp2t" out_headers["Cache-Control"] = "public, max-age=604800, immutable" out_headers.update(CORS_HEADERS) if method == "HEAD": try: writer.close() except Exception: pass return Response(status_code=status, headers=out_headers) async def tcp_stream(): try: if leftover: yield leftover while True: if await request.is_disconnected(): break chunk = await reader.read(65536) if not chunk: break yield chunk finally: try: writer.close() except Exception: pass return StreamingResponse(tcp_stream(), status_code=status, headers=out_headers) # 2. HTTPX async fallback for any non-testwave CDN or direct HTTPS URLs forward_headers = ( {"Referer": "https://stream.aryavidya.cc/"} if is_testwave_host(parsed.hostname or "") else { "Referer": "https://stream.aryavidya.cc/", "Origin": "https://stream.aryavidya.cc", "User-Agent": FIXED_UA, } ) if range_header: forward_headers["Range"] = range_header client = httpx.AsyncClient(follow_redirects=True, timeout=30.0) try: req_up = client.build_request(method, raw_url, headers=forward_headers) upstream = await client.send(req_up, stream=True) except Exception as exc: await client.aclose() return Response( content=f"Stream proxy error: {exc}", status_code=502, media_type="text/plain", headers=CORS_HEADERS, ) if upstream.status_code not in (200, 206): st = upstream.status_code await upstream.aclose() await client.aclose() return Response( content=f"Upstream CDN returned {st}", status_code=st, media_type="text/plain", headers=CORS_HEADERS, ) up_headers = {k.lower(): v for k, v in upstream.headers.items()} content_type = up_headers.get("content-type", "").lower() content_length = int(up_headers.get("content-length", "0") or "0") has_range = ("content-range" in up_headers) or (upstream.status_code == 206) is_binary = ( content_type.startswith(("video/", "audio/", "image/")) or lower_url.endswith((".mp4", ".jpeg", ".jpg", ".png", ".ts", ".m4s", ".aac")) ) is_potential_playlist = ( method != "HEAD" and not is_binary and not has_range and ( (0 < content_length < 524288) or ( content_length == 0 and (lower_url.endswith(".m3u8") or lower_url.endswith(".docx")) ) ) and ( lower_url.endswith((".m3u8", ".docx", ".pdf")) or "mpegurl" in content_type ) ) if is_potential_playlist: try: body = await upstream.aread() finally: await upstream.aclose() await client.aclose() if body.lstrip().startswith(b"#EXTM3U"): public_base = get_public_base_origin(request) proxy_prefix = ( f"{public_base}/api/stream-proxy" if public_base else "/api/stream-proxy" ) rewritten = rewrite_hls_playlist( body.decode("utf-8", errors="replace"), raw_url, proxy_prefix ) return Response( content=rewritten, status_code=200, media_type="application/vnd.apple.mpegurl", headers={ **CORS_HEADERS, "Cache-Control": "public, max-age=86400", }, ) out_headers = {h: up_headers[h] for h in PASS_HEADERS if h in up_headers} if lower_url.endswith((".pdf", ".ts", ".m4s")): out_headers["content-type"] = "video/mp2t" out_headers["Cache-Control"] = "public, max-age=604800, immutable" out_headers.update(CORS_HEADERS) return Response( content=body, status_code=upstream.status_code, headers=out_headers ) out_headers = {h: up_headers[h] for h in PASS_HEADERS if h in up_headers} if lower_url.endswith((".pdf", ".ts", ".m4s")): out_headers["content-type"] = "video/mp2t" out_headers["Cache-Control"] = "public, max-age=604800, immutable" out_headers.update(CORS_HEADERS) if method == "HEAD": await upstream.aclose() await client.aclose() return Response(status_code=upstream.status_code, headers=out_headers) async def httpx_stream(): try: async for chunk in upstream.aiter_bytes(65536): if await request.is_disconnected(): break yield chunk finally: await upstream.aclose() await client.aclose() return StreamingResponse( httpx_stream(), status_code=upstream.status_code, headers=out_headers ) api_subapp = Starlette( routes=[ Route("/health", endpoint=health_endpoint, methods=["GET", "OPTIONS"]), Route( "/api/stream-proxy", endpoint=stream_proxy_endpoint, methods=["GET", "HEAD", "OPTIONS"], ), Route( "/proxy", endpoint=stream_proxy_endpoint, methods=["GET", "HEAD", "OPTIONS"], ), ], middleware=[ Middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "HEAD", "OPTIONS"], allow_headers=["*"], expose_headers=["*"], ) ], ) def _patch_asgi_class(cls): if cls is None or getattr(cls, "_sf_patched", False): return orig_call = cls.__call__ async def _sf_call(self, scope, receive, send): if scope.get("type") == "http" and scope.get("path") in ( "/health", "/api/stream-proxy", "/proxy", ): await api_subapp(scope, receive, send) return await orig_call(self, scope, receive, send) cls.__call__ = _sf_call cls._sf_patched = True try: import gradio.routes as _gr_routes _patch_asgi_class(getattr(_gr_routes, "App", None)) except Exception: pass with gr.Blocks() as demo: gr.Markdown( "# Study Farm Stream Edge\n" "High-speed streaming edge service is active.\n\n" "- Health check: `/health`\n" "- Stream endpoint: `/api/stream-proxy?url=...`" ) status_out = gr.Textbox(value="Online", label="Status", interactive=False) check_btn = gr.Button("Verify Edge") check_btn.click(fn=_sf_gpu_ready, inputs=None, outputs=status_out) if __name__ == "__main__": launched = demo.launch( server_name="0.0.0.0", prevent_thread_lock=True, ) fastapi_app = getattr(demo, "app", None) or ( launched[0] if isinstance(launched, tuple) and len(launched) > 0 else None ) if fastapi_app is not None: _patch_asgi_class(type(fastapi_app)) demo.block_thread()