Spaces:
Running
Running
v12.0.0: absolute proxy URLs + proxy engine v2 (Range/HEAD/Origin/sniff) + PlayBox proxied + Movies4u m3u8 validation + proxied_url fallback on every stream
Browse files123456789101123456789101112131415161718192021227 unmodified lines303132333435361 unmodified line383940324142434498 unmodified lines14314414513714614714814915010 unmodified lines1611621631641651661671681 unmodified line17017117216116216317317417517617717817918018118218318416516616716816917017118518618718818919019117419219319419519619719819920020120220320420520620720820921021121221321421521621721817717821922022122218118218318418518622322422522612 unmodified lines2392402412052062072082422432442102112122452462472482492142152162172182502202212222232242512522532542552562292572582592602332342352362612622632642652662672682692702712722732742752762772782792802812822832842852382862872882892902432442912922932942959 unmodified lines3053063072603083093103113125 unmodified lines3183193203213223233243252 unmodified lines328329330280331332333284285286287288334335336337338339340291292293294295296297298341342343344345346347348528 unmodified lines87787887983388088188288332 unmodified lines916917918919920921922923924873874925926927928929217 unmodified lines11471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190411 unmodified lines160216031604160516061607152715281608160916101611161216131614161516161617161816191620153316211622162316241625162616271628162916301631163213 unmodified lines164616471648155316491650165116521 unmodified line165416551656156115621657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167912 unmodified lines1692169316941586169516961697169815891699170017011702"""StreamForge API v11 - Multi-Language Stream Scraperv11 (playability release): - NEW: built-in /proxy endpoint (Range streaming + header injection + m3u8 playlist rewriting) - NetMirror v2: embed-tmdb mp4s now served THROUGH the proxy (fixes "returns stream but won't play") (net27.cc CDN blocks direct playback - their own player proxies via workers; we do the same) - NetMirror v2: subtitle tracks passed through (proxied) - NEW source: Movies4u (m4uplay packed-player unpack -> acek-cdn m3u8 + HubCloud direct) - NEW source: PersianStremio (stremio-style API, imdb based, movie+TV, direct MKV) - REMOVED: VidLove (api.shows.st returns 403 "Website Access Blocked" for all datacenter IPs) - Kept: Castle, PlayBox, Movix (verified playable m3u8), VegaMovies (direct MKV)StreamForge API v12 - Multi-Language Stream Scraperv12 (client-playability release): - FIXED: all proxy URLs are now ABSOLUTE (https://space/proxy_range?u=...) - the v11 relative (/proxy_range?...) URLs broke players that don't know the API base (this is why NetMirror/MOON "loaded but wouldn't play") - Proxy engine v2: Range passthrough on BOTH /proxy and /proxy_range, HEAD support, Origin header injection, content-sniffed m3u8 detection, and m3u8 playlists whose every key/variant/segment URI is rewritten to ABSOLUTE proxy URLs (any player works) - PlayBox: m3u8 served through the proxy with Referer+Origin+UA injected - its gateway intermittently gates direct client fetches with a JSON error page (red tests) - Movies4u: every candidate m3u8 is validated at scrape time (acek-cdn sometimes serves PNG block pages / dead tokens) - only verified playlists are returned - Every stream now carries an absolute proxied_url fallback; Castle/Movix direct URLs unchanged (verified playable) - PersianStremio: MKV hosts confirmed Range-capable (206) - direct links kept - NetMirror: bcdnxw CDN 429-blocks ALL datacenter IPs (HF included) - primary stays the direct mp4 + Referer/UA headers (device-IP playback, like the Nuvio app); absolute proxied_url kept as fallback"""
from fastapi import FastAPI, HTTPException, Query, Request7 unmodified linesimport base64import timeimport asyncioimport contextvarsimport hashlibimport html as ihtmlfrom urllib.parse import quote, urljoin, urlparse1 unmodified lineapp = FastAPI( title="StreamForge API", description="Multi-language m3u8/mp4/MKV stream scraper", version="11.2.0", version="12.0.0",)
app.add_middleware(98 unmodified lines
def _sf_stream_result(source: str, title: str, url: str, quality: str = "Auto", language: str = "English", headers: dict = None, subtitles: list = None, direct_url: str = None) -> dict: subtitles: list = None, direct_url: str = None, proxied_url: str = None) -> dict: # strip control characters some APIs embed in URLs url = re.sub(r'[\x00-\x1f\x7f]', '', url or "") r = {10 unmodified lines r["subtitles"] = subtitles if direct_url: r["direct_url"] = direct_url if proxied_url: r["proxied_url"] = proxied_url return r
1 unmodified line return re.sub(r"[^a-z0-9]", "", (s or "").lower())
# ===== Proxy engine =====# Streams that need special headers (Referer/UA) or are IP-bound cannot be played# directly by clients. We proxy them through the API itself.# ===== Proxy engine v2 =====# Streams that need special headers (Referer/Origin/UA), are IP-bound, or lack CORS# cannot be played directly by clients. They flow through /proxy_range, which does:# * header injection (ref / origin / ua)# * Range passthrough (seek) + HEAD# * content-sniffed m3u8 detection; every key/variant/segment URI inside a playlist# is rewritten to an ABSOLUTE /proxy_range URL so any player (hls.js, ExoPlayer,# VLC, native <video>) works without knowing the API base
_DEFAULT_BASE = "https://epiccodergg-streamforge-api.hf.space"_BASE_URL: contextvars.ContextVar = contextvars.ContextVar("sf_base_url", default=_DEFAULT_BASE)
async def _proxy_fetch_upstream(url: str, headers: dict, range_header: str = None): h = dict(headers or {}) if range_header: h["Range"] = range_header client = httpx.AsyncClient(timeout=30, follow_redirects=True) resp = await client.build_request("GET", url, headers=h) return client, resp
def _get_base() -> str: try: return _BASE_URL.get() or _DEFAULT_BASE except Exception: return _DEFAULT_BASE
_M3U8_URI_RE = re.compile(r'(?m)^((?:#EXT-X-KEY:.*?URI=")([^"]+)("|))|(?!#)((?:https?://|/)[^\s"\'<>]+|"([^"]+)")')
@app.middleware("http")async def _sf_base_url_middleware(request: Request, call_next): try: host = request.headers.get("host") or "" scheme = (request.headers.get("x-forwarded-proto") or request.url.scheme or "https").lower() if ".hf.space" in host: scheme = "https" # never emit http:// proxy URLs for the Space (mixed content) base = f"{scheme}://{host}" if host else _DEFAULT_BASE _BASE_URL.set(base.rstrip("/") or _DEFAULT_BASE) except Exception: _BASE_URL.set(_DEFAULT_BASE) return await call_next(request)
def _proxy_wrap(url: str, ref: str = None, ua: str = None, origin: str = None) -> str: """Build an ABSOLUTE /proxy_range URL (players can use it as-is).""" params = [f"u={quote(url, safe='')}"] if ref: params.append(f"ref={quote(ref, safe='')}") if ua: params.append(f"ua={quote(ua, safe='')}") if origin: params.append(f"origin={quote(origin, safe='')}") return f"{_get_base()}/proxy_range?{'&'.join(params)}"
def _m3u8_rewrite(content: str, base_url: str, ref: str = None, ua: str = None) -> str: """Rewrite every URI inside an m3u8 playlist to go through /proxy."""def _m3u8_rewrite(content: str, base_url: str, ref: str = None, ua: str = None, origin: str = None) -> str: """Rewrite every URI inside an m3u8 playlist to an absolute /proxy_range URL.""" def _wrap(u: str) -> str: absu = urljoin(base_url, u) params = [f"u={quote(absu, safe='')}"] if ref: params.append(f"ref={quote(ref, safe='')}") if ua: params.append(f"ua={quote(ua, safe='')}") return f"/proxy?{'&'.join(params)}" return _proxy_wrap(absu, ref, ua, origin)
out_lines = [] for line in content.splitlines():12 unmodified lines return "\n".join(out_lines) + "\n"
@app.get("/proxy")async def proxy_stream(u: str, ref: str = None, ua: str = None, n: str = None): """Stream proxy: adds required headers, supports Range, rewrites m3u8 playlists.""" headers = {"User-Agent": ua or HEADERS["User-Agent"], "Accept": "*/*"}def _proxy_headers(ref: str = None, ua: str = None, origin: str = None) -> dict: h = {"User-Agent": ua or HEADERS["User-Agent"], "Accept": "*/*"} if ref: headers["Referer"] = ref range_header = None range_header_alt = None h["Referer"] = ref if origin: h["Origin"] = origin return h
# We need access to the raw request headers for Range; FastAPI injects Request only # if declared - so use a trick: read from the global request scope via a sub-app is # complex. Instead accept range via query for clients that can't set headers, and # also try to honor standard behavior via a Request dependency below. return await _proxy_do(u, ref, ua, None)
async def _proxy_do(u: str, ref: str, ua: str, range_header: str = None): headers = {"User-Agent": ua or HEADERS["User-Agent"], "Accept": "*/*"} if ref: headers["Referer"] = refasync def _proxy_do(u: str, ref: str, ua: str, origin: str, range_header: str = None, head_only: bool = False): headers = _proxy_headers(ref, ua, origin) if range_header: headers["Range"] = range_header
try: client = httpx.AsyncClient(timeout=45, follow_redirects=True) client = httpx.AsyncClient(timeout=httpx.Timeout(90, connect=15), follow_redirects=True) req = client.build_request("GET", u, headers=headers) resp = await client.send(req, stream=True) except Exception as e: return JSONResponse({"error": f"proxy fetch failed: {str(e)}"}, status_code=502)
ctype = resp.headers.get("content-type", "application/octet-stream") is_m3u8 = ".m3u8" in u or "mpegurl" in ctype.lower() return JSONResponse({"error": f"proxy fetch failed: {str(e)}"}, status_code=502, headers={"Access-Control-Allow-Origin": "*"})
ctype = (resp.headers.get("content-type") or "application/octet-stream").lower() final_url = str(resp.url)
# NOTE: never partially-buffer the body and try to resume - an abandoned httpx # async iterator closes the underlying stream. Playlist detection relies on the # final (post-redirect) URL and the upstream content-type, which covers every # provider we serve (all m3u8s either carry .m3u8 in the URL or an mpegurl ctype). is_playlist = ".m3u8" in final_url or "mpegurl" in ctype
if head_only: out = { "Access-Control-Allow-Origin": "*", "Accept-Ranges": "bytes", "Content-Type": ctype if (ctype and "text/html" not in ctype) else "application/octet-stream", } if resp.headers.get("content-length"): out["Content-Length"] = resp.headers["content-length"] status = resp.status_code await resp.aclose() await client.aclose() return Response(status_code=status, headers=out)
if is_m3u8: if is_playlist: try: body = (await resp.aread()).decode("utf-8", errors="ignore") finally: await resp.aclose() rewritten = _m3u8_rewrite(body, str(resp.url), ref, ua) await client.aclose() await client.aclose() rewritten = _m3u8_rewrite(body, final_url, ref, ua, origin) return Response( content=rewritten, media_type="application/vnd.apple.mpegurl",9 unmodified lines finally: await resp.aclose() await client.aclose() return Response(content=err_body, status_code=resp.status_code, media_type="text/plain") return Response(content=err_body, status_code=resp.status_code, media_type="text/plain", headers={"Access-Control-Allow-Origin": "*"})
status = resp.status_code out_headers = {5 unmodified lines if resp.headers.get("content-length"): out_headers["Content-Length"] = resp.headers["content-length"]
media_type = ctype if (ctype and "text/html" not in ctype) else "application/octet-stream"
async def iter_bytes(): try: async for chunk in resp.aiter_bytes(64 * 1024):2 unmodified lines await resp.aclose() await client.aclose()
media_type = ctype if ctype and ctype != "text/html" else "application/octet-stream" return StreamingResponse(iter_bytes(), status_code=status, media_type=media_type, headers=out_headers)
@app.api_route("/proxy_range", methods=["GET"], include_in_schema=False)async def proxy_range(request: Request, u: str, ref: str = None, ua: str = None): """Proxy that honors the client's Range header (for players that seek).""" range_header = request.headers.get("range") return await _proxy_do(u, ref, ua, range_header)@app.api_route("/proxy", methods=["GET", "HEAD"], include_in_schema=False)async def proxy_stream(u: str, ref: str = None, ua: str = None, origin: str = None, request: Request = None): """Stream proxy (Range-capable, header-injecting, m3u8-rewriting).""" range_header = request.headers.get("range") if request is not None else None return await _proxy_do(u, ref, ua, origin, range_header, head_only=(request is not None and request.method == "HEAD"))
def _proxy_wrap(url: str, ref: str = None, ua: str = None) -> str: """Build a /proxy_range URL for a client stream.""" params = [f"u={quote(url, safe='')}"] if ref: params.append(f"ref={quote(ref, safe='')}") if ua: params.append(f"ua={quote(ua, safe='')}") return f"/proxy_range?{'&'.join(params)}"@app.api_route("/proxy_range", methods=["GET", "HEAD"], include_in_schema=False)async def proxy_range(request: Request, u: str, ref: str = None, ua: str = None, origin: str = None): """Proxy that honors the client's Range header (for players that seek).""" range_header = request.headers.get("range") return await _proxy_do(u, ref, ua, origin, range_header, head_only=(request.method == "HEAD"))
# ---------- HubCloud family resolver (MediaVanced hubcloud.py, generalized) ----------528 unmodified lines quality=quality, language="Multi", headers={"Referer": "https://net27.cc/", "User-Agent": _NETMIRROR_UA}, subtitles=subs_out or None, direct_url=proxied)) direct_url=proxied, proxied_url=proxied)) except Exception as ex: errors.append(f"NetMirror: {str(ex)}") return results, errors32 unmodified lines for u in urls: if not u or not isinstance(u, str): continue # the m3u8 gateway (onlinevisibilitysystem.site) intermittently gates direct # client fetches with a JSON error page (Referer/Origin/rate gating) -> # serve through our proxy with exactly the headers the API call used pu = _proxy_wrap(u, ref="https://nextgencloudfabric.com/", ua=HEADERS["User-Agent"], origin="https://nextgencloudfabric.com") results.append(_sf_stream_result( "PlayBox", "PlayBox - m3u8", u, quality="Auto", language="Multi")) "PlayBox", "PlayBox - m3u8", pu, quality="Auto", language="Multi", direct_url=u)) except Exception as ex: errors.append(f"PlayBox: {str(ex)}") return results, errors217 unmodified lines if resolved: results_all.extend(resolved)
# validate candidate m3u8s before returning them - acek-cdn/m4uplay sometimes # serve PNG block pages or dead tokens; never hand those to the player async def _valid_m3u8(mu: str) -> bool: try: async with httpx.AsyncClient(timeout=httpx.Timeout(10, connect=6), follow_redirects=True) as vc: vr = await vc.get(mu, headers={"User-Agent": _M4U_UA, "Referer": "https://m4uplay.store/"}) if vr.status_code != 200: return False if "#EXTM3U" in (vr.text or "")[:256]: return True ct = (vr.headers.get("content-type") or "").lower() return "mpegurl" in ct or "mp2t" in ct or "video/" in ct except Exception: return False
seen = set() cand = [] for r in results_all: u = r["url"] if u in seen: continue seen.add(u) cand.append(r) m3u8_cands = [c for c in cand if ".m3u8" in c["url"]] if m3u8_cands: checks = await asyncio.gather(*[_valid_m3u8(c["url"]) for c in m3u8_cands]) ok_m3u8 = {c["url"] for c, ok in zip(m3u8_cands, checks) if ok} else: ok_m3u8 = set()
for r in cand: u = r["url"] label = r.get("label") or "Direct" if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1): continue if ".m3u8" in u: if u not in ok_m3u8: continue # m4uplay tokens are IP-bound -> serve through our proxy so the # playlist AND every segment flow from the API (same IP as the token) pu = _proxy_wrap(u, ref="https://m4uplay.store/", ua=_M4U_UA)411 unmodified lines
seen_urls = set() unique_results = [] base = _get_base() for r in all_results: r["url"] = re.sub(r'[\x00-\x1f\x7f]', '', r.get("url") or "") if r.get("direct_url"): r["direct_url"] = re.sub(r'[\x00-\x1f\x7f]', '', r["direct_url"]) for fld in ("direct_url", "proxied_url"): if r.get(fld): r[fld] = re.sub(r'[\x00-\x1f\x7f]', '', r[fld]) if r[fld].startswith("/"): r[fld] = f"{base}{r[fld]}" if r.get("subtitles"): for sub in r["subtitles"]: if isinstance(sub, dict) and isinstance(sub.get("url"), str) and sub["url"].startswith("/"): sub["url"] = f"{base}{sub['url']}" if r["url"] not in seen_urls: seen_urls.add(r["url"]) # make absolute proxy URLs if r["url"].startswith("/"): r["url"] = f"https://epiccodergg-streamforge-api.hf.space{r['url']}" r["url"] = f"{base}{r['url']}" # every stream gets an absolute proxied fallback (header injection, # IP-pinned tokens and missing CORS are all solved by playing via the API) if not r.get("proxied_url") and not r.get("direct_url"): hdrs = r.get("headers") or {} r["proxied_url"] = _proxy_wrap(r["url"], ref=hdrs.get("Referer"), ua=hdrs.get("User-Agent"), origin=hdrs.get("Origin")) unique_results.append(r)
return {13 unmodified linesasync def root(): return { "api": "StreamForge", "version": "11.2.0", "version": "12.0.0", "description": "Multi-language m3u8/mp4/MKV stream scraper", "endpoints": { "movie": {"all_sources": "/movie/{tmdb_id}", "single_source": "/movie/{tmdb_id}/{source}",1 unmodified line "tv": {"all_sources": "/tv/{tmdb_id}/{season}/{episode}", "single_source": "/tv/{tmdb_id}/{season}/{episode}/{source}", "example": "/tv/1396/1/1", "example_source": "/tv/1396/1/1/netmirror"}, "search": {"path": "/search/{query}", "example": "/search/Venom"}, "proxy": {"path": "/proxy_range?u=<url>&ref=<referer>&ua=<user-agent>", "note": "stream proxy with Range support - NetMirror and subtitle URLs come pre-proxied"}, "proxy": {"path": "/proxy_range?u=<url>&ref=<referer>&ua=<user-agent>&origin=<origin>", "note": "Range-capable stream proxy with header injection + m3u8 rewriting. ALL proxied stream URLs returned by this API are ABSOLUTE - use them as-is in any player"}, "api_endpoints": {"health": "GET /api/health", "sources": "GET /api/sources", "search": "GET /api/search?q={query}", "scrape": "POST /api/scrape", "scrape_all": "POST /api/scrape/all"}, }, "sources": {k: {kk: vv for kk, vv in v.items() if kk != "fn"} for k, v in SOURCE_MAP.items()}, "default_sources": DEFAULT_SOURCES, "changelog_v12": { "fixed": [ "Proxy URLs are ABSOLUTE now - v11 returned relative /proxy_range?... URLs which players cannot resolve (the reason NetMirror 'loaded but wouldn't play' and several servers showed red)", "Proxy engine v2: Range passthrough on both /proxy and /proxy_range, HEAD support, Origin injection, content-sniffed m3u8 detection, absolute-rewritten playlists", "PlayBox: m3u8 now served through the proxy with Referer+Origin+UA (its gateway intermittently serves a JSON error page to direct client fetches = red tests)", "Movies4u: candidate m3u8s validated at scrape time - PNG block pages / dead tokens are dropped, only verified playlists returned", "Every stream carries an absolute proxied_url fallback; Castle/Movix direct URLs unchanged (verified playable)", ], "notes": [ "NetMirror/MOON: bcdnxw CDN 429-blocks ALL datacenter IPs (HF included). Primary = direct mp4 + Referer/UA headers (plays from the viewing device's IP, like the Nuvio app). If your player cannot send headers and the device IP is blocked, NetMirror cannot play - that is a CDN-level block, not a scraper bug.", "PersianStremio: direct MKV links are Range-capable (verified 206); 4K/HEVC entries need a player with HEVC support (not browser-native)", ], }, "changelog_v11": { "fixed": [ "NetMirror: returns direct mp4 + required headers (Referer/UA) + subtitles; its CDN 429-blocks ALL datacenter IPs so server-side proxying is impossible - the client (device IP) must play with the returned headers, exactly like the Nuvio app does. proxied_url kept as fallback.",12 unmodified lines "source_repos": ["github.com/D3adlyRocket/All-in-One-Nuvio", "github.com/yogesh-hacker/MediaVanced"], "tips": [ "No source = default sources (castle, netmirror, playbox, movix, movies4u, persianstremio)", "NetMirror: play the url WITH its returned headers (Referer+UA) - its CDN 429-blocks datacenter IPs so server proxying is impossible; headers let the client (device IP) play", "Every stream includes an ABSOLUTE proxied_url fallback - if direct playback fails, play proxied_url (works from any client IP, CORS-safe)", "NetMirror: play url WITH its headers (Referer+UA) from the device IP; proxied_url exists but the CDN 429-blocks datacenter IPs (HF included)", "Castle: multi-language m3u8 (English/Tamil/Telugu)", "Movix/PlayBox/Movies4u: m3u8; PersianStremio/UHDMovies/VegaMovies: direct MKV (VLC/mpv/exoplayer)", "Each result may include: headers (native playback), direct_url (raw URL), subtitles (proxied VTT)", "Each result may include: headers (native playback), direct_url (raw URL), proxied_url (absolute proxy URL), subtitles (proxied VTT)", ], }
main.py+192-82