""" StreamForge API v7 - Multi-Language Stream Scraper Scrapes direct m3u8 URLs from multiple sources """ from fastapi import FastAPI, HTTPException, Query from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from typing import Optional import httpx import json import re import base64 import time import asyncio import hashlib app = FastAPI( title="StreamForge API", description="Multi-language m3u8 stream scraper", version="7.0.0", ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) TMDB_API_KEY = "7967738a03ec215c7d6d675faba9c973" TMDB_BASE = "https://api.themoviedb.org/3" HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "Accept": "application/json, text/html, */*", "Accept-Language": "en-US,en;q=0.5", } # ===== Models ===== class ScrapeRequest(BaseModel): tmdb_id: int media_type: str = "movie" season: Optional[int] = None episode: Optional[int] = None sources: Optional[list[str]] = None # ===== Helpers ===== async def get_tmdb_info(tmdb_id: int, media_type: str) -> dict: async with httpx.AsyncClient(timeout=10) as client: type_path = "tv" if media_type == "tv" else "movie" resp = await client.get( f"{TMDB_BASE}/{type_path}/{tmdb_id}", params={"api_key": TMDB_API_KEY, "append_to_response": "external_ids"} ) data = resp.json() return { "imdb_id": data.get("external_ids", {}).get("imdb_id"), "title": data.get("title") or data.get("name"), "year": (data.get("release_date") or data.get("first_air_date") or "")[:4], } def detect_language(label: str) -> str: lower = label.lower() if "hindi" in lower or "hin" in lower: return "Hindi" if "tamil" in lower or "tam" in lower: return "Tamil" if "telugu" in lower or "tel" in lower: return "Telugu" if "bengali" in lower or "bangla" in lower or "ben" in lower: return "Bengali" if "malayalam" in lower or "mal" in lower: return "Malayalam" if "kannada" in lower or "kan" in lower: return "Kannada" if "english" in lower or "eng" in lower or "en" == lower: return "English" if "italian" in lower or "ita" in lower or "italiano" in lower: return "Italian" if "french" in lower or "fra" in lower or "vf" in lower: return "French" if "german" in lower or "deu" in lower or "ger" in lower: return "German" if "spanish" in lower or "spa" in lower or "español" in lower: return "Spanish" if "multi" in lower: return "Multi" return "English" 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): results = [] errors = [] try: async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client: if media_type == "movie": url = f"https://cine.su/v1/stream/master/movie/{tmdb_id}.m3u8" else: s = season or 1 e = episode or 1 url = f"https://cine.su/v1/stream/master/tv/{tmdb_id}/{s}/{e}.m3u8" resp = await client.get(url, headers={ "Referer": "https://cine.su/en/watch", "Origin": "https://cine.su", }) if resp.status_code == 404: errors.append("CineSu: Content not available") return results, errors if resp.status_code != 200: errors.append(f"CineSu: HTTP {resp.status_code}") return results, errors content = resp.text if "#EXT-X-STREAM-INF" in content: lines = content.split("\n") for i, line in enumerate(lines): if line.startswith("#EXT-X-STREAM-INF:"): resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) name = re.search(r'NAME="([^"]+)"', line) quality = resolution.group(1) if resolution else "Auto" label = name.group(1) if name else quality if i + 1 < len(lines) and lines[i + 1].startswith("http"): results.append({ "source": "CineSu", "title": label, "quality": quality, "language": "English", "url": lines[i + 1].strip(), "type": "m3u8", }) elif ".m3u8" in content: m3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', content) if m3u8_match: results.append({ "source": "CineSu", "title": "English Stream", "quality": "Auto", "language": "English", "url": m3u8_match.group(0), "type": "m3u8", }) if not results: errors.append("CineSu: No streams found") except Exception as e: errors.append(f"CineSu: {str(e)}") return results, errors # ===== VixSrc Scraper ===== async def scrape_vixsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] try: async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: if media_type == "movie": api_url = f"https://vixsrc.to/api/movie/{tmdb_id}" else: s = season or 1 e = episode or 1 api_url = f"https://vixsrc.to/api/tv/{tmdb_id}/{s}/{e}" api_resp = await client.get(api_url) try: api_data = api_resp.json() except: errors.append("VixSrc: API returned non-JSON (possible Cloudflare block)") return results, errors src_path = api_data.get("src", "") if not src_path: errors.append("VixSrc: No embed path returned") return results, errors embed_resp = await client.get(f"https://vixsrc.to{src_path}") if embed_resp.status_code == 410: api_resp2 = await client.get(api_url) try: api_data2 = api_resp2.json() except: errors.append("VixSrc: API retry failed") return results, errors src_path2 = api_data2.get("src", "") if not src_path2: errors.append("VixSrc: No embed path on retry") return results, errors embed_resp = await client.get(f"https://vixsrc.to{src_path2}") src_path = src_path2 html = embed_resp.text token = None expires = None playlist_url = None mp_match = re.search(r'window\.masterPlaylist\s*=\s*(\{[\s\S]*?\})\s*\n', html) if mp_match: mp_text = mp_match.group(1) token_m = re.search(r"'token'\s*:\s*'([^']+)'", mp_text) expires_m = re.search(r"'expires'\s*:\s*'([^']+)'", mp_text) url_m = re.search(r"url\s*:\s*'([^']+)'", mp_text) if token_m: token = token_m.group(1) if expires_m: expires = expires_m.group(1) if url_m: playlist_url = url_m.group(1) if not token: token_match = re.search(r'token["\']\s*:\s*["\']([^"\']+)', html) if token_match: token = token_match.group(1) if not playlist_url: url_match = re.search(r'url\s*:\s*["\']([^"\']+playlist[^"\']*)', html) if url_match: playlist_url = url_match.group(1) if not (token and playlist_url): errors.append("VixSrc: Could not extract stream parameters from embed") return results, errors if not expires: expires = str(int(time.time()) + 86400) sep = "&" if "?" in playlist_url else "?" master_url = f"{playlist_url}{sep}token={token}&expires={expires}&h=1" pl_resp = await client.get(master_url, headers={"Referer": f"https://vixsrc.to{src_path}"}) pl_content = pl_resp.text if "#EXTM3U" in pl_content: audio_tracks = [] lines = pl_content.split("\n") for line in lines: if line.startswith("#EXT-X-MEDIA:TYPE=AUDIO"): name_match = re.search(r'NAME="([^"]+)"', line) lang_match = re.search(r'LANGUAGE="([^"]+)"', line) uri_match = re.search(r'URI="([^"]+)"', line) if name_match and uri_match: audio_tracks.append({ "language": name_match.group(1), "lang_code": lang_match.group(1) if lang_match else name_match.group(1), "uri": uri_match.group(1), }) for i, line in enumerate(lines): if line.startswith("#EXT-X-STREAM-INF:"): resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) quality = resolution.group(1) if resolution else "Auto" if i + 1 < len(lines) and lines[i + 1].startswith("http"): video_url = lines[i + 1].strip() if audio_tracks: for track in audio_tracks: results.append({ "source": "VixSrc", "title": f"{track['language']} Audio", "quality": quality, "language": detect_language(track["language"]), "url": video_url, "audio_url": track["uri"], "type": "m3u8", }) else: results.append({ "source": "VixSrc", "title": "English Stream", "quality": quality, "language": "English", "url": video_url, "type": "m3u8", }) else: results.append({ "source": "VixSrc", "title": "Stream", "quality": "Auto", "language": "Multi", "url": master_url, "type": "m3u8", }) if not results: errors.append("VixSrc: No streams found in playlist") except Exception as e: errors.append(f"VixSrc: {str(e)}") return results, errors # ===== VidRock Scraper (AES-encrypted API) ===== async def scrape_vidrock(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] try: from Crypto.Cipher import AES as CryptoAES from Crypto.Util.Padding import pad as crypto_pad passphrase = b"x7k9mPqT2rWvY8zA5bC3nF6hJ2lK4mN9" aes_key = passphrase[:32] aes_iv = passphrase[:16] if media_type == "tv": s = season or 1 e = episode or 1 item_id = f"{tmdb_id}_{s}_{e}" api_type = "tv" else: item_id = str(tmdb_id) api_type = "movie" cipher = CryptoAES.new(aes_key, CryptoAES.MODE_CBC, aes_iv) ct = cipher.encrypt(crypto_pad(item_id.encode(), CryptoAES.block_size)) encoded = base64.b64encode(ct).decode().replace("+", "-").replace("/", "_").replace("=", "") async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: resp = await client.get(f"https://vidrock.net/api/{api_type}/{encoded}") if resp.status_code != 200: errors.append(f"VidRock: HTTP {resp.status_code}") return results, errors data = resp.json() for server_name, server_data in data.items(): if isinstance(server_data, dict) and server_data.get("url"): url = server_data["url"] lang = server_data.get("language", "English") stream_type = server_data.get("type", "hls") s_type = "m3u8" if stream_type == "hls" or ".m3u8" in url else "direct" results.append({ "source": f"VidRock/{server_name}", "title": f"{server_name} - {lang}", "quality": "Auto", "language": detect_language(lang), "url": url, "type": s_type, }) if not results: errors.append("VidRock: No streams found") except ImportError: errors.append("VidRock: pycryptodome not installed") except Exception as e: errors.append(f"VidRock: {str(e)}") return results, errors # ===== DooFlix Scraper (Hindi/Indian content - API based) ===== async def scrape_dooflix(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] try: async with httpx.AsyncClient(timeout=15, follow_redirects=False) as client: BASE_API = "https://panel.watchkaroabhi.com" API_KEY = "qNhKLJiZVyoKdi9NCQGz8CIGrpUijujE" dooflix_headers = { "X-Package-Name": "com.king.moja", "User-Agent": "dooflix", "X-App-Version": "305", } STREAM_REFERER = "https://molop.art/" if media_type == "movie": url = f"{BASE_API}/api/3/movie/{tmdb_id}/links?api_key={API_KEY}" else: s = season or 1 e = episode or 1 url = f"{BASE_API}/api/3/tv/{tmdb_id}/season/{s}/episode/{e}/links?api_key={API_KEY}" resp = await client.get(url, headers=dooflix_headers) if resp.status_code != 200: errors.append(f"DooFlix: API error HTTP {resp.status_code}") return results, errors data = resp.json() links = data.get("links", []) if not links: errors.append("DooFlix: No links found") return results, errors for link_obj in links: try: link_url = link_obj.get("url", "") host = link_obj.get("host", "Server") if not link_url: continue redir_resp = await client.get( link_url, headers={ "Referer": STREAM_REFERER, "User-Agent": "dooflix", }, ) stream_url = None if redir_resp.status_code in (301, 302, 303, 307, 308): stream_url = redir_resp.headers.get("location", "") elif redir_resp.status_code == 200: stream_url = link_url else: stream_url = redir_resp.headers.get("location", link_url) if not stream_url: continue s_type = "m3u8" if ".m3u8" in stream_url else "direct" quality = "Auto" q_match = re.search(r'(\d{3,4})p', stream_url) if q_match: quality = q_match.group(1) + "p" results.append({ "source": f"DooFlix/{host}", "title": f"DooFlix - {host}", "quality": quality, "language": "Hindi", "url": stream_url, "type": s_type, "headers": { "Referer": STREAM_REFERER, "User-Agent": "dooflix", }, }) except Exception as e: errors.append(f"DooFlix/{host}: {str(e)}") if not results: errors.append("DooFlix: No streams resolved") except Exception as e: errors.append(f"DooFlix: {str(e)}") return results, errors # ===== Castle Scraper (hlowb.com API with AES-CBC) ===== async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] try: from Crypto.Cipher import AES from Crypto.Util.Padding import unpad info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") if not title: errors.append("Castle: No title from TMDB") return results, errors CASTLE_BASE = "https://api.hlowb.com" PKG = "com.gwzq.clz" CH = "1" CLI = "1" LANG = "en-US" SIGN = "ED0955EB04E67A1D9F3305B95454FED485261475" HEADERS = {"User-Agent": "okhttp/4.9.3", "Accept": "application/json", "Accept-Language": "en-US"} async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: # Get security key sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/{CH}?clientType={CLI}&lang={LANG}") if sec_r.status_code != 200: errors.append(f"Castle: sec key HTTP {sec_r.status_code}") return results, errors sec_j = sec_r.json() raw_k = sec_j.get("data", "") if not raw_k or not isinstance(raw_k, str): errors.append("Castle: bad sec key") return results, errors try: sec_key = base64.b64decode(raw_k).decode("utf-8", errors="ignore") except: sec_key = raw_k combined = (sec_key + "T!BgJB") aes_k = (combined + "\x00" * max(0, 16 - len(combined)))[:16].encode("utf-8") aes_iv = aes_k def cdec(text): d = text try: j = json.loads(text) if isinstance(j, dict) and isinstance(j.get("data"), str): d = j["data"] except: pass raw = base64.b64decode(d) c = AES.new(aes_k, AES.MODE_CBC, aes_iv) dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") return json.loads(dec) # Search kw = f"{title} {info.get('year', '')}".strip() sr = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={ "channel": CH, "clientType": CLI, "keyword": kw, "lang": LANG, "mode": "1", "packageName": PKG, "page": "1", "size": "20" }) if sr.status_code != 200: errors.append(f"Castle: search HTTP {sr.status_code}") return results, errors try: sp = cdec(sr.text) except Exception as e: errors.append(f"Castle: search decrypt fail: {e}") return results, errors if not isinstance(sp, dict) or sp.get("code") != 200: errors.append(f"Castle: search API error") return results, errors db = sp.get("data", {}) if isinstance(db, str): try: db = json.loads(db) except: db = {} rows = db.get("rows", []) if isinstance(db, dict) else [] if not rows: errors.append("Castle: no search results") return results, errors # Match by title mid = None tl = title.lower() for r in rows: if not isinstance(r, dict): continue rt = (r.get("title") or "").lower() if tl in rt or rt in tl: mid = r.get("id") break if not mid and isinstance(rows[0], dict): mid = rows[0].get("id") if not mid: errors.append("Castle: no match") return results, errors mid = str(mid) # Get details dr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={ "channel": CH, "clientType": CLI, "lang": LANG, "movieId": mid, "packageName": PKG }) if dr.status_code != 200: errors.append(f"Castle: detail HTTP {dr.status_code}") return results, errors try: dp = cdec(dr.text) except: dp = {} dd = dp.get("data", dp) if isinstance(dd, str): try: dd = json.loads(dd) except: dd = {} if not isinstance(dd, dict): dd = {} # For TV: navigate seasons/episodes ep_id = mid # Default: same as movieId for movies if media_type == "tv" and season and episode: seasons = dd.get("seasons", []) s_id = mid for s in seasons: if not isinstance(s, dict): continue if s.get("number") == season or s.get("seasonNum") == season: sid = s.get("id") if sid and str(sid) != mid: s_id = str(sid) sdr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={ "channel": CH, "clientType": CLI, "lang": LANG, "movieId": s_id, "packageName": PKG }) try: sdp = cdec(sdr.text) sdd = sdp.get("data", sdp) if isinstance(sdd, dict): dd = sdd except: pass break eps = dd.get("episodes", []) for ep in eps: if not isinstance(ep, dict): continue if ep.get("number") == episode or ep.get("episodeNum") == episode: ep_id = str(ep.get("id", "")) break mid = s_id else: # Movies: check for episodes list eps = dd.get("episodes", []) if eps and isinstance(eps[0], dict): ep_id = str(eps[0].get("id", "")) # Get video via getVideo2 (shared/no language track) for resolution in [3, 2, 1]: # Try 1080p, 720p, 480p try: body = { "mode": "1", "appMarket": "google_play", "clientType": CLI, "woolUser": "0", "apkSignKey": SIGN, "androidVersion": "13", "movieId": mid, "episodeId": str(ep_id), "isNewUser": "1", "resolution": str(resolution), "packageName": PKG } vr = await client.post( f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo?clientType={CLI}&packageName={PKG}&channel={CH}&lang={LANG}", json=body, headers={"Content-Type": "application/json"} ) if vr.status_code != 200: errors.append(f"Castle: video HTTP {vr.status_code} res={resolution}") continue try: vp = cdec(vr.text) except Exception as vde: errors.append(f"Castle: video decrypt fail res={resolution}: {vde}") continue vd = vp.get("data", vp) if isinstance(vd, str): try: vd = json.loads(vd) except: continue if not isinstance(vd, dict): errors.append(f"Castle: video not dict res={resolution}: {type(vd)}") continue vurl = vd.get("videoUrl", "") if not vurl: errors.append(f"Castle: video API error res={resolution}: code={vd.get('code')}, msg={vd.get('msg')}") continue quality_map = {1: "480p", 2: "720p", 3: "1080p"} quality = quality_map.get(resolution, "720p") # Check for quality variants in videos array vids = vd.get("videos", []) if vids and isinstance(vids, list): for v in vids: if not isinstance(v, dict): continue vu = v.get("url", vurl) q = v.get("resolutionDescription", v.get("resolution", quality)) q = re.sub(r'^(SD|HD|FHD)\s+', '', str(q)) results.append({ "source": "Castle", "title": f"Castle - {q}", "quality": q, "language": "English", "url": vu, "type": "m3u8" if ".m3u8" in vu else "direct", }) else: results.append({ "source": "Castle", "title": f"Castle - {quality}", "quality": quality, "language": "English", "url": vurl, "type": "m3u8" if ".m3u8" in vurl else "direct", }) break # Got a stream, stop trying lower resolutions except: continue # Also try per-language tracks langs = dd.get("languages", dd.get("languageList", [])) if isinstance(langs, list): for lt in langs: lid = None ln = "" if isinstance(lt, dict): lid = lt.get("languageId", lt.get("id")) ln = lt.get("name", lt.get("languageName", "")) elif isinstance(lt, str): ln = lt # Try to find languageId from languageList ll = dd.get("languageList", []) for lli in ll: if isinstance(lli, dict) and lli.get("name", "").lower() == lt.lower(): lid = lli.get("languageId", lli.get("id")) break if not lid: continue try: body = { "mode": "1", "appMarket": "google_play", "clientType": CLI, "woolUser": "0", "apkSignKey": SIGN, "androidVersion": "13", "movieId": mid, "episodeId": str(ep_id), "languageId": str(lid), "isNewUser": "1", "resolution": "3", "packageName": PKG } vr = await client.post( f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo?clientType={CLI}&packageName={PKG}&channel={CH}&lang={LANG}", json=body, headers={"Content-Type": "application/json"} ) if vr.status_code != 200: continue vp = cdec(vr.text) vd = vp.get("data", vp) if isinstance(vd, str): try: vd = json.loads(vd) except: continue if not isinstance(vd, dict): continue vurl = vd.get("videoUrl", "") if not vurl: continue results.append({ "source": f"Castle [{ln}]", "title": f"Castle {ln} - 1080p", "quality": "1080p", "language": detect_language(ln) if ln else "English", "url": vurl, "type": "m3u8" if ".m3u8" in vurl else "direct", }) except: continue # Deduplicate seen = set() uniq = [] for r in results: if r["url"] not in seen: seen.add(r["url"]) uniq.append(r) results = uniq if not results: errors.append("Castle: no streams found") except ImportError: errors.append("Castle: pycryptodome not installed") except Exception as e: errors.append(f"Castle ERR: {type(e).__name__}: {str(e)}") return results, errors # ===== MovieBox Scraper (h5-api.aoneroom.com) ===== async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] try: import urllib.parse MOVIEBOX_BASE = "https://h5-api.aoneroom.com" 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", "token": token, "Origin": "https://moviebox.app", "Referer": "https://moviebox.app/", } # 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 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 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 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 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 = 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" 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": "MovieBox", "title": name, "quality": quality, "language": lang, "url": stream_url, "type": s_type, }) if not results: errors.append("MovieBox: No streams found") except Exception as e: errors.append(f"MovieBox: {str(e)}") return results, errors # ===== Videasy Scraper (Multi-server encrypted API) ===== async def scrape_videasy(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] try: VIDEASY_HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36", "Accept": "application/json, text/plain, */*", "Origin": "https://player.videasy.net", "Referer": "https://player.videasy.net/", } DECRYPT_API = "https://enc-dec.app/api/dec-videasy" SERVERS = { "Neon": {"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) title = info.get("title", "") year = info.get("year", "") imdb_id = info.get("imdb_id", "") async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=VIDEASY_HEADERS) as client: async def fetch_server(name: str, 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 1 e = episode or 1 url += f"&seasonId={s}&episodeId={e}" resp = await client.get(url) encrypted_text = resp.text if not encrypted_text or len(encrypted_text) < 20 or encrypted_text.startswith("]*>(.*?)', search_html, re.DOTALL) if not articles: errors.append("AllMovieLand: No search results") return results, errors movie_url = None title_lower = title.lower() for article in articles: link_m = re.search(r'href="([^"]+)"', article) h3_m = re.search(r'