File size: 18,280 Bytes
abfc954 7753dac 7f34460 abfc954 7f34460 abfc954 7f34460 abfc954 7f34460 abfc954 7f34460 abfc954 7f34460 abfc954 7753dac abfc954 7f34460 abfc954 7f34460 abfc954 7f34460 7753dac 7f34460 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 | 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() |