Spaces:
Running
Running
Commit ·
900c3a8
1
Parent(s): 0334f45
v7: update scrapers - remove VidNest (discontinued), update Castle (hlowb.com AES), VidSrc (vsrc.su+vsembed.su), MovieBox (aoneroom.com); add VidLink, PrimeSrc, M4UHD; remove Popr (broken)
Browse files1223457 unmodified lines1314151617181920202122232458 unmodified lines8384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127201 unmodified lines329330331292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482332333334149 unmodified lines4844854866384874884894904914924936454944954964976486496506514984995005015026546555035045056586596606616626635065075085095105115125135146656666675155165175185195206706715215225235245255265275285295305315325335345356736745365375385395405416776786796805425435445455465475485495505516826836846856865525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156896906916926936166176186196206216226236246956966256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636996646656667026676686696707046716726736747086756766777116786796806816826836846853 unmodified lines68969069172469269369469569669769869970070173270270373470470570670770873970971074174274374474574671171274871371471571671771871972072172275075172372472572672775375472872973073173273373473575773673773873974074174274374475976076176276374574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879976576680080180280380480576977080680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784877477577677777884985085185285385485585678078185785885986086178478586286386486586678986786886987079387187287379687487587687714 unmodified lines8928938948178188198208218228238248258958968978988999009019029039049059069079082 unmodified lines91191291383491491591691791891992092192292346 unmodified lines97097197288997397497597619 unmodified lines9969979989159991000100114 unmodified lines1016101710189361019102010213 unmodified lines1025102610279461028102910309 unmodified lines1040104110429621043104410456 unmodified lines1052105310549751055105610577 unmodified lines10651066106798910681069107010711072995996107310741075100010761077107812 unmodified lines10911092109310191094109510962 unmodified lines109911001101102811021103110410321105110611078 unmodified lines11161117111810471119112011212 unmodified lines11241125112610561127112810591129113011314 unmodified lines113611371138107011391140114111423 unmodified lines1146114711481080114911501151115215 unmodified lines116811691170110211711172117311741175117611081177117811791180118111141182118311847 unmodified lines1192119311941128112911951196119748 unmodified lines1246124712481184118511861249125012519 unmodified lines12611262126312021264126512051266126712689 unmodified lines12781279128012211281128212836 unmodified lines12901291129212341293129412954 unmodified lines1300130113021245130313041305124912501306130713084 unmodified lines13131314131512611316131713181319126613201321132217 unmodified lines134013411342129013431344134518 unmodified lines136413651366131513671368136917 unmodified lines138713881389133913901391139244 unmodified lines1437143814391390139114401441144214439 unmodified lines14531454145514071408140914101411141214131456141514161457145814591460146114621463146414651418141914201466146714681422142314241425142614271428142914301431143214331434143514361437146914701471147214731439144014411474147514761477147814431444144514461447147914801481144914501451148214831484148514861453148714881489149014911492149314551456145714581459146014941495149614971498149915001501150215031504150514621463150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160514651466146714681469147016061607160816091610161116121613161416151616161714721473147416181619162016211622162316241625162616271628162916301631163216331634163514761477147814791480163616371638148214831484148516391640164114871488148914901491149214931494149514961642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551499150015011756175717581759150317601761176215061507176317641765176617671768176917701771177217731774177517761777177817791780178117821512178317841785151517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121824 unmodified lines218721882189153115321533153421902191219221932194219515411542219621972198219922002 unmodified lines22032204220515512206220722082209221022112212221322141554221522162217221854 unmodified lines227322742275161522762277227822792280228122821622228322842285228618 unmodified lines230523062307164716481649165016512308230923102311231223132314231516532316231723182319"""StreamForge API v6 - Multi-Language Stream ScraperStreamForge API v7 - Multi-Language Stream ScraperScrapes direct m3u8 URLs from multiple sources"""
7 unmodified linesimport base64import timeimport asyncioimport hashlib
app = FastAPI( title="StreamForge API", description="Multi-language m3u8 stream scraper", version="5.0.0", version="7.0.0",)
app.add_middleware(58 unmodified lines 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: d = hashlib.md5(d + password + salt).digest() dtot += d return dtot[:key_len], dtot[key_len:key_len + iv_len]
def cryptojs_aes_decrypt(ciphertext_b64: str, passphrase: str) -> str: """Decrypt CryptoJS.AES.encrypt output (OpenSSL format with Salted__ prefix).""" from Crypto.Cipher import AES from Crypto.Util.Padding import unpad
raw = base64.b64decode(ciphertext_b64) if raw[:8] != b"Salted__": cipher = AES.new(passphrase.encode()[:32], AES.MODE_CBC, passphrase.encode()[:16]) return unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")
salt = raw[8:16] ct = raw[16:] key, iv = evp_bytes_to_key(passphrase.encode(), salt) cipher = AES.new(key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(ct), AES.block_size).decode("utf-8", errors="ignore")
def castle_aes_decrypt(ciphertext_b64: str, key_str: str) -> str: """AES-CBC decrypt for Castle (hlowb.com) API responses.""" from Crypto.Cipher import AES from Crypto.Util.Padding import unpad
aes_key = (key_str + "T!BgJB")[:16].encode("utf-8") aes_iv = aes_key # IV = same as key raw = base64.b64decode(ciphertext_b64) cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) return unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")
# ===== CineSu Scraper =====
async def scrape_cinesu(tmdb_id: int, media_type: str, season: int = None, episode: int = None):201 unmodified lines return results, errors
# ===== VidNest Scraper =====
VIDNEST_ALPHABET = "RB0fpH8ZEyVLkv7c2i6MAJ5u3IKFDxlS1NTsnGaqmXYdUrtzjwObCgQP94hoeW+/="
def vidnest_b64_decode(input_str: str) -> str: lookup = {c: i for i, c in enumerate(VIDNEST_ALPHABET)} mod = len(input_str) % 4 if mod: input_str += "=" * (4 - mod) result = bytearray() for i in range(0, len(input_str), 4): chunk = input_str[i:i+4] c0 = lookup.get(chunk[0], 64) c1 = lookup.get(chunk[1], 64) c2 = 64 if chunk[2] == "=" else lookup.get(chunk[2], 64) c3 = 64 if chunk[3] == "=" else lookup.get(chunk[3], 64) result.append(((c0 << 2) | (c1 >> 4)) & 0xff) if c2 != 64: result.append((((c1 & 0x0f) << 4) | (c2 >> 2)) & 0xff) if c3 != 64: result.append((((c2 & 0x03) << 6) | c3) & 0xff) return bytes(result).decode("utf-8", errors="ignore")
async def scrape_vidnest(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
servers = { "purstream": "French", "klikxxi": "English", "hollymoviehd": "English", "moviebox": "Multi", "allmovies": "Multi", "vidlink": "English", "onehd": "English", "flixhq": "English", }
try: async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client: async def fetch_server(server_name: str, language: str): server_results = [] try: if media_type == "movie": url = f"https://new.vidnest.fun/{server_name}/movie/{tmdb_id}" else: s = season or 1 e = episode or 1 url = f"https://new.vidnest.fun/{server_name}/tv/{tmdb_id}/{s}/{e}"
resp = await client.get(url) if resp.status_code != 200: return server_results, f"{server_name}: HTTP {resp.status_code}"
data = resp.json() encoded_data = data.get("data", "") if not encoded_data: return server_results, f"{server_name}: No data"
decoded = vidnest_b64_decode(encoded_data) parsed = json.loads(decoded)
sources = parsed.get("sources", []) title = parsed.get("title", "")
for source in sources: url_key = None for key in ["url", "file", "stream", "src", "link"]: if key in source: url_key = key break if not url_key: continue
stream_url = source[url_key] quality = source.get("quality") or source.get("label") or source.get("name", "Auto") source_name = source.get("name", source.get("label", "")) stream_type = "m3u8" if ".m3u8" in stream_url or source.get("type") == "hls" else "direct"
lang = detect_language(source_name) if source_name else language
server_results.append({ "source": f"VidNest/{server_name}", "title": source_name or title, "quality": quality, "language": lang, "url": stream_url, "type": stream_type, })
except Exception as e: return server_results, f"{server_name}: {str(e)}"
return server_results, None
tasks = [fetch_server(name, lang) for name, lang in servers.items()] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): errors.append(f"VidNest: {str(result)}") else: server_results, error = result results.extend(server_results) if error: errors.append(f"VidNest {error}")
except Exception as e: errors.append(f"VidNest: {str(e)}")
return results, errors
# ===== Popr Scraper =====
async def scrape_popr(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
servers = ["default", "catflix", "hexa", "Gama", "Liligoon", "Sigma", "Prime", "Alfa", "Lamda"]
try: async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: async def fetch_server(server: str): server_results = [] try: if media_type == "movie": url = f"https://popr.ink/api/vidnest?id={tmdb_id}&type=movie&server={server}" else: s = season or 1 e = episode or 1 url = f"https://popr.ink/api/vidnest?id={tmdb_id}&type=tv&server={server}&season={s}&episode={e}"
resp = await client.get(url) if resp.status_code != 200: return server_results, f"{server}: HTTP {resp.status_code}"
data = resp.json() if not data.get("success"): return server_results, None
for r in data.get("results", []): for stream in r.get("streams", []): stream_url = stream.get("url", "") quality = stream.get("quality", "Auto") is_m3u8 = stream.get("isM3U8", False) stream_type = "m3u8" if is_m3u8 else "direct"
lang = detect_language(quality)
server_results.append({ "source": f"Popr/{server}", "title": quality, "quality": quality, "language": lang, "url": stream_url, "type": stream_type, })
except Exception as e: return server_results, f"{server}: {str(e)}"
return server_results, None
tasks = [fetch_server(s) for s in servers] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): errors.append(f"Popr: {str(result)}") else: server_results, error = result results.extend(server_results) if error: errors.append(f"Popr {error}")
seen_urls = set() unique_results = [] for r in results: if r["url"] not in seen_urls: seen_urls.add(r["url"]) unique_results.append(r) results = unique_results
except Exception as e: errors.append(f"Popr: {str(e)}")
return results, errors
# ===== VidRock Scraper (AES-encrypted API) =====
async def scrape_vidrock(tmdb_id: int, media_type: str, season: int = None, episode: int = None):149 unmodified lines return results, errors
# ===== Castle Scraper (Stremio-style aggregator) =====# ===== Castle Scraper (hlowb.com API with AES-CBC decryption) =====
async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: import urllib.parse from Crypto.Cipher import AES from Crypto.Util.Padding import unpad
info = await get_tmdb_info(tmdb_id, media_type) imdb_id = info.get("imdb_id")
if not imdb_id: errors.append("Castle: Could not get IMDB ID from TMDB") title = info.get("title", "") if not title: errors.append("Castle: Could not get title from TMDB") return results, errors
CASTLE_API = "https://meowtv.vflix.shop" SKIP_PATTERNS = ["4khdhub", "instant download", "iosmirror", "xdm", "redirecting"] CASTLE_BASE = "https://api.hlowb.com"
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: if media_type == "movie": url = f"{CASTLE_API}/stream/movie/{imdb_id}.json" else: s = season or 1 e = episode or 1 url = f"{CASTLE_API}/stream/series/{imdb_id}:{s}:{e}.json" # Step 1: Get security key sec_resp = await client.get( f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1?channel=", headers={"Accept": "application/json"} ) if sec_resp.status_code != 200: errors.append(f"Castle: Security key request failed HTTP {sec_resp.status_code}") return results, errors
resp = await client.get(url, headers={"Accept": "application/json"}) if resp.status_code != 200: errors.append(f"Castle: HTTP {resp.status_code}") sec_data = sec_resp.json() security_key = sec_data.get("data", {}).get("securityKey", "") if not security_key: errors.append("Castle: No security key in response") return results, errors
data = resp.json() streams = data.get("streams", []) # Derive AES key and IV: (securityKey + "T!BgJB")[:16] aes_key_str = (security_key + "T!BgJB")[:16] aes_key = aes_key_str.encode("utf-8") aes_iv = aes_key # IV = same as key
# Step 2: Search for the movie search_resp = await client.get( f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={"keyword": title, "channel": ""}, headers={"Accept": "application/json"} ) if search_resp.status_code != 200: errors.append(f"Castle: Search failed HTTP {search_resp.status_code}") return results, errors
if not streams: errors.append("Castle: No streams found") search_data = search_resp.json() encrypted_data = search_data.get("data", "") if not encrypted_data: errors.append("Castle: No encrypted data in search response") return results, errors
for s in streams: s_url = s.get("url", "") if not s_url: continue # Decrypt search results try: raw = base64.b64decode(encrypted_data) cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) decrypted = unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") search_results = json.loads(decrypted) except Exception as dec_err: errors.append(f"Castle: Search decryption failed - {str(dec_err)}") return results, errors
name = (s.get("name") or "").lower() title = (s.get("title") or "").lower() if any(p in name or p in title for p in SKIP_PATTERNS): continue if "github.com" in s_url or "googleusercontent" in s_url: # Find matching movie by title movie_list = search_results if isinstance(search_results, list) else search_results.get("list", search_results.get("data", [])) if not isinstance(movie_list, list): movie_list = []
title_lower = title.lower().strip() matched_movie = None for item in movie_list: item_title = (item.get("title") or item.get("name") or "").lower().strip() item_id = item.get("id") if not item_id: continue if item_title == title_lower or title_lower in item_title or item_title in title_lower: matched_movie = item break
if not matched_movie and movie_list: matched_movie = movie_list[0]
if not matched_movie: errors.append("Castle: No matching movie found in search results") return results, errors
movie_id = matched_movie.get("id")
# Step 3: Get movie details detail_resp = await client.get( f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={"channel": "", "id": movie_id}, headers={"Accept": "application/json"} ) if detail_resp.status_code != 200: errors.append(f"Castle: Detail request failed HTTP {detail_resp.status_code}") return results, errors
detail_data = detail_resp.json() encrypted_detail = detail_data.get("data", "") if encrypted_detail: try: raw = base64.b64decode(encrypted_detail) cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) decrypted_detail = unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") detail_parsed = json.loads(decrypted_detail) except: detail_parsed = {} else: detail_parsed = detail_data
# Step 4: Get video URL video_resp = await client.get( f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2", params={"clientType": "1", "channel": "", "id": movie_id}, headers={"Accept": "application/json"} ) if video_resp.status_code != 200: errors.append(f"Castle: Video request failed HTTP {video_resp.status_code}") return results, errors
video_data = video_resp.json() encrypted_video = video_data.get("data", "") if not encrypted_video: errors.append("Castle: No encrypted video data in response") return results, errors
# Castle often wraps URLs like: https://...?url=ACTUAL_URL actual_url = s_url url_param = re.search(r'[?&]url=([^&]+)', s_url) if url_param: actual_url = urllib.parse.unquote(url_param.group(1)) try: raw = base64.b64decode(encrypted_video) cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) decrypted_video = unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") video_parsed = json.loads(decrypted_video) except Exception as dec_err: errors.append(f"Castle: Video decryption failed - {str(dec_err)}") return results, errors
quality = "Auto" q_match = re.search(r'(\d{3,4})p', name + title + actual_url) # Extract stream URLs from video response def extract_castle_streams(obj, depth=0): streams = [] if depth > 10: return streams if isinstance(obj, dict): for key in ["url", "playUrl", "videoUrl", "streamUrl", "downloadUrl"]: val = obj.get(key, "") if val and isinstance(val, str) and (val.startswith("http") or ".m3u8" in val): quality = obj.get("quality") or obj.get("resolution") or obj.get("name") or "Auto" lang = obj.get("language") or obj.get("lang") or "" name = obj.get("name") or obj.get("title") or obj.get("serverName") or "" streams.append({ "url": val, "quality": str(quality), "language": lang, "name": name, }) for key in ["list", "sources", "episodes", "items", "videoInfo", "playList"]: child = obj.get(key) if child: streams.extend(extract_castle_streams(child, depth + 1)) if not streams: for v in obj.values(): if isinstance(v, (dict, list)): streams.extend(extract_castle_streams(v, depth + 1)) elif isinstance(obj, list): for item in obj: streams.extend(extract_castle_streams(item, depth + 1)) return streams
castle_streams = extract_castle_streams(video_parsed)
for cs in castle_streams: s_url = cs["url"] quality = cs.get("quality", "Auto") q_match = re.search(r'(\d{3,4})p', str(quality)) if q_match: quality = q_match.group(1) + "p" elif "4k" in (name + title).lower() or "2160" in actual_url: elif "4k" in str(quality).lower() or "2160" in str(quality): quality = "4K"
lang = detect_language(name + " " + title) lang = cs.get("language", "") lang = detect_language(lang) if lang else "English" name = cs.get("name", "")
s_type = "m3u8" if ".m3u8" in actual_url else ("direct" if ".mp4" in actual_url or ".mkv" in actual_url else "m3u8") s_type = "m3u8" if ".m3u8" in s_url else ("direct" if ".mp4" in s_url else "m3u8")
results.append({ "source": "Castle", "title": s.get("name", "Castle Stream"), "title": name or "Castle Stream", "quality": quality, "language": lang, "url": actual_url, "url": s_url, "type": s_type, })
# Deduplicate seen_urls = set() unique_results = [] for r in results:3 unmodified lines results = unique_results
if not results: errors.append("Castle: No usable streams after filtering") errors.append("Castle: No streams found after decryption")
except ImportError: errors.append("Castle: pycryptodome not installed") except Exception as e: errors.append(f"Castle: {str(e)}")
return results, errors
# ===== MovieBoxHindi Scraper (Hindi - Cloudflare Worker API) =====# ===== MovieBox Scraper (h5-api.aoneroom.com) =====
async def scrape_movieboxhindi(tmdb_id: int, media_type: str, season: int = None, episode: int = None):async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: WORKER_BASE = "https://moviebox.s4nch1tt.workers.dev" import urllib.parse
async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: url = f"{WORKER_BASE}/streams?tmdb_id={tmdb_id}&type={media_type}&proxy={WORKER_BASE}" if media_type == "tv": s = season or 1 e = episode or 1 url += f"&se={s}&ep={e}" MOVIEBOX_BASE = "https://h5-api.aoneroom.com"
resp = await client.get(url, headers={ def generate_moviebox_token() -> str: ts = str(int(time.time())) reversed_ts = ts[::-1] md5_hash = hashlib.md5(reversed_ts.encode()).hexdigest() return f"{ts}.{md5_hash}"
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: token = generate_moviebox_token() mb_headers = { "Accept": "application/json", "User-Agent": "StreamForge/1.0", }) "token": token, "Origin": "https://moviebox.app", "Referer": "https://moviebox.app/", }
if resp.status_code != 200: errors.append(f"MovieBoxHindi: HTTP {resp.status_code}") # Step 1: Search for the movie info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") year = info.get("year", "") if not title: errors.append("MovieBox: Could not get title from TMDB") return results, errors
data = resp.json() search_resp = await client.post( f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/search", json={"keyword": title, "page": 1, "size": 20}, headers=mb_headers, ) if search_resp.status_code != 200: errors.append(f"MovieBox: Search failed HTTP {search_resp.status_code}") return results, errors
raw_streams = [] if isinstance(data, list): raw_streams = data elif isinstance(data, dict): raw_streams = data.get("streams", []) search_data = search_resp.json() search_items = search_data.get("data", {}).get("items", []) if not search_items: errors.append("MovieBox: No search results") return results, errors
# Step 2: Match by normalized title + year title_norm = re.sub(r'[^a-zA-Z0-9]', '', title.lower()) matched_item = None for item in search_items: item_title = item.get("title", "") or item.get("name", "") item_year = str(item.get("year", "") or item.get("releaseYear", "")) item_norm = re.sub(r'[^a-zA-Z0-9]', '', item_title.lower())
if item_norm == title_norm: if year and item_year and year == item_year: matched_item = item break elif not year or not item_year: matched_item = item break
if not matched_item: for item in search_items: item_title = item.get("title", "") or item.get("name", "") item_norm = re.sub(r'[^a-zA-Z0-9]', '', item_title.lower()) if title_norm in item_norm or item_norm in title_norm: matched_item = item break
if not matched_item and search_items: matched_item = search_items[0]
if not matched_item: errors.append("MovieBox: No matching title found") return results, errors
subject_id = matched_item.get("id") if not subject_id: errors.append("MovieBox: No subject ID in matched item") return results, errors
# Step 3: Get download URLs token = generate_moviebox_token() mb_headers["token"] = token
dl_resp = await client.get( f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/download", params={"subjectId": subject_id}, headers=mb_headers, ) if dl_resp.status_code != 200: errors.append(f"MovieBox: Download request failed HTTP {dl_resp.status_code}") return results, errors
if not raw_streams: errors.append("MovieBoxHindi: No streams returned") dl_data = dl_resp.json() dl_items = dl_data.get("data", {}).get("items", []) if not dl_items: errors.append("MovieBox: No download items found") return results, errors
for s in raw_streams: stream_url = s.get("proxy_url") or s.get("url", "") # For TV: find season/episode if media_type == "tv": s = season or 1 e = episode or 1 token = generate_moviebox_token() mb_headers["token"] = token
detail_resp = await client.get( f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/detail", params={"subjectId": subject_id}, headers=mb_headers, ) if detail_resp.status_code == 200: detail_data = detail_resp.json() episodes = detail_data.get("data", {}).get("episodes", []) target_ep = None for ep_item in episodes: ep_season = ep_item.get("seasonNumber", ep_item.get("season", 0)) ep_num = ep_item.get("episodeNumber", ep_item.get("episode", 0)) if int(ep_season) == s and int(ep_num) == e: target_ep = ep_item break
if target_ep and target_ep.get("id"): token = generate_moviebox_token() mb_headers["token"] = token
ep_dl_resp = await client.get( f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/download", params={"subjectId": target_ep["id"]}, headers=mb_headers, ) if ep_dl_resp.status_code == 200: ep_dl_data = ep_dl_resp.json() ep_dl_items = ep_dl_data.get("data", {}).get("items", []) if ep_dl_items: dl_items = ep_dl_items
for dl_item in dl_items: stream_url = dl_item.get("url") or dl_item.get("downloadUrl") or dl_item.get("playUrl", "") if not stream_url: continue
quality = "Auto" resolution = s.get("resolution", "") if resolution: m = re.search(r'(\d+)', str(resolution)) quality = m.group(1) + "p" if m else str(resolution) quality = dl_item.get("quality") or dl_item.get("resolution") or "Auto" q_match = re.search(r'(\d{3,4})p', str(quality)) if q_match: quality = q_match.group(1) + "p"
lang = dl_item.get("language") or dl_item.get("audio", "") lang = detect_language(lang) if lang else "Hindi"
s_name = s.get("name", "") lang = detect_language(s_name) name = dl_item.get("name") or dl_item.get("title") or dl_item.get("serverName", "MovieBox Stream")
s_type = "m3u8" if ".m3u8" in stream_url else ("direct" if ".mp4" in stream_url or ".mkv" in stream_url else "m3u8")
results.append({ "source": "MovieBoxHindi", "title": s_name or "MovieBox Stream", "source": "MovieBox", "title": name, "quality": quality, "language": lang, "url": stream_url, "type": "m3u8", "type": s_type, })
if not results: errors.append("MovieBoxHindi: No valid streams parsed") errors.append("MovieBox: No streams found")
except Exception as e: errors.append(f"MovieBoxHindi: {str(e)}") errors.append(f"MovieBox: {str(e)}")
return results, errors
14 unmodified lines DECRYPT_API = "https://enc-dec.app/api/dec-videasy"
SERVERS = { "Neon": "https://api.videasy.net/myflixerzupcloud/sources-with-title", "Cypher": "https://api.videasy.net/moviebox/sources-with-title", "Reyna": "https://api.videasy.net/primewire/sources-with-title", "Omen": "https://api.videasy.net/onionplay/sources-with-title", "Breach": "https://api.videasy.net/m4uhd/sources-with-title", "Ghost": "https://api.videasy.net/primesrcme/sources-with-title", "Sage": "https://api.videasy.net/1movies/sources-with-title", "Vyse": "https://api.videasy.net/hdmovie/sources-with-title", "Raze": "https://api.videasy.net/superflix/sources-with-title", "Neon": {"url": "https://api.videasy.net/myflixerzupcloud/sources-with-title"}, "Cypher": {"url": "https://api.videasy.net/moviebox/sources-with-title"}, "Reyna": {"url": "https://api.videasy.net/primewire/sources-with-title"}, "Omen": {"url": "https://api.videasy.net/onionplay/sources-with-title"}, "Breach": {"url": "https://api.videasy.net/m4uhd/sources-with-title"}, "Ghost": {"url": "https://api.videasy.net/primesrcme/sources-with-title"}, "Sage": {"url": "https://api.videasy.net/1movies/sources-with-title"}, "Vyse": {"url": "https://api.videasy.net/hdmovie/sources-with-title"}, "Raze": {"url": "https://api.videasy.net/superflix/sources-with-title"}, "Yoru": {"url": "https://api.videasy.net/cdn/sources-with-title", "moviesOnly": True}, "SuperFlix": {"url": "https://api.videasy.net/superflix/sources-with-title"}, }
info = await get_tmdb_info(tmdb_id, media_type)2 unmodified lines imdb_id = info.get("imdb_id", "")
async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=VIDEASY_HEADERS) as client: async def fetch_server(name: str, endpoint: str): async def fetch_server(name: str, config: dict): server_results = [] try: if config.get("moviesOnly") and media_type == "tv": return server_results, f"{name}: Movies only"
endpoint = config["url"] url = f"{endpoint}?title={title}&mediaType={media_type}&year={year}&tmdbId={tmdb_id}&imdbId={imdb_id or ''}" if media_type == "tv": s = season or 146 unmodified lines
return server_results, None
tasks = [fetch_server(name, endpoint) for name, endpoint in SERVERS.items()] tasks = [fetch_server(name, config) for name, config in SERVERS.items()] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results:19 unmodified lines return results, errors
# ===== NetMirror Scraper (Netflix/PrimeVideo/Hotstar via API) =====
async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None):14 unmodified lines "x-requested-with": "NetmirrorNewTV v1.0", }
# Get API base URL api_base = FALLBACK_API try: async with httpx.AsyncClient(timeout=10) as cfg_client:3 unmodified lines except: pass
# Get media title from TMDB info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") if not title:9 unmodified lines svc_name = service["name"] headers = {**NETMIRROR_HEADERS, "ott": svc_code}
# Search for the title search_url = f"{api_base}/search.php?s={title}" search_resp = await client.get(search_url, headers=headers)
6 unmodified lines return service_results, [f"{svc_name}: Search returned non-JSON"]
search_results = search_data.get("searchResult", []) # Collect ALL matches ranked by relevance title_lower = title.lower().strip() exact_matches = [] starts_matches = []7 unmodified lines elif title_lower in item_title or item_title in title_lower: contains_matches.append(item) # Try matches in order of relevance all_matches = exact_matches + starts_matches + contains_matches if not all_matches: return service_results, [f"{svc_name}: No match found"]
# === Smart ranking: fetch metadata for top matches and score them === # Uses TMDB year + media_type vs NetMirror year, type, IMDB rating tmdb_year = info.get("year", "") expected_type = "t" if media_type == "tv" else "m"
# Fetch post.php for top matches to get metadata (limit to top 6) scored_matches = [] for match_item in all_matches[:6]: net_id = match_item.get("id")12 unmodified lines nm_year = post_data.get("year", "") nm_rating = 0 # Extract IMDB rating for detail in post_data.get("moredetails", []): if detail.get("k") == "IMDB Rating": try:2 unmodified lines nm_rating = 0 break # 1. Media type match (most important): TV→"t", movie→"m" if nm_type == expected_type: score += 50 # 2. Year proximity (very important for disambiguation) try: if tmdb_year and nm_year: year_diff = abs(int(tmdb_year) - int(nm_year))8 unmodified lines except: pass # 3. IMDB rating as tiebreaker (higher = more popular) score += nm_rating scored_matches.append({2 unmodified lines "score": score, }) # Sort by score descending (best match first) scored_matches.sort(key=lambda x: x["score"], reverse=True)
# For TV shows, try each scored match until we find one with the right season/episode final_id = None if media_type == "tv": s = season or 14 unmodified lines seasons = post_data.get("season", []) if not seasons: continue # This match has no seasons, try next continue target_term = f"Season {s}" season_entry = None3 unmodified lines break if not season_entry or not season_entry.get("id"): continue # No matching season, try next match continue season_id = season_entry["id"] episode_id = None15 unmodified lines if episode_id: final_id = episode_id break # Found a working match! break if not final_id: return service_results, [f"{svc_name}: No match with Season {s} Episode {e}"] else: # For movies, use the highest-scored match if scored_matches: final_id = scored_matches[0]["match"].get("id") else: final_id = all_matches[0].get("id")
# Get the actual stream player_resp = await client.get(f"{api_base}/player.php?id={final_id}", headers=headers) if player_resp.status_code != 200: return service_results, [f"{svc_name}: Player HTTP {player_resp.status_code}"]7 unmodified lines if not video_link: return service_results, [f"{svc_name}: No video link"]
# Verify the m3u8 stream is playable # CDN has migrated to tv.imgcdn.kim which works for all services if ".m3u8" in video_link: try: verify_resp = await client.get(video_link, headers=headers)48 unmodified lines return results, errors
# ===== AllMovieLand Scraper (Hindi/Tamil/Multi via allmovieland.one) =====
async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, episode: int = None):9 unmodified lines errors.append("AllMovieLand: Could not get title from TMDB") return results, errors
# Use single client session throughout (important for cookies/session) async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers={"User-Agent": UA}, http2=False) as client: # Step 1: Search search_resp = await client.get( "https://allmovieland.one/index.php", params={"story": title, "do": "search", "subaction": "search"}9 unmodified lines errors.append("AllMovieLand: No search results") return results, errors
# Find best match movie_url = None title_lower = title.lower() for article in articles:6 unmodified lines break if not movie_url: # Fallback: first result for article in articles: link_m = re.search(r'href="([^"]+)"', article) if link_m:4 unmodified lines errors.append("AllMovieLand: Could not find movie URL") return results, errors
# Step 2: Movie page movie_resp = await client.get(movie_url, headers={"Referer": "https://allmovieland.one/"}) movie_html = movie_resp.text
# Extract player domain and media ID from script section # The variables are inside <script> tags in tabs__content domain_match = re.search(r"AwsIndStreamDomain\s*=\s*['\"]([^'\"]+)['\"]", movie_html) player_domain = domain_match.group(1).rstrip("/") if domain_match else None 4 unmodified lines errors.append(f"AllMovieLand: No player info (domain={player_domain}, id={media_id})") return results, errors
# Step 3: Embed page - get p3 data embed_url = f"{player_domain}/play/{media_id}" embed_resp = await client.get(embed_url, headers={"Referer": movie_url}) embed_html = embed_resp.text
# Find p3 - try multiple patterns p3_m = re.search(r'let\s+p3\s*=\s*(\{.*?\})\s*;', embed_html) if not p3_m: p3_m = re.search(r'p3\s*=\s*(\{[^;]+\})\s*;', embed_html)17 unmodified lines errors.append("AllMovieLand: Missing file URL or CSRF key in p3") return results, errors
# Step 4: POST to get file list - burst with fresh clients file_list = None post_headers = { "X-CSRF-TOKEN": csrf_key,18 unmodified lines errors.append("AllMovieLand: Could not get file list (7 attempts)") return results, errors
# Filter files based on media type target_files = [] if media_type == "movie": target_files = [f for f in file_list if f.get("file")]17 unmodified lines if not target_files: target_files = [f for f in file_list if f.get("file")][:3]
# Step 5: Get m3u8 URL for each file - burst for file_obj in target_files: file_path = file_obj.get("file", "").lstrip("~") stream_title = file_obj.get("title", "Stream")44 unmodified lines return results, errors
# ===== VidSrc Scraper (cloudnestra via vidsrc.me) =====# ===== VidSrc Scraper (dual approach: Nuvio + MediaVanced) =====
async def scrape_vidsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = []9 unmodified lines DECRYPT_API = "https://enc-dec.app/api/dec-cloudnestra"
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: # Step 1: Get embed page from vidsrc.me if media_type == "tv": s = season or 1 e = episode or 1 embed_url = f"https://vidsrc.me/embed/tv/{imdb_id}/{s}/{e}/" else: embed_url = f"https://vidsrc.me/embed/movie/{imdb_id}/"
embed_resp = await client.get(embed_url) embed_html = embed_resp.text # ===== Approach 1: Nuvio - vsrc.su → vsembed.su → cloudorchestranova ===== try: if media_type == "tv": s = season or 1 e = episode or 1 nuvio_embed = f"https://vsrc.su/embed/tv/{imdb_id}/{s}/{e}" else: nuvio_embed = f"https://vsrc.su/embed/movie/{imdb_id}"
if "Cloudflare" in embed_html or embed_resp.status_code == 403: errors.append("VidSrc: Cloudflare blocked (datacenter IP)") return results, errors nuvio_resp = await client.get(nuvio_embed) nuvio_html = nuvio_resp.text
# Extract cloudnestra iframe src iframe_m = re.search(r'<iframe[^>]+src="//cloudnestra\.com/rcp/([^"]+)"', embed_html) if not iframe_m: # Try alternative: vsembed.ru from vidsrc.to iframe_m2 = re.search(r'<iframe[^>]+src="(https://vsembed\.ru/[^"]+)"', embed_html) if iframe_m2: vsembed_url = iframe_m2.group(1) vsembed_resp = await client.get(vsembed_url, headers={"Referer": "https://vidsrc.to/"}) if "Cloudflare" in vsembed_resp.text or vsembed_resp.status_code == 403: errors.append("VidSrc: Cloudflare blocked on vsembed.ru") return results, errors # Parse vsembed page for streams (same flow as below) embed_html = vsembed_resp.text else: errors.append("VidSrc: No iframe found in embed page") return results, errors # Look for vsembed.su iframe vsembed_m = re.search(r'<iframe[^>]+src="(?:https?:)?//vsembed\.su/embed/([^"]+)"', nuvio_html) if not vsembed_m: vsembed_m = re.search(r'src="((?:https?:)?//vsembed\.su/[^"]+)"', nuvio_html)
if iframe_m: encoded_path = iframe_m.group(1) cloudnestra_url = f"https://cloudnestra.com/rcp/{encoded_path}" if vsembed_m: vsembed_path = vsembed_m.group(1) if not vsembed_path.startswith("http"): vsembed_path = f"https://vsembed.su{vsembed_path}" if vsembed_path.startswith("/") else f"https://{vsembed_path}"
# Step 2: Get cloudnestra page cloud_resp = await client.get(cloudnestra_url, headers={ "Referer": "https://vidsrc.me/", "Origin": "https://vidsrc.me", }) vsembed_resp = await client.get(vsembed_path, headers={"Referer": "https://vsrc.su/"}) vsembed_html = vsembed_resp.text
if cloud_resp.status_code == 403 or "Cloudflare" in cloud_resp.text: errors.append("VidSrc: Cloudflare blocked on cloudnestra.com") return results, errors # Look for cloudorchestranova iframe cloud_m = re.search(r'<iframe[^>]+src="(?:https?:)?//cloudorchestranova\.com/([^"]+)"', vsembed_html) if not cloud_m: cloud_m = re.search(r'src="((?:https?:)?//cloudorchestranova\.com/[^"]+)"', vsembed_html)
cloud_html = cloud_resp.text if cloud_m: cloud_path = cloud_m.group(1) if not cloud_path.startswith("http"): cloud_url = f"https://cloudorchestranova.com/{cloud_path}" if not cloud_path.startswith("http") else cloud_path else: cloud_url = cloud_path
# Find hidden div with id and text for decryption hidden_pattern = r"""<div id="([^"]+)"[^>]*style=["\x27]display\s*:\s*none;?["\x27][^>]*>([a-zA-Z0-9:/.,{}_=+ -]+)</div>""" hidden_m = re.search(hidden_pattern, cloud_html) if not hidden_m: errors.append("VidSrc: No hidden div found in cloudnestra page") return results, errors cloud_resp = await client.get(cloud_url, headers={ "Referer": "https://vsembed.su/", "Origin": "https://vsembed.su", })
if cloud_resp.status_code != 403 and "Cloudflare" not in cloud_resp.text: cloud_html = cloud_resp.text
# Find hidden div for decryption hidden_pattern = r"""<div id="([^"]+)"[^>]*style=["\x27]display\s*:\s*none;?["\x27][^>]*>([a-zA-Z0-9:/.,{}_=+ -]+)</div>""" hidden_m = re.search(hidden_pattern, cloud_html) if hidden_m: div_id = hidden_m.group(1) div_text = hidden_m.group(2) div_id = hidden_m.group(1) div_text = hidden_m.group(2)
dec_resp = await client.post( DECRYPT_API, json={"text": div_text, "div_id": div_id}, headers={"Content-Type": "application/json"}, )
if dec_resp.status_code == 200: dec_data = dec_resp.json() stream_urls = dec_data.get("result", []) if isinstance(stream_urls, list): for idx, stream_url in enumerate(stream_urls): if not stream_url: continue quality = "Auto" url_lower = stream_url.lower() if "2160" in url_lower or "4k" in url_lower: quality = "2160p" elif "1440" in url_lower: quality = "1440p" elif "1080" in url_lower: quality = "1080p" elif "720" in url_lower: quality = "720p"
results.append({ "source": f"VidSrc/nuvio{idx + 1}", "title": f"VidSrc Nuvio Server {idx + 1}", "quality": quality, "language": "English", "url": stream_url, "type": "m3u8", "headers": { "Referer": "https://cloudorchestranova.com/", "Origin": "https://cloudorchestranova.com", }, }) except Exception as nuvio_err: errors.append(f"VidSrc Nuvio: {str(nuvoio_err)}")
# ===== Approach 2: MediaVanced - vidsrc.to → #player_iframe → prorcp_iframe ===== if not results: try: if media_type == "tv": s = season or 1 e = episode or 1 mv_embed = f"https://vidsrc.to/embed/tv/{imdb_id}/{s}/{e}" else: mv_embed = f"https://vidsrc.to/embed/movie/{imdb_id}"
mv_resp = await client.get(mv_embed) if mv_resp.status_code != 403 and "Cloudflare" not in mv_resp.text: mv_html = mv_resp.text
# Look for #player_iframe or data-id player_iframe_m = re.search(r'id="player_iframe"[^>]*src="([^"]+)"', mv_html) if not player_iframe_m: player_iframe_m = re.search(r'data-id="([^"]+)"', mv_html)
if player_iframe_m: iframe_src = player_iframe_m.group(1) if not iframe_src.startswith("http"): iframe_src = f"https://vidsrc.to{iframe_src}"
iframe_resp = await client.get(iframe_src, headers={"Referer": "https://vidsrc.to/"}) iframe_html = iframe_resp.text
# Look for prorcp_iframe prorcp_m = re.search(r'id="prorcp_iframe"[^>]*src="([^"]+)"', iframe_html) if not prorcp_m: prorcp_m = re.search(r'src="([^"]+prorcp[^"]*)"', iframe_html)
if prorcp_m: prorcp_url = prorcp_m.group(1) if not prorcp_url.startswith("http"): prorcp_url = f"https:{prorcp_url}" if prorcp_url.startswith("//") else prorcp_url
prorcp_resp = await client.get(prorcp_url, headers={"Referer": "https://vidsrc.to/"}) prorcp_html = prorcp_resp.text
# Extract file: URL from the source file_match = re.search(r'file\s*:\s*"(https?://[^"]+\.m3u8[^"]*)"', prorcp_html) if not file_match: file_match = re.search(r'"(https?://[^"]+\.m3u8[^"]*)"', prorcp_html)
if file_match: stream_url = file_match.group(1) quality = "Auto" url_lower = stream_url.lower() if "2160" in url_lower or "4k" in url_lower: quality = "2160p" elif "1440" in url_lower: quality = "1440p" elif "1080" in url_lower: quality = "1080p" elif "720" in url_lower: quality = "720p"
# Step 3: Decrypt via enc-dec.app dec_resp = await client.post( DECRYPT_API, json={"text": div_text, "div_id": div_id}, headers={"Content-Type": "application/json"}, ) results.append({ "source": "VidSrc/mediavanced", "title": "VidSrc MediaVanced", "quality": quality, "language": "English", "url": stream_url, "type": "m3u8", "headers": { "Referer": "https://vidsrc.to/", }, })
if dec_resp.status_code != 200: errors.append(f"VidSrc: Decrypt failed HTTP {dec_resp.status_code}") return results, errors # Alternative: extract source directly from iframe page if not results: src_match = re.search(r'file\s*:\s*"(https?://[^"]+\.m3u8[^"]*)"', iframe_html) if src_match: results.append({ "source": "VidSrc/mediavanced", "title": "VidSrc MediaVanced", "quality": "Auto", "language": "English", "url": src_match.group(1), "type": "m3u8", "headers": { "Referer": "https://vidsrc.to/", }, }) except Exception as mv_err: errors.append(f"VidSrc MediaVanced: {str(mv_err)}")
dec_data = dec_resp.json() stream_urls = dec_data.get("result", []) if not isinstance(stream_urls, list) or not stream_urls: errors.append("VidSrc: No stream URLs after decryption") return results, errors if not results: errors.append("VidSrc: No streams found from either approach")
# Step 4: Process stream URLs for idx, stream_url in enumerate(stream_urls): if not stream_url: continue except Exception as e: errors.append(f"VidSrc: {str(e)}")
quality = "Auto" url_lower = stream_url.lower() if "2160" in url_lower or "4k" in url_lower: quality = "2160p" elif "1440" in url_lower: quality = "1440p" elif "1080" in url_lower: quality = "1080p" elif "720" in url_lower: quality = "720p" return results, errors
# ===== VidLink Scraper (vidlink.pro with encrypted ID) =====
async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: ENCRYPT_API = "https://enc-dec.app/api/enc-vidlink" VIDLINK_BASE = "https://vidlink.pro"
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: # Step 1: Get encrypted ID enc_resp = await client.get( ENCRYPT_API, params={"text": str(tmdb_id)}, headers={"Accept": "application/json"} ) if enc_resp.status_code != 200: errors.append(f"VidLink: Encrypt API failed HTTP {enc_resp.status_code}") return results, errors
enc_data = enc_resp.json() encrypted_id = enc_data.get("result") or enc_data.get("encrypted") or enc_data.get("data", "") if not encrypted_id: errors.append("VidLink: No encrypted ID returned") return results, errors
# Step 2: Get stream URL if media_type == "movie": stream_url = f"{VIDLINK_BASE}/api/b/movie/{encrypted_id}" else: s = season or 1 e = episode or 1 stream_url = f"{VIDLINK_BASE}/api/b/tv/{encrypted_id}/{s}/{e}"
stream_resp = await client.get(stream_url, headers={ "Accept": "application/json", "Referer": f"{VIDLINK_BASE}/", "Origin": VIDLINK_BASE, })
if stream_resp.status_code != 200: errors.append(f"VidLink: Stream API failed HTTP {stream_resp.status_code}") return results, errors
stream_data = stream_resp.json() playlist_url = None
# Extract playlist URL from response if stream_data.get("stream"): playlist_url = stream_data["stream"].get("playlist") or stream_data["stream"].get("url", "")
if not playlist_url: for key in ["playlist", "url", "file", "source"]: if stream_data.get(key): playlist_url = stream_data[key] break
if not playlist_url: errors.append("VidLink: No playlist URL in response") return results, errors
# Step 3: Parse M3U8 master playlist for quality variants if playlist_url.endswith(".m3u8") or "m3u8" in playlist_url: try: m3u8_resp = await client.get(playlist_url, headers={ "Referer": f"{VIDLINK_BASE}/", "Origin": VIDLINK_BASE, })
if "#EXT-X-STREAM-INF" in m3u8_resp.text: lines = m3u8_resp.text.split("\n") for i, line in enumerate(lines): if line.startswith("#EXT-X-STREAM-INF:"): resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) name = re.search(r'NAME="([^"]+)"', line) quality = resolution.group(1) if resolution else "Auto" label = name.group(1) if name else quality if i + 1 < len(lines) and lines[i + 1].strip(): variant_url = lines[i + 1].strip() if not variant_url.startswith("http"): base_url = playlist_url.rsplit("/", 1)[0] variant_url = f"{base_url}/{variant_url}"
results.append({ "source": "VidLink", "title": label, "quality": quality, "language": "English", "url": variant_url, "type": "m3u8", "headers": { "Referer": f"{VIDLINK_BASE}/", "Origin": VIDLINK_BASE, }, }) else: results.append({ "source": "VidLink", "title": "VidLink Stream", "quality": "Auto", "language": "English", "url": playlist_url, "type": "m3u8", "headers": { "Referer": f"{VIDLINK_BASE}/", "Origin": VIDLINK_BASE, }, }) except Exception: results.append({ "source": f"VidSrc/srv{idx + 1}", "title": f"VidSrc Server {idx + 1}", "quality": quality, "source": "VidLink", "title": "VidLink Stream", "quality": "Auto", "language": "English", "url": stream_url, "url": playlist_url, "type": "m3u8", "headers": { "Referer": "https://cloudnestra.com/", "Origin": "https://cloudnestra.com", "Referer": f"{VIDLINK_BASE}/", "Origin": VIDLINK_BASE, }, }) else: s_type = "direct" if ".mp4" in playlist_url else "m3u8" results.append({ "source": "VidLink", "title": "VidLink Stream", "quality": "Auto", "language": "English", "url": playlist_url, "type": s_type, "headers": { "Referer": f"{VIDLINK_BASE}/", "Origin": VIDLINK_BASE, }, })
if not results: errors.append("VidSrc: No usable streams found") errors.append("VidLink: No streams found")
except Exception as e: errors.append(f"VidSrc: {str(e)}") errors.append(f"VidLink: {str(e)}")
return results, errors
# ===== PrimeSrc Scraper (primesrc.me with AES-CBC decryption) =====
async def scrape_primesrc(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
PRIMESRC_BASE = "https://primesrc.me" PRIMESRC_KEY = b"kiemtienmua911ca" PRIMESRC_IV = b"1234567890oiuytr"
info = await get_tmdb_info(tmdb_id, media_type) imdb_id = info.get("imdb_id") if not imdb_id: errors.append("PrimeSrc: Could not get IMDB ID from TMDB") return results, errors
content_type = "tv" if media_type == "tv" else "movie"
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: # Step 1: Get servers servers_resp = await client.get( f"{PRIMESRC_BASE}/api/v1/s", params={"imdb": imdb_id, "type": content_type}, headers={"Accept": "application/json"} ) if servers_resp.status_code != 200: errors.append(f"PrimeSrc: Servers API failed HTTP {servers_resp.status_code}") return results, errors
servers_data = servers_resp.json() servers_list = servers_data if isinstance(servers_data, list) else servers_data.get("servers", servers_data.get("data", []))
if not servers_list: errors.append("PrimeSrc: No servers found") return results, errors
for server in servers_list: try: server_key = server.get("key") or server.get("id") or server.get("serverKey", "") server_name = server.get("name") or server.get("serverName", "Server") if not server_key: continue
# Step 2: Get server link link_resp = await client.get( f"{PRIMESRC_BASE}/api/v1/l", params={"key": server_key}, headers={"Accept": "application/json"} ) if link_resp.status_code != 200: continue
link_data = link_resp.json() server_id = link_data.get("id") or link_data.get("serverId") or link_data.get("key", server_key) if not server_id: continue
# Step 3: Get encrypted video video_resp = await client.get( f"{PRIMESRC_BASE}/api/v1/video", params={"id": server_id}, headers={"Accept": "application/json"} ) if video_resp.status_code != 200: continue
video_data = video_resp.json() encrypted_text = video_data.get("data") or video_data.get("encrypted") or video_data.get("url", "")
if not encrypted_text: continue
# Step 4: AES-CBC decrypt (hex-encoded ciphertext) try: if isinstance(encrypted_text, str): try: ct_bytes = bytes.fromhex(encrypted_text) except ValueError: ct_bytes = base64.b64decode(encrypted_text) else: continue
cipher = AES.new(PRIMESRC_KEY, AES.MODE_CBC, PRIMESRC_IV) decrypted = unpad(cipher.decrypt(ct_bytes), AES.block_size) decrypted_str = decrypted.decode("utf-8", errors="ignore")
try: dec_json = json.loads(decrypted_str) source_url = dec_json.get("source") or dec_json.get("url") or dec_json.get("file", "") except json.JSONDecodeError: url_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', decrypted_str) source_url = url_match.group(0) if url_match else decrypted_str.strip()
if not source_url or not source_url.startswith("http"): continue
s_type = "m3u8" if ".m3u8" in source_url else "direct" quality = "Auto" q_match = re.search(r'(\d{3,4})p', source_url) if q_match: quality = q_match.group(1) + "p"
results.append({ "source": f"PrimeSrc/{server_name}", "title": f"PrimeSrc - {server_name}", "quality": quality, "language": "English", "url": source_url, "type": s_type, "headers": { "Referer": f"{PRIMESRC_BASE}/", "Origin": PRIMESRC_BASE, }, })
except Exception as dec_err: errors.append(f"PrimeSrc/{server_name}: Decryption failed - {str(dec_err)}") continue
except Exception as srv_err: errors.append(f"PrimeSrc/{server_name}: {str(srv_err)}") continue
if not results: errors.append("PrimeSrc: No streams found")
except ImportError: errors.append("PrimeSrc: pycryptodome not installed") except Exception as e: errors.append(f"PrimeSrc: {str(e)}")
return results, errors
# ===== M4UHD Scraper (m4uhd.vip with CryptoJS-compatible AES-CBC) =====
async def scrape_m4uhd(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 pad as crypto_pad, unpad
M4UHD_BASE = "https://m4uhd.vip" FILE_ID_SECRET = "jcLycoRJT6OWjoWspgLMOZwS3aSS0lEn" USER_ID_SECRET = "PZZ3J3LDbLT0GY7qSA5wW5vchqgpO36O" ENCRYPT_PAYLOAD_SECRET = "vlVbUQhkOhoSfyteyzGeeDzU0BHoeTyZ" DECRYPT_RESPONSE_SECRET = "oJwmvmVBajMaRCTklxbfjavpQO7SZpsL" HMAC_KEY = "KRWN3AdgmxEMcd2vLN1ju9qKe8Feco5h" PLAY_API = "https://api-play-270325.ppzj-youtube.cfd/api/tp1rd/playiframe"
info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") if not title: errors.append("M4UHD: Could not get title from TMDB") return results, errors
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: # Step 1: Search for the movie search_resp = await client.get(f"{M4UHD_BASE}/search/{title.replace(' ', '-')}.html") if search_resp.status_code != 200: errors.append(f"M4UHD: Search failed HTTP {search_resp.status_code}") return results, errors
search_html = search_resp.text
# Extract movie links and titles using regex movie_blocks = re.findall( r'<div[^>]*class="[^"]*item[^"]*"[^>]*>.*?<a[^>]*href="([^"]+)"[^>]*>.*?(?:<img[^>]*alt="([^"]*)")?', search_html, re.DOTALL )
if not movie_blocks: movie_links = re.findall(r'href="(/movie/\d+/[^"]+\.html)"', search_html) movie_titles = re.findall(r'alt="([^"]+)"', search_html) movie_blocks = [(link, title) for link, title in zip(movie_links, movie_titles)]
if not movie_blocks: errors.append("M4UHD: No search results found") return results, errors
# Find best match movie_page_url = None title_lower = title.lower() for link, mtitle in movie_blocks: if mtitle and (title_lower in mtitle.lower() or mtitle.lower() in title_lower): movie_page_url = link if link.startswith("http") else f"{M4UHD_BASE}{link}" break
if not movie_page_url and movie_blocks: link = movie_blocks[0][0] movie_page_url = link if link.startswith("http") else f"{M4UHD_BASE}{link}"
if not movie_page_url: errors.append("M4UHD: Could not find movie page") return results, errors
# Step 2: Get movie page - extract server list and CSRF token movie_resp = await client.get(movie_page_url) if movie_resp.status_code != 200: errors.append(f"M4UHD: Movie page HTTP {movie_resp.status_code}") return results, errors
movie_html = movie_resp.text
# Extract CSRF token csrf_match = re.search(r'name="csrf[_-]token"\s+(?:value|content)="([^"]+)"', movie_html, re.I) if not csrf_match: csrf_match = re.search(r'(?:value|content)="([^"]+)"[^>]*name="csrf[_-]token"', movie_html, re.I) if not csrf_match: csrf_match = re.search(r'csrf[_-]?token["\s:=]+["\']?([a-fA-F0-9]+)', movie_html, re.I) csrf_token = csrf_match.group(1) if csrf_match else ""
# Extract server list servers = re.findall(r'data-id="(\d+)"[^>]*>([^<]+)', movie_html) if not servers: servers = re.findall(r'class="[^"]*server[^"]*"[^>]*data-id="(\d+)"[^>]*>([^<]*)', movie_html) if not servers: servers = re.findall(r'href="([^"]*ajax[^"]*)"[^>]*>([^<]+)', movie_html)
if not servers: errors.append("M4UHD: No servers found on movie page") return results, errors
# Process each server for server_id, server_name in servers[:3]: try: # Step 3: POST /ajax to get embed URL ajax_data = { "id": server_id, "csrf_token": csrf_token, } if media_type == "tv": s = season or 1 e = episode or 1 ajax_data["season"] = str(s) ajax_data["episode"] = str(e)
ajax_resp = await client.post( f"{M4UHD_BASE}/ajax", data=ajax_data, headers={ "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/x-www-form-urlencoded", "Referer": movie_page_url, } )
if ajax_resp.status_code != 200: continue
ajax_result = ajax_resp.json() embed_url = ajax_result.get("url") or ajax_result.get("link") or ajax_result.get("data", "") if not embed_url: embed_m = re.search(r'(https?://[^"\'<>\s]+)', ajax_resp.text) embed_url = embed_m.group(1) if embed_m else ""
if not embed_url: continue
# Step 4: GET embed page if not embed_url.startswith("http"): embed_url = f"{M4UHD_BASE}{embed_url}"
embed_resp = await client.get(embed_url, headers={"Referer": movie_page_url}) embed_html = embed_resp.text
# Extract encrypted idfile_enc and idUser_enc idfile_match = re.search(r'idfile_enc["\s:=]+["\']?([a-zA-Z0-9+/=]+)', embed_html) iduser_match = re.search(r'idUser_enc["\s:=]+["\']?([a-zA-Z0-9+/=]+)', embed_html)
idfile_enc = idfile_match.group(1) if idfile_match else "" iduser_enc = iduser_match.group(1) if iduser_match else ""
if not idfile_enc: errors.append(f"M4UHD/{server_name}: No encrypted file ID found") continue
# Step 5: Decrypt with EVP_BytesToKey def m4uhd_decrypt(ciphertext_b64: str, secret: str) -> str: raw = base64.b64decode(ciphertext_b64) if raw[:8] == b"Salted__": salt = raw[8:16] ct = raw[16:] else: salt = b"" ct = raw key, iv = evp_bytes_to_key(secret.encode(), salt) cipher = AES.new(key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(ct), AES.block_size).decode("utf-8", errors="ignore")
def m4uhd_encrypt(plaintext: str, secret: str) -> str: import os salt = os.urandom(8) key, iv = evp_bytes_to_key(secret.encode(), salt) cipher = AES.new(key, AES.MODE_CBC, iv) ct = cipher.encrypt(crypto_pad(plaintext.encode(), AES.block_size)) return base64.b64encode(b"Salted__" + salt + ct).decode()
# Decrypt file ID and user ID idfile = m4uhd_decrypt(idfile_enc, FILE_ID_SECRET) iduser = m4uhd_decrypt(iduser_enc, USER_ID_SECRET) if iduser_enc else ""
# Step 6: Build encrypted payload and POST to playiframe API payload_data = { "idfile": idfile, "idUser": iduser, } payload_json = json.dumps(payload_data) encrypted_payload = m4uhd_encrypt(payload_json, ENCRYPT_PAYLOAD_SECRET)
# Compute HMAC hmac_val = hashlib.md5((encrypted_payload + HMAC_KEY).encode()).hexdigest()
play_resp = await client.post( PLAY_API, json={"data": encrypted_payload, "hmac": hmac_val}, headers={ "Content-Type": "application/json", "Referer": embed_url, "Origin": M4UHD_BASE, } )
if play_resp.status_code != 200: continue
play_data = play_resp.json() encrypted_response = play_data.get("data") or play_data.get("encrypted") or play_data.get("url", "")
if not encrypted_response: continue
# Step 7: Decrypt response try: decrypted_response = m4uhd_decrypt(encrypted_response, DECRYPT_RESPONSE_SECRET)
# Extract video URL from decrypted response try: dec_json = json.loads(decrypted_response) video_url = dec_json.get("url") or dec_json.get("source") or dec_json.get("file") or dec_json.get("link", "") except json.JSONDecodeError: url_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', decrypted_response) if not url_match: url_match = re.search(r'https?://[^\s"\'<>]+', decrypted_response) video_url = url_match.group(0) if url_match else ""
if not video_url or not video_url.startswith("http"): continue
s_type = "m3u8" if ".m3u8" in video_url else "direct" quality = "Auto" q_match = re.search(r'(\d{3,4})p', video_url) if q_match: quality = q_match.group(1) + "p"
lang = detect_language(server_name)
results.append({ "source": f"M4UHD/{server_name.strip()}", "title": f"M4UHD - {server_name.strip()}", "quality": quality, "language": lang, "url": video_url, "type": s_type, })
except Exception as dec_err: errors.append(f"M4UHD/{server_name}: Response decrypt failed - {str(dec_err)}") continue
except Exception as srv_err: errors.append(f"M4UHD/{server_name}: {str(srv_err)}") continue
if not results: errors.append("M4UHD: No streams found")
except ImportError: errors.append("M4UHD: pycryptodome not installed") except Exception as e: errors.append(f"M4UHD: {str(e)}")
return results, errors
# ===== Source Map =====4 unmodified lines "vixsrc": {"name": "VixSrc", "fn": lambda tid, mt, s, e: scrape_vixsrc(tid, mt, s, e), "languages": ["English", "Italian", "Multi"], "reliability": "low", "note": "Cloudflare-blocked from datacenter IPs, works from residential only"}, "vidnest": {"name": "VidNest", "fn": lambda tid, mt, s, e: scrape_vidnest(tid, mt, s, e), "languages": ["French", "English", "Multi"], "reliability": "medium"}, "popr": {"name": "Popr", "fn": lambda tid, mt, s, e: scrape_popr(tid, mt, s, e), "languages": ["Hindi", "Tamil", "Telugu", "English", "French"], "reliability": "broken", "note": "API returns 403 Forbidden since May 2026"}, "vidrock": {"name": "VidRock", "fn": lambda tid, mt, s, e: scrape_vidrock(tid, mt, s, e), "languages": ["English"], "reliability": "high"}, "dooflix": {"name": "DooFlix", "fn": lambda tid, mt, s, e: scrape_dooflix(tid, mt, s, e), "languages": ["Hindi", "English", "Multi"], "reliability": "high"}, "castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e), "languages": ["English", "Hindi", "Multi"], "reliability": "high"}, "movieboxhindi": {"name": "MovieBoxHindi", "fn": lambda tid, mt, s, e: scrape_movieboxhindi(tid, mt, s, e), "languages": ["Hindi", "English"], "reliability": "high"}, "moviebox": {"name": "MovieBox", "fn": lambda tid, mt, s, e: scrape_moviebox(tid, mt, s, e), "languages": ["Hindi", "English"], "reliability": "high"}, "allmovieland": {"name": "AllMovieLand", "fn": lambda tid, mt, s, e: scrape_allmovieland(tid, mt, s, e), "languages": ["Hindi", "Tamil", "Telugu", "English", "Multi"], "reliability": "medium"}, "netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e),2 unmodified lines "languages": ["English", "Multi"], "reliability": "medium"}, "vidsrc": {"name": "VidSrc", "fn": lambda tid, mt, s, e: scrape_vidsrc(tid, mt, s, e), "languages": ["English"], "reliability": "low", "note": "Cloudflare-blocked from datacenter IPs (vsrc.su/cloudnestra.com)"}, "note": "Cloudflare-blocked from datacenter IPs (vsrc.su/cloudorchestranova)"}, "vidlink": {"name": "VidLink", "fn": lambda tid, mt, s, e: scrape_vidlink(tid, mt, s, e), "languages": ["English"], "reliability": "medium"}, "primesrc": {"name": "PrimeSrc", "fn": lambda tid, mt, s, e: scrape_primesrc(tid, mt, s, e), "languages": ["English"], "reliability": "medium"}, "m4uhd": {"name": "M4UHD", "fn": lambda tid, mt, s, e: scrape_m4uhd(tid, mt, s, e), "languages": ["English", "Hindi", "Multi"], "reliability": "medium"},}
DEFAULT_SOURCES = ["cinesu", "vidnest", "dooflix", "castle", "movieboxhindi", "netmirror", "vidrock"]DEFAULT_SOURCES = ["cinesu", "dooflix", "castle", "moviebox", "netmirror", "vidrock", "vidlink", "primesrc"]
# ===== Helper: Run scrapers =====54 unmodified linesasync def root(): return { "api": "StreamForge", "version": "6.0.0", "version": "7.0.0", "description": "Multi-language m3u8 stream scraper", "endpoints": { "movie": { "all_sources": "/movie/{tmdb_id}", "single_source": "/movie/{tmdb_id}/{source}", "example": "/movie/912649", "example_source": "/movie/912649/popr", "example_source": "/movie/912649/castle", }, "tv": { "all_sources": "/tv/{tmdb_id}/{season}/{episode}",18 unmodified lines for key, src in SOURCE_MAP.items()}, "default_sources": DEFAULT_SOURCES, "tips": [ "No source = default sources (cinesu, vidnest, dooflix, castle, movieboxhindi, netmirror, vidrock)", "Best for Hindi: /movie/ID/allmovieland or /movie/ID/dooflix or /movie/ID/movieboxhindi or /movie/ID/castle", "Best for English: /movie/ID/cinesu or /movie/ID/vidrock or /movie/ID/videasy", "Best for French: /movie/ID/vidnest", "Castle: Stremio aggregator, returns multiple streams from different providers", "No source = default sources (cinesu, dooflix, castle, moviebox, netmirror, vidrock, vidlink, primesrc)", "Best for Hindi: /movie/ID/allmovieland or /movie/ID/dooflix or /movie/ID/moviebox or /movie/ID/castle", "Best for English: /movie/ID/cinesu or /movie/ID/vidrock or /movie/ID/vidlink or /movie/ID/videasy", "Castle: hlowb.com API with AES-CBC encryption, returns multiple quality streams", "NetMirror: Searches Netflix, PrimeVideo, Hotstar via API - great for Hindi/English", "VidLink: vidlink.pro with encrypted TMDB ID, supports M3U8 quality variants", "PrimeSrc: primesrc.me with AES-CBC decryption", "M4UHD: m4uhd.vip with CryptoJS-compatible AES-CBC (EVP_BytesToKey key derivation)", "VixSrc: Blocked from cloud IPs, works residential only", "VixSrc/VidSrc: Blocked from cloud IPs, works residential only", "m3u8 links work in VLC, mpv, or any HLS player", ], }main.py+1085-422