Spaces:
Running
Running
Download main.py from EpicCoderGG/streamforge-api: direct link, hf CLI and curl.
- Browser
- Download file 124 kB
-
https://huggingface.co/spaces/EpicCoderGG/streamforge-api/resolve/e1c936b8aef29e223c856fc0c16126db14cab0a7/main.py
- Command line
-
hf download hf://spaces/EpicCoderGG/streamforge-api@e1c936b8aef29e223c856fc0c16126db14cab0a7/main.py
-
curl -L -o main.py https://huggingface.co/spaces/EpicCoderGG/streamforge-api/resolve/e1c936b8aef29e223c856fc0c16126db14cab0a7/main.py
124 kB
"""
StreamForge API v14 - Multi-Language Stream Scraper
v14 (Vyla SDK provider wave):
- 8 NEW sources ported from the Vyla SDK (github.com/vyla-entertainment/sdk,
40 provider files tested one-by-one with playlist+segment verification from
a datacenter IP):
WORKING -> integrated: vidfast (2160p fMP4), vidup, meowtv (castle-CDN
multi-language), lookmovie, lmscript, fsonic (direct MP4), vidrock
(AES-GCM), hexa (intermittent).
DEAD from datacenter (documented, NOT integrated): vidlink (site down,
403s), vidsync (enc dec issues), pengu (google auth wall), videasy
(Cineby property - excluded per policy), vidnest (playlist 403), cinesu
(playlist 403), vidfast-via-nuvio (old impl), anikoto/anineko (segment
403), vidrift/vidcore/vidvault/opstream/peachify/vixsrc/xpass/1embed/
cinejoy/flaxmovies/fsharetv/fsonline/mapple/kisskh/anizone/anipm/
anihq/123anime/reanime/kickassanime (no streams / anime-only catalogs).
- Note: vidfast/vidup/meowtv/hexa depend on enc-dec.app (public crypto relay
the sites themselves use client-side; it is also what the Vyla SDK uses).
- Known upstream catalog gaps: NetMirror genuinely lacks some older titles
(e.g. Venom 2018 -> noSource:true from net27.cc upstream) - the API now
returns 13+ other sources for such titles; players should fall back.
v13 (netmirror+castle rebuild, Nuvio port):
- NetMirror REBUILT from All-in-One-Nuvio netmirror.js: the bcdnxw CDN 429s are
REFERER-gating: the CDN requires Referer "https://videodownloader.site/"
(exact, trailing slash; net27.cc referers get 429 from any IP).
Verified: viewer device IP + correct referer -> 206 video/mp4 (PRIMARY:
play url + returned headers, Nuvio-app model); non-blocked server via our
proxy -> 206; bcdnxw additionally 426-range-blocks HF Spaces IPs (use the
direct url+headers path there). 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 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, unquote
import random
app = FastAPI(
title="StreamForge API",
description="Multi-language m3u8/mp4/MKV stream scraper",
version="14.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.
URI= attributes are rewritten too (not only KEY/MAP): multi-audio masters
(e.g. m4uplay/acek) carry their audio track playlists in
#EXT-X-MEDIA:...URI="index-a1.m3u8?..." attributes. Leaving them relative
used to break players that resolved them against the proxy URL instead of
the upstream base (404 -> audioTrackLoadError retry loops -> the stream
never starts even though the languages parsed fine)."""
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("#") and 'URI="' in ls:
# #EXT-X-MEDIA (audio tracks), #EXT-X-I-FRAME-STREAM-INF, session-data
# and any other tag carrying a URI= attribute: resolve it against the
# upstream base and route it through this proxy, same as plain lines.
def attr_uri(mm):
return f'URI="{_wrap(mm.group(1))}"'
ls = re.sub(r'URI="([^"]+)"', attr_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 _boosted_segment(u: str, headers: dict, total: int, parts: int = 6):
"""Fetch a binary segment as `parts` parallel HTTP Range requests and
reassemble. Returns the full bytes on success, or None on ANY problem
(caller falls back to the normal single-stream path). Segments are
bounded (a few MB), so buffering the reassembled body is fine.
parts=6: measured per-connection throttle is ~450KB/s and parallel
connections keep most of their individual rate (3 concurrent ≈ 433KB/s
each), so 6 parts ≈ 2.2MB/s aggregate — a 10s/5MB segment lands in
~2-3s instead of 11s, comfortably inside hls.js's fragment budget."""
step = total // parts
if step < 256 * 1024:
return None
bounds = []
start = 0
for i in range(parts):
end = total - 1 if i == parts - 1 else start + step - 1
bounds.append((start, end))
start = end + 1
async def fetch_range(s: int, e: int) -> bytes:
c = httpx.AsyncClient(timeout=httpx.Timeout(90, connect=15), follow_redirects=True)
try:
h = dict(headers)
h["Range"] = f"bytes={s}-{e}"
req = c.build_request("GET", u, headers=h)
r = await c.send(req, stream=True)
if r.status_code != 206:
await r.aclose()
raise RuntimeError(f"range fetch status {r.status_code}")
data = await r.aread()
await r.aclose()
if len(data) != e - s + 1:
raise RuntimeError(f"range {s}-{e} gave {len(data)}B")
return data
finally:
await c.aclose()
try:
chunks = await asyncio.gather(*[fetch_range(s, e) for (s, e) in bounds])
data = b"".join(chunks)
if len(data) != total:
return None
return data
except Exception:
return None
async def _proxy_do(u: str, ref: str, ua: str, origin: str, range_header: str = None, head_only: bool = False, boost: int = 0):
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)
# Upstream errors are relayed FAITHFULLY (status code + short body) BEFORE
# any playlist handling: an HTML error page whose URL happens to end in
# .m3u8 must NOT be rewritten into a fake 200 playlist - hls.js would parse
# garbage forever and the player would spin instead of failing honestly.
if resp.status_code not in (200, 206):
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": "*"})
# 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": "*"},
)
# ── Parallel-range segment booster (boost=1) ─────────────────────────────
# Some CDNs per-CONNECTION throttle (acek-cdn's token carries sp=500 →
# ~450KB/s per connection). A 5MB video segment then takes ~11s: hls.js's
# default 20s frag timeout is one hiccup away from killing playback
# ("languages show, duration shows, then the server stops responding").
# The SAME CDN happily serves parallel Range requests at full per-
# connection speed (verified 206 + 4x aggregate), so for big segments we
# fetch 4 ranges concurrently and reassemble. Falls back to the normal
# single-stream path on ANY inconsistency (no content-length, wrong
# status, size mismatch) - the booster is strictly best-effort.
if boost and not range_header and resp.status_code == 200:
try:
total = int(resp.headers.get("content-length") or 0)
except Exception:
total = 0
if total >= 1_000_000:
try:
await resp.aclose()
finally:
await client.aclose()
boosted = await _boosted_segment(u, headers, total)
if boosted is not None:
ctype_b = ctype if (ctype and "text/html" not in ctype) else "application/octet-stream"
return Response(
content=boosted,
media_type=ctype_b,
headers={
"Access-Control-Allow-Origin": "*",
"Accept-Ranges": "bytes",
"Content-Length": str(total),
"Cache-Control": "no-cache",
},
)
# booster failed -> reconnect and stream normally below
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)
if resp.status_code not in (200, 206):
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": "*"})
except Exception:
return JSONResponse({"error": "proxy fetch failed"}, status_code=502,
headers={"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, boost: int = 0, 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"), boost=boost)
@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, boost: int = 0):
"""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"), boost=boost)
# ---------- 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
def _sf_fname_from_url(u: str) -> str:
"""Best-effort FILENAME extraction from a direct-file URL.
VegaMovies' hubcloud results are mostly R2 SIGNED URLs whose only human
readable name lives in `response-content-disposition=<File.Name.mkv>`
(or as the /hub2/<File.Name.mkv> path basename). Without the filename the
episode filter sees label="Direct" and passes EVERYTHING - that is the
wrong-episode bug (S05E01 served for an S01E01 request). r2.dev content
hashes / pixeldrain ids carry no name at all -> "" (unverifiable)."""
try:
from urllib.parse import urlsplit, parse_qs
sp = urlsplit(u)
q = parse_qs(sp.query)
for k in ("response-content-disposition", "response-content-disposition*"):
for v in (q.get(k) or []):
v = (v or "").strip()
if not v:
continue
# R2 signs the BARE filename; full headers look like
# `attachment; filename="X.mkv"` / `filename*=UTF-8''X.mkv`
m = re.search(r"filename\*?=(?:UTF-8'')?\"?([^\";]+)\"?", v)
cand = m.group(1).strip() if m else v
if "." in cand and len(cand) < 200:
return cand
base = (sp.path or "").rsplit("/", 1)[-1]
if base and "." in base:
stem = base.rsplit(".", 1)[0]
if re.fullmatch(r"[0-9a-fA-F]{16,64}", stem):
return "" # content-hash only - no episode info
return base
except Exception:
pass
return ""
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 "") or _sf_fname_from_url(u)
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:
if ".zip" not in u.lower(): # season-pack zips are not playable
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
# Explicit DIFFERENT season ("S05 Complete" packs, "Season 2" labels):
# never a match for the requested season even without episode info.
sm = re.search(r'\bs(\d{1,2})\b|season\s*(\d{1,2})\b', low)
if sm:
found = int(sm.group(1) or sm.group(2))
if found != season:
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.get("label") or "")
if u in seen_urls:
continue
seen_urls.add(u)
# Real label = download-attr name or a name recovered from the URL.
# "Direct"/"" means UNVERIFIABLE - for TV that is dangerous (the file
# can be any episode of any season: this served S05E01 for S01E01 and
# the same pixeldrain file for two different shows). Serving nothing
# is honest - the player falls back to its next source.
eff = label if (label and label != "Direct") else _sf_fname_from_url(u)
if media_type == "tv":
if not eff:
continue # unnamed file - episode cannot be verified
if not _sf_episode_matches(eff, season or 1, episode or 1):
continue
results.append(_sf_stream_result(
f"{source_name}/HubCloud", f"{source_name} - {eff or 'Direct'}", u,
quality=_sf_quality_from_name(eff), language=_sf_lang_from_name(eff)))
return results
# ===== 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 = []
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
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": 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
try:
sec_key = base64.b64decode(sec_r.json().get("data", "")).decode("utf-8", errors="ignore")
except Exception:
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"
aes_k = (combined + "\x00" * max(0, 16 - len(combined)))[:16].encode("utf-8")
aes_iv = aes_k
def castle_decrypt(text: str):
d = text
try:
j = json.loads(text)
if isinstance(j, dict) and isinstance(j.get("data"), str):
d = j["data"]
except Exception:
pass
raw = None
try:
raw = base64.b64decode(d + "=" * (-len(d) % 4))
except Exception:
pass
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)
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": 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, 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
# 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
if _norm_row(r) == tl and r.get("movieType", r.get("subjectType", 0)) == want_type:
mid = r.get("id")
break
if mid is None:
for r in rows:
if not isinstance(r, dict):
continue
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 mid is None:
for r in rows:
if not isinstance(r, dict):
continue
rt = _norm_row(r)
if tl in rt or rt in tl:
mid = r.get("id")
break
if mid is None and isinstance(rows[0], dict):
mid = rows[0].get("id")
if mid is None:
errors.append("Castle: no match")
return results, errors
# 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:
dp = castle_decrypt(dr.text)
except Exception:
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
if media_type == "tv" and season and episode:
# 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:
s_mid = s_item.get("movieId") or s_item.get("id")
break
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
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 = [e for e in (dd.get("episodes") or []) if isinstance(e, dict)]
if eps:
ep_id = str(eps[0].get("id", ""))
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:
vd = json.loads(vd)
except Exception:
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))
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")
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 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/",
"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
subs_out = []
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"
name = sub.get("name") or lang
subs_out.append({"language": name, "url": surl})
except Exception:
continue
# 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")))
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
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")
# 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": _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"
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 the operator
# burst-rate-limits by IP (2nd rapid playlist fetch from one IP -> PNG block
# page). So: NO pre-validation (it burns the token), return exactly ONE fresh
# m4uplay-hosted token per scrape (m4uplay preferred, longest-lived).
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[:1]
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 "") or _sf_fname_from_url(u) or "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:
if ".zip" not in u.lower(): # season-pack zips are not playable
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"}
# =====================================================================
# Vyla SDK ports (github.com/vyla-entertainment/sdk) — v14 additions.
# Tested one-by-one from a datacenter IP with playlist+segment verification.
# =====================================================================
_ENC_DEC = "https://enc-dec.app/api"
def _b64url_bytes(v: str) -> bytes:
pad = "=" * (-len(v) % 4)
return base64.urlsafe_b64decode(v + pad)
# ===== VidRock (Vyla vidrock.js): vidrock.ru/api + AES-GCM =====
_VIDROCK_GCM_KEY = "7f3e9c2a8b5d1f4e6a9c3b7d2e5f8a1c4b6d9e2f5a8c1b4d7e9f2a5c8b1d4e7f"
_VIDROCK_PROXY_PREFIX = "https://proxy.vidrock.store/"
def _vidrock_decrypt(value: str):
try:
from Crypto.Cipher import AES
data = _b64url_bytes(value)
if len(data) < 28:
return None
iv, ct = data[:12], data[12:]
key = bytes.fromhex(_VIDROCK_GCM_KEY)
cipher = AES.new(key, AES.MODE_GCM, nonce=iv)
try:
return cipher.decrypt_and_verify(ct[:-16], ct[-16:]).decode()
except Exception:
out = cipher.decrypt(ct).decode(errors="ignore")
return out.split("\x00")[0].strip()
except Exception:
return None
async def scrape_vidrock(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results, errors = [], []
try:
async with httpx.AsyncClient(timeout=20, follow_redirects=True) as client:
path = f"tv/{tmdb_id}/{season or 1}/{episode or 1}" if media_type == "tv" else f"movie/{tmdb_id}"
resp = await client.get(f"https://vidrock.ru/api/{path}", headers={
"User-Agent": HEADERS["User-Agent"], "Referer": "https://vidrock.ru/",
"Origin": "https://vidrock.ru"})
if resp.status_code != 200:
errors.append(f"VidRock: API HTTP {resp.status_code}")
return results, errors
data = resp.json()
for provider, info in (data or {}).items():
try:
enc_url = (info or {}).get("url") if isinstance(info, dict) else None
if not enc_url:
continue
url = _vidrock_decrypt(enc_url)
if not url or not url.startswith("http"):
continue
if url.startswith(_VIDROCK_PROXY_PREFIX):
url = unquote(url[len(_VIDROCK_PROXY_PREFIX):].lstrip("/"))
is_xpass = "xpass.top" in url
vheaders = {
"User-Agent": HEADERS["User-Agent"],
"Referer": "https://play.xpass.top/" if is_xpass else "https://vidrock.ru/",
"Origin": "https://play.xpass.top" if is_xpass else "https://vidrock.ru",
}
results.append(_sf_stream_result(
f"VidRock/{provider}", f"VidRock - {provider}", url,
quality=info.get("type") or "Auto", language="English", headers=vheaders))
except Exception:
continue
if not results:
errors.append("VidRock: no streams")
except Exception as ex:
errors.append(f"VidRock: {str(ex)}")
return results, errors
# ===== VidFast + VidUp (Vyla vidfast.js / vidup.js): enc-dec.app protocol =====
async def _vidfamily_scrape(domain: str, enc_path: str, dec_path: str, label: str,
tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results, errors = [], []
try:
async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
if media_type == "tv":
embed_url = f"{domain}/tv/{tmdb_id}/{season or 1}/{episode or 1}/"
else:
embed_url = f"{domain}/movie/{tmdb_id}/"
resp = await client.get(embed_url, headers={"User-Agent": HEADERS["User-Agent"]})
html = resp.text
m = (re.search(r'\\"(?:en|token)\\":\\"(.*?)\\"', html)
or re.search(r'"(?:en|token)":"(.*?)"', html))
if not m:
errors.append(f"{label}: no token in embed")
return results, errors
resp = await client.get(f"{_ENC_DEC}/{enc_path}", params={"text": m.group(1)})
enc = resp.json()
if enc.get("status") != 200 or not enc.get("result"):
errors.append(f"{label}: enc failed")
return results, errors
meta = enc["result"]
req_headers = {
"User-Agent": HEADERS["User-Agent"],
"Referer": f"{domain}/",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": meta["token"],
}
resp = await client.post(meta["servers"], headers=req_headers)
resp = await client.post(f"{_ENC_DEC}/{dec_path}", json={"text": resp.text})
dec = resp.json()
if dec.get("status") != 200 or not dec.get("result"):
errors.append(f"{label}: servers decrypt failed")
return results, errors
servers = dec["result"]
for srv in servers:
try:
resp = await client.post(f"{meta['stream']}/{srv['data']}", headers=req_headers)
resp = await client.post(f"{_ENC_DEC}/{dec_path}", json={"text": resp.text})
sd = resp.json()
sres = (sd.get("result") or {}) if sd.get("status") == 200 else {}
surl = sres.get("url")
if not surl:
continue
subs = []
for cap in (sres.get("captions") or []):
if cap.get("file"):
subs.append({"language": cap.get("label") or "Sub", "url": cap["file"]})
vheaders = {
"User-Agent": HEADERS["User-Agent"],
"Referer": f"{domain}/",
"Origin": domain,
}
results.append(_sf_stream_result(
f"{label}/{srv.get('name') or 'Server'}", f"{label} - {srv.get('name') or 'Server'}",
surl, quality="Auto", language="English", headers=vheaders,
subtitles=subs or None))
except Exception:
continue
if not results:
errors.append(f"{label}: no playable servers")
except Exception as ex:
errors.append(f"{label}: {str(ex)}")
return results, errors
async def scrape_vidfast(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
return await _vidfamily_scrape("https://vidfast.vc", "enc-vidfast", "dec-vidfast",
"VidFast", tmdb_id, media_type, season, episode)
async def scrape_vidup(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
return await _vidfamily_scrape("https://vidup.to", "enc-vidup", "dec-vidup",
"VidUp", tmdb_id, media_type, season, episode)
# ===== MeowTV (Vyla meowtv.js): api.meowtv.ru + enc-dec.app (castle-CDN family) =====
async def scrape_meowtv(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results, errors = [], []
try:
async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
for srv in ["tik", "hindiv3"]:
try:
if media_type == "tv":
path = f"/streams/tv/{tmdb_id}/{season or 1}/{episode or 1}?s={srv}"
else:
path = f"/streams/movie/{tmdb_id}?s={srv}"
resp = await client.get(f"https://api.meowtv.ru{path}", headers={
"User-Agent": HEADERS["User-Agent"], "Accept": "application/json",
"Referer": "https://meowtv.ru/", "Origin": "https://meowtv.ru",
"Accept-Language": "en-US,en;q=0.9"})
payload = resp.json()
resp = await client.post(f"{_ENC_DEC}/dec-meowtv", json={"data": payload})
dec = resp.json()
if dec.get("status") != 200 or not dec.get("result"):
continue
res = dec["result"]
if isinstance(res, str):
res = json.loads(res)
vheaders = {
"User-Agent": HEADERS["User-Agent"],
"Referer": "https://meowtv.ru/",
"Origin": "https://meowtv.ru",
}
if str(res.get("url") or "").startswith("http"):
results.append(_sf_stream_result(
f"MeowTV/{srv}", f"MeowTV - {srv}", res["url"],
quality="Auto", language="Multi", headers=vheaders))
for st in (res.get("streams") or []):
if str(st.get("url") or "").startswith("http"):
results.append(_sf_stream_result(
f"MeowTV/{srv}", f"MeowTV - {srv} ({st.get('language') or 'Multi'})",
st["url"], quality="Auto",
language=st.get("language") or "Multi", headers=vheaders))
except Exception:
continue
if not results:
errors.append("MeowTV: no streams")
except Exception as ex:
errors.append(f"MeowTV: {str(ex)}")
return results, errors
# ===== LookMovie (Vyla lookmovie.js): title search + security access =====
async def scrape_lookmovie(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, year = info.get("title"), info.get("year")
if not title:
errors.append("LookMovie: no TMDB title")
return results, errors
is_tv = media_type == "tv"
typestr = "shows" if is_tv else "movies"
async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
base = match = None
for b in ["https://www.lookmovie2.to", "https://lookmovie2.to"]:
try:
resp = await client.get(f"{b}/api/v1/{typestr}/do-search/", params={"q": title},
headers={"User-Agent": HEADERS["User-Agent"], "Accept": "application/json",
"Referer": f"{b}/", "X-Requested-With": "XMLHttpRequest"})
res = (resp.json() or {}).get("result") or []
if res:
match = next((x for x in res if str(x.get("year")) == str(year)), None) \
or next((x for x in res if _sf_norm(x.get("title")) == _sf_norm(title)), None) \
or res[0]
base = b
break
except Exception:
continue
if not match:
errors.append("LookMovie: title not in catalog")
return results, errors
resp = await client.get(f"{base}/{typestr}/play/{match['slug']}", headers={
"User-Agent": HEADERS["User-Agent"], "Referer": f"{base}/", "Accept": "text/html"})
html = resp.text
storage = re.search(r"window\[['\"](?:movie|show)_storage['\"]\]\s*=\s*\{(.+?)\};", html, re.S)
if not storage:
errors.append("LookMovie: no storage block")
return results, errors
block = storage.group(1)
hm = re.search(r"hash\s*:\s*['\"]([^'\"]+)['\"]", block)
em = re.search(r"expires\s*:\s*(\d+)", block)
if not (hm and em):
errors.append("LookMovie: no hash/expires")
return results, errors
stream_id = match.get("id_movie") or match.get("id")
if is_tv:
sid = None
parts = re.split(r"id_episode['\"]?\s*[:=]\s*['\"]?(\d+)['\"]?", html)
for i in range(1, len(parts) - 1, 2):
ctx = parts[i - 1][-300:] + parts[i + 1][:300]
if re.search(rf"['\"]?episode['\"]?\s*[:=]\s*['\"]?{episode}['\"]?", ctx) and \
re.search(rf"['\"]?season['\"]?\s*[:=]\s*['\"]?{season}['\"]?", ctx):
sid = parts[i]
break
if not sid:
am = re.search(rf'data-season=["\']{season}["\'][^>]*?data-episode=["\']{episode}["\'][^>]*?data-id=["\'](\d+)["\']', html) or \
re.search(rf'data-episode=["\']{episode}["\'][^>]*?data-season=["\']{season}["\'][^>]*?data-id=["\'](\d+)["\']', html)
sid = am.group(1) if am else None
if not sid:
errors.append(f"LookMovie: episode S{season}E{episode} not found")
return results, errors
stream_id = sid
kind = "episode" if is_tv else "movie"
resp = await client.get(f"{base}/api/v1/security/{kind}-access", params={
f"id_{kind}": stream_id, "hash": hm.group(1), "expires": em.group(1)},
headers={"User-Agent": HEADERS["User-Agent"], "Accept": "application/json",
"Referer": f"{base}/", "X-Requested-With": "XMLHttpRequest"})
d = resp.json()
streams = d.get("streams") or (d.get("result") or {}).get("streams") \
or (d.get("data") or {}).get("streams") or d
if isinstance(streams, dict):
for quality, u in streams.items():
if isinstance(u, str) and ".m3u8" in u:
results.append(_sf_stream_result(
"LookMovie", f"LookMovie - {quality}", u,
quality=str(quality), language="English"))
if not results:
errors.append("LookMovie: no m3u8 streams")
except Exception as ex:
errors.append(f"LookMovie: {str(ex)}")
return results, errors
# ===== LMScript (Vyla lmscript.js): lmscript.xyz JSON API =====
async def scrape_lmscript(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results, errors = [], []
if media_type == "tv":
errors.append("LMScript: movies only")
return results, errors
try:
info = await get_tmdb_info(tmdb_id, media_type)
title = info.get("title")
if not title:
errors.append("LMScript: no TMDB title")
return results, errors
async with httpx.AsyncClient(timeout=20, follow_redirects=True) as client:
resp = await client.get("https://lmscript.xyz/v1/movies",
params={"filters[q]": title, "expand": "streams"})
d = resp.json()
movie = next((it for it in (d.get("items") or [])
if str(it.get("tmdb_id")) == str(tmdb_id)
or str(it.get("tmdb_prefix")) == str(tmdb_id)), None)
if not movie:
errors.append("LMScript: title not in catalog")
return results, errors
order = {"1080p": 0, "720p": 1, "480p": 2, "360p": 3}
for quality in sorted((movie.get("streams") or {}).keys(),
key=lambda q: order.get(q, 9)):
u = (movie.get("streams") or {})[quality]
if isinstance(u, str) and u.startswith("http"):
results.append(_sf_stream_result(
"LMScript", f"LMScript - {quality}", u,
quality=str(quality), language="English"))
if not results:
errors.append("LMScript: no streams")
except Exception as ex:
errors.append(f"LMScript: {str(ex)}")
return results, errors
# ===== Fsonic (Vyla fsonic.js): fsonic.net search + fsharetv.co mp4 =====
async def scrape_fsonic(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results, errors = [], []
if media_type == "tv":
errors.append("Fsonic: movies only")
return results, errors
try:
info = await get_tmdb_info(tmdb_id, media_type)
title, year = info.get("title"), str(info.get("year") or "")
if not title:
errors.append("Fsonic: no TMDB title")
return results, errors
H = {"User-Agent": HEADERS["User-Agent"],
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9"}
watch_slug = None
async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
resp = await client.get(f"https://www.fsonic.net/movie/search/{quote(title)}", headers=H)
for m in re.finditer(r'href="(/watch/[^"]+)"', resp.text):
if year and year in m.group(1):
watch_slug = m.group(1)
break
if not watch_slug:
watch_slug = m.group(1)
if not watch_slug:
errors.append("Fsonic: title not in catalog")
return results, errors
resp = await client.get(f"https://www.fsonic.net{watch_slug}", headers=H)
m = re.search(r"init\('([^']+)',\s*(?:'[^']*',\s*)?'([^']+)'", resp.text)
if not m:
errors.append("Fsonic: no init token")
return results, errors
resp = await client.get(f"https://www.fsonic.net/api/source/{m.group(1)}",
params={"trailer": m.group(2), "type": "watch"},
headers={**H, "Accept": "application/json",
"Referer": f"https://www.fsonic.net{watch_slug}"})
j = resp.json()
if j.get("status") != "ok":
errors.append("Fsonic: source API error")
return results, errors
f = (j.get("data") or {}).get("file") or {}
groups = [f.get("sources") or []] + [g for g in (f.get("alternatives") or []) if g]
vheaders = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://fsharetv.co/"}
seen = set()
for g in groups:
best = sorted([x for x in g if x.get("src")],
key=lambda x: int(re.sub(r"\D", "", str(x.get("quality") or "0")) or 0),
reverse=True)
if not best:
continue
src = best[0]["src"]
if not src.startswith("http"):
src = f"https://fsharetv.co{src}"
if src in seen:
continue
seen.add(src)
results.append(_sf_stream_result(
"Fsonic", f"Fsonic - {best[0].get('quality') or 'Auto'} MP4", src,
quality=str(best[0].get("quality") or "Auto"), language="English", headers=vheaders))
if not results:
errors.append("Fsonic: no streams")
except Exception as ex:
errors.append(f"Fsonic: {str(ex)}")
return results, errors
# ===== Hexa (Vyla hexa.js): theemoviedb.hexa.su + enc-dec.app =====
async def scrape_hexa(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results, errors = [], []
try:
async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
resp = await client.get(f"{_ENC_DEC}/enc-hexa")
j = resp.json()
if j.get("status") != 200:
errors.append("Hexa: challenge failed")
return results, errors
cap_token = (j.get("result") or {}).get("token")
api_key = "%064x" % random.getrandbits(256)
decrypted = None
for domain in ["hexa.su", "flixer.su"]:
try:
if media_type == "tv":
url = f"https://theemoviedb.{domain}/api/tmdb/tv/{tmdb_id}/season/{season or 1}/episode/{episode or 1}/images"
else:
url = f"https://theemoviedb.{domain}/api/tmdb/movie/{tmdb_id}/images"
resp = await client.get(url, headers={
"User-Agent": HEADERS["User-Agent"], "Referer": f"https://{domain}/",
"Accept": "text/plain", "X-Fingerprint-Lite": "e9136c41504646444",
"X-Api-Key": api_key, "X-Cap-Token": cap_token})
if not resp.text:
continue
resp = await client.post(f"{_ENC_DEC}/dec-hexa",
json={"text": resp.text, "key": api_key})
j = resp.json()
if j.get("status") == 200 and (j.get("result") or {}).get("sources"):
decrypted = j["result"]
break
except Exception:
continue
if not decrypted:
errors.append("Hexa: no sources")
return results, errors
subs = [{"language": s.get("label") or s.get("lang") or "Sub", "url": s.get("url")}
for s in (decrypted.get("subtitles") or []) if s.get("url")]
for src in decrypted.get("sources") or []:
u = src.get("url")
if u and u.startswith("http"):
results.append(_sf_stream_result(
f"Hexa/{src.get('name') or 'Server'}", f"Hexa - {src.get('name') or 'Server'}",
u, quality=str(src.get("quality") or "Auto"), language="English",
subtitles=subs or None))
if not results:
errors.append("Hexa: no streams")
except Exception as ex:
errors.append(f"Hexa: {str(ex)}")
return results, errors
# ===== Yamie (vidrift direct VOD endpoint — movies only, browser-direct) =====
# Found via ZETIC7Z/nexus3.0 (their #2 ranked source). media.vidrift.in serves
# a LITERAL per-TMDB movie playlist: https://media.vidrift.in/movie_{tmdb_id}/vod.m3u8
# Flat VOD, relative .ts segments, Access-Control-Allow-Origin: * on playlists
# AND segments (verified) — the player loads it browser-direct at residential
# speed with zero proxy load. TV is not supported upstream (404 for every
# series URL pattern; nexus3.0 also marks it moviesOnly).
async def scrape_yamie(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results, errors = [], []
if media_type != "movie":
errors.append("Yamie: movies only upstream")
return results, errors
url = f"https://media.vidrift.in/movie_{tmdb_id}/vod.m3u8"
try:
async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:
r = await client.get(url, headers={"User-Agent": HEADERS["User-Agent"]})
if r.status_code == 200 and r.text.lstrip().startswith("#EXTM3U"):
if any(l.strip() and not l.strip().startswith("#") for l in r.text.splitlines()):
results.append(_sf_stream_result(
"Yamie", "Yamie - VOD Direct", url,
quality="Auto", language="English"))
else:
errors.append("Yamie: empty playlist")
else:
errors.append(f"Yamie: HTTP {r.status_code}")
except Exception as ex:
errors.append(f"Yamie: {str(ex)}")
return results, errors
# ===== Showbox via stycanine1 TMDB-Embed-API (FebBox / hls.shegu.net) =====
# Showbox/FebBox needs a ui= login cookie on www.febbox.com/file/player that we
# do not own. The public stycanine1-tmdb-embed-api.hf.space deployment (Node
# port of Inside4ndroid/TMDB-Embed-API) carries FEBBOX_COOKIES and returns
# signed hls.shegu.net masters (multi CDN nodes, multi-audio tracks, movie+TV)
# with no auth and CORS open. Verified: 18 streams for Venom 912649 in 4.4s,
# master + media playlist + segment all 200 through our proxy chain.
# Third-party dependency: if that Space sleeps or disappears, this source just
# fails fast and the player's chain moves on — same failure mode as any other
# upstream outage.
_STY_BASE = "https://stycanine1-tmdb-embed-api.hf.space"
async def scrape_stycanine(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
results, errors = [], []
try:
path = f"{_STY_BASE}/api/streams/showbox/{'series' if media_type == 'tv' else 'movie'}/{tmdb_id}"
params = {}
if media_type == "tv":
params = {"season": season or 1, "episode": episode or 1}
async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
r = await client.get(path, params=params)
if r.status_code != 200:
errors.append(f"Showbox: aggregator HTTP {r.status_code}")
return results, errors
d = r.json()
if not d.get("success"):
errors.append("Showbox: aggregator reported failure")
return results, errors
seen_ids = set()
for s in (d.get("streams") or []):
u = (s or {}).get("url") or ""
# m3u8 masters only — the /vip/ extensionless entries are raw MKVs
if ".m3u8" not in u:
continue
m = re.search(r"shegu\.net/(\d+)\.m3u8", u)
key = m.group(1) if m else u
if key in seen_ids:
continue
seen_ids.add(key)
title = (s.get("title") or "stream")[:48]
quality = (s.get("quality") or "Auto")
if quality == "ORG":
quality = "Auto"
pu = _proxy_wrap(u)
results.append(_sf_stream_result(
"Showbox", f"Showbox - {title}", pu,
quality=quality, language="English"))
if len(results) >= 6:
break
if not results:
errors.append("Showbox: no streams")
except Exception as ex:
errors.append(f"Showbox: {str(ex)}")
return results, errors
# ===== Source Map =====
SOURCE_MAP = {
"castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e),
"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": ["English", "Multi"], "reliability": "high",
"note": "net27.cc embed-tmdb, mp4 360p-1080p + subtitles (Nuvio netmirror.js port). CDN requires Referer https://videodownloader.site/ (the v12 429s were wrong-referer 429s, NOT IP blocks). Primary: play url + returned headers from the viewer device (Nuvio-app model, verified 206). proxied_url works on non-blocked hosts; bcdnxw additionally 426-range-blocks HF Spaces IPs"},
"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"},
# --- v14: Vyla SDK ports (tested one-by-one from datacenter + HF) ---
"vidfast": {"name": "VidFast", "fn": lambda tid, mt, s, e: scrape_vidfast(tid, mt, s, e),
"languages": ["English"], "reliability": "high",
"note": "vidfast.vc embed + enc-dec.app crypto relay (Vyla vidfast.js port). fMP4 HLS up to 2160p, multi-server, movie+TV, subtitles"},
"vidup": {"name": "VidUp", "fn": lambda tid, mt, s, e: scrape_vidup(tid, mt, s, e),
"languages": ["English"], "reliability": "high",
"note": "vidup.to embed + enc-dec.app (Vyla vidup.js port). Same peakstorm CDN family as VidFast via a different upstream - complementary coverage, movie+TV"},
"meowtv": {"name": "MeowTV", "fn": lambda tid, mt, s, e: scrape_meowtv(tid, mt, s, e),
"languages": ["Hindi", "Multi", "English"], "reliability": "high",
"note": "api.meowtv.ru + enc-dec.app dec-meowtv (Vyla meowtv.js port). Castle-CDN m3u8 (hindiv3), movie+TV"},
"lookmovie": {"name": "LookMovie", "fn": lambda tid, mt, s, e: scrape_lookmovie(tid, mt, s, e),
"languages": ["English"], "reliability": "medium",
"note": "lookmovie2.to title search + security access API (Vyla lookmovie.js port). undersel.buzz HLS, movie+TV"},
"lmscript": {"name": "LMScript", "fn": lambda tid, mt, s, e: scrape_lmscript(tid, mt, s, e),
"languages": ["English"], "reliability": "medium",
"note": "lmscript.xyz/v1/movies JSON API (Vyla lmscript.js port). undersel.buzz HLS 360-1080p, movies only"},
"fsonic": {"name": "Fsonic", "fn": lambda tid, mt, s, e: scrape_fsonic(tid, mt, s, e),
"languages": ["English"], "reliability": "medium",
"note": "fsonic.net search + fsharetv.co direct MP4 720/1080 (Vyla fsonic.js port). Movies only"},
"vidrock": {"name": "VidRock", "fn": lambda tid, mt, s, e: scrape_vidrock(tid, mt, s, e),
"languages": ["English"], "reliability": "medium",
"note": "vidrock.ru/api + AES-GCM decrypt (Vyla vidrock.js port). ngcorp.dad/flamingo workers m3u8. Movies verified playable; TV episodes route segments via ByteDance ipstatp CDN that 403s datacenter IPs"},
"hexa": {"name": "Hexa", "fn": lambda tid, mt, s, e: scrape_hexa(tid, mt, s, e),
"languages": ["English"], "reliability": "low",
"note": "theemoviedb.hexa.su + enc-dec.app (Vyla hexa.js port). dragonballzfans CDNs, movie+TV, intermittent"},
# --- v15: new sources (Sep 2026 research round) ---
"yamie": {"name": "Yamie", "fn": lambda tid, mt, s, e: scrape_yamie(tid, mt, s, e),
"languages": ["English"], "reliability": "high",
"note": "media.vidrift.in literal per-TMDB VOD playlist (from ZETIC7Z/nexus3.0). Browser-direct (ACAO * on playlist+segments), movies only, 4MB/s+ segment speed"},
"stycanine": {"name": "Showbox", "fn": lambda tid, mt, s, e: scrape_stycanine(tid, mt, s, e),
"languages": ["English", "Multi"], "reliability": "medium",
"note": "Showbox/FebBox hls.shegu.net streams via the public stycanine1 TMDB-Embed-API deployment (it carries the FEBBOX_COOKIES we lack). movie+TV, multi CDN nodes, proxied through this Space"},
}
DEFAULT_SOURCES = ["castle", "netmirror", "playbox", "movix", "vidfast", "vidup",
"meowtv", "lookmovie", "lmscript", "fsonic", "vidrock", "hexa",
"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": "13.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, sources: str = None):
keys = None
if sources:
keys = [k.strip() for k in sources.split(",") if k.strip() in SOURCE_MAP] or None
return await run_scrape(tmdb_id, "movie", source_keys=keys)
@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, sources: str = None):
keys = None
if sources:
keys = [k.strip() for k in sources.split(",") if k.strip() in SOURCE_MAP] or None
return await run_scrape(tmdb_id, "tv", season=season, episode=episode, source_keys=keys)
@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)
# ─── Vyla SDK integration (Node.js sidecar) ─────────────────────────────────
# Calls the Vyla SDK (65 providers) via a Node.js subprocess. The Python API
# can't import the Node.js SDK directly, so we spawn a subprocess that runs
# vyla-resolver.js and parses its JSON output.
import subprocess, json as _json
@app.get('/vyla/{tmdb_id}')
async def vyla_resolve(tmdb_id: int, type: str = 'movie', season: int = 0, episode: int = 0, sources: str = ''):
'''Resolve streams via Vyla SDK (65 providers). Returns JSON with candidates per source.'''
try:
args = _json.dumps({
'tmdbId': tmdb_id,
'type': type,
'season': season if type == 'tv' else None,
'episode': episode if type == 'tv' else None,
'sources': sources,
})
proc = subprocess.run(
['node', 'vyla-resolver.js'],
input=args, capture_output=True, text=True, timeout=60
)
if proc.returncode != 0:
return {'success': False, 'error': proc.stderr[:500]}
return _json.loads(proc.stdout)
except subprocess.TimeoutExpired:
return {'success': False, 'error': 'Vyla resolver timed out (60s)'}
except Exception as e:
return {'success': False, 'error': str(e)[:200]}
"""
StreamForge API v14 - Multi-Language Stream Scraper
v14 (Vyla SDK provider wave):
- 8 NEW sources ported from the Vyla SDK (github.com/vyla-entertainment/sdk,
40 provider files tested one-by-one with playlist+segment verification from
a datacenter IP):
WORKING -> integrated: vidfast (2160p fMP4), vidup, meowtv (castle-CDN
multi-language), lookmovie, lmscript, fsonic (direct MP4), vidrock
(AES-GCM), hexa (intermittent).
DEAD from datacenter (documented, NOT integrated): vidlink (site down,
403s), vidsync (enc dec issues), pengu (google auth wall), videasy
(Cineby property - excluded per policy), vidnest (playlist 403), cinesu
(playlist 403), vidfast-via-nuvio (old impl), anikoto/anineko (segment
403), vidrift/vidcore/vidvault/opstream/peachify/vixsrc/xpass/1embed/
cinejoy/flaxmovies/fsharetv/fsonline/mapple/kisskh/anizone/anipm/
anihq/123anime/reanime/kickassanime (no streams / anime-only catalogs).
- Note: vidfast/vidup/meowtv/hexa depend on enc-dec.app (public crypto relay
the sites themselves use client-side; it is also what the Vyla SDK uses).
- Known upstream catalog gaps: NetMirror genuinely lacks some older titles
(e.g. Venom 2018 -> noSource:true from net27.cc upstream) - the API now
returns 13+ other sources for such titles; players should fall back.
v13 (netmirror+castle rebuild, Nuvio port):
- NetMirror REBUILT from All-in-One-Nuvio netmirror.js: the bcdnxw CDN 429s are
REFERER-gating: the CDN requires Referer "https://videodownloader.site/"
(exact, trailing slash; net27.cc referers get 429 from any IP).
Verified: viewer device IP + correct referer -> 206 video/mp4 (PRIMARY:
play url + returned headers, Nuvio-app model); non-blocked server via our
proxy -> 206; bcdnxw additionally 426-range-blocks HF Spaces IPs (use the
direct url+headers path there). 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 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, unquote
import random
app = FastAPI(
title="StreamForge API",
description="Multi-language m3u8/mp4/MKV stream scraper",
version="14.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",
}