Spaces:
Running
Running
v11.0.0: NetMirror proxied playback fix (CDN blocks direct), /proxy_range endpoint with Range+m3u8 rewrite, NEW Movies4u + PersianStremio, remove VidLove (403), Castle key retry
Browse files1234567891011121314153 unmodified lines19202122232425262728293041 unmodified lines7273747576777879808182838485868788899091927 unmodified lines1001011021031041051061071081091101113 unmodified lines1151161171181191201211 unmodified line1231241251261271281293 unmodified lines1331341351361371381391401 unmodified line14214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618750 unmodified lines2382392402412422432446 unmodified lines2512522532542552562572582592602612629 unmodified lines27227327427527627727827928028128228328428513 unmodified lines29930030130230330430530630730830931031125 unmodified lines3373383393403413423437 unmodified lines3513523533543553563573583593603613623633643653663673683692 unmodified lines3723733743753763773782 unmodified lines3813823833843853863872 unmodified lines39039139239339439539639739839940040140224 unmodified lines4274284294304314324334344354364374383 unmodified lines4424434444454464474484 unmodified lines4534544554564574584593 unmodified lines4634644654664674684692 unmodified lines47247347447547647747816 unmodified lines49549649749849950050150225 unmodified lines52852953053153253353453553653753853954054154236 unmodified lines57958058158258358458558624 unmodified lines61161261361461561661761861962062113 unmodified lines63563663763863964064164264364464564664764864965065165265312 unmodified lines6666676686696706716726736747 unmodified lines68268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074134 unmodified lines77677777877978078178278311 unmodified lines7957967977987998008018028038048058061 unmodified line8088098108118128138141 unmodified line81681781881982082182212 unmodified lines8358368378388398408414 unmodified lines8468478488498508518524 unmodified lines85785885986086186286386486586686786886987012 unmodified lines8838848858868878888892 unmodified lines8928938948958968978987 unmodified lines9069079089099109119129139149156 unmodified lines92292392492592692792892993093193293393493593693793893994094194294394494594694794894995095111 unmodified lines96396496596696796896997097197211 unmodified lines98498598698798898999099113 unmodified lines10051006100710081009101010111 unmodified line101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106160 unmodified lines1122112311241125112611271128"""StreamForge API v9 - Multi-Language Stream ScraperScrapes direct m3u8 URLs from multiple sourcesUpdated: MovieBox, Castle, VidLink, VidSrc, NetMirrorAdded: VidFast, ShowBox, GoatAPIRemoved: CineSu (dead), PrimeSrc (Cloudflare), DooFlix (API key revoked)v9: Added Cineby, PurStream, Movix, MoviesHunt, HDHub4u, VegaMovies, Movies4u(ported + live-tested from All-in-One-Nuvio & MediaVanced repos)"""from fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optionalimport httpx3 unmodified linesimport timeimport asyncioimport hashlibfrom urllib.parse import quoteapp = FastAPI(title="StreamForge API",description="Multi-language m3u8 stream scraper",version="10.0.0",)app.add_middleware(41 unmodified lines}async def get_tmdb_info_with_key(tmdb_id: int, media_type: str, api_key: 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": 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"7 unmodified linesif "french" in lower or "fra" in lower or "vf" in lower: return "French"if "german" in lower or "deu" in lower or "ger" in lower: return "German"if "spanish" in lower or "spa" in lower or "español" in lower: return "Spanish"if "multi" in lower: return "Multi"return "English"def evp_bytes_to_key(password: bytes, salt: bytes, key_len: int = 32, iv_len: int = 16):"""OpenSSL EVP_BytesToKey compatible key derivation (MD5 iterative)."""dtot = b""d = b""while len(dtot) < key_len + iv_len:3 unmodified linesdef normalize_title(title: str) -> str:"""Normalize title by removing brackets, (Dub), (HD), etc."""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()1 unmodified linedef extract_language_from_title(title: str) -> str:"""Extract language from title brackets like [Hindi], [Tamil] etc."""bracket_match = re.search(r'\[([^\]]+)\]', title)if bracket_match:lang_text = bracket_match.group(1)3 unmodified linesreturn ""def _sf_stream_result(source: str, title: str, url: str, quality: str = "Auto", language: str = "English") -> dict:return {"source": source,"title": title,"quality": quality,1 unmodified line"url": url,"type": "m3u8" if ".m3u8" in url else "direct",}def _sf_norm(s: str) -> str:return re.sub(r"[^a-z0-9]", "", (s or "").lower())# ---------- 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:continuename = 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# ---------- HubCloud family resolver (MediaVanced hubcloud.py, generalized) ----------50 unmodified linesout.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:out.append({"url": u, "label": fname or "Direct"})except Exception:pass6 unmodified linesif "1080" in low: return "1080p FHD"if "720" in low: return "720p HD"if "480" in low: return "480p SD"return "Auto"def _sf_lang_from_name(name: str) -> str:low = (name or "").lower()if "dual audio" 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")9 unmodified liness_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)# Correct-episode or correct-season labels always matchif s_ok or season_only or (e_ok and (season_only or "season" in low)):return True# Labels mentioning a DIFFERENT season/episode are rejectedother = 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# No markers at all -> generic pack link, acceptreturn True13 unmodified linesreturn resultsPHISHER_DOMAINS = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json"VEGA_URLS = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json"_SF_HUB_HEADERS = {"User-Agent": _SF_MOBILE_UA, "Accept": "text/html,application/xhtml+xml,*/*", "Accept-Language": "en-US,en;q=0.5"}# ===== Castle Scraper (hlowb.com API with AES-CBC) - v10 FIXED (multi-language m3u8) =====async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []25 unmodified lines}async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client:# Step 1: Get security keysec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1", params={"channel": CH, "clientType": CLI, "lang": LANG})7 unmodified lineserrors.append("Castle: bad sec key response")return results, errors# The security key may be base64-encoded or plain texttry:sec_key = base64.b64decode(raw_k).decode("utf-8", errors="ignore")except Exception:sec_key = raw_k# AES decryption: key = first 16 chars of (sec_key + "T!BgJB"), IV = samecombined = (sec_key + "T!BgJB")aes_k = (combined + "\x00" * max(0, 16 - len(combined)))[:16].encode("utf-8")aes_iv = aes_kdef castle_decrypt(text):"""Decrypt Castle API response."""d = texttry:j = json.loads(text)2 unmodified linesexcept Exception:pass# Try base64 decode firsttry:raw = base64.b64decode(d)c = AES.new(aes_k, AES.MODE_CBC, aes_iv)2 unmodified linesexcept Exception:pass# Try hex decodetry:raw = bytes.fromhex(d)c = AES.new(aes_k, AES.MODE_CBC, aes_iv)2 unmodified linesexcept Exception:pass# Try plain JSON (some endpoints may return unencrypted)try:return json.loads(text)except Exception:raise ValueError(f"Castle decrypt failed for data length={len(d)}")# Step 2: Searchkw = f"{title} {info.get('year', '')}".strip()sr = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={"channel": CH, "clientType": CLI, "keyword": kw, "lang": LANG,24 unmodified lineserrors.append("Castle: no search results")return results, errors# Match by title - also check subjectType for movie/tv filteringmid = Nonetl = normalize_title(title).lower()target_subject_type = 1 if media_type == "movie" else 2# First try: exact normalized title match + correct subjectTypefor r in rows:if not isinstance(r, dict):continue3 unmodified linesmid = r.get("id")break# Second try: substring match + correct subjectTypeif not mid:for r in rows:if not isinstance(r, dict):4 unmodified linesmid = r.get("id")break# Third try: exact/substring match without type filterif not mid:for r in rows:if not isinstance(r, dict):3 unmodified linesmid = r.get("id")break# Fallback: first resultif not mid and isinstance(rows[0], dict):mid = rows[0].get("id")2 unmodified linesreturn results, errorsmid = str(mid)# Step 3: Get detailsdr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={"channel": CH, "clientType": CLI, "lang": LANG,"movieId": mid, "packageName": PKG16 unmodified linesif not isinstance(dd, dict):dd = {}# For TV: navigate seasons/episodesep_id = mid # Default: same as movieId for moviesif media_type == "tv" and season and episode:seasons = dd.get("seasons", [])s_id = mid25 unmodified linesbreakmid = s_idelse:# Movies: check for episodes list (some movies have a single "episode")eps = dd.get("episodes", [])if eps and isinstance(eps[0], dict):ep_id = str(eps[0].get("id", ""))# Step 4: Get video via getVideo2 - v10 fixed flow (multi-language, ported from Nuvio castle.js)CASTLE_LANGS = [("English", "1003"), ("Tamil", "1033"), ("Telugu", "1037")]for lang_name, lang_id in CASTLE_LANGS:for resolution in [3, 2, 1]: # Try 1080p, 720p, 480ptry:body = {"mode": "1",36 unmodified linesif not vurl:continuequality_map = {1: "480p", 2: "720p", 3: "1080p"}quality = quality_map.get(resolution, "720p")vids = vd.get("videos", [])if vids and isinstance(vids, list):24 unmodified lines"url": vurl,"type": "m3u8" if ".m3u8" in vurl else "direct",})break # Got a stream, stop trying lower resolutionsexcept Exception:continue# Deduplicateseen = set()uniq = []for r in results:13 unmodified linesreturn results, errors# ===== NetMirror Scraper (net27.cc embed-tmdb API) - v10 REWRITE =====# Ported from All-in-One-Nuvio netmirror.js (live-tested: mp4 360p-1080p, movie+TV)_NETMIRROR_BASE = "https://net27.cc"_NETMIRROR_HEADERS = {"Accept": "application/json, text/plain, */*","Referer": "https://net27.cc/","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36",}async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None):"""NetMirror via net27.cc - takes TMDB id directly, returns direct mp4 streams (multi-res)."""results = []errors = []try:12 unmodified lineserrors.append("NetMirror: non-JSON response")return results, errorsstreams = data.get("streams") or []if not isinstance(streams, list) or not streams:# Fallback: single mp4 fieldmp4 = data.get("mp4")if mp4:streams = [{"url": mp4, "resolution": data.get("resolution", "Auto")}]7 unmodified linesu = s.get("url")if not u:continueres = str(s.get("resolution") or "").strip()quality = {"2160": "4K", "1080": "1080p", "720": "720p", "480": "480p", "360": "360p"}.get(res, res if res else "Auto")results.append(_sf_stream_result("NetMirror", f"NetMirror - {quality}", u,quality=quality, language="Multi"))except Exception as ex:errors.append(f"NetMirror: {str(ex)}")return results, errors# ===== VidLove Scraper (api.shows.st JSON API) - v10 NEW =====# Ported from player.vidlove.cc frontend (replaces 111movies which redirects here)# Live-tested: m3u8 master playlist, movie+TV_VIDLOVE_API = "https://api.shows.st"async def scrape_vidlove(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []errors = []try:if media_type == "tv":url = f"{_VIDLOVE_API}/tv?id={tmdb_id}&season={season or 1}&episode={episode or 1}&mode=json"else:url = f"{_VIDLOVE_API}/movie?id={tmdb_id}&mode=json"async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:resp = await client.get(url, headers={"User-Agent": HEADERS["User-Agent"],"Referer": "https://player.vidlove.cc/","Accept": "application/json, text/plain, */*",})if resp.status_code != 200:errors.append(f"VidLove: API HTTP {resp.status_code}")return results, errorsdata = resp.json()src = data.get("source") or {}stream_url = src.get("url")if not stream_url:errors.append("VidLove: no source url in response")return results, errorslabel = src.get("label") or "VidLove"results.append(_sf_stream_result("VidLove", f"VidLove - {label}", stream_url,quality="Auto (multi-quality)", language="Multi"))except Exception as ex:errors.append(f"VidLove: {str(ex)}")return results, errors# ===== PlayBox Scraper (streamdata.vaplayer.ru API) - v10 NEW =====# Ported from MediaVanced playbox.py / Nuvio playimdb.js (live-tested: m3u8 multi-quality, movie+TV)_PLAYBOX_API = "https://streamdata.vaplayer.ru/api.php"34 unmodified linesreturn results, errors# ---------- VegaMovies (Nuvio vegamovies.js port, v10): search.php?q=imdb -> wp-json -> nexdrive -> vcloud/hubcloud ----------# Live-tested: direct MKV (2160p/1080p/720p) via pixeldrain + r2, movie+TVVEGA_URLS = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json"_VEGA_DEFAULT_SITE = "https://new2.vegamovies.futbol"11 unmodified linesasync def _sf_resolve_vcloud(client: httpx.AsyncClient, vcloud_url: str, referer: str) -> list:"""Resolve a vcloud.fit page: fetch -> decode atob(atob()) token url -> fetch -> extract btn links."""out = []try:page = (await client.get(vcloud_url, headers={"User-Agent": _SF_MOBILE_UA, "Referer": referer, "Cookie": "xla=s4t"})).text# Tokenized re-entry URL (double base64) - follow itm = re.search(r"atob\(atob\('([A-Za-z0-9+/=]+)'\)\)", page)if m:dec = _sf_b64_all(m.group(1))1 unmodified linepage2 = (await client.get(dec, headers={"User-Agent": _SF_MOBILE_UA, "Referer": vcloud_url, "Cookie": "xla=s4t"})).textpage = page2# Extract download button linksfor b in re.finditer(r'<a[^>]+href="(https?://[^"]+)"[^>]+class="[^"]*btn[^"]*"', page):u = b.group(1)chunk = page[b.start():b.start() + 800]1 unmodified linefname = fm.group(1) if fm else "Direct"if "pixeldrain" in u:out.append({"url": _sf_pixeldrain_direct(u), "label": fname})elif "cloudflarestorage" in u or "workers.dev" in u or ".r2.dev" in u: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})12 unmodified lineserrors.append("VegaMovies: no imdb id")return results, errors# Resolve current domainsite = _VEGA_DEFAULT_SITEtry:async with httpx.AsyncClient(timeout=10) as c:4 unmodified linespassasync with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=_SF_HUB_HEADERS) as client:# Step 1: search by imdb idsr = 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}")4 unmodified lineserrors.append("VegaMovies: search non-JSON")return results, errors# Typesense-style response: {"found": n, "hits": [{"document": {...}}]}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# Match post by titletitle_norm = _sf_norm(info.get("title") or "")year = str(info.get("year") or "")chosen = None12 unmodified lineserrors.append("VegaMovies: no matching post")return results, errors# Step 2: fetch post contentpr = 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}")2 unmodified linesnexdrive_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:# Broad fallback: any locker link in contentnexdrive_links = re.findall(r'https?://[^\s"\'<>]*(?:vcloud|nexdrive|dgdrive|fastdl)\.[a-z]+/[^\s"\'<>]{4,60}', content)resolved = []7 unmodified lines"User-Agent": _SF_MOBILE_UA, "Referer": f"{site}/"})).textexcept Exception:continue# hubcloud links inside nexdrive pagefor 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))# vcloud links inside nexdrive page (2 fastest: usually 1080p/720p first)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)))6 unmodified linesreturn results, errors# ===== Source Map =====SOURCE_MAP = {"castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e),"languages": ["English", "Tamil", "Telugu"], "reliability": "high","note": "hlowb.com API, AES-CBC, multi-language m3u8 (EN/Tamil/Telugu), fixed languageId flow"},"netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e),"languages": ["Hindi", "English", "Multi"], "reliability": "high","note": "net27.cc embed-tmdb API, direct mp4 360p-1080p, TMDB id based, movie+TV"},"vidlove": {"name": "VidLove", "fn": lambda tid, mt, s, e: scrape_vidlove(tid, mt, s, e),"languages": ["English", "Multi"], "reliability": "high","note": "api.shows.st JSON API, m3u8 master multi-quality, replaces dead 111movies"},"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"},"vegamovies": {"name": "VegaMovies", "fn": lambda tid, mt, s, e: scrape_vegamovies(tid, mt, s, e),"languages": ["Hindi", "English", "Multi"], "reliability": "medium","note": "search.php?q=imdb + nexdrive + vcloud chain, direct MKV up to 4K"},}DEFAULT_SOURCES = ["castle", "netmirror", "vidlove", "playbox", "movix"]# ===== Helper: Run scrapers =====11 unmodified linesif not src:return [], [f"{key}: Unknown source"]try:r, e = await asyncio.wait_for(src["fn"](tmdb_id, media_type, season, episode), timeout=45)return r, eexcept asyncio.TimeoutError:return [], [f"{src['name']}: Timeout (45s)"]except Exception as ex:return [], [f"{src['name']}: {str(ex)}"]11 unmodified linesseen_urls = set()unique_results = []for r in all_results:if r["url"] not in seen_urls:seen_urls.add(r["url"])unique_results.append(r)return {13 unmodified linesasync def root():return {"api": "StreamForge","version": "10.0.0","description": "Multi-language m3u8/mp4/MKV stream scraper","endpoints": {"movie": {"all_sources": "/movie/{tmdb_id}", "single_source": "/movie/{tmdb_id}/{source}",1 unmodified line"tv": {"all_sources": "/tv/{tmdb_id}/{season}/{episode}", "single_source": "/tv/{tmdb_id}/{season}/{episode}/{source}","example": "/tv/1396/1/1", "example_source": "/tv/1396/1/1/netmirror"},"search": {"path": "/search/{query}", "example": "/search/Venom"},"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_v10": {"updated": ["Castle - fixed getVideo2 (appMarket=GuanWang, languageId 1003/1033/1037) -> multi-language m3u8 restored","NetMirror - rewritten on net27.cc embed-tmdb (TMDB-id based, mp4 360p-1080p, movie+TV)","MoviesHunt - new domains (movieshunt.casa) + abhilinks + hubcloud.cx resolver, verified MKV via pixeldrain","VegaMovies - new flow (search.php?q=imdb -> wp-json -> nexdrive -> vcloud token chain), up to 4K MKV",],"added": ["VidLove - api.shows.st, m3u8 master multi-quality, movie+TV (replaces dead 111movies)","PlayBox - streamdata.vaplayer.ru, multi-quality m3u8, movie+TV",],"kept": ["Movix (verified working)"],"removed": {"Cineby": "shutting down (user request)","Videasy": "cineby-owned (user request)","VidRock": "dead (vidrock.net 403, vidrock.ru timeout)","MovieBox": "API removed (themoviebox.org -> HTML, fmoviesunblocked 404)","AllMovieLand": "HTTP 403 (Cloudflare)","VidLink": "no playlist in response (dead)","VidSrc": "cloudnestra flow broken","M4UHD": "m4uhd.vip Cloudflare 403","VidFast": "worker route config stale vs site rebuild","ShowBox": "febbox.com DNS dead","GoatAPI": "empty responses","HDHub4u": "DNS dead","Movies4u": "m4uplay player fully string-obfuscated, unverifiable","PurStream": "API blocks HF IPs (worked from sandbox, fails on Space)","MoviesHunt": "abhilinks/hubcloud Cloudflare-challenges HF IPs (worked from sandbox)",},},"source_repos": ["github.com/D3adlyRocket/All-in-One-Nuvio", "github.com/yogesh-hacker/MediaVanced"],"tips": ["No source = default sources (castle, netmirror, vidlove, playbox, movix) - the verified-working set","Castle: multi-language m3u8 (English/Tamil/Telugu), best for new Bollywood/Hollywood","NetMirror: instant mp4 links 360p-1080p, movie+TV, TMDB id based","VidLove/PlayBox/Movix: m3u8, work for both movie and TV","MoviesHunt/VegaMovies: direct MKV downloads (Hindi multi-audio), movies+TV packs","Direct MKV links work in VLC/mpv; m3u8 works in any HLS player",],}60 unmodified linesreturn {"status": "ok", "timestamp": int(time.time())}@app.get("/api/sources")async def list_sources():return {123456789101112131415161718193 unmodified lines2324252627282930313233343541 unmodified lines7778798081827 unmodified lines909192939495969798991001013 unmodified lines1051061071081091101 unmodified line1121131141151161173 unmodified lines1211221231241251261271281291301311321 unmodified line13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929050 unmodified lines3413423433443453463476 unmodified lines3543553563573583593603613623633643653669 unmodified lines37637737837938038138238338438538613 unmodified lines40040140240340440540625 unmodified lines4324334344354364377 unmodified lines4454464474484494504514524534544554564574584594602 unmodified lines4634644654664674682 unmodified lines4714724734744754762 unmodified lines47948048148248348448548648748848924 unmodified lines5145155165175185195205215225233 unmodified lines5275285295305315324 unmodified lines5375385395405415423 unmodified lines5465475485495505512 unmodified lines55455555655755855916 unmodified lines57657757857958058158225 unmodified lines60860961061161261361461561661761861962036 unmodified lines65765865966066166266366466566666766866967067167267367467567667767867968068168268368468524 unmodified lines71071171271371471571671771871913 unmodified lines73373473573673773873974074174274374474574674774874975075175212 unmodified lines7657667677687697707717727737747757767777787797807817827837847857867877887897907917927937 unmodified lines80180280380480580680780880981081181281381481581681781881982082182282334 unmodified lines8588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130411 unmodified lines13161317131813191320132113221323132413251 unmodified line1327132813291330133113321 unmodified line133413351336133713381339134012 unmodified lines1353135413551356135713584 unmodified lines1363136413651366136713684 unmodified lines13731374137513761377137813791380138113821383138412 unmodified lines1397139813991400140114022 unmodified lines1405140614071408140914107 unmodified lines141814191420142114221423142414256 unmodified lines143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146811 unmodified lines148014811482148314841485148614871488148911 unmodified lines1501150215031504150515061507150815091510151115121513151413 unmodified lines15281529153015311532153315341 unmodified line1536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157060 unmodified lines163116321633163416351636"""StreamForge API v11 - Multi-Language Stream Scraperv11 (playability release):- NEW: built-in /proxy endpoint (Range streaming + header injection + m3u8 playlist rewriting)- NetMirror v2: embed-tmdb mp4s now served THROUGH the proxy (fixes "returns stream but won't play")(net27.cc CDN blocks direct playback - their own player proxies via workers; we do the same)- NetMirror v2: subtitle tracks passed through (proxied)- NEW source: Movies4u (m4uplay packed-player unpack -> acek-cdn m3u8 + HubCloud direct)- NEW source: PersianStremio (stremio-style API, imdb based, movie+TV, direct MKV)- REMOVED: VidLove (api.shows.st returns 403 "Website Access Blocked" for all datacenter IPs)- Kept: Castle, PlayBox, Movix (verified playable m3u8), VegaMovies (direct MKV)"""from fastapi import FastAPI, HTTPException, Query, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponse, Response, JSONResponsefrom pydantic import BaseModelfrom typing import Optionalimport httpx3 unmodified linesimport timeimport asyncioimport hashlibimport html as ihtmlfrom urllib.parse import quote, urljoin, urlparseapp = FastAPI(title="StreamForge API",description="Multi-language m3u8/mp4/MKV stream scraper",version="11.0.0",)app.add_middleware(41 unmodified lines}def detect_language(label: str) -> str:lower = label.lower()if "hindi" in lower or "hin" in lower: return "Hindi"7 unmodified linesif "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:3 unmodified linesdef 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()1 unmodified linedef extract_language_from_title(title: str) -> str:bracket_match = re.search(r'\[([^\]]+)\]', title)if bracket_match:lang_text = bracket_match.group(1)3 unmodified linesreturn ""def _sf_stream_result(source: str, title: str, url: str, quality: str = "Auto",language: str = "English", headers: dict = None,subtitles: list = None, direct_url: str = None) -> dict:# strip control characters some APIs embed in URLsurl = re.sub(r'[\x00-\x1f\x7f]', '', url or "")r = {"source": source,"title": title,"quality": quality,1 unmodified line"url": url,"type": "m3u8" if ".m3u8" in url else "direct",}if headers:r["headers"] = headersif subtitles:r["subtitles"] = subtitlesif direct_url:r["direct_url"] = direct_urlreturn rdef _sf_norm(s: str) -> str:return re.sub(r"[^a-z0-9]", "", (s or "").lower())# ===== Proxy engine =====# Streams that need special headers (Referer/UA) or are IP-bound cannot be played# directly by clients. We proxy them through the API itself.async def _proxy_fetch_upstream(url: str, headers: dict, range_header: str = None):h = dict(headers or {})if range_header:h["Range"] = range_headerclient = httpx.AsyncClient(timeout=30, follow_redirects=True)resp = await client.build_request("GET", url, headers=h)return client, resp_M3U8_URI_RE = re.compile(r'(?m)^((?:#EXT-X-KEY:.*?URI=")([^"]+)("|))|(?!#)((?:https?://|/)[^\s"\'<>]+|"([^"]+)")')def _m3u8_rewrite(content: str, base_url: str, ref: str = None, ua: str = None) -> str:"""Rewrite every URI inside an m3u8 playlist to go through /proxy."""def _wrap(u: str) -> str:absu = urljoin(base_url, u)params = [f"u={quote(absu, safe='')}"]if ref:params.append(f"ref={quote(ref, safe='')}")if ua:params.append(f"ua={quote(ua, safe='')}")return f"/proxy?{'&'.join(params)}"out_lines = []for line in content.splitlines():ls = line.strip()if not ls:continueif ls.startswith("#EXT-X-KEY") or ls.startswith("#EXT-X-MAP"):def key_uri(mm):return f'URI="{_wrap(mm.group(1))}"'ls = re.sub(r'URI="([^"]+)"', key_uri, ls)out_lines.append(ls)elif ls.startswith("#"):out_lines.append(ls)else:out_lines.append(_wrap(ls.strip('"')))return "\n".join(out_lines) + "\n"@app.get("/proxy")async def proxy_stream(u: str, ref: str = None, ua: str = None, n: str = None):"""Stream proxy: adds required headers, supports Range, rewrites m3u8 playlists."""headers = {"User-Agent": ua or HEADERS["User-Agent"], "Accept": "*/*"}if ref:headers["Referer"] = refrange_header = Nonerange_header_alt = None# We need access to the raw request headers for Range; FastAPI injects Request only# if declared - so use a trick: read from the global request scope via a sub-app is# complex. Instead accept range via query for clients that can't set headers, and# also try to honor standard behavior via a Request dependency below.return await _proxy_do(u, ref, ua, None)async def _proxy_do(u: str, ref: str, ua: str, range_header: str = None):headers = {"User-Agent": ua or HEADERS["User-Agent"], "Accept": "*/*"}if ref:headers["Referer"] = refif range_header:headers["Range"] = range_headertry:client = httpx.AsyncClient(timeout=45, follow_redirects=True)req = client.build_request("GET", u, headers=headers)resp = await client.send(req, stream=True)except Exception as e:return JSONResponse({"error": f"proxy fetch failed: {str(e)}"}, status_code=502)ctype = resp.headers.get("content-type", "application/octet-stream")is_m3u8 = ".m3u8" in u or "mpegurl" in ctype.lower()if is_m3u8:try:body = (await resp.aread()).decode("utf-8", errors="ignore")finally:await resp.aclose()rewritten = _m3u8_rewrite(body, str(resp.url), ref, ua)await client.aclose()return Response(content=rewritten,media_type="application/vnd.apple.mpegurl",headers={"Cache-Control": "no-cache", "Access-Control-Allow-Origin": "*"},)# binary stream (mp4/mkv/ts/segment): pipe with Range support# pass upstream errors through faithfully so players can fall backif 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")status = resp.status_codeout_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"]async def iter_bytes():try:async for chunk in resp.aiter_bytes(64 * 1024):yield chunkfinally:await resp.aclose()await client.aclose()media_type = ctype if ctype and ctype != "text/html" else "application/octet-stream"return StreamingResponse(iter_bytes(), status_code=status, media_type=media_type, headers=out_headers)@app.api_route("/proxy_range", methods=["GET"], include_in_schema=False)async def proxy_range(request: Request, u: str, ref: str = None, ua: str = None):"""Proxy that honors the client's Range header (for players that seek)."""range_header = request.headers.get("range")return await _proxy_do(u, ref, ua, range_header)def _proxy_wrap(url: str, ref: str = None, ua: str = None) -> str:"""Build a /proxy_range URL for a client stream."""params = [f"u={quote(url, safe='')}"]if ref:params.append(f"ref={quote(ref, safe='')}")if ua:params.append(f"ua={quote(ua, safe='')}")return f"/proxy_range?{'&'.join(params)}"# ---------- HubCloud family resolver (MediaVanced hubcloud.py, generalized) ----------50 unmodified linesout.append({"url": _sf_pixeldrain_direct(u), "label": fname or "Direct"})elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) and ".zip" not in u:out.append({"url": u, "label": fname or "Direct"})elif "cloudflarestorage" in u or "workers.dev" in u or "googleusercontent.com" in u:out.append({"url": u, "label": fname or "Direct"})except Exception:pass6 unmodified linesif "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")9 unmodified liness_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 Trueother = 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 Falsereturn True13 unmodified linesreturn results# ===== Castle Scraper (hlowb.com API with AES-CBC) - multi-language m3u8 =====async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []25 unmodified lines}async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client:sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1", params={"channel": CH, "clientType": CLI, "lang": LANG})7 unmodified lineserrors.append("Castle: bad sec key response")return results, errorstry:sec_key = base64.b64decode(raw_k).decode("utf-8", errors="ignore")except Exception:sec_key = raw_kcombined = (sec_key + "T!BgJB")aes_k = (combined + "\x00" * max(0, 16 - len(combined)))[:16].encode("utf-8")aes_iv = aes_kdef castle_decrypt(text):d = texttry:j = json.loads(text)2 unmodified linesexcept Exception:passtry:raw = base64.b64decode(d)c = AES.new(aes_k, AES.MODE_CBC, aes_iv)2 unmodified linesexcept Exception:passtry:raw = bytes.fromhex(d)c = AES.new(aes_k, AES.MODE_CBC, aes_iv)2 unmodified linesexcept Exception:passtry:return json.loads(text)except Exception:raise ValueError(f"Castle decrypt failed for data length={len(d)}")kw = f"{title} {info.get('year', '')}".strip()sr = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={"channel": CH, "clientType": CLI, "keyword": kw, "lang": LANG,24 unmodified lineserrors.append("Castle: no search results")return results, errorsmid = Nonetl = normalize_title(title).lower()target_subject_type = 1 if media_type == "movie" else 2for r in rows:if not isinstance(r, dict):continue3 unmodified linesmid = r.get("id")breakif not mid:for r in rows:if not isinstance(r, dict):4 unmodified linesmid = r.get("id")breakif not mid:for r in rows:if not isinstance(r, dict):3 unmodified linesmid = r.get("id")breakif not mid and isinstance(rows[0], dict):mid = rows[0].get("id")2 unmodified linesreturn results, errorsmid = str(mid)dr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={"channel": CH, "clientType": CLI, "lang": LANG,"movieId": mid, "packageName": PKG16 unmodified linesif not isinstance(dd, dict):dd = {}ep_id = midif media_type == "tv" and season and episode:seasons = dd.get("seasons", [])s_id = mid25 unmodified linesbreakmid = s_idelse:eps = dd.get("episodes", [])if eps and isinstance(eps[0], dict):ep_id = str(eps[0].get("id", ""))CASTLE_LANGS = [("English", "1003"), ("Tamil", "1033"), ("Telugu", "1037")]for lang_name, lang_id in CASTLE_LANGS:for resolution in [3, 2, 1]:try:body = {"mode": "1",36 unmodified linesif not vurl:continue# some key batches contain control chars (corrupt auth_key) - retry onceif re.search(r'[\x00-\x1f\x7f]', vurl):vr = await client.post(f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2",params={"clientType": CLI, "packageName": PKG, "channel": CH, "lang": LANG},json=body,headers={"Content-Type": "application/json"})if vr.status_code == 200:try:vp = castle_decrypt(vr.text)vd = vp.get("data", vp)if isinstance(vd, str):vd = json.loads(vd)if isinstance(vd, dict) and vd.get("videoUrl"):vurl = vd["videoUrl"]except Exception:passif re.search(r'[\x00-\x1f\x7f]', vurl):continuequality_map = {1: "480P", 2: "720P", 3: "1080P"}quality = quality_map.get(resolution, "720P")vids = vd.get("videos", [])if vids and isinstance(vids, list):24 unmodified lines"url": vurl,"type": "m3u8" if ".m3u8" in vurl else "direct",})breakexcept Exception:continueseen = set()uniq = []for r in results:13 unmodified linesreturn results, errors# ===== NetMirror v2 (net27.cc embed-tmdb + API proxy) =====# net27.cc CDN (bcdnxw.hakunaymatata.com) blocks direct playback (429) - the site's own# player proxies through a worker. We do the same via /proxy_range with Referer+UA._NETMIRROR_BASE = "https://net27.cc"_NETMIRROR_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"_NETMIRROR_HEADERS = {"Accept": "application/json, text/plain, */*","Referer": "https://net27.cc/","User-Agent": _NETMIRROR_UA,}async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []errors = []try:12 unmodified lineserrors.append("NetMirror: non-JSON response")return results, errorsif data.get("ok") is False or data.get("noSource"):errors.append("NetMirror: title not available on NetMirror")return results, errors# Subtitle tracks (proxied)subs_out = []for sub in (data.get("subtitles") or []):try:surl = sub.get("url") if isinstance(sub, dict) else Noneif not surl:continueif surl.startswith("/"):surl = _NETMIRROR_BASE + surllang = sub.get("lang") or sub.get("language") or "Sub"subs_out.append({"language": lang,"url": _proxy_wrap(surl, ref="https://net27.cc/", ua=_NETMIRROR_UA),})except Exception:continuestreams = data.get("streams") or []if not isinstance(streams, list) or not streams:mp4 = data.get("mp4")if mp4:streams = [{"url": mp4, "resolution": data.get("resolution", "Auto")}]7 unmodified linesu = s.get("url")if not u:continueif u.startswith("/"):u = _NETMIRROR_BASE + ures = str(s.get("resolution") or "").strip()quality = {"2160": "4K", "1080": "1080p", "720": "720p", "480": "480p", "360": "360p"}.get(res, res if res else "Auto")proxied = _proxy_wrap(u, ref="https://net27.cc/", ua=_NETMIRROR_UA)results.append(_sf_stream_result("NetMirror", f"NetMirror - {quality}", proxied,quality=quality, language="Multi",headers={"Referer": "https://net27.cc/", "User-Agent": _NETMIRROR_UA},subtitles=subs_out or None,direct_url=u))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"34 unmodified linesreturn 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:continuename = 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_textrest = html_text[anchor.end():]endm = re.search(r"',(\d+),(\d+),'", rest)if not endm:return html_textpayload = 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_textwords = rest2[:wend].split('|')ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'def enc(i):out = ""while True:out = ALPHABET[i % radix] + outi //= radixif i == 0:breakreturn outunpacked = payloadfor 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_textdef _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 m3u8if 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 uniqasync 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_SITEtry: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:passresults_all = []async with httpx.AsyncClient(timeout=25, follow_redirects=True,headers={"User-Agent": _M4U_UA, "Referer": site + "/"}) as client:# 1) searchsr = await client.get(f"{site}/?s={quote(title)}")if sr.status_code != 200:errors.append(f"Movies4u: search HTTP {sr.status_code}")return results, errorsposts = []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 patternfor 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 posttl_norm = _sf_norm(f"{title} {year}")chosen = Nonefor 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 = pbreakif 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 = pbreakif not chosen:chosen = posts[0]# episode filter for TV: prefer post with S..E markerif 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 = pbreakpr = await client.get(chosen["url"])if pr.status_code != 200:errors.append(f"Movies4u: post HTTP {pr.status_code}")return results, errorspost_html = pr.text# 3) find m4uplay file linkm4u_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 anchorsif 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:continuefor 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 pagehc_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 + "/"})).textfor 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:continueif resolved:results_all.extend(resolved)seen = set()for r in results_all:u = r["url"]if u in seen:continueseen.add(u)label = r.get("label") or "Direct"if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1):continueif ".m3u8" in u:results.append(_sf_stream_result("Movies4u", f"Movies4u - {label}", u,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, errorsif 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 = Nonelast_status = 0for attempt in range(3): # persianstremio (CF-fronted) intermittently 503sresp = 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_codeif resp.status_code == 200:data = resp.json()breakawait asyncio.sleep(1.5 * (attempt + 1))if data is None:errors.append(f"PersianStremio: API HTTP {last_status}")return results, errorsstreams = data.get("streams") or []if not streams:errors.append("PersianStremio: no streams")return results, errorsseen = set()for st in streams:if not isinstance(st, dict):continueu = st.get("url")if not u or u in seen:continueseen.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_urlif "/r?key=" in u:rp = (await client.get(u, headers={"User-Agent": _SF_MOBILE_UA, "Referer": "https://driveseed.org/"})).textm = 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 linkszf = 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})).textfor 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})breakexcept Exception:passreturn outasync 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_SITEtry: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:passasync 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, errorsposts = []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, errorstl_norm = _sf_norm(title)chosen = Nonefor 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 = pbreakif not chosen:for p in posts:if tl_norm in _sf_norm(p["url"]):chosen = pbreakif not chosen and media_type == "movie":# movies often have "Season 1" style posts; prefer plain movie postsfor p in posts:if "season" not in p["title"].lower():chosen = pbreakif 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, errorspost_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 TVseen = set()for r in resolved:u, label = r["url"], r["label"]if u in seen:continueseen.add(u)if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1):continueresults.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"11 unmodified linesasync 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"})).textm = re.search(r"atob\(atob\('([A-Za-z0-9+/=]+)'\)\)", page)if m:dec = _sf_b64_all(m.group(1))1 unmodified linepage2 = (await client.get(dec, headers={"User-Agent": _SF_MOBILE_UA, "Referer": vcloud_url, "Cookie": "xla=s4t"})).textpage = page2for b in re.finditer(r'<a[^>]+href="(https?://[^"]+)"[^>]+class="[^"]*btn[^"]*"', page):u = b.group(1)chunk = page[b.start():b.start() + 800]1 unmodified linefname = fm.group(1) if fm else "Direct"if "pixeldrain" in u:out.append({"url": _sf_pixeldrain_direct(u), "label": fname})elif "cloudflarestorage" in u or "workers.dev" in u or ".r2.dev" in u or "googleusercontent" in u:out.append({"url": u, "label": fname})elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) and ".zip" not in u:out.append({"url": u, "label": fname})12 unmodified lineserrors.append("VegaMovies: no imdb id")return results, errorssite = _VEGA_DEFAULT_SITEtry:async with httpx.AsyncClient(timeout=10) as c:4 unmodified linespassasync 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}")4 unmodified lineserrors.append("VegaMovies: search non-JSON")return results, errorshits = 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, errorstitle_norm = _sf_norm(info.get("title") or "")year = str(info.get("year") or "")chosen = None12 unmodified lineserrors.append("VegaMovies: no matching post")return results, errorspr = 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}")2 unmodified linesnexdrive_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 = []7 unmodified lines"User-Agent": _SF_MOBILE_UA, "Referer": f"{site}/"})).textexcept Exception:continuefor 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)))6 unmodified linesreturn results, errors_SF_HUB_HEADERS = {"User-Agent": _SF_MOBILE_UA, "Accept": "text/html,application/xhtml+xml,*/*", "Accept-Language": "en-US,en;q=0.5"}# ===== Source Map =====SOURCE_MAP = {"castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e),"languages": ["English", "Tamil", "Telugu"], "reliability": "high","note": "hlowb.com API, AES-CBC, multi-language m3u8 (EN/Tamil/Telugu)"},"netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e),"languages": ["Hindi", "English", "Multi"], "reliability": "high","note": "net27.cc embed-tmdb, mp4 360p-1080p served via /proxy_range (CDN blocks direct playback); subtitles included"},"playbox": {"name": "PlayBox", "fn": lambda tid, mt, s, e: scrape_playbox(tid, mt, s, e),"languages": ["English", "Multi"], "reliability": "high","note": "streamdata.vaplayer.ru API, multi-quality m3u8, TMDB id based"},"movix": {"name": "Movix", "fn": lambda tid, mt, s, e: scrape_movix(tid, mt, s, e),"languages": ["English", "Multi"], "reliability": "high","note": "api.movix.cash direct API, m3u8 1080p"},"movies4u": {"name": "Movies4u", "fn": lambda tid, mt, s, e: scrape_movies4u(tid, mt, s, e),"languages": ["Hindi", "English", "Multi"], "reliability": "medium","note": "m4uplay packed player -> acek-cdn m3u8 + HubCloud/Google direct, movie+TV"},"persianstremio": {"name": "PersianStremio", "fn": lambda tid, mt, s, e: scrape_persianstremio(tid, mt, s, e),"languages": ["Multi", "Persian"], "reliability": "high","note": "stremio-style API (imdb based), direct MKV up to 2160p, movie+TV"},"vegamovies": {"name": "VegaMovies", "fn": lambda tid, mt, s, e: scrape_vegamovies(tid, mt, s, e),"languages": ["Hindi", "English", "Multi"], "reliability": "medium","note": "search.php?q=imdb + nexdrive + vcloud chain, direct MKV up to 4K"},}DEFAULT_SOURCES = ["castle", "netmirror", "playbox", "movix", "movies4u", "persianstremio"]# ===== Helper: Run scrapers =====11 unmodified linesif 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, eexcept asyncio.TimeoutError:return [], [f"{src['name']}: Timeout (60s)"]except Exception as ex:return [], [f"{src['name']}: {str(ex)}"]11 unmodified linesseen_urls = set()unique_results = []for r in all_results:r["url"] = re.sub(r'[\x00-\x1f\x7f]', '', r.get("url") or "")if r.get("direct_url"):r["direct_url"] = re.sub(r'[\x00-\x1f\x7f]', '', r["direct_url"])if r["url"] not in seen_urls:seen_urls.add(r["url"])# make absolute proxy URLsif r["url"].startswith("/"):r["url"] = f"https://epiccodergg-streamforge-api.hf.space{r['url']}"unique_results.append(r)return {13 unmodified linesasync def root():return {"api": "StreamForge","version": "11.0.0","description": "Multi-language m3u8/mp4/MKV stream scraper","endpoints": {"movie": {"all_sources": "/movie/{tmdb_id}", "single_source": "/movie/{tmdb_id}/{source}",1 unmodified line"tv": {"all_sources": "/tv/{tmdb_id}/{season}/{episode}", "single_source": "/tv/{tmdb_id}/{season}/{episode}/{source}","example": "/tv/1396/1/1", "example_source": "/tv/1396/1/1/netmirror"},"search": {"path": "/search/{query}", "example": "/search/Venom"},"proxy": {"path": "/proxy_range?u=<url>&ref=<referer>&ua=<user-agent>","note": "stream proxy with Range support - NetMirror and subtitle URLs come pre-proxied"},"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_v11": {"fixed": ["NetMirror: streams now served through built-in /proxy_range (net27 CDN 429-blocks direct playback - the site's own player proxies too). Subtitles included. direct_url + headers also returned.",],"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)","NetMirror URLs are proxied through this API - play them as-is, no extra headers needed","Castle: multi-language m3u8 (English/Tamil/Telugu)","Movix/PlayBox/Movies4u: m3u8; PersianStremio/UHDMovies/VegaMovies: direct MKV (VLC/mpv/exoplayer)","Each result may include: headers (native playback), direct_url (raw URL), subtitles (proxied VTT)",],}60 unmodified linesreturn {"status": "ok", "timestamp": int(time.time())}@app.get("/api/sources")async def list_sources():return {
main.py+709-201