Spaces:
Running
Running
v12.0.2: movies4u - drop pre-validation (it burns single-use tokens), return fresh tokens m4uplay-first capped at 2
57f30e5 verified Download main.py from EpicCoderGG/streamforge-api: direct link, hf CLI and curl.
- Browser
- Download file 77.8 kB
-
https://huggingface.co/spaces/EpicCoderGG/streamforge-api/resolve/57f30e596bd349ca3f56963af6edb8b199742587/main.py
- Command line
-
hf download hf://spaces/EpicCoderGG/streamforge-api@57f30e596bd349ca3f56963af6edb8b199742587/main.py
-
curl -L -o main.py https://huggingface.co/spaces/EpicCoderGG/streamforge-api/resolve/57f30e596bd349ca3f56963af6edb8b199742587/main.py
77.8 kB
"""
StreamForge API v12 - Multi-Language Stream Scraper
v12 (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, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, Response, JSONResponse
from pydantic import BaseModel
from typing import Optional
import httpx
import json
import re
import base64
import time
import asyncio
import contextvars
import hashlib
import html as ihtml
from urllib.parse import quote, urljoin, urlparse
app = FastAPI(
title="StreamForge API",
description="Multi-language m3u8/mp4/MKV stream scraper",
version="12.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
TMDB_API_KEY = "7967738a03ec215c7d6d675faba9c973"
TMDB_BASE = "https://api.themoviedb.org/3"
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Accept": "application/json, text/html, */*",
"Accept-Language": "en-US,en;q=0.5",
}
# ===== Models =====
class ScrapeRequest(BaseModel):
tmdb_id: int
media_type: str = "movie"
season: Optional[int] = None
episode: Optional[int] = None
sources: Optional[list[str]] = None
# ===== Helpers =====
async def get_tmdb_info(tmdb_id: int, media_type: str) -> dict:
async with httpx.AsyncClient(timeout=10) as client:
type_path = "tv" if media_type == "tv" else "movie"
resp = await client.get(
f"{TMDB_BASE}/{type_path}/{tmdb_id}",
params={"api_key": TMDB_API_KEY, "append_to_response": "external_ids"}
)
data = resp.json()
return {
"imdb_id": data.get("external_ids", {}).get("imdb_id"),
"title": data.get("title") or data.get("name"),
"year": (data.get("release_date") or data.get("first_air_date") or "")[:4],
}
def detect_language(label: str) -> str:
lower = label.lower()
if "hindi" in lower or "hin" in lower: return "Hindi"
if "tamil" in lower or "tam" in lower: return "Tamil"
if "telugu" in lower or "tel" in lower: return "Telugu"
if "bengali" in lower or "bangla" in lower or "ben" in lower: return "Bengali"
if "malayalam" in lower or "mal" in lower: return "Malayalam"
if "kannada" in lower or "kan" in lower: return "Kannada"
if "english" in lower or "eng" in lower or "en" == lower: return "English"
if "italian" in lower or "ita" in lower or "italiano" in lower: return "Italian"
if "french" in lower or "fra" in lower or "vf" in lower: return "French"
if "german" in lower or "deu" in lower or "ger" in lower: return "German"
if "spanish" in lower or "spa" in lower or "español" in lower: return "Spanish"
if "persian" in lower or "farsi" in lower: return "Persian"
if "multi" in lower or "dual" in lower: return "Multi"
return "English"
def evp_bytes_to_key(password: bytes, salt: bytes, key_len: int = 32, iv_len: int = 16):
dtot = b""
d = b""
while len(dtot) < key_len + iv_len:
d = hashlib.md5(d + password + salt).digest()
dtot += d
return dtot[:key_len], dtot[key_len:key_len + iv_len]
def normalize_title(title: str) -> str:
cleaned = re.sub(r'\[[^\]]*\]', '', title)
cleaned = re.sub(r'\((?:Dub|HD|Cam|TS|HDRip|BRRip|DVDRip|WEBRip|WEB-DL)\)', '', cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
return cleaned
def extract_language_from_title(title: str) -> str:
bracket_match = re.search(r'\[([^\]]+)\]', title)
if bracket_match:
lang_text = bracket_match.group(1)
detected = detect_language(lang_text)
if detected != "English" or lang_text.lower() == "english":
return detected
return ""
_SF_CTRL_ENC = re.compile(r'%(0[0-9a-f]|1[0-9a-f]|7f)', re.IGNORECASE)
def _sf_url_has_ctrl(u: str) -> bool:
"""Detect literal or percent-encoded control characters in a URL."""
if not u:
return True
if re.search(r'[\x00-\x1f\x7f]', u):
return True
return bool(_SF_CTRL_ENC.search(u))
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,
proxied_url: str = None) -> dict:
# strip control characters some APIs embed in URLs
url = re.sub(r'[\x00-\x1f\x7f]', '', url or "")
r = {
"source": source,
"title": title,
"quality": quality,
"language": detect_language(language) if language else "English",
"url": url,
"type": "m3u8" if ".m3u8" in url else "direct",
}
if headers:
r["headers"] = headers
if subtitles:
r["subtitles"] = subtitles
if direct_url:
r["direct_url"] = direct_url
if proxied_url:
r["proxied_url"] = proxied_url
return r
def _sf_norm(s: str) -> str:
return re.sub(r"[^a-z0-9]", "", (s or "").lower())
# ===== 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)
def _get_base() -> str:
try:
return _BASE_URL.get() or _DEFAULT_BASE
except Exception:
return _DEFAULT_BASE
@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, 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)
return _proxy_wrap(absu, ref, ua, origin)
out_lines = []
for line in content.splitlines():
ls = line.strip()
if not ls:
continue
if ls.startswith("#EXT-X-KEY") or ls.startswith("#EXT-X-MAP"):
def key_uri(mm):
return f'URI="{_wrap(mm.group(1))}"'
ls = re.sub(r'URI="([^"]+)"', key_uri, ls)
out_lines.append(ls)
elif ls.startswith("#"):
out_lines.append(ls)
else:
out_lines.append(_wrap(ls.strip('"')))
return "\n".join(out_lines) + "\n"
def _proxy_headers(ref: str = None, ua: str = None, origin: str = None) -> dict:
h = {"User-Agent": ua or HEADERS["User-Agent"], "Accept": "*/*"}
if ref:
h["Referer"] = ref
if origin:
h["Origin"] = origin
return h
async 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=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, 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_playlist:
try:
body = (await resp.aread()).decode("utf-8", errors="ignore")
finally:
await resp.aclose()
await client.aclose()
rewritten = _m3u8_rewrite(body, final_url, ref, ua, origin)
return Response(
content=rewritten,
media_type="application/vnd.apple.mpegurl",
headers={"Cache-Control": "no-cache", "Access-Control-Allow-Origin": "*"},
)
# binary stream (mp4/mkv/ts/segment): pipe with Range support
# pass upstream errors through faithfully so players can fall back
if resp.status_code not in (200, 206):
err_body = b""
try:
err_body = (await resp.aread())[:400]
finally:
await resp.aclose()
await client.aclose()
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 = {
"Access-Control-Allow-Origin": "*",
"Accept-Ranges": resp.headers.get("accept-ranges", "bytes"),
}
if resp.headers.get("content-range"):
out_headers["Content-Range"] = resp.headers["content-range"]
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):
yield chunk
finally:
await resp.aclose()
await client.aclose()
return StreamingResponse(iter_bytes(), status_code=status, media_type=media_type, headers=out_headers)
@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"))
@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) ----------
_SF_LINK_PROVIDERS = re.compile(
r'https?://[^\s"\'<>]*(?:hubcloud\.[a-z]+/(?:drive|video)/[A-Za-z0-9_\-]+'
r'|hubdrive\.[a-z]+/file/[A-Za-z0-9]+'
r'|hblinks\.[a-z]+/archives/\d+'
r'|vcloud\.[a-z]+/[A-Za-z0-9]+'
r'|nexdrive\.[a-z]+/[A-Za-z0-9]+'
r'|abhilinks\.[a-z]+/archives/\d+/?)',
)
_SF_SPORTVERSE = re.compile(r'https?://sportverse\.cc/hubcloud\.php\?[^"\'<>]+')
_SF_MOBILE_UA = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Mobile Safari/537.36"
def _sf_extract_links(html: str) -> list:
seen, out = set(), []
for m in _SF_LINK_PROVIDERS.finditer(html or ""):
u = m.group(0)
if u not in seen:
seen.add(u)
out.append(u)
return out
def _sf_pixeldrain_direct(u: str) -> str:
m = re.search(r'pixeldrain\.[a-z]+/u/([A-Za-z0-9]+)', u)
if m:
return f"https://pixeldrain.com/api/file/{m.group(1)}?download"
return u
async def _sf_resolve_hubcloud(client: httpx.AsyncClient, link: str) -> list:
"""Resolve one hubcloud-family page into direct file URLs."""
out = []
try:
if "/video/" in link or "hubvid" in link:
page = (await client.get(link)).text
sport = _SF_SPORTVERSE.search(page)
if sport:
page = (await client.get(sport.group(0), headers={"Referer": link})).text
else:
page = (await client.post(link)).text
m = re.search(r"var\s+url\s*=\s*'(https?://[^']+)'", page)
if m:
page = (await client.get(m.group(1))).text
for b in re.finditer(r'<a[^>]+href="(https?://[^"]+)"[^>]+class="[^"]*btn[^"]*"', page):
u = b.group(1)
chunk = page[b.start():b.start() + 800]
fm = re.search(r'download="([^"]{5,110})"', chunk)
fname = fm.group(1) if fm else ""
if "pixeldrain" in u:
out.append({"url": _sf_pixeldrain_direct(u), "label": fname or "Direct"})
elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) and ".zip" not in u:
out.append({"url": u, "label": fname or "Direct"})
elif "cloudflarestorage" in u or "workers.dev" in u or "googleusercontent.com" in u:
out.append({"url": u, "label": fname or "Direct"})
except Exception:
pass
return out
def _sf_quality_from_name(name: str) -> str:
low = (name or "").lower()
if "2160" in low or "4k" in low: return "4K"
if "1080" in low: return "1080p FHD"
if "720" in low: return "720p HD"
if "480" in low: return "480p SD"
if "360" in low: return "360p"
return "Auto"
def _sf_lang_from_name(name: str) -> str:
low = (name or "").lower()
if "dual audio" in low or "dual" in low or "multi" in low: return "Multi"
langs = []
if "hindi" in low or "esubs" in low: langs.append("Hindi")
if "tamil" in low: langs.append("Tamil")
if "telugu" in low: langs.append("Telugu")
if "english" in low or "eng" in low: langs.append("English")
return " + ".join(langs) if langs else "English"
def _sf_episode_matches(label: str, season: int, episode: int) -> bool:
if not label:
return True
low = label.lower()
s_ok = re.search(rf'\bs{season:02d}e{episode:02d}\b|s{season}\.?e{episode}\b|season.{season}\b', low)
e_ok = re.search(rf'\be{episode:02d}\b|episode.{episode}\b|ep.{episode}\b|e{episode}\b', low)
season_only = re.search(rf'season.{season}\b|s{season:02d}\b|s{season}\b', low)
if s_ok or season_only or (e_ok and (season_only or "season" in low)):
return True
other = re.search(r'\bs\d{1,2}e\d{1,2}\b|season.\d+\b|\be\d{1,2}\b|episode.\d+\b', low)
if other:
return False
return True
def _sf_hubcloud_results(source_name: str, resolved: list, media_type: str, season, episode) -> list:
results = []
seen_urls = set()
for r in resolved:
u, label = r["url"], r["label"]
if u in seen_urls:
continue
seen_urls.add(u)
if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1):
continue
results.append(_sf_stream_result(
f"{source_name}/HubCloud", f"{source_name} - {label or 'Direct'}", u,
quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label)))
return results
# ===== Castle Scraper (hlowb.com API with AES-CBC) - multi-language m3u8 =====
async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results = []
errors = []
try:
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
info = await get_tmdb_info(tmdb_id, media_type)
title = info.get("title", "")
if not title:
errors.append("Castle: No title from TMDB")
return results, errors
CASTLE_BASE = "https://api.hlowb.com"
PKG = "com.external.castle"
CH = "IndiaA"
CLI = "1"
LANG = "en-US"
SIGN = "ED0955EB04E67A1D9F3305B95454FED485261475"
CASTLE_HEADERS = {
"User-Agent": "okhttp/4.9.3",
"Accept": "application/json",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "Keep-Alive",
"Referer": "https://api.hlowb.com",
}
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client:
sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1", params={
"channel": CH, "clientType": CLI, "lang": LANG
})
if sec_r.status_code != 200:
errors.append(f"Castle: sec key HTTP {sec_r.status_code}")
return results, errors
sec_j = sec_r.json()
raw_k = sec_j.get("data", "")
if not raw_k or not isinstance(raw_k, str):
errors.append("Castle: bad sec key response")
return results, errors
try:
sec_key = base64.b64decode(raw_k).decode("utf-8", errors="ignore")
except Exception:
sec_key = raw_k
combined = (sec_key + "T!BgJB")
aes_k = (combined + "\x00" * max(0, 16 - len(combined)))[:16].encode("utf-8")
aes_iv = aes_k
def castle_decrypt(text):
d = text
try:
j = json.loads(text)
if isinstance(j, dict) and isinstance(j.get("data"), str):
d = j["data"]
except Exception:
pass
try:
raw = base64.b64decode(d)
c = AES.new(aes_k, AES.MODE_CBC, aes_iv)
dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")
return json.loads(dec)
except Exception:
pass
try:
raw = bytes.fromhex(d)
c = AES.new(aes_k, AES.MODE_CBC, aes_iv)
dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")
return json.loads(dec)
except Exception:
pass
try:
return json.loads(text)
except Exception:
raise ValueError(f"Castle decrypt failed for data length={len(d)}")
kw = f"{title} {info.get('year', '')}".strip()
sr = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={
"channel": CH, "clientType": CLI, "keyword": kw, "lang": LANG,
"mode": "1", "packageName": PKG, "page": "1", "size": "30"
})
if sr.status_code != 200:
errors.append(f"Castle: search HTTP {sr.status_code}")
return results, errors
try:
sp = castle_decrypt(sr.text)
except Exception as e:
errors.append(f"Castle: search decrypt fail: {e}")
return results, errors
if not isinstance(sp, dict) or sp.get("code") != 200:
errors.append(f"Castle: search API error (code={sp.get('code') if isinstance(sp, dict) else 'N/A'})")
return results, errors
db = sp.get("data", {})
if isinstance(db, str):
try:
db = json.loads(db)
except Exception:
db = {}
rows = db.get("rows", []) if isinstance(db, dict) else []
if not rows:
errors.append("Castle: no search results")
return results, errors
mid = None
tl = normalize_title(title).lower()
target_subject_type = 1 if media_type == "movie" else 2
for r in rows:
if not isinstance(r, dict):
continue
rt = normalize_title(r.get("title", "") or r.get("name", "")).lower()
r_type = r.get("subjectType", r.get("type", 0))
if tl == rt and r_type == target_subject_type:
mid = r.get("id")
break
if not mid:
for r in rows:
if not isinstance(r, dict):
continue
rt = normalize_title(r.get("title", "") or r.get("name", "")).lower()
r_type = r.get("subjectType", r.get("type", 0))
if (tl in rt or rt in tl) and r_type == target_subject_type:
mid = r.get("id")
break
if not mid:
for r in rows:
if not isinstance(r, dict):
continue
rt = normalize_title(r.get("title", "") or r.get("name", "")).lower()
if tl in rt or rt in tl:
mid = r.get("id")
break
if not mid and isinstance(rows[0], dict):
mid = rows[0].get("id")
if not mid:
errors.append("Castle: no match")
return results, errors
mid = str(mid)
dr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={
"channel": CH, "clientType": CLI, "lang": LANG,
"movieId": mid, "packageName": PKG
})
if dr.status_code != 200:
errors.append(f"Castle: detail HTTP {dr.status_code}")
return results, errors
try:
dp = castle_decrypt(dr.text)
except Exception:
dp = {}
dd = dp.get("data", dp)
if isinstance(dd, str):
try:
dd = json.loads(dd)
except Exception:
dd = {}
if not isinstance(dd, dict):
dd = {}
ep_id = mid
if media_type == "tv" and season and episode:
seasons = dd.get("seasons", [])
s_id = mid
for s_item in seasons:
if not isinstance(s_item, dict):
continue
if s_item.get("number") == season or s_item.get("seasonNum") == season:
sid = s_item.get("id")
if sid and str(sid) != mid:
s_id = str(sid)
sdr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={
"channel": CH, "clientType": CLI, "lang": LANG,
"movieId": s_id, "packageName": PKG
})
try:
sdp = castle_decrypt(sdr.text)
sdd = sdp.get("data", sdp)
if isinstance(sdd, dict):
dd = sdd
except Exception:
pass
break
eps = dd.get("episodes", [])
for ep in eps:
if not isinstance(ep, dict):
continue
if ep.get("number") == episode or ep.get("episodeNum") == episode:
ep_id = str(ep.get("id", ""))
break
mid = s_id
else:
eps = dd.get("episodes", [])
if eps and isinstance(eps[0], dict):
ep_id = str(eps[0].get("id", ""))
CASTLE_LANGS = [("English", "1003"), ("Tamil", "1033"), ("Telugu", "1037")]
for lang_name, lang_id in CASTLE_LANGS:
for resolution in [3, 2, 1]:
try:
body = {
"mode": "1",
"appMarket": "GuanWang",
"clientType": CLI,
"woolUser": "false",
"apkSignKey": SIGN,
"androidVersion": "13",
"movieId": mid,
"episodeId": str(ep_id),
"languageId": lang_id,
"isNewUser": "true",
"resolution": str(resolution),
"packageName": PKG,
}
vr = await client.post(
f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2",
params={"clientType": CLI, "packageName": PKG, "channel": CH, "lang": LANG},
json=body,
headers={"Content-Type": "application/json"}
)
if vr.status_code != 200:
continue
try:
vp = castle_decrypt(vr.text)
except Exception:
continue
vd = vp.get("data", vp)
if isinstance(vd, str):
try:
vd = json.loads(vd)
except Exception:
continue
if not isinstance(vd, dict):
continue
vurl = vd.get("videoUrl", "")
if not vurl:
continue
# some key batches contain control chars (corrupt auth_key) - retry once
if _sf_url_has_ctrl(vurl):
vr = await client.post(
f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2",
params={"clientType": CLI, "packageName": PKG, "channel": CH, "lang": LANG},
json=body,
headers={"Content-Type": "application/json"}
)
if vr.status_code == 200:
try:
vp = castle_decrypt(vr.text)
vd = vp.get("data", vp)
if isinstance(vd, str):
vd = json.loads(vd)
if isinstance(vd, dict) and vd.get("videoUrl"):
vurl = vd["videoUrl"]
except Exception:
pass
if _sf_url_has_ctrl(vurl):
continue
quality_map = {1: "480P", 2: "720P", 3: "1080P"}
quality = quality_map.get(resolution, "720P")
vids = vd.get("videos", [])
if vids and isinstance(vids, list):
for v in vids:
if not isinstance(v, dict):
continue
vu = v.get("url", vurl)
# skip entries with corrupted auth_key (control chars, raw or %XX)
if _sf_url_has_ctrl(vu):
continue
q = v.get("resolutionDescription", v.get("resolution", quality))
q = re.sub(r'^(SD|HD|FHD)\s+', '', str(q))
subs = v.get("subtitles", [])
result_item = {
"source": "Castle",
"title": f"Castle [{lang_name}] - {q}",
"quality": q,
"language": lang_name,
"url": vu,
"type": "m3u8" if ".m3u8" in vu else "direct",
}
if subs:
result_item["subtitles"] = subs
results.append(result_item)
else:
if _sf_url_has_ctrl(vurl):
continue
results.append({
"source": "Castle",
"title": f"Castle [{lang_name}] - {quality}",
"quality": quality,
"language": lang_name,
"url": vurl,
"type": "m3u8" if ".m3u8" in vurl else "direct",
})
break
except Exception:
continue
seen = set()
uniq = []
for r in results:
if r["url"] not in seen:
seen.add(r["url"])
uniq.append(r)
results = uniq
if not results:
errors.append("Castle: no streams found")
except ImportError:
errors.append("Castle: pycryptodome not installed")
except Exception as e:
errors.append(f"Castle ERR: {type(e).__name__}: {str(e)}")
return results, errors
# ===== NetMirror v2 (net27.cc embed-tmdb + API proxy) =====
# net27.cc CDN (bcdnxw.hakunaymatata.com) blocks direct playback (429) - the site's own
# player proxies through a worker. We do the same via /proxy_range with Referer+UA.
_NETMIRROR_BASE = "https://net27.cc"
_NETMIRROR_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
_NETMIRROR_HEADERS = {
"Accept": "application/json, text/plain, */*",
"Referer": "https://net27.cc/",
"User-Agent": _NETMIRROR_UA,
}
async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results = []
errors = []
try:
url = f"{_NETMIRROR_BASE}/api/embed-tmdb/{tmdb_id}"
if media_type == "tv":
url += f"?type=tv&s={season or 1}&e={episode or 1}"
async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
resp = await client.get(url, headers=_NETMIRROR_HEADERS)
if resp.status_code != 200:
errors.append(f"NetMirror: embed-tmdb HTTP {resp.status_code}")
return results, errors
try:
data = resp.json()
except Exception:
errors.append("NetMirror: non-JSON response")
return results, errors
if data.get("ok") is False or data.get("noSource"):
errors.append("NetMirror: title not available on NetMirror")
return results, errors
# Subtitle tracks (proxied)
subs_out = []
for sub in (data.get("subtitles") or []):
try:
surl = sub.get("url") if isinstance(sub, dict) else None
if not surl:
continue
if surl.startswith("/"):
surl = _NETMIRROR_BASE + surl
lang = sub.get("lang") or sub.get("language") or "Sub"
subs_out.append({
"language": lang,
"url": _proxy_wrap(surl, ref="https://net27.cc/", ua=_NETMIRROR_UA),
})
except Exception:
continue
streams = data.get("streams") or []
if not isinstance(streams, list) or not streams:
mp4 = data.get("mp4")
if mp4:
streams = [{"url": mp4, "resolution": data.get("resolution", "Auto")}]
else:
errors.append("NetMirror: no streams in response")
return results, errors
for s in streams:
if not isinstance(s, dict):
continue
u = s.get("url")
if not u:
continue
if u.startswith("/"):
u = _NETMIRROR_BASE + u
res = str(s.get("resolution") or "").strip()
quality = {"2160": "4K", "1080": "1080p", "720": "720p", "480": "480p", "360": "360p"}.get(res, res if res else "Auto")
# bcdnxw CDN 429-blocks ALL datacenter IPs (HF included), so proxying through
# the Space fails. Primary = direct URL + required headers (device IP plays,
# same as the Nuvio app); proxied fallback kept in case CDN unblocks.
proxied = _proxy_wrap(u, ref="https://net27.cc/", ua=_NETMIRROR_UA)
results.append(_sf_stream_result(
"NetMirror", f"NetMirror - {quality}", u,
quality=quality, language="Multi",
headers={"Referer": "https://net27.cc/", "User-Agent": _NETMIRROR_UA},
subtitles=subs_out or None,
direct_url=proxied, proxied_url=proxied))
except Exception as ex:
errors.append(f"NetMirror: {str(ex)}")
return results, errors
# ===== PlayBox Scraper (streamdata.vaplayer.ru API) =====
_PLAYBOX_API = "https://streamdata.vaplayer.ru/api.php"
async def scrape_playbox(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results = []
errors = []
try:
url = f"{_PLAYBOX_API}?tmdb={tmdb_id}&type={media_type}"
if media_type != "movie":
url += f"&season={season or 1}&episode={episode or 1}"
async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
resp = await client.get(url, headers={
"User-Agent": HEADERS["User-Agent"],
"Referer": "https://nextgencloudfabric.com",
"Origin": "https://nextgencloudfabric.com",
"Accept": "*/*",
})
if resp.status_code != 200:
errors.append(f"PlayBox: API HTTP {resp.status_code}")
return results, errors
data = resp.json()
urls = ((data.get("data") or {}).get("stream_urls")) or []
if not urls:
errors.append("PlayBox: no stream urls")
return results, errors
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", pu,
quality="Auto", language="Multi", direct_url=u))
except Exception as ex:
errors.append(f"PlayBox: {str(ex)}")
return results, errors
# ===== Movix (Nuvio movix.js): api.movix.cash direct API =====
async def scrape_movix(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results = []
errors = []
try:
headers = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://movix.cash/"}
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=headers) as client:
if media_type == "tv":
url = f"https://api.movix.cash/api/purstream/tv/{tmdb_id}/stream"
params = {"season": season or 1, "episode": episode or 1}
else:
url = f"https://api.movix.cash/api/purstream/movie/{tmdb_id}/stream"
params = {}
resp = await client.get(url, params=params)
data = resp.json()
if data.get("error"):
return [], [f"Movix: {data.get('error')}"]
for src in data.get("sources", []):
surl = src.get("url")
if not surl:
continue
name = src.get("name") or "Movix"
results.append(_sf_stream_result(f"Movix/{name}", f"Movix - {name}", surl))
if not results:
errors.append("Movix: no sources")
except Exception as e:
errors.append(f"Movix: {str(e)}")
return results, errors
# ===== Movies4u (Nuvio movies4u.js port) =====
# Flow: domains.json -> site search -> post page -> m4uplay packed player (Dean Edwards
# unpack) -> hls2 m3u8 + m4ulinks -> hubcloud -> googleusercontent direct
_PHISHER_DOMAINS = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json"
_M4U_DEFAULT_SITE = "https://new5.movies4u.clinic"
_M4U_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
def _sf_dean_unpack(html_text: str) -> str:
"""Unpack eval(function(p,a,c,k,e,d){...}('payload',radix,count,'words'.split('|')))"""
try:
anchor = re.search(r"eval\(function\(p,a,c,k,e,d\)\{.*?\}\('", html_text, re.DOTALL)
if not anchor:
return html_text
rest = html_text[anchor.end():]
endm = re.search(r"',(\d+),(\d+),'", rest)
if not endm:
return html_text
payload = rest[:endm.start()]
radix, count = int(endm.group(1)), int(endm.group(2))
rest2 = rest[endm.end():]
wend = rest2.find("'.split(")
if wend == -1:
return html_text
words = rest2[:wend].split('|')
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def enc(i):
out = ""
while True:
out = ALPHABET[i % radix] + out
i //= radix
if i == 0:
break
return out
unpacked = payload
for c in range(count - 1, -1, -1):
if c < len(words) and words[c]:
unpacked = re.sub(r'\b' + re.escape(enc(c)) + r'\b',
words[c].replace('\\', '\\\\'), unpacked)
return ihtml.unescape(unpacked)
except Exception:
return html_text
def _sf_m4uplay_extract(page_html: str, page_url: str) -> list:
"""Extract m3u8 links from an m4uplay player page."""
out = []
unpacked = _sf_dean_unpack(page_html)
# links object: {"hls4": "...", "hls3": "...", "hls2": "https://...master.m3u8?t=..."}
for m in re.finditer(r'"(hls\d)"\s*:\s*"([^"]+)"', unpacked):
u = m.group(2)
if u.startswith("/"):
u = urljoin(page_url, u)
if ".m3u8" in u:
out.append(u)
# Fallback: any literal m3u8
if not out:
for m in re.finditer(r'https?://[^"\'\s]+\.m3u8[^"\'\s]*', unpacked):
out.append(m.group(0))
# Deduplicate, keep order (hls4 preferred first like the player)
seen = set()
uniq = []
for u in out:
if u not in seen:
seen.add(u)
uniq.append(u)
return uniq
async def scrape_movies4u(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results = []
errors = []
try:
info = await get_tmdb_info(tmdb_id, media_type)
title = info.get("title") or ""
year = info.get("year") or ""
site = _M4U_DEFAULT_SITE
try:
async with httpx.AsyncClient(timeout=10) as c:
cfg = (await c.get(_PHISHER_DOMAINS)).json()
cand = cfg.get("movies4u")
if isinstance(cand, str) and cand.startswith("http"):
site = cand.rstrip("/")
elif isinstance(cand, list) and cand:
site = str(cand[0]).rstrip("/")
except Exception:
pass
results_all = []
async with httpx.AsyncClient(timeout=25, follow_redirects=True,
headers={"User-Agent": _M4U_UA, "Referer": site + "/"}) as client:
# 1) search
sr = await client.get(f"{site}/?s={quote(title)}")
if sr.status_code != 200:
errors.append(f"Movies4u: search HTTP {sr.status_code}")
return results, errors
posts = []
for m in re.finditer(r'<article[^>]+id="post-(\d+)"[^>]*>.*?<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', sr.text, re.DOTALL):
pid, url, ttl = m.group(1), m.group(2), re.sub(r'<[^>]+>', '', m.group(3))
posts.append({"id": pid, "url": url, "title": ttl.strip()})
if not posts:
# simpler pattern
for m in re.finditer(r'<h2[^>]*class="[^"]*entry-title[^"]*"[^>]*>\s*<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', sr.text, re.DOTALL):
url, ttl = m.group(1), re.sub(r'<[^>]+>', '', m.group(2)).strip()
posts.append({"id": None, "url": url, "title": ttl})
if not posts:
errors.append("Movies4u: no search results")
return results, errors
# 2) pick matching post
tl_norm = _sf_norm(f"{title} {year}")
chosen = None
for p in posts:
pt = _sf_norm(p["title"])
if _sf_norm(title) in pt and (not year or year in pt or year in p["url"]):
chosen = p
break
if not chosen:
for p in posts:
if _sf_norm(title) in _sf_norm(p["title"]) or _sf_norm(title) in _sf_norm(p["url"]):
chosen = p
break
if not chosen:
chosen = posts[0]
# episode filter for TV: prefer post with S..E marker
if media_type == "tv" and season and episode:
marker = f"s{season:02d}e{episode:02d}"
marker2 = f"s{season}e{episode}"
for p in posts:
pu = (p["title"] + " " + p["url"]).lower().replace(" ", "")
if marker in pu or marker2 in pu:
chosen = p
break
pr = await client.get(chosen["url"])
if pr.status_code != 200:
errors.append(f"Movies4u: post HTTP {pr.status_code}")
return results, errors
post_html = pr.text
# 3) find m4uplay file link
m4u_links = re.findall(r'https?://m4uplay\.[a-z.]+/file/[A-Za-z0-9]+', post_html)
if not m4u_links:
m4u_links = re.findall(r'https?://[a-z0-9.]*m4uplay[^"\'\s<]*file[^"\'\s<]*', post_html)
# also quality-labeled anchors
if not m4u_links:
m4u_links = re.findall(r'https?://[^"\'\s<]*player[^"\'\s<]*/file/[^"\'\s<]+', post_html)
m4u_links = list(dict.fromkeys(m4u_links))[:3]
if not m4u_links:
errors.append("Movies4u: no m4uplay links")
else:
for link in m4u_links:
try:
lr = await client.get(link, headers={"User-Agent": _M4U_UA, "Referer": site + "/"})
if lr.status_code != 200:
continue
for u in _sf_m4uplay_extract(lr.text, str(lr.url)):
results_all.append({"url": u, "label": "M4U Player Direct"})
except Exception:
continue
# 4) hubcloud direct fallbacks from post page
hc_links = re.findall(r'https?://m4ulinks\.[a-z]+/\S+', post_html)[:2]
resolved = []
for hl in hc_links:
try:
lp = (await client.get(hl, headers={"User-Agent": _SF_MOBILE_UA, "Referer": site + "/"})).text
for hcl in re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[A-Za-z0-9_]+', lp)[:2]:
resolved.extend(await _sf_resolve_hubcloud(client, hcl))
except Exception:
continue
if resolved:
results_all.extend(resolved)
# m4uplay / acek-cdn m3u8 tokens are extremely short-lived and behave as
# effectively single-use (a validation GET burns them -> PNG block page for
# the player). So we do NOT pre-validate; instead return FRESH tokens per
# scrape, m4uplay-hosted first (longest-lived), capped at 2 entries.
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"]]
m3u8_cands.sort(key=lambda c: (0 if "m4uplay" in c["url"] else 1))
m3u8_cands = m3u8_cands[:2]
ok_m3u8 = {c["url"] for c in m3u8_cands}
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)
results.append(_sf_stream_result(
"Movies4u", f"Movies4u - {label}", pu,
quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label)))
elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) or "googleusercontent" in u:
results.append(_sf_stream_result(
"Movies4u", f"Movies4u - {label}", u,
quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label)))
if not results:
errors.append("Movies4u: no playable streams")
except Exception as ex:
errors.append(f"Movies4u: {str(ex)}")
return results, errors
# ===== PersianStremio (stremio addon API, imdb based) =====
_PERSIAN_API = "https://persianstremio.vercel.app"
async def scrape_persianstremio(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results = []
errors = []
try:
info = await get_tmdb_info(tmdb_id, media_type)
imdb_id = info.get("imdb_id")
if not imdb_id:
errors.append("PersianStremio: no imdb id")
return results, errors
if media_type == "tv":
url = f"{_PERSIAN_API}/stream/series/{imdb_id}:{season or 1}:{episode or 1}.json"
else:
url = f"{_PERSIAN_API}/stream/movie/{imdb_id}.json"
async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
data = None
last_status = 0
# the vercel API intermittently 503s datacenter IPs (HF included) ->
# retry with real backoff before giving up (1.5s / 3s / 4.5s)
for attempt in range(4):
try:
resp = await client.get(url, headers={
"User-Agent": HEADERS["User-Agent"],
"Accept": "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.9",
})
last_status = resp.status_code
if resp.status_code == 200:
data = resp.json()
break
except Exception:
last_status = 0
if attempt < 3:
await asyncio.sleep(1.5 * (attempt + 1))
if data is None:
errors.append(f"PersianStremio: API HTTP {last_status}")
return results, errors
streams = data.get("streams") or []
if not streams:
errors.append("PersianStremio: no streams")
return results, errors
seen = set()
for st in streams:
if not isinstance(st, dict):
continue
u = st.get("url")
if not u or u in seen:
continue
seen.add(u)
name = re.sub(r'[^\x20-\x7e-ۿ]|[🌸]', '', (st.get("name") or ""))
name = re.sub(r'\s+', ' ', name).strip()
label = (st.get("title") or name or "Direct")[:90]
quality = _sf_quality_from_name(label + " " + name)
results.append(_sf_stream_result(
"PersianStremio", f"PersianStremio - {label}", u,
quality=quality, language="Multi"))
except Exception as ex:
errors.append(f"PersianStremio: {str(ex)}")
return results, errors
# ===== UHDMovies (driveseed chain) =====
# uhdmovies site -> post -> cloud gate -> driveseed r?key -> zfile -> direct
_UHD_DEFAULT_SITE = "https://uhdmovies.autos"
async def _sf_resolve_driveseed(client: httpx.AsyncClient, drive_url: str) -> list:
"""Resolve driveseed.org r?key / file links to direct URLs."""
out = []
try:
u = drive_url
if "/r?key=" in u:
rp = (await client.get(u, headers={"User-Agent": _SF_MOBILE_UA, "Referer": "https://driveseed.org/"})).text
m = re.search(r'action="([^"]*/file/[^"]*)"', rp)
if not m:
m = re.search(r'href="(https?://driveseed\.org/file/[^"]+)"', rp)
if m:
u = ihtml.unescape(m.group(1))
if "/file/" in u:
fp = (await client.get(u, headers={"User-Agent": _SF_MOBILE_UA, "Referer": "https://driveseed.org/"})).text
# zfile / app download links
zf = re.search(r'href="(https?://[^"]*zfile[^"]*)"', fp)
direct = re.search(r'href="(https?://[^"]+\.(?:mkv|mp4)[^"]*)"', fp)
if direct:
chunk = fp[direct.start():direct.start() + 500]
fm = re.search(r'download="([^"]{5,110})"', chunk)
out.append({"url": direct.group(1), "label": fm.group(1) if fm else "Direct"})
elif zf:
zp = (await client.get(ihtml.unescape(zf.group(1)), headers={"User-Agent": _SF_MOBILE_UA, "Referer": u})).text
for b in re.finditer(r'<a[^>]+href="(https?://[^"]+)"[^>]*class="[^"]*btn[^"]*', zp):
bu = b.group(1)
chunk = zp[b.start():b.start() + 800]
fm = re.search(r'download="([^"]{5,110})"', chunk)
fname = fm.group(1) if fm else "Direct"
if "googleusercontent" in bu or ".mkv" in bu or ".mp4" in bu or "workers.dev" in bu or "video-gen" in bu:
out.append({"url": bu, "label": fname})
break
except Exception:
pass
return out
async def scrape_uhdmovies(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results = []
errors = []
try:
info = await get_tmdb_info(tmdb_id, media_type)
title = info.get("title") or ""
year = info.get("year") or ""
site = _UHD_DEFAULT_SITE
try:
async with httpx.AsyncClient(timeout=10) as c:
cfg = (await c.get(_PHISHER_DOMAINS)).json()
cand = cfg.get("uhdmovies")
if isinstance(cand, str) and cand.startswith("http"):
site = cand.rstrip("/")
except Exception:
pass
async with httpx.AsyncClient(timeout=30, follow_redirects=True,
headers={"User-Agent": _SF_MOBILE_UA, "Referer": site + "/"}) as client:
sr = await client.get(f"{site}/?s={quote(title)}")
if sr.status_code != 200:
errors.append(f"UHDMovies: search HTTP {sr.status_code}")
return results, errors
posts = []
for m in re.finditer(r'href="(https?://[^"]*uhdmovies[^"]*/download-[^"\s<>]+)"[^>]*>([^<]{4,150})', sr.text):
url, ttl = m.group(1), m.group(2).strip()
posts.append({"url": url, "title": ttl})
if not posts:
# bare download- links (title from slug)
for m in re.finditer(r'https?://[a-z0-9.]*uhdmovies[a-z0-9.]*/download-([a-z0-9\-]+)/?', sr.text):
slug = m.group(1)
posts.append({"url": f"{site}/download-{slug}/", "title": slug.replace('-', ' ')})
if not posts:
errors.append("UHDMovies: no search results")
return results, errors
tl_norm = _sf_norm(title)
chosen = None
for p in posts:
pt = _sf_norm(p["title"])
if tl_norm in pt and (not year or year in p["title"] or year in p["url"]):
chosen = p
break
if not chosen:
for p in posts:
if tl_norm in _sf_norm(p["url"]):
chosen = p
break
if not chosen and media_type == "movie":
# movies often have "Season 1" style posts; prefer plain movie posts
for p in posts:
if "season" not in p["title"].lower():
chosen = p
break
if not chosen:
chosen = posts[0]
pr = await client.get(chosen["url"])
if pr.status_code != 200:
errors.append(f"UHDMovies: post HTTP {pr.status_code}")
return results, errors
post_html = pr.text
# drive links (driveseed / workers gate)
resolved = []
drive_links = re.findall(r'https?://[^\s"\'<>]*(?:driveseed\.org/[^\s"\'<>]+|cloud\.unblockedgames\.world/[^\s"\'<>]+)', post_html)
seen_links = list(dict.fromkeys(drive_links))[:4]
for dl in seen_links:
resolved.extend(await _sf_resolve_driveseed(client, dl))
# episode filter for TV
seen = set()
for r in resolved:
u, label = r["url"], r["label"]
if u in seen:
continue
seen.add(u)
if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1):
continue
results.append(_sf_stream_result(
"UHDMovies", f"UHDMovies - {label or 'Direct'}", u,
quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label)))
if not results:
errors.append("UHDMovies: no resolvable streams")
except Exception as ex:
errors.append(f"UHDMovies: {str(ex)}")
return results, errors
# ---------- VegaMovies (search.php?q=imdb -> wp-json -> nexdrive -> vcloud/hubcloud) ----------
VEGA_URLS = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json"
_VEGA_DEFAULT_SITE = "https://new2.vegamovies.futbol"
def _sf_b64_all(s: str) -> str:
s = s.strip()
for _ in range(2):
try:
pad = s + "=" * (-len(s) % 4)
s = base64.b64decode(pad).decode("utf-8", errors="ignore")
except Exception:
break
return s
async def _sf_resolve_vcloud(client: httpx.AsyncClient, vcloud_url: str, referer: str) -> list:
out = []
try:
page = (await client.get(vcloud_url, headers={
"User-Agent": _SF_MOBILE_UA, "Referer": referer, "Cookie": "xla=s4t"})).text
m = re.search(r"atob\(atob\('([A-Za-z0-9+/=]+)'\)\)", page)
if m:
dec = _sf_b64_all(m.group(1))
if dec.startswith("http"):
page2 = (await client.get(dec, headers={
"User-Agent": _SF_MOBILE_UA, "Referer": vcloud_url, "Cookie": "xla=s4t"})).text
page = page2
for b in re.finditer(r'<a[^>]+href="(https?://[^"]+)"[^>]+class="[^"]*btn[^"]*"', page):
u = b.group(1)
chunk = page[b.start():b.start() + 800]
fm = re.search(r'download="([^"]{5,110})"', chunk)
fname = fm.group(1) if fm else "Direct"
if "pixeldrain" in u:
out.append({"url": _sf_pixeldrain_direct(u), "label": fname})
elif "cloudflarestorage" in u or "workers.dev" in u or ".r2.dev" in u or "googleusercontent" in u:
out.append({"url": u, "label": fname})
elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) and ".zip" not in u:
out.append({"url": u, "label": fname})
except Exception:
pass
return out
async def scrape_vegamovies(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results = []
errors = []
try:
info = await get_tmdb_info(tmdb_id, media_type)
imdb_id = info.get("imdb_id")
if not imdb_id:
errors.append("VegaMovies: no imdb id")
return results, errors
site = _VEGA_DEFAULT_SITE
try:
async with httpx.AsyncClient(timeout=10) as c:
cfg = (await c.get(VEGA_URLS)).json()
if isinstance(cfg, dict) and cfg.get("vegamovies"):
site = cfg["vegamovies"].rstrip("/")
except Exception:
pass
async with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=_SF_HUB_HEADERS) as client:
sr = await client.get(f"{site}/search.php", params={"q": imdb_id, "page": 1, "per_page": 15})
if sr.status_code != 200:
errors.append(f"VegaMovies: search HTTP {sr.status_code}")
return results, errors
try:
sdata = sr.json()
except Exception:
errors.append("VegaMovies: search non-JSON")
return results, errors
hits = sdata.get("hits") or []
posts = [h.get("document", h) if isinstance(h, dict) else h for h in hits]
if not posts:
errors.append("VegaMovies: no search results")
return results, errors
title_norm = _sf_norm(info.get("title") or "")
year = str(info.get("year") or "")
chosen = None
for p in posts:
if not isinstance(p, dict):
continue
pt = p.get("post_title") or p.get("title") or ""
if title_norm and title_norm in _sf_norm(pt):
chosen = p
break
if chosen is None and posts:
chosen = posts[0]
post_id = chosen.get("id") if isinstance(chosen, dict) else None
if not post_id:
errors.append("VegaMovies: no matching post")
return results, errors
pr = await client.get(f"{site}/wp-json/wp/v2/posts/{post_id}")
if pr.status_code != 200:
errors.append(f"VegaMovies: post HTTP {pr.status_code}")
return results, errors
content = (pr.json().get("content") or {}).get("rendered", "")
nexdrive_links = re.findall(r'https?://nexdrive\.[a-z]+/[a-z0-9]+/[a-zA-Z0-9]+/?', content)
hubcloud_links = re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', content)
if not nexdrive_links and not hubcloud_links:
nexdrive_links = re.findall(r'https?://[^\s"\'<>]*(?:vcloud|nexdrive|dgdrive|fastdl)\.[a-z]+/[^\s"\'<>]{4,60}', content)
resolved = []
for hl in hubcloud_links[:4]:
resolved.extend(await _sf_resolve_hubcloud(client, hl))
for nl in nexdrive_links[:5]:
if len(resolved) >= 10:
break
try:
np = (await client.get(nl, headers={
"User-Agent": _SF_MOBILE_UA, "Referer": f"{site}/"})).text
except Exception:
continue
for hl in re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', np)[:2]:
resolved.extend(await _sf_resolve_hubcloud(client, hl))
vc_refs = list(dict.fromkeys(re.findall(r'https?://vcloud\.[a-z]+/[a-zA-Z0-9]+', np)))[:2]
for vl in vc_refs:
resolved.extend(await _sf_resolve_vcloud(client, vl, str(nl)))
results.extend(_sf_hubcloud_results("VegaMovies", resolved, media_type, season, episode))
if not results:
errors.append("VegaMovies: no resolvable streams")
except Exception as ex:
errors.append(f"VegaMovies: {str(ex)}")
return results, errors
_SF_HUB_HEADERS = {"User-Agent": _SF_MOBILE_UA, "Accept": "text/html,application/xhtml+xml,*/*", "Accept-Language": "en-US,en;q=0.5"}
# ===== Source Map =====
SOURCE_MAP = {
"castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e),
"languages": ["English", "Tamil", "Telugu"], "reliability": "high",
"note": "hlowb.com API, AES-CBC, multi-language m3u8 (EN/Tamil/Telugu)"},
"netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e),
"languages": ["Hindi", "English", "Multi"], "reliability": "high",
"note": "net27.cc embed-tmdb, mp4 360p-1080p + subtitles. CDN blocks datacenter IPs: play url WITH the returned headers (Referer+UA) from the client, like the Nuvio app does. proxied_url available as fallback"},
"playbox": {"name": "PlayBox", "fn": lambda tid, mt, s, e: scrape_playbox(tid, mt, s, e),
"languages": ["English", "Multi"], "reliability": "high",
"note": "streamdata.vaplayer.ru API, multi-quality m3u8, TMDB id based"},
"movix": {"name": "Movix", "fn": lambda tid, mt, s, e: scrape_movix(tid, mt, s, e),
"languages": ["English", "Multi"], "reliability": "high",
"note": "api.movix.cash direct API, m3u8 1080p"},
"movies4u": {"name": "Movies4u", "fn": lambda tid, mt, s, e: scrape_movies4u(tid, mt, s, e),
"languages": ["Hindi", "English", "Multi"], "reliability": "medium",
"note": "m4uplay packed player -> acek-cdn m3u8 + HubCloud/Google direct, movie+TV"},
"persianstremio": {"name": "PersianStremio", "fn": lambda tid, mt, s, e: scrape_persianstremio(tid, mt, s, e),
"languages": ["Multi", "Persian"], "reliability": "high",
"note": "stremio-style API (imdb based), direct MKV up to 2160p, movie+TV"},
"vegamovies": {"name": "VegaMovies", "fn": lambda tid, mt, s, e: scrape_vegamovies(tid, mt, s, e),
"languages": ["Hindi", "English", "Multi"], "reliability": "medium",
"note": "search.php?q=imdb + nexdrive + vcloud chain, direct MKV up to 4K"},
}
DEFAULT_SOURCES = ["castle", "netmirror", "playbox", "movix", "movies4u", "persianstremio"]
# ===== Helper: Run scrapers =====
async def run_scrape(tmdb_id: int, media_type: str, season: int = None, episode: int = None, source_keys: list = None):
info = await get_tmdb_info(tmdb_id, media_type)
title = info.get("title")
imdb_id = info.get("imdb_id")
all_results = []
all_errors = []
keys = source_keys or DEFAULT_SOURCES
async def run_one(key: str):
src = SOURCE_MAP.get(key)
if not src:
return [], [f"{key}: Unknown source"]
try:
r, e = await asyncio.wait_for(src["fn"](tmdb_id, media_type, season, episode), timeout=60)
return r, e
except asyncio.TimeoutError:
return [], [f"{src['name']}: Timeout (60s)"]
except Exception as ex:
return [], [f"{src['name']}: {str(ex)}"]
tasks = [run_one(k) for k in keys]
task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results:
if isinstance(result, Exception):
all_errors.append(f"Scraper failed: {str(result)}")
else:
r, e = result
all_results.extend(r)
all_errors.extend(e)
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 "")
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"{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 {
"success": len(unique_results) > 0,
"tmdb_id": tmdb_id,
"imdb_id": imdb_id,
"title": title,
"year": info.get("year"),
"results": unique_results,
"errors": all_errors if all_errors else None,
}
# ===== Root: JSON documentation =====
@app.get("/")
async def root():
return {
"api": "StreamForge",
"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}",
"example": "/movie/912649", "example_source": "/movie/912649/castle"},
"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>&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.",
],
"added": [
"Movies4u - m4uplay packed-player unpack -> acek-cdn m3u8 + HubCloud/Google direct",
"PersianStremio - stremio-style imdb API, direct MKV up to 2160p, movie+TV",
"UHDMovies - works in Nuvio (node) but its unblockedgames gate fingerprint-blocks the final hop from Python/httpx - noted, not added",
"/proxy_range - Range-capable stream proxy with header injection + m3u8 rewriting",
],
"removed": [
"VidLove - api.shows.st 403 'Website Access Blocked' for all datacenter IPs (dead for server-side use)",
],
"kept": ["Castle, PlayBox, Movix (verified playable), VegaMovies (registered)"],
},
"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)",
"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), proxied_url (absolute proxy URL), subtitles (proxied VTT)",
],
}
# ===== Simple GET endpoints =====
@app.get("/movie/{tmdb_id}")
async def movie_all(tmdb_id: int):
return await run_scrape(tmdb_id, "movie")
@app.get("/movie/{tmdb_id}/{source}")
async def movie_source(tmdb_id: int, source: str):
source = source.lower()
if source not in SOURCE_MAP:
raise HTTPException(400, {"error": f"Unknown source '{source}'", "available": list(SOURCE_MAP.keys())})
return await run_scrape(tmdb_id, "movie", source_keys=[source])
@app.get("/tv/{tmdb_id}/{season}/{episode}")
async def tv_all(tmdb_id: int, season: int, episode: int):
return await run_scrape(tmdb_id, "tv", season=season, episode=episode)
@app.get("/tv/{tmdb_id}/{season}/{episode}/{source}")
async def tv_source(tmdb_id: int, season: int, episode: int, source: str):
source = source.lower()
if source not in SOURCE_MAP:
raise HTTPException(400, {"error": f"Unknown source '{source}'", "available": list(SOURCE_MAP.keys())})
return await run_scrape(tmdb_id, "tv", season=season, episode=episode, source_keys=[source])
@app.get("/search/{query}")
async def search_simple(query: str, page: int = 1):
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.get(
f"{TMDB_BASE}/search/multi",
params={"api_key": TMDB_API_KEY, "query": query, "page": page, "include_adult": False}
)
data = resp.json()
filtered = [r for r in data.get("results", []) if r.get("media_type") in ("movie", "tv")]
results = []
for r in filtered[:20]:
mid = r.get("id")
mt = r.get("media_type", "movie")
t = r.get("title") or r.get("name", "Unknown")
year = (r.get("release_date") or r.get("first_air_date") or "")[:4]
results.append({
"id": mid,
"type": "TV" if mt == "tv" else "Movie",
"title": t,
"year": year,
"url": f"/{mt}/{mid}" if mt == "movie" else f"/tv/{mid}/1/1",
})
return {
"query": query,
"count": len(results),
"results": results,
}
# ===== JSON API endpoints =====
@app.get("/api/health")
async def health():
return {"status": "ok", "timestamp": int(time.time())}
@app.get("/api/sources")
async def list_sources():
return {
"sources": {key: {"name": src["name"], "languages": src["languages"], "reliability": src["reliability"],
**({"note": src["note"]} if "note" in src else {})}
for key, src in SOURCE_MAP.items()},
"default": DEFAULT_SOURCES,
}
@app.get("/api/search")
async def search_tmdb(q: str = Query(...), page: int = 1):
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.get(
f"{TMDB_BASE}/search/multi",
params={"api_key": TMDB_API_KEY, "query": q, "page": page, "include_adult": False}
)
data = resp.json()
filtered = [r for r in data.get("results", []) if r.get("media_type") in ("movie", "tv")]
return {
"page": data.get("page"),
"total_pages": data.get("total_pages"),
"total_results": data.get("total_results"),
"results": filtered,
}
@app.post("/api/scrape")
async def scrape(request: ScrapeRequest):
source_keys = None
if request.sources:
source_keys = [s.lower() for s in request.sources]
return await run_scrape(request.tmdb_id, request.media_type, request.season, request.episode, source_keys)
@app.post("/api/scrape/all")
async def scrape_all(request: ScrapeRequest):
return await run_scrape(request.tmdb_id, request.media_type, request.season, request.episode, list(SOURCE_MAP.keys()))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
"""
StreamForge API v12 - Multi-Language Stream Scraper
v12 (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, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, Response, JSONResponse
from pydantic import BaseModel
from typing import Optional
import httpx
import json
import re
import base64
import time
import asyncio
import contextvars
import hashlib
import html as ihtml
from urllib.parse import quote, urljoin, urlparse
app = FastAPI(
title="StreamForge API",
description="Multi-language m3u8/mp4/MKV stream scraper",
version="12.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
TMDB_API_KEY = "7967738a03ec215c7d6d675faba9c973"
TMDB_BASE = "https://api.themoviedb.org/3"
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Accept": "application/json, text/html, */*",
"Accept-Language": "en-US,en;q=0.5",
}
# ===== Models =====
class ScrapeRequest(BaseModel):
tmdb_id: int
media_type: str = "movie"
season: Optional[int] = None
episode: Optional[int] = None
sources: Optional[list[str]] = None
# ===== Helpers =====
async def get_tmdb_info(tmdb_id: int, media_type: str) -> dict:
async with httpx.AsyncClient(timeout=10) as client:
type_path = "tv" if media_type == "tv" else "movie"
resp = await client.get(
f"{TMDB_BASE}/{type_path}/{tmdb_id}",
params={"api_key": TMDB_API_KEY, "append_to_response": "external_ids"}
)
data = resp.json()
return {
"imdb_id": data.get("external_ids", {}).get("imdb_id"),
"title": data.get("title") or data.get("name"),
"year": (data.get("release_date") or data.get("first_air_date") or "")[:4],
}
def detect_language(label: str) -> str:
lower = label.lower()
if "hindi" in lower or "hin" in lower: return "Hindi"
if "tamil" in lower or "tam" in lower: return "Tamil"
if "telugu" in lower or "tel" in lower: return "Telugu"
if "bengali" in lower or "bangla" in lower or "ben" in lower: return "Bengali"
if "malayalam" in lower or "mal" in lower: return "Malayalam"
if "kannada" in lower or "kan" in lower: return "Kannada"
if "english" in lower or "eng" in lower or "en" == lower: return "English"
if "italian" in lower or "ita" in lower or "italiano" in lower: return "Italian"
if "french" in lower or "fra" in lower or "vf" in lower: return "French"
if "german" in lower or "deu" in lower or "ger" in lower: return "German"