Spaces:
Running
v13: NetMirror + Castle rebuilt from All-in-One-Nuvio (verified playable)
Browse filesNetMirror v3:
- bcdnxw CDN 429s were REFERER-gating (requires videodownloader.site referer), not IP blocks
- direct + proxied playback both verified 206 video/mp4 (360p-1080p)
- movie subtitles proxied (real SRT); NewTV fallback dead upstream, not ported
Castle v2 (castle.js port):
- v2.0.1 getVideo2 flow, seasons[].movieId traversal fixes wrong-episode TV bug
- movieType 2=Movies/1=TV match fix; per-language tracks + TV shared stream
- VTT subtitles; TS-segments-as-image/jpeg disguise handled
Not integrated (tested dead): vidlink, vidfast, vidsrc.me, kurage, vixsrc, goated, 1shows, showbox, allmovieland, moviebox, vidrock, NewTV
Not added per policy: Cineby (dead), Videasy (Cineby property)
Vyla: private GitLab repo, no public hosted API - cannot be self-hosted
Files changed (4)
- __pycache__/main.cpython-312.pycDeleted
- main.py+312-264
- main.py.bakDeleted-1754
- main_v9.py.bakDeleted
122345678910111213141516171819202122232432 unmodified lines5758594160616263413 unmodified lines4774784794614804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145159 unmodified lines5255265274774784794804814824834844854864874884894904915285295304945315325335345354995005015025035045055365075375385095395405415425435115445455465475155485495505511 unmodified line5535545555235245255265275285295305315565575335345355365585595605395405615625635645655665675685695425435705715725735745755475485765775785795805815535825835845855865595875885899 unmodified lines5996006015755765776026036046056066076086096106116125825835846136146155875886166176186195925935946206216226235975986246256266276026286296306316066076326336096106346356366136376156166176186196206216226236246256266276286296386396406416426436446456466316476486336346356496506516526536546556566576586596606616626636646656666376676396406416686696706716726736456466476486496506516526536546556566576586746756606616626636646766776786796806816826836846856676866876886896906916926936946956696706966976986726736746756997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547556776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087567097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767577787587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987807817827837847857867998008018028038048058068078088098108118128138147887898158168178188193 unmodified lines82382482579980080182682782882983083183283383483583683783883984084184284384484584684784884985085185224 unmodified lines877878879835880881837882883884885886887888889890891892893845846847848894895896897898852853854855856857858859899900901902903904905906861862863864865907908909910911912913914915916917869918919920871872873874921922923924925926927878928929930931932933884885934935936645 unmodified lines15821583158415371538158515861587154015411588158915901591159294 unmodified lines16871688168916421690169116921693"""StreamForge API v12 - Multi-Language Stream ScraperStreamForge API v13 - Multi-Language Stream Scraperv13 (netmirror+castle rebuild, Nuvio port): - NetMirror REBUILT from All-in-One-Nuvio netmirror.js: the bcdnxw CDN 429s are REFERER-gating, not IP-blocking - the CDN requires Referer "https://videodownloader.site/" (net27.cc referers get 429 from any IP). With it, direct playback AND the Space proxy both return 206 video/mp4 (360p-1080p verified). Movie subtitles proxied (real SRT). NewTV platform fallback is dead upstream - not ported. - Castle REBUILT from All-in-One-Nuvio castle.js: v2.0.1 getVideo2 flow with correct seasons[] "movieId" traversal (fixes WRONG-EPISODE bug), correct movieType matching (2=Movies/1=TV), per-language tracks (Tamil/OST/English) + TV shared-stream fallback, VTT subtitles. img*.com CDNs serve TS segments disguised as image/jpeg - intentional upstream obfuscation, plays fine. - Tested & dead (NOT integrated): vidlink, vidfast, vidsrc.me, kurage, vixsrc, goated, 1shows, showbox, allmovieland, moviebox, vidrock, Nuvio NewTV. - NOT added per policy: Cineby (dead), Videasy (Cineby property - absent). - Vyla (docs.vyla.cc): private GitLab repo + no public hosted API - cannot be self-hosted without repo access (documented, not integrated). - All 6 default sources verified playable end-to-end (m3u8 playlist + segment fetch + real TS/MP4 bytes) from a datacenter IP.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 base32 unmodified linesapp = FastAPI( title="StreamForge API", description="Multi-language m3u8/mp4/MKV stream scraper", version="12.0.0", version="13.0.0",)
app.add_middleware(413 unmodified lines return results
# ===== Castle Scraper (hlowb.com API with AES-CBC) - multi-language m3u8 =====# ===== Castle Scraper v2 (hlowb.com API with AES-CBC) - multi-language m3u8 =====# Ported from All-in-One-Nuvio providers/castle.js (verified playable 2025-09).# Fixes vs the old v12 scraper:# - getVideo2 is now film-api/v2.0.1 (POST JSON body, movieId+episodeId+languageId)# - seasons[] entries carry the season id in the "movieId" field (NOT "id") -# the old scraper read the wrong field and served TV requests from the WRONG# SEASON (e.g. S5E1 when S1E1 was requested)# - movieType match: 2 = Movies, 1 = TV shows (old code had the values inverted# and only survived via its fallback loops)# - language tracks come from episodes[0].tracks[]: every track with# existIndividualVideo=true gets its own getVideo2 call (Tamil/OST/...),# the default (English) track is queried with its languageId, and TV falls# back to the shared stream (no languageId) exactly like the Nuvio app# - NOTE: the img*.com Castle CDNs disguise MPEG-TS segments as image/jpeg# (".jpg" URLs) - that is intentional upstream obfuscation, the bytes are# real TS (magic 47 40 11) and every HLS player handles them fine
CASTLE_BASE = "https://api.hlowb.com"CASTLE_PKG = "com.external.castle"CASTLE_CH = "IndiaA"CASTLE_CLI = "1"CASTLE_LANG = "en-US"CASTLE_SIGN = "ED0955EB04E67A1D9F3305B95454FED485261475"CASTLE_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
CASTLE_HEADERS = { "User-Agent": CASTLE_UA, "Accept": "application/json", "Accept-Language": "en-US,en;q=0.9", "Connection": "Keep-Alive", "Referer": "https://api.hlowb.com",}
async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = []9 unmodified lines 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: # 1) security key -> AES key/iv (base64 payload, key = sec + "T!BgJB" zero-padded to 16) sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1", params={ "channel": CH, "clientType": CLI, "lang": LANG "channel": CASTLE_CH, "clientType": CASTLE_CLI, "lang": CASTLE_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") sec_key = base64.b64decode(sec_r.json().get("data", "")).decode("utf-8", errors="ignore") except Exception: sec_key = raw_k sec_key = sec_r.json().get("data", "") if not sec_key: errors.append("Castle: bad sec key response") return results, errors
combined = (sec_key + "T!BgJB") 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): def castle_decrypt(text: str): d = text try: j = json.loads(text)1 unmodified line 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
raw = None 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) raw = base64.b64decode(d + "=" * (-len(d) % 4)) except Exception: pass
try: if raw is None or len(raw) % 16 != 0: raw = None try: raw = bytes.fromhex(d) except Exception: pass if raw is None or len(raw) % 16 != 0 or not raw: # maybe it is plain JSON already return json.loads(text) except Exception: raise ValueError(f"Castle decrypt failed for data length={len(d)}") dec = unpad(AES.new(aes_k, AES.MODE_CBC, aes_iv).decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") return json.loads(dec)
# 2) search by "title year" 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" "channel": CASTLE_CH, "clientType": CASTLE_CLI, "keyword": kw, "lang": CASTLE_LANG, "mode": "1", "packageName": CASTLE_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, errors9 unmodified lines 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 # movieType: 2 = Movies, 1 = TV shows want_type = 2 if media_type == "movie" else 1 tl = _sf_norm(title)
def _norm_row(r): return _sf_norm(r.get("title", "") or r.get("name", ""))
mid = None 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: if _norm_row(r) == tl and r.get("movieType", r.get("subjectType", 0)) == want_type: mid = r.get("id") break
if not mid: if mid is None: 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: rt = _norm_row(r) if (tl in rt or rt in tl) and r.get("movieType", r.get("subjectType", 0)) == want_type: mid = r.get("id") break
if not mid: if mid is None: for r in rows: if not isinstance(r, dict): continue rt = normalize_title(r.get("title", "") or r.get("name", "")).lower() rt = _norm_row(r) if tl in rt or rt in tl: mid = r.get("id") break
if not mid and isinstance(rows[0], dict): if mid is None and isinstance(rows[0], dict): mid = rows[0].get("id")
if not mid: if mid is None: 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): # 3) details (v1.9.9) -> episodes + seasons + language tracks async def fetch_details(movie_id): dr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={ "channel": CASTLE_CH, "clientType": CASTLE_CLI, "lang": CASTLE_LANG, "movieId": str(movie_id), "packageName": CASTLE_PKG }) if dr.status_code != 200: return {} try: dd = json.loads(dd) dp = castle_decrypt(dr.text) except Exception: dd = {} if not isinstance(dd, dict): dd = {} return {} dd = dp.get("data", dp) if isinstance(dd, str): try: dd = json.loads(dd) except Exception: dd = {} return dd if isinstance(dd, dict) else {}
dd = await fetch_details(mid) if not dd: errors.append("Castle: detail fetch failed") return results, errors
video_movie_id = str(mid) ep_id = None ep_info = None
ep_id = mid if media_type == "tv" and season and episode: seasons = dd.get("seasons", []) s_id = mid for s_item in seasons: # find the season's own movieId ("movieId" field, NOT "id") s_mid = None for s_item in (dd.get("seasons") or []): 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 s_mid = s_item.get("movieId") or s_item.get("id") 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: if s_mid and str(s_mid) != str(mid): video_movie_id = str(s_mid) sdd = await fetch_details(s_mid) if sdd.get("episodes"): dd = sdd for ep in (dd.get("episodes") or []): if isinstance(ep, dict) and (ep.get("number") == episode or ep.get("episodeNum") == episode): ep_id = str(ep.get("id", "")) ep_info = ep break mid = s_id if not ep_id and (dd.get("episodes") or []): # fallback: positional eps = [e for e in dd.get("episodes") if isinstance(e, dict)] if 0 < episode <= len(eps): ep_id = str(eps[episode - 1].get("id", "")) ep_info = eps[episode - 1] if not ep_id: errors.append(f"Castle: episode S{season}E{episode} not found") return results, errors else: eps = dd.get("episodes", []) if eps and isinstance(eps[0], dict): eps = [e for e in (dd.get("episodes") or []) if isinstance(e, dict)] if eps: 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]: ep_info = eps[0] else: ep_id = str(mid)
# 4) language tracks from the episode payload tracks = [] if isinstance(ep_info, dict): tracks = [t for t in (ep_info.get("tracks") or []) if isinstance(t, dict)]
lang_calls = [] default_track = next((t for t in tracks if t.get("isDefault")), None) if default_track and default_track.get("languageId"): lang_calls.append((default_track.get("languageName") or "Default", str(default_track["languageId"]))) for t in tracks: if t.get("existIndividualVideo") and t.get("languageId"): lid = str(t["languageId"]) if lid not in [x[1] for x in lang_calls]: lang_calls.append((t.get("languageName") or "Track", lid))
if not lang_calls: lang_calls = [("English", "1003")]
# TV additionally gets the shared stream (no languageId) - that is # what the Nuvio app falls back to when per-language video is absent include_shared = media_type == "tv"
async def get_video2(movie_id: str, episode_id: str, language_id: str = None): body = { "mode": "1", "appMarket": "GuanWang", "clientType": CASTLE_CLI, "woolUser": "false", "apkSignKey": CASTLE_SIGN, "androidVersion": "13", "movieId": str(movie_id), "episodeId": str(episode_id), "isNewUser": "true", "resolution": "2", "packageName": CASTLE_PKG, } if language_id: body["languageId"] = str(language_id) vr = await client.post( f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2", params={"clientType": CASTLE_CLI, "packageName": CASTLE_PKG, "channel": CASTLE_CH, "lang": CASTLE_LANG}, json=body, headers={"Content-Type": "application/json"}, ) if vr.status_code != 200: return None try: vp = castle_decrypt(vr.text) except Exception: return None vd = vp.get("data", vp) if isinstance(vd, str): 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) 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 return None return vd if isinstance(vd, dict) else None
def quality_from(vd: dict, vurl: str) -> str: # the real ladder is in the URL path (/720/...) - label from that m = re.search(r'/(\d{3,4})/', vurl) if m: return f"{m.group(1)}P" best = "720P" for v in (vd.get("videos") or []): if isinstance(v, dict) and not v.get("premiumProPermission"): q = str(v.get("resolutionDescription", "")).strip() q = re.sub(r'^(SD|HD|FHD|UHD)\s+', '', q).upper() if q: best = q return best
emitted_urls = set()
async def emit(vd: dict, label: str): if not vd: return vurl = vd.get("videoUrl", "") if not vurl or _sf_url_has_ctrl(vurl) or vurl in emitted_urls: return emitted_urls.add(vurl) quality = quality_from(vd, vurl) subs_out = [] for sub in (vd.get("subtitles") or []): if isinstance(sub, dict) and sub.get("url"): subs_out.append({"language": sub.get("title") or sub.get("abbreviate") or "Sub", "url": sub["url"]}) hdrs = {"User-Agent": CASTLE_UA} proxied = _proxy_wrap(vurl, ua=CASTLE_UA) results.append(_sf_stream_result( "Castle", f"Castle [{label}] - {quality}", vurl, quality=quality, language=label if label != "Default" else "English", headers=hdrs, subtitles=subs_out or None, direct_url=proxied, proxied_url=proxied))
seen = set() uniq = [] for r in results: if r["url"] not in seen: seen.add(r["url"]) uniq.append(r) results = uniq for label, lid in lang_calls: try: vd = await get_video2(video_movie_id, ep_id, lid) if vd and vd.get("videoUrl"): await emit(vd, label) except Exception: continue
if include_shared: try: vd = await get_video2(video_movie_id, ep_id, None) if vd and vd.get("videoUrl"): await emit(vd, "Shared") except Exception: pass
if not results: errors.append("Castle: no streams found") if not results: errors.append("Castle: no streams found")
except ImportError: errors.append("Castle: pycryptodome not installed")3 unmodified lines 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 v3 (net27.cc embed-tmdb) - mp4 with SOLVED CDN gating =====# Ported from All-in-One-Nuvio providers/netmirror.js (verified playable 2025-09).## THE 429 MYSTERY, SOLVED: bcdnxw.hakunaymatata.com (the NetMirror CDN) does NOT# block datacenter IPs. It gates on the REFERER: requests must carry# "https://videodownloader.site/" (the referer the Nuvio web player uses).# The v12 scraper sent "https://net27.cc/" and got 429 from every IP - that is# why MOON appeared dead. With the correct referer:# * direct client playback (device IP + Referer/UA headers) -> 206 video/mp4# * playback through the Space proxy (which injects those headers) -> 206 too# Both paths verified from a datacenter IP, all qualities (360/480/720/1080).## Subtitles: movie captions go through net27.cc /api/proxy/video (302 to a# streamhub worker, serves real SRT - proxied through us). TV captions point# at an R2 cache (net27-r2-cache...workers.dev) that 403s datacenter IPs, so# they are returned as direct URLs for the client's own IP to fetch.## Nuvio's "NewTV" platform fallback (mobiledetects.com -> tv.imgcdn.kim) is# dead upstream ("Page Not Found" even with the app's exact headers) - not ported.
_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"# the referer the CDN actually requires - NOT net27.cc_NETMIRROR_CDN_REF = "https://videodownloader.site/"_NETMIRROR_HEADERS = { "Accept": "application/json, text/plain, */*", "Referer": "https://net27.cc/",24 unmodified lines errors.append("NetMirror: title not available on NetMirror") return results, errors
# Subtitle tracks (proxied) # Subtitle tracks subs_out = [] for sub in (data.get("subtitles") or []): for sub in (data.get("captions") or 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 # net27.cc's own proxy (movie captions) - verified SRT via our proxy surl = _proxy_wrap(surl, ref="https://net27.cc/", ua=_NETMIRROR_UA) # TV captions (absolute workers.dev URLs) stay direct: the R2 cache # 403s datacenter IPs, so let the client's own IP try them 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), }) name = sub.get("name") or lang subs_out.append({"language": name, "url": surl}) 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 # Streams: "streams" ladder (360/480/720) + "mp4" (top quality) entries = [] for s in (data.get("streams") or []): if isinstance(s, dict) and s.get("url"): entries.append((s.get("url"), s.get("resolution"))) if data.get("mp4"): entries.append((data.get("mp4"), data.get("resolution", "1080")))
for s in streams: if not isinstance(s, dict): continue u = s.get("url") if not u: if not entries: errors.append("NetMirror: no streams in response") return results, errors
seen = set() for u, res in entries: u = str(u or "") if not u or u in seen: continue if u.startswith("/"): u = _NETMIRROR_BASE + u res = str(s.get("resolution") or "").strip() seen.add(u) res = str(res 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) # CDN requires the videodownloader.site referer - with it, both the # direct URL (players that can send headers) and the proxy URL # (any player, embedded anywhere) return 206 video/mp4 proxied = _proxy_wrap(u, ref=_NETMIRROR_CDN_REF, 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}, headers={"Referer": _NETMIRROR_CDN_REF, "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"645 unmodified lines
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)"}, "languages": ["English", "Tamil", "Multi"], "reliability": "high", "note": "hlowb.com API v2.0.1 getVideo2 (Nuvio castle.js port), AES-CBC, per-language m3u8 + TV shared stream. TS segments arrive disguised as image/jpeg (upstream obfuscation) - players handle them, and the proxy rewrites playlists end-to-end"}, "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"}, "languages": ["English", "Multi"], "reliability": "high", "note": "net27.cc embed-tmdb, mp4 360p-1080p + subtitles (Nuvio netmirror.js port). CDN requires Referer https://videodownloader.site/ - with it BOTH direct playback (url + returned headers, device IP) AND the proxied_url (any player, embedded anywhere) stream fine. No IP blocking - the v12 429s were wrong-referer 429s"}, "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"},94 unmodified linesasync def root(): return { "api": "StreamForge", "version": "12.0.0", "version": "13.0.0", "description": "Multi-language m3u8/mp4/MKV stream scraper", "endpoints": { "movie": {"all_sources": "/movie/{tmdb_id}", "single_source": "/movie/{tmdb_id}/{source}",12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754"""StreamForge API v5 - Multi-Language Stream ScraperScrapes direct m3u8 URLs from multiple sources"""
from fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optionalimport httpximport jsonimport reimport base64import timeimport asyncio
app = FastAPI( title="StreamForge API", description="Multi-language m3u8 stream scraper", version="5.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 "multi" in lower: return "Multi" return "English"
# ===== CineSu Scraper =====
async def scrape_cinesu(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client: if media_type == "movie": url = f"https://cine.su/v1/stream/master/movie/{tmdb_id}.m3u8" else: s = season or 1 e = episode or 1 url = f"https://cine.su/v1/stream/master/tv/{tmdb_id}/{s}/{e}.m3u8"
resp = await client.get(url, headers={ "Referer": "https://cine.su/en/watch", "Origin": "https://cine.su", })
if resp.status_code == 404: errors.append("CineSu: Content not available") return results, errors
if resp.status_code != 200: errors.append(f"CineSu: HTTP {resp.status_code}") return results, errors
content = resp.text if "#EXT-X-STREAM-INF" in content: lines = content.split("\n") for i, line in enumerate(lines): if line.startswith("#EXT-X-STREAM-INF:"): resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) name = re.search(r'NAME="([^"]+)"', line) quality = resolution.group(1) if resolution else "Auto" label = name.group(1) if name else quality if i + 1 < len(lines) and lines[i + 1].startswith("http"): results.append({ "source": "CineSu", "title": label, "quality": quality, "language": "English", "url": lines[i + 1].strip(), "type": "m3u8", }) elif ".m3u8" in content: m3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', content) if m3u8_match: results.append({ "source": "CineSu", "title": "English Stream", "quality": "Auto", "language": "English", "url": m3u8_match.group(0), "type": "m3u8", })
if not results: errors.append("CineSu: No streams found")
except Exception as e: errors.append(f"CineSu: {str(e)}")
return results, errors
# ===== VixSrc Scraper =====
async def scrape_vixsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: if media_type == "movie": api_url = f"https://vixsrc.to/api/movie/{tmdb_id}" else: s = season or 1 e = episode or 1 api_url = f"https://vixsrc.to/api/tv/{tmdb_id}/{s}/{e}"
api_resp = await client.get(api_url)
try: api_data = api_resp.json() except: errors.append("VixSrc: API returned non-JSON (possible Cloudflare block)") return results, errors
src_path = api_data.get("src", "") if not src_path: errors.append("VixSrc: No embed path returned") return results, errors
embed_resp = await client.get(f"https://vixsrc.to{src_path}")
if embed_resp.status_code == 410: api_resp2 = await client.get(api_url) try: api_data2 = api_resp2.json() except: errors.append("VixSrc: API retry failed") return results, errors src_path2 = api_data2.get("src", "") if not src_path2: errors.append("VixSrc: No embed path on retry") return results, errors embed_resp = await client.get(f"https://vixsrc.to{src_path2}") src_path = src_path2
html = embed_resp.text
token = None expires = None playlist_url = None
mp_match = re.search(r'window\.masterPlaylist\s*=\s*(\{[\s\S]*?\})\s*\n', html) if mp_match: mp_text = mp_match.group(1) token_m = re.search(r"'token'\s*:\s*'([^']+)'", mp_text) expires_m = re.search(r"'expires'\s*:\s*'([^']+)'", mp_text) url_m = re.search(r"url\s*:\s*'([^']+)'", mp_text)
if token_m: token = token_m.group(1) if expires_m: expires = expires_m.group(1) if url_m: playlist_url = url_m.group(1)
if not token: token_match = re.search(r'token["\']\s*:\s*["\']([^"\']+)', html) if token_match: token = token_match.group(1) if not playlist_url: url_match = re.search(r'url\s*:\s*["\']([^"\']+playlist[^"\']*)', html) if url_match: playlist_url = url_match.group(1)
if not (token and playlist_url): errors.append("VixSrc: Could not extract stream parameters from embed") return results, errors
if not expires: expires = str(int(time.time()) + 86400) sep = "&" if "?" in playlist_url else "?" master_url = f"{playlist_url}{sep}token={token}&expires={expires}&h=1"
pl_resp = await client.get(master_url, headers={"Referer": f"https://vixsrc.to{src_path}"}) pl_content = pl_resp.text
if "#EXTM3U" in pl_content: audio_tracks = [] lines = pl_content.split("\n") for line in lines: if line.startswith("#EXT-X-MEDIA:TYPE=AUDIO"): name_match = re.search(r'NAME="([^"]+)"', line) lang_match = re.search(r'LANGUAGE="([^"]+)"', line) uri_match = re.search(r'URI="([^"]+)"', line) if name_match and uri_match: audio_tracks.append({ "language": name_match.group(1), "lang_code": lang_match.group(1) if lang_match else name_match.group(1), "uri": uri_match.group(1), })
for i, line in enumerate(lines): if line.startswith("#EXT-X-STREAM-INF:"): resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) quality = resolution.group(1) if resolution else "Auto" if i + 1 < len(lines) and lines[i + 1].startswith("http"): video_url = lines[i + 1].strip() if audio_tracks: for track in audio_tracks: results.append({ "source": "VixSrc", "title": f"{track['language']} Audio", "quality": quality, "language": detect_language(track["language"]), "url": video_url, "audio_url": track["uri"], "type": "m3u8", }) else: results.append({ "source": "VixSrc", "title": "English Stream", "quality": quality, "language": "English", "url": video_url, "type": "m3u8", }) else: results.append({ "source": "VixSrc", "title": "Stream", "quality": "Auto", "language": "Multi", "url": master_url, "type": "m3u8", })
if not results: errors.append("VixSrc: No streams found in playlist")
except Exception as e: errors.append(f"VixSrc: {str(e)}")
return results, errors
# ===== VidNest Scraper =====
VIDNEST_ALPHABET = "RB0fpH8ZEyVLkv7c2i6MAJ5u3IKFDxlS1NTsnGaqmXYdUrtzjwObCgQP94hoeW+/="
def vidnest_b64_decode(input_str: str) -> str: lookup = {c: i for i, c in enumerate(VIDNEST_ALPHABET)} mod = len(input_str) % 4 if mod: input_str += "=" * (4 - mod) result = bytearray() for i in range(0, len(input_str), 4): chunk = input_str[i:i+4] c0 = lookup.get(chunk[0], 64) c1 = lookup.get(chunk[1], 64) c2 = 64 if chunk[2] == "=" else lookup.get(chunk[2], 64) c3 = 64 if chunk[3] == "=" else lookup.get(chunk[3], 64) result.append(((c0 << 2) | (c1 >> 4)) & 0xff) if c2 != 64: result.append((((c1 & 0x0f) << 4) | (c2 >> 2)) & 0xff) if c3 != 64: result.append((((c2 & 0x03) << 6) | c3) & 0xff) return bytes(result).decode("utf-8", errors="ignore")
async def scrape_vidnest(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
servers = { "purstream": "French", "klikxxi": "English", "hollymoviehd": "English", "moviebox": "Multi", "allmovies": "Multi", "vidlink": "English", "onehd": "English", "flixhq": "English", }
try: async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client: async def fetch_server(server_name: str, language: str): server_results = [] try: if media_type == "movie": url = f"https://new.vidnest.fun/{server_name}/movie/{tmdb_id}" else: s = season or 1 e = episode or 1 url = f"https://new.vidnest.fun/{server_name}/tv/{tmdb_id}/{s}/{e}"
resp = await client.get(url) if resp.status_code != 200: return server_results, f"{server_name}: HTTP {resp.status_code}"
data = resp.json() encoded_data = data.get("data", "") if not encoded_data: return server_results, f"{server_name}: No data"
decoded = vidnest_b64_decode(encoded_data) parsed = json.loads(decoded)
sources = parsed.get("sources", []) title = parsed.get("title", "")
for source in sources: url_key = None for key in ["url", "file", "stream", "src", "link"]: if key in source: url_key = key break if not url_key: continue
stream_url = source[url_key] quality = source.get("quality") or source.get("label") or source.get("name", "Auto") source_name = source.get("name", source.get("label", "")) stream_type = "m3u8" if ".m3u8" in stream_url or source.get("type") == "hls" else "direct"
lang = detect_language(source_name) if source_name else language
server_results.append({ "source": f"VidNest/{server_name}", "title": source_name or title, "quality": quality, "language": lang, "url": stream_url, "type": stream_type, })
except Exception as e: return server_results, f"{server_name}: {str(e)}"
return server_results, None
tasks = [fetch_server(name, lang) for name, lang in servers.items()] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): errors.append(f"VidNest: {str(result)}") else: server_results, error = result results.extend(server_results) if error: errors.append(f"VidNest {error}")
except Exception as e: errors.append(f"VidNest: {str(e)}")
return results, errors
# ===== Popr Scraper =====
async def scrape_popr(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
servers = ["default", "catflix", "hexa", "Gama", "Liligoon", "Sigma", "Prime", "Alfa", "Lamda"]
try: async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: async def fetch_server(server: str): server_results = [] try: if media_type == "movie": url = f"https://popr.ink/api/vidnest?id={tmdb_id}&type=movie&server={server}" else: s = season or 1 e = episode or 1 url = f"https://popr.ink/api/vidnest?id={tmdb_id}&type=tv&server={server}&season={s}&episode={e}"
resp = await client.get(url) if resp.status_code != 200: return server_results, f"{server}: HTTP {resp.status_code}"
data = resp.json() if not data.get("success"): return server_results, None
for r in data.get("results", []): for stream in r.get("streams", []): stream_url = stream.get("url", "") quality = stream.get("quality", "Auto") is_m3u8 = stream.get("isM3U8", False) stream_type = "m3u8" if is_m3u8 else "direct"
lang = detect_language(quality)
server_results.append({ "source": f"Popr/{server}", "title": quality, "quality": quality, "language": lang, "url": stream_url, "type": stream_type, })
except Exception as e: return server_results, f"{server}: {str(e)}"
return server_results, None
tasks = [fetch_server(s) for s in servers] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): errors.append(f"Popr: {str(result)}") else: server_results, error = result results.extend(server_results) if error: errors.append(f"Popr {error}")
seen_urls = set() unique_results = [] for r in results: if r["url"] not in seen_urls: seen_urls.add(r["url"]) unique_results.append(r) results = unique_results
except Exception as e: errors.append(f"Popr: {str(e)}")
return results, errors
# ===== VidRock Scraper (AES-encrypted API) =====
async def scrape_vidrock(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: from Crypto.Cipher import AES as CryptoAES from Crypto.Util.Padding import pad as crypto_pad
passphrase = b"x7k9mPqT2rWvY8zA5bC3nF6hJ2lK4mN9" aes_key = passphrase[:32] aes_iv = passphrase[:16]
if media_type == "tv": s = season or 1 e = episode or 1 item_id = f"{tmdb_id}_{s}_{e}" api_type = "tv" else: item_id = str(tmdb_id) api_type = "movie"
cipher = CryptoAES.new(aes_key, CryptoAES.MODE_CBC, aes_iv) ct = cipher.encrypt(crypto_pad(item_id.encode(), CryptoAES.block_size)) encoded = base64.b64encode(ct).decode().replace("+", "-").replace("/", "_").replace("=", "")
async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: resp = await client.get(f"https://vidrock.net/api/{api_type}/{encoded}") if resp.status_code != 200: errors.append(f"VidRock: HTTP {resp.status_code}") return results, errors
data = resp.json() for server_name, server_data in data.items(): if isinstance(server_data, dict) and server_data.get("url"): url = server_data["url"] lang = server_data.get("language", "English") stream_type = server_data.get("type", "hls") s_type = "m3u8" if stream_type == "hls" or ".m3u8" in url else "direct"
results.append({ "source": f"VidRock/{server_name}", "title": f"{server_name} - {lang}", "quality": "Auto", "language": detect_language(lang), "url": url, "type": s_type, })
if not results: errors.append("VidRock: No streams found")
except ImportError: errors.append("VidRock: pycryptodome not installed") except Exception as e: errors.append(f"VidRock: {str(e)}")
return results, errors
# ===== DooFlix Scraper (Hindi/Indian content - API based) =====
async def scrape_dooflix(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: async with httpx.AsyncClient(timeout=15, follow_redirects=False) as client: BASE_API = "https://panel.watchkaroabhi.com" API_KEY = "qNhKLJiZVyoKdi9NCQGz8CIGrpUijujE"
dooflix_headers = { "X-Package-Name": "com.king.moja", "User-Agent": "dooflix", "X-App-Version": "305", } STREAM_REFERER = "https://molop.art/"
if media_type == "movie": url = f"{BASE_API}/api/3/movie/{tmdb_id}/links?api_key={API_KEY}" else: s = season or 1 e = episode or 1 url = f"{BASE_API}/api/3/tv/{tmdb_id}/season/{s}/episode/{e}/links?api_key={API_KEY}"
resp = await client.get(url, headers=dooflix_headers) if resp.status_code != 200: errors.append(f"DooFlix: API error HTTP {resp.status_code}") return results, errors
data = resp.json() links = data.get("links", [])
if not links: errors.append("DooFlix: No links found") return results, errors
for link_obj in links: try: link_url = link_obj.get("url", "") host = link_obj.get("host", "Server") if not link_url: continue
redir_resp = await client.get( link_url, headers={ "Referer": STREAM_REFERER, "User-Agent": "dooflix", }, )
stream_url = None if redir_resp.status_code in (301, 302, 303, 307, 308): stream_url = redir_resp.headers.get("location", "") elif redir_resp.status_code == 200: stream_url = link_url else: stream_url = redir_resp.headers.get("location", link_url)
if not stream_url: continue
s_type = "m3u8" if ".m3u8" in stream_url else "direct" quality = "Auto" q_match = re.search(r'(\d{3,4})p', stream_url) if q_match: quality = q_match.group(1) + "p"
results.append({ "source": f"DooFlix/{host}", "title": f"DooFlix - {host}", "quality": quality, "language": "Hindi", "url": stream_url, "type": s_type, "headers": { "Referer": STREAM_REFERER, "User-Agent": "dooflix", }, })
except Exception as e: errors.append(f"DooFlix/{host}: {str(e)}")
if not results: errors.append("DooFlix: No streams resolved")
except Exception as e: errors.append(f"DooFlix: {str(e)}")
return results, errors
# ===== Castle Scraper (Stremio-style aggregator) =====
async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: import urllib.parse
info = await get_tmdb_info(tmdb_id, media_type) imdb_id = info.get("imdb_id")
if not imdb_id: errors.append("Castle: Could not get IMDB ID from TMDB") return results, errors
CASTLE_API = "https://meowtv.vflix.shop" SKIP_PATTERNS = ["4khdhub", "instant download", "iosmirror", "xdm", "redirecting"]
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: if media_type == "movie": url = f"{CASTLE_API}/stream/movie/{imdb_id}.json" else: s = season or 1 e = episode or 1 url = f"{CASTLE_API}/stream/series/{imdb_id}:{s}:{e}.json"
resp = await client.get(url, headers={"Accept": "application/json"}) if resp.status_code != 200: errors.append(f"Castle: HTTP {resp.status_code}") return results, errors
data = resp.json() streams = data.get("streams", [])
if not streams: errors.append("Castle: No streams found") return results, errors
for s in streams: s_url = s.get("url", "") if not s_url: continue
name = (s.get("name") or "").lower() title = (s.get("title") or "").lower() if any(p in name or p in title for p in SKIP_PATTERNS): continue if "github.com" in s_url or "googleusercontent" in s_url: continue
# Castle often wraps URLs like: https://...?url=ACTUAL_URL actual_url = s_url url_param = re.search(r'[?&]url=([^&]+)', s_url) if url_param: actual_url = urllib.parse.unquote(url_param.group(1))
quality = "Auto" q_match = re.search(r'(\d{3,4})p', name + title + actual_url) if q_match: quality = q_match.group(1) + "p" elif "4k" in (name + title).lower() or "2160" in actual_url: quality = "4K"
lang = detect_language(name + " " + title)
s_type = "m3u8" if ".m3u8" in actual_url else ("direct" if ".mp4" in actual_url or ".mkv" in actual_url else "m3u8")
results.append({ "source": "Castle", "title": s.get("name", "Castle Stream"), "quality": quality, "language": lang, "url": actual_url, "type": s_type, })
seen_urls = set() unique_results = [] for r in results: if r["url"] not in seen_urls: seen_urls.add(r["url"]) unique_results.append(r) results = unique_results
if not results: errors.append("Castle: No usable streams after filtering")
except Exception as e: errors.append(f"Castle: {str(e)}")
return results, errors
# ===== MovieBoxHindi Scraper (Hindi - Cloudflare Worker API) =====
async def scrape_movieboxhindi(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: WORKER_BASE = "https://moviebox.s4nch1tt.workers.dev"
async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: url = f"{WORKER_BASE}/streams?tmdb_id={tmdb_id}&type={media_type}&proxy={WORKER_BASE}" if media_type == "tv": s = season or 1 e = episode or 1 url += f"&se={s}&ep={e}"
resp = await client.get(url, headers={ "Accept": "application/json", "User-Agent": "StreamForge/1.0", })
if resp.status_code != 200: errors.append(f"MovieBoxHindi: HTTP {resp.status_code}") return results, errors
data = resp.json()
raw_streams = [] if isinstance(data, list): raw_streams = data elif isinstance(data, dict): raw_streams = data.get("streams", [])
if not raw_streams: errors.append("MovieBoxHindi: No streams returned") return results, errors
for s in raw_streams: stream_url = s.get("proxy_url") or s.get("url", "") if not stream_url: continue
quality = "Auto" resolution = s.get("resolution", "") if resolution: m = re.search(r'(\d+)', str(resolution)) quality = m.group(1) + "p" if m else str(resolution)
s_name = s.get("name", "") lang = detect_language(s_name)
results.append({ "source": "MovieBoxHindi", "title": s_name or "MovieBox Stream", "quality": quality, "language": lang, "url": stream_url, "type": "m3u8", })
if not results: errors.append("MovieBoxHindi: No valid streams parsed")
except Exception as e: errors.append(f"MovieBoxHindi: {str(e)}")
return results, errors
# ===== Videasy Scraper (Multi-server encrypted API) =====
async def scrape_videasy(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: VIDEASY_HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36", "Accept": "application/json, text/plain, */*", "Origin": "https://player.videasy.net", "Referer": "https://player.videasy.net/", } DECRYPT_API = "https://enc-dec.app/api/dec-videasy"
SERVERS = { "Neon": "https://api.videasy.net/myflixerzupcloud/sources-with-title", "Cypher": "https://api.videasy.net/moviebox/sources-with-title", "Reyna": "https://api.videasy.net/primewire/sources-with-title", "Omen": "https://api.videasy.net/onionplay/sources-with-title", "Breach": "https://api.videasy.net/m4uhd/sources-with-title", "Ghost": "https://api.videasy.net/primesrcme/sources-with-title", "Sage": "https://api.videasy.net/1movies/sources-with-title", "Vyse": "https://api.videasy.net/hdmovie/sources-with-title", "Raze": "https://api.videasy.net/superflix/sources-with-title", }
info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") year = info.get("year", "") imdb_id = info.get("imdb_id", "")
async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=VIDEASY_HEADERS) as client: async def fetch_server(name: str, endpoint: str): server_results = [] try: url = f"{endpoint}?title={title}&mediaType={media_type}&year={year}&tmdbId={tmdb_id}&imdbId={imdb_id or ''}" if media_type == "tv": s = season or 1 e = episode or 1 url += f"&seasonId={s}&episodeId={e}"
resp = await client.get(url) encrypted_text = resp.text
if not encrypted_text or len(encrypted_text) < 20 or encrypted_text.startswith("<!"): return server_results, f"{name}: No data or blocked"
dec_resp = await client.post( DECRYPT_API, json={"text": encrypted_text, "id": str(tmdb_id)}, headers={"Content-Type": "application/json"}, )
if dec_resp.status_code != 200: return server_results, f"{name}: Decrypt failed"
decrypted = dec_resp.json() res_data = decrypted.get("result") or decrypted
if not res_data or not res_data.get("sources"): return server_results, f"{name}: No sources"
for s in res_data["sources"]: stream_url = s.get("url", "") if not stream_url: continue quality = s.get("quality", "Auto")
server_results.append({ "source": f"Videasy/{name}", "title": f"Videasy {name}", "quality": quality, "language": "English", "url": stream_url, "type": "m3u8", "headers": { "Referer": "https://player.videasy.net/", "Origin": "https://player.videasy.net", "User-Agent": VIDEASY_HEADERS["User-Agent"], }, })
except Exception as e: return server_results, f"{name}: {str(e)}"
return server_results, None
tasks = [fetch_server(name, endpoint) for name, endpoint in SERVERS.items()] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): errors.append(f"Videasy: {str(result)}") else: server_results, error = result results.extend(server_results) if error: errors.append(f"Videasy {error}")
seen_urls = set() unique_results = [] for r in results: if r["url"] not in seen_urls: seen_urls.add(r["url"]) unique_results.append(r) results = unique_results
except Exception as e: errors.append(f"Videasy: {str(e)}")
return results, errors
# ===== NetMirror Scraper (Netflix/PrimeVideo/Hotstar via API) =====
async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: CONFIG_URL = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json" FALLBACK_API = "https://tv.imgcdn.kim/newtv" OTT_SERVICES = [ {"code": "nf", "name": "Netflix"}, {"code": "pv", "name": "PrimeVideo"}, {"code": "hs", "name": "Hotstar"}, ]
NETMIRROR_HEADERS = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0 /OS.GatuNewTV v1.0", "x-requested-with": "NetmirrorNewTV v1.0", }
# Get API base URL api_base = FALLBACK_API try: async with httpx.AsyncClient(timeout=10) as cfg_client: cfg_resp = await cfg_client.get(CONFIG_URL) cfg_data = cfg_resp.json() api_base = cfg_data.get("nfmirror", FALLBACK_API) except: pass
# Get media title from TMDB info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") if not title: errors.append("NetMirror: Could not get title from TMDB") return results, errors
async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: async def fetch_service(service: dict): service_results = [] service_errors = [] try: svc_code = service["code"] svc_name = service["name"] headers = {**NETMIRROR_HEADERS, "ott": svc_code}
# Search for the title search_url = f"{api_base}/search.php?s={title}" search_resp = await client.get(search_url, headers=headers)
if search_resp.status_code != 200: return service_results, [f"{svc_name}: Search HTTP {search_resp.status_code}"]
try: search_data = search_resp.json() except: return service_results, [f"{svc_name}: Search returned non-JSON"]
search_results = search_data.get("searchResult", []) # Fuzzy match: exact first, then starts-with, then contains match = None title_lower = title.lower() for item in search_results: item_title = item.get("t", "").strip().lower() if item_title == title_lower: match = item break if not match: for item in search_results: item_title = item.get("t", "").strip().lower() if item_title.startswith(title_lower) or title_lower.startswith(item_title): match = item break if not match: for item in search_results: item_title = item.get("t", "").strip().lower() if title_lower in item_title or item_title in title_lower: match = item break
if not match or not match.get("id"): return service_results, [f"{svc_name}: No match found"]
net_id = match["id"] final_id = net_id
# For TV, drill down to season/episode if media_type == "tv": s = season or 1 e = episode or 1
post_resp = await client.get(f"{api_base}/post.php?id={net_id}", headers=headers) if post_resp.status_code != 200: return service_results, [f"{svc_name}: Post HTTP {post_resp.status_code}"]
try: post_data = post_resp.json() except: return service_results, [f"{svc_name}: Post returned non-JSON"]
seasons = post_data.get("season", []) target_term = f"Season {s}" season_entry = None for se in seasons: if se.get("s", "").__str__().find(target_term) >= 0: season_entry = se break
if not season_entry or not season_entry.get("id"): return service_results, [f"{svc_name}: Season {s} not found"]
season_id = season_entry["id"] episode_id = None page = 1
while not episode_id and page < 10: ep_resp = await client.get( f"{api_base}/episodes.php?id={season_id}&page={page}", headers=headers ) if ep_resp.status_code != 200: break try: ep_data = ep_resp.json() except: break
episodes_list = ep_data.get("episodes", []) for ep in episodes_list: if str(ep.get("ep", "")) == str(e): episode_id = ep.get("id") break
if ep_data.get("nextPageShow") != "1": break page += 1
if not episode_id: return service_results, [f"{svc_name}: S{s}E{e} not found"]
final_id = episode_id
# Get the actual stream player_resp = await client.get(f"{api_base}/player.php?id={final_id}", headers=headers) if player_resp.status_code != 200: return service_results, [f"{svc_name}: Player HTTP {player_resp.status_code}"]
try: player_data = player_resp.json() except: return service_results, [f"{svc_name}: Player returned non-JSON"]
video_link = player_data.get("video_link", "") if not video_link: return service_results, [f"{svc_name}: No video link"]
# Verify the m3u8 stream is actually playable # PrimeVideo/Hotstar use freecdn2.top which returns 404 on segments if ".m3u8" in video_link: try: verify_resp = await client.get(video_link, headers=headers) verify_text = verify_resp.text if "#EXTM3U" not in verify_text: return service_results, [f"{svc_name}: Master playlist unreachable"] # Check for broken CDN - freecdn2.top segments always return 404 if "freecdn2.top" in verify_text: seg_match = re.search(r'(https?://[^\s"]+\.m3u8[^\s"]*)', verify_text) if seg_match: seg_resp = await client.get(seg_match.group(1).split('"')[0].split()[0], headers=headers) if seg_resp.status_code == 404: return service_results, [f"{svc_name}: Stream unplayable (CDN segments 404)"] except: pass
s_type = "m3u8" if ".m3u8" in video_link else ("direct" if ".mp4" in video_link or ".mkv" in video_link else "m3u8") quality = "Auto" q_match = re.search(r'(\d{3,4})p', video_link) if q_match: quality = q_match.group(1) + "p"
lang = "Hindi" if svc_code == "hs" else "English"
service_results.append({ "source": f"NetMirror/{svc_name}", "title": f"{svc_name} Stream", "quality": quality, "language": lang, "url": video_link, "type": s_type, "headers": { "Referer": player_data.get("referer", ""), "User-Agent": NETMIRROR_HEADERS["user-agent"], }, })
except Exception as ex: service_errors.append(f"{service['name']}: {str(ex)}")
return service_results, service_errors
tasks = [fetch_service(svc) for svc in OTT_SERVICES] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): errors.append(f"NetMirror: {str(result)}") else: r, e = result results.extend(r) errors.extend(e)
if not results: errors.append("NetMirror: No streams found")
except Exception as e: errors.append(f"NetMirror: {str(e)}")
return results, errors
# ===== HDMovie2 Scraper (Hindi/Hollywood Hindi Dubbed) =====
async def scrape_hdmovie2(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: BASE = "https://hdmovie2.com.se" CDN = "https://hdm2.ink" UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
# Get title from TMDB info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") year = info.get("year", "") if not title: errors.append("HDMovie2: Could not get title from TMDB") return results, errors
async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers={"User-Agent": UA}) as client:
# Step 1: Search on the site search_url = f"{BASE}/?s={title}" search_resp = await client.get(search_url, headers={"Referer": f"{BASE}/"}) search_html = search_resp.text
# Parse search results - find matching movie page movie_url = None import re as _re article_pattern = _re.compile(r'<article[^>]*>(.*?)</article>', _re.DOTALL) link_pattern = _re.compile(r'href="(https://hdmovie2\.com\.se/movies/([^"]+)/)"') alt_pattern = _re.compile(r'alt="([^"]+)"')
best_match = None best_score = 0 title_lower = title.lower().replace(":", "").replace("-", " ").strip()
for article_match in article_pattern.finditer(search_html): article = article_match.group(1) link_m = link_pattern.search(article) if not link_m: continue if "/feed/" in link_m.group(1): continue
alt_m = alt_pattern.search(article) if not alt_m: continue
item_url = link_m.group(1) item_title = alt_m.group(1).strip()
# Simple scoring: exact match > starts with > contains item_lower = item_title.lower().replace(":", "").replace("-", " ").strip() score = 0 if item_lower == title_lower: score = 100 elif item_lower.startswith(title_lower) or title_lower.startswith(item_lower): score = 80 elif title_lower in item_lower: score = 60
# Year bonus if year and year in item_title: score += 10
if score > best_score: best_score = score best_match = item_url
if not best_match or best_score < 30: errors.append("HDMovie2: No matching result found") return results, errors
# Step 2: Get the movie page to extract post ID page_resp = await client.get(best_match, headers={"Referer": f"{BASE}/"}) page_html = page_resp.text
post_id_match = re.search(r'postid-(\d+)', page_html) if not post_id_match: errors.append("HDMovie2: Could not find post ID") return results, errors
post_id = post_id_match.group(1)
# Step 3: Try servers (up to 4) via AJAX for nume in range(1, 5): try: ajax_resp = await client.post( f"{BASE}/wp-admin/admin-ajax.php", data=f"action=doo_player_ajax&post={post_id}&nume={nume}&type=movie", headers={ "Referer": best_match, "Content-Type": "application/x-www-form-urlencoded", "User-Agent": UA, }, )
if ajax_resp.status_code != 200: continue
try: ajax_data = ajax_resp.json() except: continue
embed_url = ajax_data.get("embed_url", "") if not embed_url: continue
embed_url = embed_url.replace("\\/", "/")
# Try hdm2.ink player hdm2_match = re.search(r'src="(https://hdm2\.ink/play\?v=[^"]+)"', embed_url) if hdm2_match: player_resp = await client.get(hdm2_match.group(1), headers={"Referer": f"{BASE}/"}) player_html = player_resp.text stream_match = re.search(r'data-stream-url="([^"]+)"', player_html) if stream_match: stream_path = stream_match.group(1).replace("&", "&") final_url = f"{CDN}{stream_path}" if ".m3u8" not in final_url: final_url += "#index.m3u8"
results.append({ "source": f"HDMovie2/srv{nume}", "title": "Hindi Dubbed HD", "quality": "1080p", "language": "Hindi", "url": final_url, "type": "m3u8", "headers": { "Referer": f"{CDN}/", "Origin": CDN, "User-Agent": UA, }, }) break
# Try molop.art player molop_match = re.search(r'src="(https://molop\.art/watch\?v=[^"]+)"', embed_url) if molop_match: molop_resp = await client.get(molop_match.group(1), headers={"Referer": f"{BASE}/"}) molop_html = molop_resp.text sniff_match = re.search(r'sniff\([^,]+,[^,]+,\S+?([a-f0-9]{20,})', molop_html) if sniff_match: hash_val = sniff_match.group(1) m3u8_url = f"https://molop.art/m3u8/1/{hash_val}/master.m3u8?s=1&cache=1" results.append({ "source": f"HDMovie2/molop{nume}", "title": "Hindi Dubbed HD", "quality": "1080p", "language": "Hindi", "url": m3u8_url, "type": "m3u8", "headers": { "Referer": "https://molop.art/", "Origin": "https://molop.art", "User-Agent": UA, }, }) break
# Skip prvs.top and ok.ru if "prvs.top" in embed_url or "ok.ru" in embed_url: continue
except Exception as e: errors.append(f"HDMovie2/srv{nume}: {str(e)}") continue
if not results: errors.append("HDMovie2: No working streams found")
except Exception as e: errors.append(f"HDMovie2: {str(e)}")
return results, errors
# ===== AllMovieLand Scraper (Hindi/Tamil/Multi via allmovieland.one) =====
async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36" info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") if not title: errors.append("AllMovieLand: Could not get title from TMDB") return results, errors
# Use single client session throughout (important for cookies/session) async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers={"User-Agent": UA}, http2=False) as client: # Step 1: Search search_resp = await client.get( "https://allmovieland.one/index.php", params={"story": title, "do": "search", "subaction": "search"} ) if search_resp.status_code != 200: errors.append(f"AllMovieLand: Search HTTP {search_resp.status_code}") return results, errors
search_html = search_resp.text articles = re.findall(r'<article[^>]*>(.*?)</article>', search_html, re.DOTALL) if not articles: errors.append("AllMovieLand: No search results") return results, errors
# Find best match movie_url = None title_lower = title.lower() for article in articles: link_m = re.search(r'href="([^"]+)"', article) h3_m = re.search(r'<h3[^>]*>(.*?)</h3>', article) if link_m and h3_m: item_title = h3_m.group(1).strip().lower() if item_title == title_lower or title_lower in item_title: movie_url = link_m.group(1) break if not movie_url: # Fallback: first result for article in articles: link_m = re.search(r'href="([^"]+)"', article) if link_m: movie_url = link_m.group(1) break
if not movie_url: errors.append("AllMovieLand: Could not find movie URL") return results, errors
# Step 2: Movie page movie_resp = await client.get(movie_url, headers={"Referer": "https://allmovieland.one/"}) movie_html = movie_resp.text
# Extract player domain and media ID from script section # The variables are inside <script> tags in tabs__content domain_match = re.search(r"AwsIndStreamDomain\s*=\s*['\"]([^'\"]+)['\"]", movie_html) player_domain = domain_match.group(1).rstrip("/") if domain_match else None id_match = re.search(r"src:\s*['\"]([^'\"]+)['\"]", movie_html) media_id = id_match.group(1) if id_match else None
if not player_domain or not media_id: errors.append(f"AllMovieLand: No player info (domain={player_domain}, id={media_id})") return results, errors
# Step 3: Embed page - get p3 data embed_url = f"{player_domain}/play/{media_id}" embed_resp = await client.get(embed_url, headers={"Referer": movie_url}) embed_html = embed_resp.text
# Find p3 - try multiple patterns p3_m = re.search(r'let\s+p3\s*=\s*(\{.*?\})\s*;', embed_html) if not p3_m: p3_m = re.search(r'p3\s*=\s*(\{[^;]+\})\s*;', embed_html) if not p3_m: p3_m = re.search(r'(\{"file".*?"key".*?\})', embed_html) if not p3_m: errors.append("AllMovieLand: Could not find player data in embed") return results, errors
try: p3 = json.loads(p3_m.group(1)) except json.JSONDecodeError: errors.append(f"AllMovieLand: Invalid p3 JSON: {p3_m.group(1)[:80]}") return results, errors
file_url = p3.get("file", "").replace("\\/", "/") csrf_key = p3.get("key", "")
if not file_url or not csrf_key: errors.append("AllMovieLand: Missing file URL or CSRF key in p3") return results, errors
# Step 4: POST to get file list - burst with fresh clients file_list = None post_headers = { "X-CSRF-TOKEN": csrf_key, "Referer": embed_url, "Origin": player_domain, "Accept": "application/json, text/plain, */*", "User-Agent": UA, }
for attempt in range(7): try: async with httpx.AsyncClient(timeout=10, follow_redirects=True, http2=False) as fresh_client: resp = await fresh_client.post(file_url, headers=post_headers) text = resp.text.strip() if text != "7" and text.startswith("["): file_list = json.loads(text.replace(",]", "]")) break except: pass
if not file_list: errors.append("AllMovieLand: Could not get file list (7 attempts)") return results, errors
# Filter files based on media type target_files = [] if media_type == "movie": target_files = [f for f in file_list if f.get("file")] else: s = season or 1 e = episode or 1 for item in file_list: item_title = item.get("title", "") s_m = re.search(r'Season\s*(\d+)', item_title, re.I) if s_m and int(s_m.group(1)) == s: if item.get("folder"): for ep_item in item["folder"]: ep_title = ep_item.get("title", "") e_m = re.search(r'Episode\s*(\d+)', ep_title, re.I) if e_m and int(e_m.group(1)) == e: if ep_item.get("folder"): target_files = [f for f in ep_item["folder"] if f.get("file")] break break
if not target_files: target_files = [f for f in file_list if f.get("file")][:3]
# Step 5: Get m3u8 URL for each file - burst for file_obj in target_files: file_path = file_obj.get("file", "").lstrip("~") stream_title = file_obj.get("title", "Stream") if not file_path: continue
playlist_url = f"{player_domain}/playlist/{file_path}.txt" m3u8_url = None for attempt in range(7): try: async with httpx.AsyncClient(timeout=10, follow_redirects=True, http2=False) as fresh_client: resp = await fresh_client.post(playlist_url, headers=post_headers) text = resp.text.strip() if text != "7" and text.startswith("http"): m3u8_url = text break except: pass
if m3u8_url: lang = detect_language(stream_title) quality = "Auto" q_m = re.search(r'(\d{3,4})p', stream_title) if q_m: quality = q_m.group(1) + "p"
results.append({ "source": "AllMovieLand", "title": f"AllMovieLand - {stream_title}", "quality": quality, "language": lang, "url": m3u8_url, "type": "m3u8", "headers": { "Referer": f"{player_domain}/", "Origin": player_domain, "User-Agent": UA, }, })
if not results: errors.append("AllMovieLand: Could not resolve any m3u8 URLs")
except Exception as e: errors.append(f"AllMovieLand: {str(e)}")
return results, errors
# ===== Source Map =====
SOURCE_MAP = { "cinesu": {"name": "CineSu", "fn": lambda tid, mt, s, e: scrape_cinesu(tid, mt, s, e), "languages": ["English"], "reliability": "high"}, "vixsrc": {"name": "VixSrc", "fn": lambda tid, mt, s, e: scrape_vixsrc(tid, mt, s, e), "languages": ["English", "Italian", "Multi"], "reliability": "low", "note": "Cloudflare-blocked from datacenter IPs, works from residential only"}, "vidnest": {"name": "VidNest", "fn": lambda tid, mt, s, e: scrape_vidnest(tid, mt, s, e), "languages": ["French", "English", "Multi"], "reliability": "medium"}, "popr": {"name": "Popr", "fn": lambda tid, mt, s, e: scrape_popr(tid, mt, s, e), "languages": ["Hindi", "Tamil", "Telugu", "English", "French"], "reliability": "broken", "note": "API returns 403 Forbidden since May 2026"}, "vidrock": {"name": "VidRock", "fn": lambda tid, mt, s, e: scrape_vidrock(tid, mt, s, e), "languages": ["English"], "reliability": "high"}, "dooflix": {"name": "DooFlix", "fn": lambda tid, mt, s, e: scrape_dooflix(tid, mt, s, e), "languages": ["Hindi", "English", "Multi"], "reliability": "high"}, "castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e), "languages": ["English", "Hindi", "Multi"], "reliability": "high"}, "movieboxhindi": {"name": "MovieBoxHindi", "fn": lambda tid, mt, s, e: scrape_movieboxhindi(tid, mt, s, e), "languages": ["Hindi", "English"], "reliability": "high"}, "allmovieland": {"name": "AllMovieLand", "fn": lambda tid, mt, s, e: scrape_allmovieland(tid, mt, s, e), "languages": ["Hindi", "Tamil", "Telugu", "English", "Multi"], "reliability": "medium"}, "hdmovie2": {"name": "HDMovie2", "fn": lambda tid, mt, s, e: scrape_hdmovie2(tid, mt, s, e), "languages": ["Hindi", "English"], "reliability": "medium"}, "netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e), "languages": ["Hindi", "English", "Multi"], "reliability": "high"}, "videasy": {"name": "Videasy", "fn": lambda tid, mt, s, e: scrape_videasy(tid, mt, s, e), "languages": ["English", "Multi"], "reliability": "medium"},}
DEFAULT_SOURCES = ["cinesu", "vidnest", "dooflix", "castle", "movieboxhindi", "netmirror", "allmovieland", "vidrock"]
# ===== 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=45) return r, e except asyncio.TimeoutError: return [], [f"{src['name']}: Timeout (45s)"] 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 = [] for r in all_results: if r["url"] not in seen_urls: seen_urls.add(r["url"]) 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": "5.0.0", "description": "Multi-language m3u8 stream scraper", "endpoints": { "movie": { "all_sources": "/movie/{tmdb_id}", "single_source": "/movie/{tmdb_id}/{source}", "example": "/movie/912649", "example_source": "/movie/912649/popr", }, "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/cinesu", }, "search": { "path": "/search/{query}", "example": "/search/Venom", }, "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": {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_sources": DEFAULT_SOURCES, "tips": [ "No source = default sources (cinesu, vidnest, dooflix, castle, movieboxhindi, netmirror, allmovieland, vidrock)", "Best for Hindi: /movie/ID/allmovieland or /movie/ID/dooflix or /movie/ID/movieboxhindi or /movie/ID/castle", "Best for English: /movie/ID/cinesu or /movie/ID/vidrock or /movie/ID/videasy", "Best for French: /movie/ID/vidnest", "Castle: Stremio aggregator, returns multiple streams from different providers", "NetMirror: Searches Netflix, PrimeVideo, Hotstar via API - great for Hindi/English", "VixSrc: Blocked from cloud IPs, works residential only", "m3u8 links work in VLC, mpv, or any HLS player", ], }
# ===== 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)