diff --git "a/main.py" "b/main.py" --- "a/main.py" +++ "b/main.py" @@ -24,7 +24,7 @@ from urllib.parse import quote app = FastAPI( title="StreamForge API", description="Multi-language m3u8 stream scraper", - version="9.0.0", + version="10.0.0", ) app.add_middleware( @@ -114,23 +114,6 @@ def evp_bytes_to_key(password: bytes, salt: bytes, key_len: int = 32, iv_len: in 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 normalize_title(title: str) -> str: """Normalize title by removing brackets, (Dub), (HD), etc.""" cleaned = re.sub(r'\[[^\]]*\]', '', title) @@ -150,101 +133,239 @@ def extract_language_from_title(title: str) -> str: return "" -def parse_m3u8_quality(m3u8_content: str, base_url: str = "") -> list: - """Parse m3u8 master playlist and extract quality variants.""" - variants = [] - if "#EXT-X-STREAM-INF" in m3u8_content: - lines = m3u8_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].strip(): - variant_url = lines[i + 1].strip() - if not variant_url.startswith("http") and base_url: - variant_url = f"{base_url}/{variant_url}" - variants.append({"label": label, "quality": quality, "url": variant_url}) - return variants - - -def detect_quality_from_label(label: str) -> str: - """Detect quality from stream label text.""" - lower = label.lower() - if "4k" in lower or "2160" in lower: - return "4K" - if "1080" in lower or "fhd" in lower: - return "1080p FHD" - if "720" in lower or "hd" in lower: - return "720p HD" - if "480" in lower or "sd" in lower: - return "480p SD" - return "Auto" +def _sf_stream_result(source: str, title: str, url: str, quality: str = "Auto", language: str = "English") -> dict: + return { + "source": source, + "title": title, + "quality": quality, + "language": detect_language(language) if language else "English", + "url": url, + "type": "m3u8" if ".m3u8" in url else "direct", + } + +def _sf_norm(s: str) -> str: + return re.sub(r"[^a-z0-9]", "", (s or "").lower()) -# ===== VidRock Scraper (AES-encrypted API) - KEEP AS-IS ===== -async def scrape_vidrock(tmdb_id: int, media_type: str, season: int = None, episode: int = None): +# ---------- PurStream (Nuvio purstream.js): search + sheet API ---------- + +async def scrape_purstream(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 + info = await get_tmdb_info(tmdb_id, media_type) + title = info.get("title") + if not title: + return [], ["PurStream: no TMDB title"] - passphrase = b"x7k9mPqT2rWvY8zA5bC3nF6hJ2lK4mN9" - aes_key = passphrase[:32] - aes_iv = passphrase[:16] + headers = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://purstream.club/"} + async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=headers) as client: + resp = await client.get(f"https://api.purstream.club/api/v1/search-bar/search/{quote(str(title))}") + items = resp.json().get("data", {}).get("items", {}) + candidates = [] + for key in ("movies", "tv", "series", "tvshows"): + bucket = items.get(key) or {} + sub = bucket.get("items") if isinstance(bucket, dict) else bucket + if isinstance(sub, list): + candidates.extend(sub) - 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" + # catalog items lack tmdbId -> match by title, verify tmdbId via sheet + media_id, sheet = None, None + for item in candidates: + if _sf_norm(item.get("title")) == _sf_norm(title): + try: + probe = (await client.get( + f"https://api.purstream.club/api/v1/media/{item['id']}/sheet")).json() + if str(probe.get("data", {}).get("items", {}).get("tmdbId")) == str(tmdb_id): + media_id, sheet = item.get("id"), probe + break + except Exception: + continue + if not media_id or sheet is None: + return [], ["PurStream: title not found in catalog"] - 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("=", "") + urls = sheet.get("data", {}).get("items", {}).get("urls", []) + if media_type == "tv": + s, e = season or 1, episode or 1 + pat = re.compile(rf"/S{s:02d}/E{e:02d}/|S{s}\.?E{e}\b", re.I) + urls = [u for u in urls if pat.search(u.get("url") or "") or pat.search(u.get("name") or "")] - 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 + for u in urls: + url = u.get("url") + if not url: + continue + name = u.get("name") or "PurStream" + results.append(_sf_stream_result(f"PurStream/{name}", f"PurStream - {name}", url)) + if not results: + errors.append("PurStream: no stream urls") + + except Exception as e: + errors.append(f"PurStream: {str(e)}") + + return results, errors + + +# ---------- Movix (Nuvio movix.js): api.movix.cash direct API ---------- + +async def scrape_movix(tmdb_id: int, media_type: str, season: int = None, episode: int = None): + results = [] + errors = [] + + try: + headers = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://movix.cash/"} + async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=headers) as client: + if media_type == "tv": + url = f"https://api.movix.cash/api/purstream/tv/{tmdb_id}/stream" + params = {"season": season or 1, "episode": episode or 1} + else: + url = f"https://api.movix.cash/api/purstream/movie/{tmdb_id}/stream" + params = {} + resp = await client.get(url, params=params) data = resp.json() - 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 data.get("error"): + return [], [f"Movix: {data.get('error')}"] + + for src in data.get("sources", []): + surl = src.get("url") + if not surl: + continue + name = src.get("name") or "Movix" + results.append(_sf_stream_result(f"Movix/{name}", f"Movix - {name}", surl)) if not results: - errors.append("VidRock: No streams found") + errors.append("Movix: no sources") - except ImportError: - errors.append("VidRock: pycryptodome not installed") except Exception as e: - errors.append(f"VidRock: {str(e)}") + errors.append(f"Movix: {str(e)}") return results, errors -# ===== Castle Scraper (hlowb.com API with AES-CBC) - COMPLETE REWRITE ===== +# ---------- HubCloud family resolver (MediaVanced hubcloud.py, generalized) ---------- + +_SF_LINK_PROVIDERS = re.compile( + r'https?://[^\s"\'<>]*(?:hubcloud\.[a-z]+/(?:drive|video)/[A-Za-z0-9_\-]+' + r'|hubdrive\.[a-z]+/file/[A-Za-z0-9]+' + r'|hblinks\.[a-z]+/archives/\d+' + r'|vcloud\.[a-z]+/[A-Za-z0-9]+' + r'|nexdrive\.[a-z]+/[A-Za-z0-9]+' + r'|abhilinks\.[a-z]+/archives/\d+/?)', +) +_SF_SPORTVERSE = re.compile(r'https?://sportverse\.cc/hubcloud\.php\?[^"\'<>]+') +_SF_MOBILE_UA = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Mobile Safari/537.36" + + +def _sf_extract_links(html: str) -> list: + seen, out = set(), [] + for m in _SF_LINK_PROVIDERS.finditer(html or ""): + u = m.group(0) + if u not in seen: + seen.add(u) + out.append(u) + return out + + +def _sf_pixeldrain_direct(u: str) -> str: + m = re.search(r'pixeldrain\.[a-z]+/u/([A-Za-z0-9]+)', u) + if m: + return f"https://pixeldrain.com/api/file/{m.group(1)}?download" + return u + + +async def _sf_resolve_hubcloud(client: httpx.AsyncClient, link: str) -> list: + """Resolve one hubcloud-family page into direct file URLs.""" + out = [] + try: + if "/video/" in link or "hubvid" in link: + page = (await client.get(link)).text + sport = _SF_SPORTVERSE.search(page) + if sport: + page = (await client.get(sport.group(0), headers={"Referer": link})).text + else: + page = (await client.post(link)).text + m = re.search(r"var\s+url\s*=\s*'(https?://[^']+)'", page) + if m: + page = (await client.get(m.group(1))).text + for b in re.finditer(r']+href="(https?://[^"]+)"[^>]+class="[^"]*btn[^"]*"', page): + u = b.group(1) + chunk = page[b.start():b.start() + 800] + fm = re.search(r'download="([^"]{5,110})"', chunk) + fname = fm.group(1) if fm else "" + if "pixeldrain" in u: + out.append({"url": _sf_pixeldrain_direct(u), "label": fname or "Direct"}) + elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) and ".zip" not in u: + out.append({"url": u, "label": fname or "Direct"}) + elif "cloudflarestorage" in u or "workers.dev" in u: + out.append({"url": u, "label": fname or "Direct"}) + except Exception: + pass + return out + + +def _sf_quality_from_name(name: str) -> str: + low = (name or "").lower() + if "2160" in low or "4k" in low: return "4K" + if "1080" in low: return "1080p FHD" + if "720" in low: return "720p HD" + if "480" in low: return "480p SD" + return "Auto" + + +def _sf_lang_from_name(name: str) -> str: + low = (name or "").lower() + if "dual audio" in low or "multi" in low: return "Multi" + langs = [] + if "hindi" in low or "esubs" in low: langs.append("Hindi") + if "tamil" in low: langs.append("Tamil") + if "telugu" in low: langs.append("Telugu") + if "english" in low or "eng" in low: langs.append("English") + return " + ".join(langs) if langs else "English" + + +def _sf_episode_matches(label: str, season: int, episode: int) -> bool: + if not label: + return True + low = label.lower() + s_ok = re.search(rf'\bs{season:02d}e{episode:02d}\b|s{season}\.?e{episode}\b|season.{season}\b', low) + e_ok = re.search(rf'\be{episode:02d}\b|episode.{episode}\b|ep.{episode}\b|e{episode}\b', low) + season_only = re.search(rf'season.{season}\b|s{season:02d}\b|s{season}\b', low) + # Correct-episode or correct-season labels always match + if s_ok or season_only or (e_ok and (season_only or "season" in low)): + return True + # Labels mentioning a DIFFERENT season/episode are rejected + other = re.search(r'\bs\d{1,2}e\d{1,2}\b|season.\d+\b|\be\d{1,2}\b|episode.\d+\b', low) + if other: + return False + # No markers at all -> generic pack link, accept + return True + + +def _sf_hubcloud_results(source_name: str, resolved: list, media_type: str, season, episode) -> list: + results = [] + seen_urls = set() + for r in resolved: + u, label = r["url"], r["label"] + if u in seen_urls: + continue + seen_urls.add(u) + if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1): + continue + results.append(_sf_stream_result( + f"{source_name}/HubCloud", f"{source_name} - {label or 'Direct'}", u, + quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label))) + return results + + +PHISHER_DOMAINS = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json" +VEGA_URLS = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json" + +_SF_HUB_HEADERS = {"User-Agent": _SF_MOBILE_UA, "Accept": "text/html,application/xhtml+xml,*/*", "Accept-Language": "en-US,en;q=0.5"} + + +# ===== Castle Scraper (hlowb.com API with AES-CBC) - v10 FIXED (multi-language m3u8) ===== async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] @@ -472,125 +593,39 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo if eps and isinstance(eps[0], dict): ep_id = str(eps[0].get("id", "")) - # Step 4: Get video via getVideo2 - 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/getVideo2", - params={"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 = castle_decrypt(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 Exception: - continue - if not isinstance(vd, dict): - errors.append(f"Castle: video not dict res={resolution}") - 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)) - # Extract subtitles if present - subs = v.get("subtitles", []) - - result_item = { - "source": "Castle", - "title": f"Castle - {q}", - "quality": q, - "language": "English", - "url": vu, - "type": "m3u8" if ".m3u8" in vu else "direct", - } - if subs: - result_item["subtitles"] = subs - results.append(result_item) - 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 Exception: - 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 - 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 + # Step 4: Get video via getVideo2 - v10 fixed flow (multi-language, ported from Nuvio castle.js) + CASTLE_LANGS = [("English", "1003"), ("Tamil", "1033"), ("Telugu", "1037")] + for lang_name, lang_id in CASTLE_LANGS: + for resolution in [3, 2, 1]: # Try 1080p, 720p, 480p 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, + "mode": "1", + "appMarket": "GuanWang", + "clientType": CLI, + "woolUser": "false", + "apkSignKey": SIGN, + "androidVersion": "13", + "movieId": mid, + "episodeId": str(ep_id), + "languageId": lang_id, + "isNewUser": "true", + "resolution": str(resolution), + "packageName": PKG, } vr = await client.post( f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2", params={"clientType": CLI, "packageName": PKG, "channel": CH, "lang": LANG}, - json=body, headers={"Content-Type": "application/json"} + json=body, + headers={"Content-Type": "application/json"} ) if vr.status_code != 200: continue - vp = castle_decrypt(vr.text) + + try: + vp = castle_decrypt(vr.text) + except Exception: + continue + vd = vp.get("data", vp) if isinstance(vd, str): try: @@ -599,17 +634,44 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo 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", - }) + + quality_map = {1: "480p", 2: "720p", 3: "1080p"} + quality = quality_map.get(resolution, "720p") + + vids = vd.get("videos", []) + if vids and isinstance(vids, list): + for v in vids: + if not isinstance(v, dict): + continue + vu = v.get("url", vurl) + q = v.get("resolutionDescription", v.get("resolution", quality)) + q = re.sub(r'^(SD|HD|FHD)\s+', '', str(q)) + subs = v.get("subtitles", []) + result_item = { + "source": "Castle", + "title": f"Castle [{lang_name}] - {q}", + "quality": q, + "language": lang_name, + "url": vu, + "type": "m3u8" if ".m3u8" in vu else "direct", + } + if subs: + result_item["subtitles"] = subs + results.append(result_item) + else: + results.append({ + "source": "Castle", + "title": f"Castle [{lang_name}] - {quality}", + "quality": quality, + "language": lang_name, + "url": vurl, + "type": "m3u8" if ".m3u8" in vurl else "direct", + }) + break # Got a stream, stop trying lower resolutions except Exception: continue @@ -633,2501 +695,393 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo return results, errors -# ===== MovieBox Scraper (themoviebox.org) - UPDATED ===== +# ===== NetMirror Scraper (net27.cc embed-tmdb API) - v10 REWRITE ===== +# Ported from All-in-One-Nuvio netmirror.js (live-tested: mp4 360p-1080p, movie+TV) + +_NETMIRROR_BASE = "https://net27.cc" +_NETMIRROR_HEADERS = { + "Accept": "application/json, text/plain, */*", + "Referer": "https://net27.cc/", + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36", +} + -async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, episode: int = None): +async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None): + """NetMirror via net27.cc - takes TMDB id directly, returns direct mp4 streams (multi-res).""" results = [] errors = [] - try: - MOVIEBOX_SITE = "https://themoviebox.org" - MOVIEBOX_BASE = "https://h5-api.aoneroom.com" - MOVIEBOX_TMDB_KEY = "d131017ccc6e5462a81c9304d21476de" - - 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, - "x-client-info": json.dumps({"timezone": "Asia/Calcutta"}), - "x-request-lang": "en", - "X-Client-Token": token, - "Origin": MOVIEBOX_SITE, - "Referer": f"{MOVIEBOX_SITE}/", - } - - # Step 1: Search for the movie/TV show - 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 + url = f"{_NETMIRROR_BASE}/api/embed-tmdb/{tmdb_id}" + if media_type == "tv": + url += f"?type=tv&s={season or 1}&e={episode or 1}" - search_resp = await client.post( - f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/search", - json={ - "keyword": title, - "page": 1, - "perPage": 28, - "subjectType": 0, # 0 = all, 1 = movie, 2 = tv - }, - headers=mb_headers, - ) - if search_resp.status_code != 200: - errors.append(f"MovieBox: Search failed HTTP {search_resp.status_code}") + async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client: + resp = await client.get(url, headers=_NETMIRROR_HEADERS) + if resp.status_code != 200: + errors.append(f"NetMirror: embed-tmdb HTTP {resp.status_code}") + return results, errors + try: + data = resp.json() + except Exception: + errors.append("NetMirror: non-JSON response") return results, errors - 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, with subjectType filtering - title_norm = re.sub(r'[^a-zA-Z0-9]', '', normalize_title(title).lower()) - target_subject_type = 1 if media_type == "movie" else 2 - matched_item = None - - # First: exact title match + correct subjectType + year - 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_type = item.get("subjectType", item.get("type", 0)) - item_norm = re.sub(r'[^a-zA-Z0-9]', '', normalize_title(item_title).lower()) - - if item_norm == title_norm and item_type == target_subject_type: - if year and item_year and year == item_year: - matched_item = item - break - elif not year or not item_year: - matched_item = item - break - - # Second: substring match + correct subjectType - if not matched_item: - for item in search_items: - item_title = item.get("title", "") or item.get("name", "") - item_type = item.get("subjectType", item.get("type", 0)) - item_norm = re.sub(r'[^a-zA-Z0-9]', '', normalize_title(item_title).lower()) - - if (title_norm in item_norm or item_norm in title_norm) and item_type == target_subject_type: - matched_item = item - break - - # Third: match without subjectType filter - 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]', '', normalize_title(item_title).lower()) - if item_norm == title_norm: - matched_item = item - break - - # Fourth: substring without type filter - 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]', '', normalize_title(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") - detail_path = matched_item.get("detailPath", "") - if not subject_id: - errors.append("MovieBox: No subject ID in matched item") - return results, errors - - # Step 3: Get detail using detailPath (new API) - token = generate_moviebox_token() - mb_headers["token"] = token - mb_headers["X-Client-Token"] = token - - if detail_path: - detail_resp = await client.get( - f"{MOVIEBOX_BASE}/wefeed-h5api-bff/detail", - params={"detailPath": detail_path}, - headers=mb_headers, - ) - else: - detail_resp = await client.get( - f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/detail", - params={"subjectId": subject_id}, - headers=mb_headers, - ) - - detail_data = {} - if detail_resp.status_code == 200: - detail_data = detail_resp.json().get("data", {}) - - # Step 4: Get download URLs - token = generate_moviebox_token() - mb_headers["token"] = token - mb_headers["X-Client-Token"] = token - - dp = detail_path or f"/subject/{subject_id}" - - # For TV: find season/episode, then get download for specific episode - dl_subject_id = subject_id - if media_type == "tv": - s = season or 1 - e = episode or 1 - - episodes = detail_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"): - dl_subject_id = target_ep["id"] - ep_dp = target_ep.get("detailPath", "") - if ep_dp: - dp = ep_dp - - dl_resp = await client.get( - f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/download", - params={"subjectId": dl_subject_id, "ep": str(dl_subject_id)}, - headers={**mb_headers, "Referer": f"{MOVIEBOX_SITE}/play/{dp}"}, - ) - 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 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" - - # Extract language from title brackets or from language field - dl_name = dl_item.get("name") or dl_item.get("title") or dl_item.get("serverName", "") - lang = dl_item.get("language") or dl_item.get("audio", "") - if lang: - lang = detect_language(lang) - else: - bracket_lang = extract_language_from_title(dl_name) - if bracket_lang: - lang = bracket_lang - else: - lang = "English" - - name = dl_name or "MovieBox Stream" - name = normalize_title(name) if name else "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) - KEEP AS-IS ===== - -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']*>(.*?)', article) - if link_m and h3_m: - item_title = h3_m.group(1).strip().lower() - if item_title == title_lower or title_lower in item_title: - movie_url = link_m.group(1) - break - - if not movie_url: - for article in articles: - link_m = re.search(r'href="([^"]+)"', article) - if link_m: - movie_url = link_m.group(1) - break - - if not movie_url: - errors.append("AllMovieLand: Could not find movie URL") - return results, errors - - movie_resp = await client.get(movie_url, headers={"Referer": "https://allmovieland.one/"}) - movie_html = movie_resp.text - - domain_match = re.search(r"AwsIndStreamDomain\s*=\s*['\"]([^'\"]+)['\"]", movie_html) - player_domain = domain_match.group(1).rstrip("/") if domain_match else None - - id_match = re.search(r"src:\s*['\"]([^'\"]+)['\"]", movie_html) - media_id = id_match.group(1) if id_match else None - - if not player_domain or not media_id: - errors.append(f"AllMovieLand: No player info (domain={player_domain}, id={media_id})") - return results, errors - - embed_url = f"{player_domain}/play/{media_id}" - embed_resp = await client.get(embed_url, headers={"Referer": movie_url}) - embed_html = embed_resp.text - - p3_m = re.search(r'let\s+p3\s*=\s*(\{.*?\})\s*;', embed_html) - if not p3_m: - p3_m = re.search(r'p3\s*=\s*(\{[^;]+\})\s*;', embed_html) - if not p3_m: - p3_m = re.search(r'(\{"file".*?"key".*?\})', embed_html) - - if not p3_m: - errors.append("AllMovieLand: Could not find player data in embed") - return results, errors - - try: - p3 = json.loads(p3_m.group(1)) - except json.JSONDecodeError: - errors.append(f"AllMovieLand: Invalid p3 JSON: {p3_m.group(1)[:80]}") - return results, errors - - file_url = p3.get("file", "").replace("\\/", "/") - csrf_key = p3.get("key", "") - - if not file_url or not csrf_key: - errors.append("AllMovieLand: Missing file URL or CSRF key in p3") - return results, errors - - file_list = None - post_headers = { - "X-CSRF-TOKEN": csrf_key, - "Referer": embed_url, - "Origin": player_domain, - "Accept": "application/json, text/plain, */*", - "User-Agent": UA, - } - - for attempt in range(7): - try: - async with httpx.AsyncClient(timeout=10, follow_redirects=True, http2=False) as fresh_client: - resp = await fresh_client.post(file_url, headers=post_headers) - text = resp.text.strip() - if text != "7" and text.startswith("["): - file_list = json.loads(text.replace(",]", "]")) - break - except Exception: - pass - - if not file_list: - errors.append("AllMovieLand: Could not get file list (7 attempts)") - return results, errors - - target_files = [] - if media_type == "movie": - target_files = [f for f in file_list if f.get("file")] - else: - s = season or 1 - e = episode or 1 - for item in file_list: - item_title = item.get("title", "") - s_m = re.search(r'Season\s*(\d+)', item_title, re.I) - if s_m and int(s_m.group(1)) == s: - if item.get("folder"): - for ep_item in item["folder"]: - ep_title = ep_item.get("title", "") - e_m = re.search(r'Episode\s*(\d+)', ep_title, re.I) - if e_m and int(e_m.group(1)) == e: - if ep_item.get("folder"): - target_files = [f for f in ep_item["folder"] if f.get("file")] - break - break - - if not target_files: - target_files = [f for f in file_list if f.get("file")][:3] - - for file_obj in target_files: - file_path = file_obj.get("file", "").lstrip("~") - stream_title = file_obj.get("title", "Stream") - if not file_path: - continue - - playlist_url = f"{player_domain}/playlist/{file_path}.txt" - - m3u8_url = None - for attempt in range(7): - try: - async with httpx.AsyncClient(timeout=10, follow_redirects=True, http2=False) as fresh_client: - resp = await fresh_client.post(playlist_url, headers=post_headers) - text = resp.text.strip() - if text != "7" and text.startswith("http"): - m3u8_url = text - break - except Exception: - pass - - if m3u8_url: - lang = detect_language(stream_title) - quality = "Auto" - q_m = re.search(r'(\d{3,4})p', stream_title) - if q_m: - quality = q_m.group(1) + "p" - - results.append({ - "source": "AllMovieLand", - "title": f"AllMovieLand - {stream_title}", - "quality": quality, - "language": lang, - "url": m3u8_url, - "type": "m3u8", - "headers": { - "Referer": f"{player_domain}/", - "Origin": player_domain, - "User-Agent": UA, - }, - }) - - if not results: - errors.append("AllMovieLand: Could not resolve any m3u8 URLs") - - except Exception as e: - errors.append(f"AllMovieLand: {str(e)}") - - return results, errors - - -# ===== VidLink Scraper (vidlink.pro with encrypted ID) - REWRITTEN ===== - -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" - VIDLINK_TMDB_KEY = "68e094699525b18a70bab2f86b1fa706" - - VIDLINK_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", - "Connection": "keep-alive", - "Referer": "https://vidlink.pro/", - "Origin": "https://vidlink.pro", - "Accept": "application/json", - } - - 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_api = f"{VIDLINK_BASE}/api/b/movie/{encrypted_id}" - else: - s = season or 1 - e = episode or 1 - stream_api = f"{VIDLINK_BASE}/api/b/tv/{encrypted_id}/{s}/{e}" - - stream_resp = await client.get(stream_api, headers=VIDLINK_HEADERS) - - 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 - primary: stream.playlist - 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": "https://vidlink.pro/", - "Origin": "https://vidlink.pro", - }) - - if "#EXT-X-STREAM-INF" in m3u8_resp.text: - base_url = playlist_url.rsplit("/", 1)[0] - variants = parse_m3u8_quality(m3u8_resp.text, base_url) - - for variant in variants: - quality = detect_quality_from_label(variant["label"]) - if quality == "Auto": - res_match = re.search(r'(\d+)x(\d+)', variant["quality"]) - if res_match: - height = int(res_match.group(2)) - if height >= 2160: - quality = "4K" - elif height >= 1440: - quality = "1440p" - elif height >= 1080: - quality = "1080p FHD" - elif height >= 720: - quality = "720p HD" - elif height >= 480: - quality = "480p SD" - - results.append({ - "source": "VidLink", - "title": variant["label"], - "quality": quality, - "language": "English", - "url": variant["url"], - "type": "m3u8", - "headers": { - "Referer": "https://vidlink.pro/", - "Origin": "https://vidlink.pro", - }, - }) - else: - results.append({ - "source": "VidLink", - "title": "VidLink Stream", - "quality": "Auto", - "language": "English", - "url": playlist_url, - "type": "m3u8", - "headers": { - "Referer": "https://vidlink.pro/", - "Origin": "https://vidlink.pro", - }, - }) - except Exception: - results.append({ - "source": "VidLink", - "title": "VidLink Stream", - "quality": "Auto", - "language": "English", - "url": playlist_url, - "type": "m3u8", - "headers": { - "Referer": "https://vidlink.pro/", - "Origin": "https://vidlink.pro", - }, - }) - 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": "https://vidlink.pro/", - "Origin": "https://vidlink.pro", - }, - }) - - if not results: - errors.append("VidLink: No streams found") - - except Exception as e: - errors.append(f"VidLink: {str(e)}") - - return results, errors - - -# ===== VidSrc Scraper (cloudnestra approach) - REWRITTEN ===== - -async def scrape_vidsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - VIDSRC_TMDB_KEY = "439c478a771f35c05022f9feabcca01c" - DECRYPT_API = "https://enc-dec.app/api/dec-cloudnestra" - - # Get IMDB ID using the VidSrc-specific TMDB key - info = await get_tmdb_info_with_key(tmdb_id, media_type, VIDSRC_TMDB_KEY) - imdb_id = info.get("imdb_id") - if not imdb_id: - info = await get_tmdb_info(tmdb_id, media_type) - imdb_id = info.get("imdb_id") - if not imdb_id: - errors.append("VidSrc: Could not get IMDB ID from TMDB") - return results, errors - - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: - - # Step 1: Fetch embed page from vsrc.su - if media_type == "tv": - s = season or 1 - e = episode or 1 - embed_url = f"https://vsrc.su/embed/tv?imdb={imdb_id}&season={s}&episode={e}" - else: - embed_url = f"https://vsrc.su/embed/movie?imdb={imdb_id}" - - embed_resp = await client.get(embed_url) - embed_html = embed_resp.text - - # Step 2: Parse iframe src from HTML - iframe_src = None - iframe_m = re.search(r']+src="([^"]+)"', embed_html) - if iframe_m: - iframe_src = iframe_m.group(1) - if iframe_src.startswith("//"): - iframe_src = f"https:{iframe_src}" - elif iframe_src.startswith("/"): - iframe_src = f"https://vsrc.su{iframe_src}" - - if not iframe_src: - iframe_m = re.search(r'src=["\x27]([^"\x27]+)["\x27]', embed_html) - if iframe_m: - iframe_src = iframe_m.group(1) - if iframe_src.startswith("//"): - iframe_src = f"https:{iframe_src}" - - if not iframe_src: - errors.append("VidSrc: No iframe found in embed page") - return results, errors - - # Step 3: Fetch iframe page, extract JS src pattern - iframe_resp = await client.get(iframe_src, headers={"Referer": "https://vsrc.su/"}) - iframe_html = iframe_resp.text - - # Look for src: "..." pattern in JS - js_src = None - src_match = re.search(r'src:\s*["\x27](/[^"\x27]+)["\x27]', iframe_html) - if not src_match: - src_match = re.search(r'file:\s*["\x27](https?://[^"\x27]+\.m3u8[^"\x27]*)["\x27]', iframe_html) - - if src_match: - js_src = src_match.group(1) - # If it's a direct m3u8 URL, return it - if js_src.startswith("http") and ".m3u8" in js_src: - quality = "Auto" - if "2160" in js_src or "4k" in js_src.lower(): - quality = "4K" - elif "1080" in js_src: - quality = "1080p" - elif "720" in js_src: - quality = "720p" - - results.append({ - "source": "VidSrc", - "title": "VidSrc Stream", - "quality": quality, - "language": "English", - "url": js_src, - "type": "m3u8", - "headers": { - "Referer": "https://cloudnestra.com/", - }, - }) - return results, errors - - # Step 4: Fetch cloudnestra page with the src path - if js_src and not js_src.startswith("http"): - cloudnestra_url = f"https://cloudnestra.com{js_src}" - elif js_src: - cloudnestra_url = js_src - else: - cloud_m = re.search(r'(https?://cloudnestra\.com[^\s"\'<>]+)', iframe_html) - if cloud_m: - cloudnestra_url = cloud_m.group(1) - else: - errors.append("VidSrc: Could not find cloudnestra source path") - return results, errors - - cloud_resp = await client.get(cloudnestra_url, headers={ - "Referer": "https://vsrc.su/", - "Origin": "https://vsrc.su", - }) - - if cloud_resp.status_code == 403 or "Cloudflare" in cloud_resp.text: - errors.append("VidSrc: Cloudflare blocked on cloudnestra") - return results, errors - - cloud_html = cloud_resp.text - - # Step 5: Parse HTML for hidden div - div_id = None - div_text = None - hidden_pattern = r']*style=["\x27][^"\x27]*display\s*:\s*none[^"\x27]*["\x27][^>]*>([\s\S]*?)' - hidden_m = re.search(hidden_pattern, cloud_html) - if hidden_m: - div_id = hidden_m.group(1) - div_text = hidden_m.group(2).strip() - - if not div_text: - hidden_pattern2 = r']*style=["\x27]display\s*:\s*none;?["\x27][^>]*>([a-zA-Z0-9:/.,{}_=+ \-]+)' - hidden_m2 = re.search(hidden_pattern2, cloud_html) - if hidden_m2: - div_id = hidden_m2.group(1) - div_text = hidden_m2.group(2).strip() - - if not div_text or not div_id: - errors.append("VidSrc: Could not find hidden div for decryption") - return results, errors - - # Step 6: 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"}, - ) - - if dec_resp.status_code != 200: - errors.append(f"VidSrc: Decrypt API failed HTTP {dec_resp.status_code}") - return results, errors - - dec_data = dec_resp.json() - stream_urls = dec_data.get("result", []) - - if isinstance(stream_urls, str): - stream_urls = [stream_urls] - - if not stream_urls: - errors.append("VidSrc: No streams from decryption") - return results, errors - - # Step 7: Parse decrypted m3u8 URLs and detect quality - for idx, stream_url in enumerate(stream_urls): - if not stream_url or not isinstance(stream_url, str): - continue - - quality = "Auto" - url_lower = stream_url.lower() - if "2160" in url_lower or "4k" in url_lower: - quality = "4K" - elif "1440" in url_lower: - quality = "1440p" - elif "1080" in url_lower: - quality = "1080p" - elif "720" in url_lower: - quality = "720p" - elif "480" in url_lower: - quality = "480p" - else: - # Try fetching the m3u8 to detect max quality - try: - m3u8_resp = await client.get(stream_url, headers={ - "Referer": "https://cloudnestra.com/", - }) - m3u8_content = m3u8_resp.text - if "#EXT-X-STREAM-INF" in m3u8_content: - resolutions = re.findall(r'RESOLUTION=\d+x(\d+)', m3u8_content) - if resolutions: - max_h = max(int(r) for r in resolutions) - if max_h >= 2160: - quality = "4K" - elif max_h >= 1440: - quality = "1440p" - elif max_h >= 1080: - quality = "1080p" - elif max_h >= 720: - quality = "720p" - elif max_h >= 480: - quality = "480p" - except Exception: - pass - - results.append({ - "source": f"VidSrc{idx + 1 if len(stream_urls) > 1 else ''}", - "title": f"VidSrc Server {idx + 1}" if len(stream_urls) > 1 else "VidSrc Stream", - "quality": quality, - "language": "English", - "url": stream_url, - "type": "m3u8", - "headers": { - "Referer": "https://cloudnestra.com/", - "Origin": "https://cloudnestra.com", - }, - }) - - if not results: - errors.append("VidSrc: No streams found") - - except Exception as e: - errors.append(f"VidSrc: {str(e)}") - - return results, errors - - -# ===== M4UHD Scraper (m4uhd.vip with CryptoJS-compatible AES-CBC) - KEEP AS-IS ===== - -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 - - movie_blocks = re.findall( - r']*class="[^"]*item[^"]*"[^>]*>.*?]*href="([^"]+)"[^>]*>.*?(?:]*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 - - 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 - - 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 - - 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 "" - - 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 - - for server_id, server_name in servers[:3]: - try: - 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 - - 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 - - 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 - - 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() - - idfile = m4uhd_decrypt(idfile_enc, FILE_ID_SECRET) - iduser = m4uhd_decrypt(iduser_enc, USER_ID_SECRET) if iduser_enc else "" - - payload_data = { - "idfile": idfile, - "idUser": iduser, - } - payload_json = json.dumps(payload_data) - encrypted_payload = m4uhd_encrypt(payload_json, ENCRYPT_PAYLOAD_SECRET) - - 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 - - try: - decrypted_response = m4uhd_decrypt(encrypted_response, DECRYPT_RESPONSE_SECRET) - - 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 - - -# ===== VidFast Scraper (vidfast.pro with encrypted ID) - NEW ===== - -async def scrape_vidfast(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - ENCRYPT_API = "https://enc-dec.app/api/enc-vidfast" - VIDFAST_BASE = "https://vidfast.pro" - - VIDFAST_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", - "Referer": "https://vidfast.pro/", - "X-Requested-With": "XMLHttpRequest", - "Accept": "application/json", - } - - 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"VidFast: 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("VidFast: No encrypted ID returned") - return results, errors - - # Step 2: Get stream URL - if media_type == "movie": - stream_api = f"{VIDFAST_BASE}/api/movie/{encrypted_id}" - else: - s = season or 1 - e = episode or 1 - stream_api = f"{VIDFAST_BASE}/api/tv/{encrypted_id}/{s}/{e}" - - stream_resp = await client.get(stream_api, headers=VIDFAST_HEADERS) - - if stream_resp.status_code != 200: - errors.append(f"VidFast: Stream API failed HTTP {stream_resp.status_code}") - return results, errors - - stream_data = stream_resp.json() - - # Extract stream data - check various response structures - playlist_url = None - streams = [] - - # Try stream.playlist pattern (like VidLink) - if stream_data.get("stream"): - playlist_url = stream_data["stream"].get("playlist") or stream_data["stream"].get("url", "") - - # Try direct sources array - if not playlist_url and stream_data.get("sources"): - for source in stream_data["sources"]: - if isinstance(source, dict) and source.get("url"): - streams.append(source) - elif isinstance(source, str) and source.startswith("http"): - streams.append({"url": source}) - - # Try direct URL fields - if not playlist_url and not streams: - for key in ["url", "file", "source", "playlist", "link"]: - if stream_data.get(key): - val = stream_data[key] - if isinstance(val, str): - playlist_url = val - break - elif isinstance(val, dict) and val.get("url"): - playlist_url = val["url"] - break - - # Process direct streams - if streams: - for source in streams: - url = source.get("url", "") - if not url: - continue - quality = source.get("quality", "Auto") - name = source.get("name", "VidFast Stream") - - if quality == "Auto": - quality = detect_quality_from_label(name + " " + url) - - s_type = "m3u8" if ".m3u8" in url else "direct" - - results.append({ - "source": "VidFast", - "title": name, - "quality": quality, - "language": "English", - "url": url, - "type": s_type, - "headers": { - "Referer": "https://vidfast.pro/", - "Origin": "https://vidfast.pro", - }, - }) - - elif playlist_url: - if ".m3u8" in playlist_url: - try: - m3u8_resp = await client.get(playlist_url, headers={ - "Referer": "https://vidfast.pro/", - "Origin": "https://vidfast.pro", - }) - - if "#EXT-X-STREAM-INF" in m3u8_resp.text: - base_url = playlist_url.rsplit("/", 1)[0] - variants = parse_m3u8_quality(m3u8_resp.text, base_url) - - for variant in variants: - quality = detect_quality_from_label(variant["label"]) - if quality == "Auto": - res_match = re.search(r'(\d+)x(\d+)', variant["quality"]) - if res_match: - height = int(res_match.group(2)) - if height >= 2160: - quality = "4K" - elif height >= 1080: - quality = "1080p FHD" - elif height >= 720: - quality = "720p HD" - elif height >= 480: - quality = "480p SD" - - results.append({ - "source": "VidFast", - "title": variant["label"], - "quality": quality, - "language": "English", - "url": variant["url"], - "type": "m3u8", - "headers": { - "Referer": "https://vidfast.pro/", - "Origin": "https://vidfast.pro", - }, - }) - else: - results.append({ - "source": "VidFast", - "title": "VidFast Stream", - "quality": "Auto", - "language": "English", - "url": playlist_url, - "type": "m3u8", - "headers": { - "Referer": "https://vidfast.pro/", - "Origin": "https://vidfast.pro", - }, - }) - except Exception: - results.append({ - "source": "VidFast", - "title": "VidFast Stream", - "quality": "Auto", - "language": "English", - "url": playlist_url, - "type": "m3u8", - "headers": { - "Referer": "https://vidfast.pro/", - "Origin": "https://vidfast.pro", - }, - }) - else: - s_type = "direct" if ".mp4" in playlist_url else "m3u8" - results.append({ - "source": "VidFast", - "title": "VidFast Stream", - "quality": "Auto", - "language": "English", - "url": playlist_url, - "type": s_type, - "headers": { - "Referer": "https://vidfast.pro/", - "Origin": "https://vidfast.pro", - }, - }) - - if not results: - errors.append("VidFast: No streams found") - - except Exception as e: - errors.append(f"VidFast: {str(e)}") - - return results, errors - - -# ===== ShowBox Scraper (nuvioapp.space API) - NEW ===== - -async def scrape_showbox(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - SHOWBOX_API = "https://febapi.nuvioapp.space/api/media" - SHOWBOX_TMDB_KEY = "439c478a771f35c05022f9feabcca01c" - - SHOWBOX_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", - "Referer": "https://showbox.6hprojin7o.com/", - } - - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=SHOWBOX_HEADERS) as client: - # ShowBox requires a uiToken cookie from the app settings - # Try without token first - some content may be accessible - ui_token = "" - - if media_type == "movie": - url = f"{SHOWBOX_API}/movie/{tmdb_id}" - if ui_token: - url += f"?cookie={ui_token}" - else: - s = season or 1 - e = episode or 1 - # For TV, need ossGroup from the movie endpoint first - base_url = f"{SHOWBOX_API}/tv/{tmdb_id}" - if ui_token: - base_url += f"?cookie={ui_token}" - - base_resp = await client.get(base_url) - oss_group = "" - - if base_resp.status_code == 200: - try: - base_data = base_resp.json() - versions = base_data.get("versions", []) - if versions and isinstance(versions, list): - first_version = versions[0] if isinstance(versions[0], dict) else {} - oss_group = first_version.get("ossGroup", "") - except Exception: - pass - - url = f"{SHOWBOX_API}/tv/{tmdb_id}/{oss_group}/{s}/{e}" - if ui_token: - url += f"?cookie={ui_token}" - - resp = await client.get(url) - - if resp.status_code == 401: - errors.append("ShowBox: Requires uiToken cookie (not available server-side)") - return results, errors - - if resp.status_code != 200: - errors.append(f"ShowBox: API failed HTTP {resp.status_code}") - return results, errors - - data = resp.json() - - # Process versions -> sources - versions = data.get("versions", []) - if not versions: - # Try direct sources - sources = data.get("sources", []) - for source in sources: - if isinstance(source, dict) and source.get("url"): - quality = source.get("quality", "Auto") - name = source.get("name", "ShowBox Stream") - s_url = source["url"] - s_type = "m3u8" if ".m3u8" in s_url else "direct" - - results.append({ - "source": "ShowBox", - "title": name, - "quality": quality, - "language": "English", - "url": s_url, - "type": s_type, - }) - - for version in versions: - if not isinstance(version, dict): - continue - - version_name = version.get("name", "Server") - sources = version.get("sources", []) - - for source in sources: - if not isinstance(source, dict): - continue - - s_url = source.get("url", "") - if not s_url: - continue - - quality = source.get("quality", "Auto") - name = source.get("name", version_name) - - if quality == "Auto": - quality = detect_quality_from_label(name) - - s_type = "m3u8" if ".m3u8" in s_url else "direct" - lang = detect_language(name) - - results.append({ - "source": f"ShowBox/{version_name}", - "title": name, - "quality": quality, - "language": lang, - "url": s_url, - "type": s_type, - }) - - if not results: - errors.append("ShowBox: No streams found") - - except Exception as e: - errors.append(f"ShowBox: {str(e)}") - - return results, errors - - -# ===== GoatAPI Scraper (goatapi workers) - NEW ===== - -async def scrape_goatapi(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - GOAT_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", - } - - # For TV shows, use a different endpoint pattern - if media_type == "tv": - s = season or 1 - e = episode or 1 - api_url = f"https://goatapi.imreallydagoatt.workers.dev/api/downloader/tv/{tmdb_id}/{s}/{e}" - else: - api_url = f"https://goatapi.imreallydagoatt.workers.dev/api/downloader/movie/{tmdb_id}" - - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=GOAT_HEADERS) as client: - resp = await client.get(api_url) - - if resp.status_code != 200: - errors.append(f"GoatAPI: API failed HTTP {resp.status_code}") - return results, errors - - data = resp.json() - - # Process streams array - streams = data.get("streams", []) - for stream in streams: - if not isinstance(stream, dict): - continue - - url = stream.get("url", "") - if not url: - continue - - name = stream.get("name", "GoatAPI Stream") - label = stream.get("label", "") - quality = "Auto" - - if label: - quality = detect_quality_from_label(label) - if quality == "Auto": - quality = detect_quality_from_label(name) - if quality == "Auto": - quality = detect_quality_from_label(url) - - s_type = "m3u8" if ".m3u8" in url else "direct" - lang = detect_language(name + " " + label) - - results.append({ - "source": "GoatAPI", - "title": label or name, - "quality": quality, - "language": lang, - "url": url, - "type": s_type, - }) - - # Process downloads array - downloads = data.get("downloads", []) - for dl in downloads: - if not isinstance(dl, dict): - continue - - dl_sources = dl.get("sources", []) - for source in dl_sources: - if not isinstance(source, dict): - continue - - url = source.get("url", "") - if not url: - continue - - name = source.get("name", dl.get("name", "GoatAPI Download")) - quality = source.get("quality", "Auto") - - if quality == "Auto": - quality = detect_quality_from_label(name + " " + url) - - s_type = "m3u8" if ".m3u8" in url else "direct" - lang = detect_language(name) - - results.append({ - "source": "GoatAPI", - "title": name, - "quality": quality, - "language": lang, - "url": url, - "type": s_type, - }) - - # 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("GoatAPI: No streams found") - - except Exception as e: - errors.append(f"GoatAPI: {str(e)}") - - return results, errors - - -# ===== v9 Scrapers (ported from All-in-One-Nuvio & MediaVanced, tested) ===== - -def _sf_stream_result(source: str, title: str, url: str, quality: str = "Auto", language: str = "English") -> dict: - return { - "source": source, - "title": title, - "quality": quality, - "language": detect_language(language) if language else "English", - "url": url, - "type": "m3u8" if ".m3u8" in url else "direct", - } - - -def _sf_norm(s: str) -> str: - return re.sub(r"[^a-z0-9]", "", (s or "").lower()) - - -# ---------- Cineby (Nuvio cineby.js): speedracelight API + custom keystream cipher ---------- - -_CB_MAGIC = b"mvm1" -_CB_GOLDEN = 0x9E3779B9 -_CB_API = "https://api.speedracelight.com" -_CB_HEADERS = { - "User-Agent": HEADERS["User-Agent"], - "Referer": "https://www.cineby.at/", - "Origin": "https://www.cineby.at", -} - - -def _cb_imul(a: int, b: int) -> int: - return (a * b) & 0xFFFFFFFF - - -def _cb_fmix32(h: int) -> int: - h &= 0xFFFFFFFF - h ^= h >> 16 - h = _cb_imul(h, 0x85EBCA6B) - h ^= h >> 13 - h = _cb_imul(h, 0xC2B2AE35) - h ^= h >> 16 - return h - - -def _cb_fnv1a32(s: str) -> int: - h = 0x811C9DC5 - for ch in s: - h = _cb_imul(h ^ ord(ch), 0x01000193) - return _cb_fmix32(h) - - -def _cb_rotl32(x: int, n: int) -> int: - n &= 31 - x &= 0xFFFFFFFF - if n == 0: - return x - return ((x << n) | (x >> (32 - n))) & 0xFFFFFFFF - - -def _cb_keystream(seed: str, media_id: int, length: int) -> bytes: - """Python port of cineby's custom keystream generator (mvm1 magic).""" - state = _cb_fmix32(_cb_fnv1a32(seed) ^ _cb_fmix32((media_id ^ _CB_GOLDEN) & 0xFFFFFFFF)) - slots = {} - for i in range(8): - idx = state % 61 - state = _cb_rotl32((state + _CB_GOLDEN) & 0xFFFFFFFF, 7 + (7 & i)) - slots[idx] = (state ^ _cb_fmix32(state)) & 0xFFFFFFFF - state = _cb_fmix32((state + idx) & 0xFFFFFFFF) - acc = _cb_fmix32((0xA5A5A5A5 ^ state) & 0xFFFFFFFF) - out = bytearray() - cnt = 0 - while len(out) < length: - idx = acc % 61 - in_slots = 0xFFFFFFFF if idx in slots else 0 - slot = slots.get(idx, 0) & 0xFFFFFFFF - a = (slot ^ _cb_imul(_CB_GOLDEN, cnt + 1)) & 0xFFFFFFFF - b = ((acc ^ a) | (acc & a & in_slots)) & 0xFFFFFFFF - c = (_cb_rotl32((b + acc) & 0xFFFFFFFF, 31 & idx) ^ _cb_rotl32(acc, 31 & _cb_imul(idx, 7))) & 0xFFFFFFFF - w = _cb_fmix32((c + _CB_GOLDEN) & 0xFFFFFFFF) - slots[idx] = w - acc = w - cnt += 1 - out.append(w & 0xFF) - if len(out) < length: out.append((w >> 8) & 0xFF) - if len(out) < length: out.append((w >> 16) & 0xFF) - if len(out) < length: out.append((w >> 24) & 0xFF) - return bytes(out) - - -def _cb_decrypt(payload_b64: str, seed: str, media_id: int) -> str: - b64 = payload_b64.replace("-", "+").replace("_", "/") - b64 += "=" * (-len(b64) % 4) - data = base64.b64decode(b64) - ks = _cb_keystream(seed, media_id, len(data)) - xored = bytes(x ^ y for x, y in zip(data, ks)) - if xored[:4] != _CB_MAGIC: - raise ValueError("bad magic (decrypt failed)") - return xored[4:].decode("utf-8", errors="ignore") - - -async def scrape_cineby(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - info = await get_tmdb_info(tmdb_id, media_type) - if not info.get("title"): - return [], ["Cineby: no TMDB title"] - - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=_CB_HEADERS) as client: - seed_resp = await client.get(f"{_CB_API}/seed", params={"mediaId": tmdb_id}) - seed = seed_resp.json().get("seed") - if not seed: - return [], ["Cineby: no seed returned"] - - params = { - "title": info["title"], - "mediaType": "tv" if media_type == "tv" else "movie", - "year": info.get("year") or "", - "episodeId": str(episode or 1), - "seasonId": str(season or 1), - "tmdbId": str(tmdb_id), - "imdbId": info.get("imdb_id") or "", - "enc": "2", - "seed": seed, - } - src_resp = await client.get(f"{_CB_API}/cdn/sources-with-title", params=params) - data = json.loads(_cb_decrypt(src_resp.text, seed, tmdb_id)) - - for src in data.get("sources", []): - url = src.get("url") - if not url: - continue - q = src.get("quality") or "Auto" - lang = src.get("lang") or src.get("language") or "English" - results.append(_sf_stream_result( - f"Cineby/{q}", f"Cineby {q} - {lang}", url, - quality=(q.upper() if isinstance(q, str) and q.endswith("p") else "Auto"), - language=lang, - )) - - if not results: - errors.append("Cineby: no streams in payload") - - except Exception as e: - errors.append(f"Cineby: {str(e)}") - - return results, errors - - -# ---------- PurStream (Nuvio purstream.js): search + sheet API ---------- - -async def scrape_purstream(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - info = await get_tmdb_info(tmdb_id, media_type) - title = info.get("title") - if not title: - return [], ["PurStream: no TMDB title"] - - headers = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://purstream.club/"} - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=headers) as client: - resp = await client.get(f"https://api.purstream.club/api/v1/search-bar/search/{quote(str(title))}") - items = resp.json().get("data", {}).get("items", {}) - candidates = [] - for key in ("movies", "tv", "series", "tvshows"): - bucket = items.get(key) or {} - sub = bucket.get("items") if isinstance(bucket, dict) else bucket - if isinstance(sub, list): - candidates.extend(sub) - - # catalog items lack tmdbId -> match by title, verify tmdbId via sheet - media_id, sheet = None, None - for item in candidates: - if _sf_norm(item.get("title")) == _sf_norm(title): - try: - probe = (await client.get( - f"https://api.purstream.club/api/v1/media/{item['id']}/sheet")).json() - if str(probe.get("data", {}).get("items", {}).get("tmdbId")) == str(tmdb_id): - media_id, sheet = item.get("id"), probe - break - except Exception: - continue - if not media_id or sheet is None: - return [], ["PurStream: title not found in catalog"] - - urls = sheet.get("data", {}).get("items", {}).get("urls", []) - if media_type == "tv": - s, e = season or 1, episode or 1 - pat = re.compile(rf"/S{s:02d}/E{e:02d}/|S{s}\.?E{e}\b", re.I) - urls = [u for u in urls if pat.search(u.get("url") or "") or pat.search(u.get("name") or "")] - - for u in urls: - url = u.get("url") - if not url: - continue - name = u.get("name") or "PurStream" - results.append(_sf_stream_result(f"PurStream/{name}", f"PurStream - {name}", url)) - - if not results: - errors.append("PurStream: no stream urls") - - except Exception as e: - errors.append(f"PurStream: {str(e)}") + streams = data.get("streams") or [] + if not isinstance(streams, list) or not streams: + # Fallback: single mp4 field + mp4 = data.get("mp4") + if mp4: + streams = [{"url": mp4, "resolution": data.get("resolution", "Auto")}] + else: + errors.append("NetMirror: no streams in response") + return results, errors + for s in streams: + if not isinstance(s, dict): + continue + u = s.get("url") + if not u: + continue + res = str(s.get("resolution") or "").strip() + quality = {"2160": "4K", "1080": "1080p", "720": "720p", "480": "480p", "360": "360p"}.get(res, res if res else "Auto") + results.append(_sf_stream_result( + "NetMirror", f"NetMirror - {quality}", u, + quality=quality, language="Multi")) + except Exception as ex: + errors.append(f"NetMirror: {str(ex)}") return results, errors -# ---------- Movix (Nuvio movix.js): api.movix.cash direct API ---------- +# ===== VidLove Scraper (api.shows.st JSON API) - v10 NEW ===== +# Ported from player.vidlove.cc frontend (replaces 111movies which redirects here) +# Live-tested: m3u8 master playlist, movie+TV -async def scrape_movix(tmdb_id: int, media_type: str, season: int = None, episode: int = None): +_VIDLOVE_API = "https://api.shows.st" + + +async def scrape_vidlove(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] - try: - headers = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://movix.cash/"} - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=headers) as client: - if media_type == "tv": - url = f"https://api.movix.cash/api/purstream/tv/{tmdb_id}/stream" - params = {"season": season or 1, "episode": episode or 1} - else: - url = f"https://api.movix.cash/api/purstream/movie/{tmdb_id}/stream" - params = {} - resp = await client.get(url, params=params) + if media_type == "tv": + url = f"{_VIDLOVE_API}/tv?id={tmdb_id}&season={season or 1}&episode={episode or 1}&mode=json" + else: + url = f"{_VIDLOVE_API}/movie?id={tmdb_id}&mode=json" + + async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client: + resp = await client.get(url, headers={ + "User-Agent": HEADERS["User-Agent"], + "Referer": "https://player.vidlove.cc/", + "Accept": "application/json, text/plain, */*", + }) + if resp.status_code != 200: + errors.append(f"VidLove: API HTTP {resp.status_code}") + return results, errors data = resp.json() - if data.get("error"): - return [], [f"Movix: {data.get('error')}"] - for src in data.get("sources", []): - surl = src.get("url") - if not surl: - continue - name = src.get("name") or "Movix" - results.append(_sf_stream_result(f"Movix/{name}", f"Movix - {name}", surl)) + src = data.get("source") or {} + stream_url = src.get("url") + if not stream_url: + errors.append("VidLove: no source url in response") + return results, errors - if not results: - errors.append("Movix: no sources") + label = src.get("label") or "VidLove" + results.append(_sf_stream_result( + "VidLove", f"VidLove - {label}", stream_url, + quality="Auto (multi-quality)", language="Multi")) + except Exception as ex: + errors.append(f"VidLove: {str(ex)}") + return results, errors - except Exception as e: - errors.append(f"Movix: {str(e)}") - return results, errors +# ===== PlayBox Scraper (streamdata.vaplayer.ru API) - v10 NEW ===== +# Ported from MediaVanced playbox.py / Nuvio playimdb.js (live-tested: m3u8 multi-quality, movie+TV) +_PLAYBOX_API = "https://streamdata.vaplayer.ru/api.php" -# ---------- HubCloud family resolver (MediaVanced hubcloud.py, generalized) ---------- -_SF_LINK_PROVIDERS = re.compile( - r'https?://[^\s"\'<>]*(?:hubcloud\.[a-z]+/(?:drive|video)/[A-Za-z0-9_\-]+' - r'|hubdrive\.[a-z]+/file/[A-Za-z0-9]+' - r'|hblinks\.[a-z]+/archives/\d+' - r'|vcloud\.[a-z]+/[A-Za-z0-9]+' - r'|nexdrive\.[a-z]+/[A-Za-z0-9]+' - r'|abhilinks\.[a-z]+/archives/\d+/?)', -) -_SF_SPORTVERSE = re.compile(r'https?://sportverse\.cc/hubcloud\.php\?[^"\'<>]+') -_SF_MOBILE_UA = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Mobile Safari/537.36" +async def scrape_playbox(tmdb_id: int, media_type: str, season: int = None, episode: int = None): + results = [] + errors = [] + try: + url = f"{_PLAYBOX_API}?tmdb={tmdb_id}&type={media_type}" + if media_type != "movie": + url += f"&season={season or 1}&episode={episode or 1}" + + async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client: + resp = await client.get(url, headers={ + "User-Agent": HEADERS["User-Agent"], + "Referer": "https://nextgencloudfabric.com", + "Origin": "https://nextgencloudfabric.com", + "Accept": "*/*", + }) + if resp.status_code != 200: + errors.append(f"PlayBox: API HTTP {resp.status_code}") + return results, errors + data = resp.json() + + urls = ((data.get("data") or {}).get("stream_urls")) or [] + if not urls: + errors.append("PlayBox: no stream urls") + return results, errors + for u in urls: + if not u or not isinstance(u, str): + continue + results.append(_sf_stream_result( + "PlayBox", "PlayBox - m3u8", u, + quality="Auto", language="Multi")) + except Exception as ex: + errors.append(f"PlayBox: {str(ex)}") + return results, errors -def _sf_extract_links(html: str) -> list: - seen, out = set(), [] - for m in _SF_LINK_PROVIDERS.finditer(html or ""): - u = m.group(0) - if u not in seen: - seen.add(u) - out.append(u) - return out +# ---------- VegaMovies (Nuvio vegamovies.js port, v10): search.php?q=imdb -> wp-json -> nexdrive -> vcloud/hubcloud ---------- +# Live-tested: direct MKV (2160p/1080p/720p) via pixeldrain + r2, movie+TV -def _sf_pixeldrain_direct(u: str) -> str: - m = re.search(r'pixeldrain\.[a-z]+/u/([A-Za-z0-9]+)', u) - if m: - return f"https://pixeldrain.com/api/file/{m.group(1)}?download" - return u +VEGA_URLS = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json" +_VEGA_DEFAULT_SITE = "https://new2.vegamovies.futbol" -async def _sf_resolve_hubcloud(client: httpx.AsyncClient, link: str) -> list: - """Resolve one hubcloud-family page into direct file URLs.""" +def _sf_b64_all(s: str) -> str: + s = s.strip() + for _ in range(2): + try: + pad = s + "=" * (-len(s) % 4) + s = base64.b64decode(pad).decode("utf-8", errors="ignore") + except Exception: + break + return s + + +async def _sf_resolve_vcloud(client: httpx.AsyncClient, vcloud_url: str, referer: str) -> list: + """Resolve a vcloud.fit page: fetch -> decode atob(atob()) token url -> fetch -> extract btn links.""" out = [] try: - if "/video/" in link or "hubvid" in link: - page = (await client.get(link)).text - sport = _SF_SPORTVERSE.search(page) - if sport: - page = (await client.get(sport.group(0), headers={"Referer": link})).text - else: - page = (await client.post(link)).text - m = re.search(r"var\s+url\s*=\s*'(https?://[^']+)'", page) - if m: - page = (await client.get(m.group(1))).text + page = (await client.get(vcloud_url, headers={ + "User-Agent": _SF_MOBILE_UA, "Referer": referer, "Cookie": "xla=s4t"})).text + # Tokenized re-entry URL (double base64) - follow it + m = re.search(r"atob\(atob\('([A-Za-z0-9+/=]+)'\)\)", page) + if m: + dec = _sf_b64_all(m.group(1)) + if dec.startswith("http"): + page2 = (await client.get(dec, headers={ + "User-Agent": _SF_MOBILE_UA, "Referer": vcloud_url, "Cookie": "xla=s4t"})).text + page = page2 + # Extract download button links for b in re.finditer(r']+href="(https?://[^"]+)"[^>]+class="[^"]*btn[^"]*"', page): u = b.group(1) chunk = page[b.start():b.start() + 800] fm = re.search(r'download="([^"]{5,110})"', chunk) - fname = fm.group(1) if fm else "" + fname = fm.group(1) if fm else "Direct" if "pixeldrain" in u: - out.append({"url": _sf_pixeldrain_direct(u), "label": fname or "Direct"}) + out.append({"url": _sf_pixeldrain_direct(u), "label": fname}) + elif "cloudflarestorage" in u or "workers.dev" in u or ".r2.dev" in u: + out.append({"url": u, "label": fname}) elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) and ".zip" not in u: - out.append({"url": u, "label": fname or "Direct"}) - elif "cloudflarestorage" in u or "workers.dev" in u: - out.append({"url": u, "label": fname or "Direct"}) + out.append({"url": u, "label": fname}) except Exception: pass return out -def _sf_quality_from_name(name: str) -> str: - low = (name or "").lower() - if "2160" in low or "4k" in low: return "4K" - if "1080" in low: return "1080p FHD" - if "720" in low: return "720p HD" - if "480" in low: return "480p SD" - return "Auto" - - -def _sf_lang_from_name(name: str) -> str: - low = (name or "").lower() - if "dual audio" in low or "multi" in low: return "Multi" - langs = [] - if "hindi" in low or "esubs" in low: langs.append("Hindi") - if "tamil" in low: langs.append("Tamil") - if "telugu" in low: langs.append("Telugu") - if "english" in low or "eng" in low: langs.append("English") - return " + ".join(langs) if langs else "English" - - -def _sf_episode_matches(label: str, season: int, episode: int) -> bool: - if not label: - return True - low = label.lower() - s_ok = re.search(rf'\bs{season:02d}e{episode:02d}\b|s{season}\.?e{episode}\b|season.{season}\b', low) - e_ok = re.search(rf'\be{episode:02d}\b|episode.{episode}\b|ep.{episode}\b|e{episode}\b', low) - season_only = re.search(rf'season.{season}\b|s{season:02d}\b|s{season}\b', low) - return bool(s_ok or (e_ok and (season_only or "season" in low)) or season_only) - - -def _sf_hubcloud_results(source_name: str, resolved: list, media_type: str, season, episode) -> list: - results = [] - seen_urls = set() - for r in resolved: - u, label = r["url"], r["label"] - if u in seen_urls: - continue - seen_urls.add(u) - if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1): - continue - results.append(_sf_stream_result( - f"{source_name}/HubCloud", f"{source_name} - {label or 'Direct'}", u, - quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label))) - return results - - -PHISHER_DOMAINS = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json" -VEGA_URLS = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json" - -_SF_HUB_HEADERS = {"User-Agent": _SF_MOBILE_UA, "Accept": "text/html,application/xhtml+xml,*/*", "Accept-Language": "en-US,en;q=0.5"} - - -# ---------- HDHub4u (Nuvio hdhub4u.js): Typesense search + hubcloud resolve ---------- - -async def scrape_hdhub4u(tmdb_id: int, media_type: str, season: int = None, episode: int = None): +async def scrape_vegamovies(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] - try: info = await get_tmdb_info(tmdb_id, media_type) - title, imdb, year = info.get("title"), info.get("imdb_id"), info.get("year") - if not title: - return [], ["HDHub4u: no TMDB title"] - - headers = {**_SF_HUB_HEADERS, "Cookie": "xla=s4t", "Referer": "https://new1.hdhub4u.cl/"} - async with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=headers) as client: - doms = (await client.get(PHISHER_DOMAINS)).json() - site = (doms.get("HDHUB4u") or "https://new5.hdhub4u.cl").rstrip("/") - search = await client.get( - "https://search.pingora.fyi/collections/post/documents/search", - params={ - "q": f"{title} {year}".strip(), - "query_by": "post_title,category", - "query_by_weights": "4,2", - "sort_by": "sort_by_date:desc", - "limit": "15", - "highlight_fields": "none", - "use_cache": "true", - "page": "1", - }) - hits = search.json().get("hits", []) - permalink = None - for h in hits: - doc = h.get("document", {}) - if doc.get("imdb_id") == imdb: - permalink = doc.get("permalink") - break - if not permalink and hits: - doc = hits[0].get("document", {}) - if _sf_norm(title) in _sf_norm(doc.get("post_title")): - permalink = doc.get("permalink") - if not permalink: - return [], ["HDHub4u: post not found"] - if not permalink.startswith("http"): - permalink = f"{site}/{permalink.lstrip('/')}" - - post_html = (await client.get(permalink)).text - links = _sf_extract_links(post_html) - expanded = [] - for lk in links[:14]: - if any(x in lk for x in ("hubdrive.", "hblinks.", "abhilinks.")): - try: - sub_html = (await client.get(lk)).text - expanded.extend(_sf_extract_links(sub_html)[:6]) - except Exception: - pass - else: - expanded.append(lk) - - seen, resolved = set(), [] - for lk in expanded: - if lk in seen: - continue - seen.add(lk) - resolved.extend(await _sf_resolve_hubcloud(client, lk)) - - results = _sf_hubcloud_results("HDHub4u", resolved, media_type, season, episode) - if not results: - errors.append("HDHub4u: no resolvable streams (hubcloud may be CF-blocked)") - - except Exception as e: - errors.append(f"HDHub4u: {str(e)}") - - return results, errors - + imdb_id = info.get("imdb_id") + if not imdb_id: + errors.append("VegaMovies: no imdb id") + return results, errors -# ---------- VegaMovies (Nuvio vegamovies.js): WP search by imdb + nexdrive/vcloud ---------- + # Resolve current domain + site = _VEGA_DEFAULT_SITE + try: + async with httpx.AsyncClient(timeout=10) as c: + cfg = (await c.get(VEGA_URLS)).json() + if isinstance(cfg, dict) and cfg.get("vegamovies"): + site = cfg["vegamovies"].rstrip("/") + except Exception: + pass -async def scrape_vegamovies(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] + async with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=_SF_HUB_HEADERS) as client: + # Step 1: search by imdb id + sr = await client.get(f"{site}/search.php", params={"q": imdb_id, "page": 1, "per_page": 15}) + if sr.status_code != 200: + errors.append(f"VegaMovies: search HTTP {sr.status_code}") + return results, errors + try: + sdata = sr.json() + except Exception: + errors.append("VegaMovies: search non-JSON") + return results, errors - try: - info = await get_tmdb_info(tmdb_id, media_type) - imdb = info.get("imdb_id") - if not imdb: - return [], ["VegaMovies: no imdb id"] + # Typesense-style response: {"found": n, "hits": [{"document": {...}}]} + hits = sdata.get("hits") or [] + posts = [h.get("document", h) if isinstance(h, dict) else h for h in hits] + if not posts: + errors.append("VegaMovies: no search results") + return results, errors - async with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=_SF_HUB_HEADERS) as client: - urls_cfg = (await client.get(VEGA_URLS)).json() - site = (urls_cfg.get("vegamovies") or "https://new2.vegamovies.futbol").rstrip("/") - search = (await client.get(f"{site}/search.php", params={"q": imdb, "page": 1, "per_page": 15})).json() - hits = search.get("hits", []) - if not hits: - return [], ["VegaMovies: not found"] - - doc = None - for h in hits: - d = h.get("document", {}) - if d.get("imdb_id") == imdb: - doc = d + # Match post by title + title_norm = _sf_norm(info.get("title") or "") + year = str(info.get("year") or "") + chosen = None + for p in posts: + if not isinstance(p, dict): + continue + pt = p.get("post_title") or p.get("title") or "" + if title_norm and title_norm in _sf_norm(pt): + chosen = p break - if not doc: - slug_frag = re.sub(r'[^a-z0-9]+', '-', (info.get("title") or "").lower()).strip('-') - for h in hits: - d = h.get("document", {}) - if slug_frag in (d.get("permalink") or "").lower(): - doc = d - break - if not doc: - return [], ["VegaMovies: no exact match for this title"] + if chosen is None and posts: + chosen = posts[0] - post = (await client.get(f"{site}/wp-json/wp/v2/posts/{doc.get('id')}")).json() - content = post.get("content", {}).get("rendered", "") - links = _sf_extract_links(content) + post_id = chosen.get("id") if isinstance(chosen, dict) else None + if not post_id: + errors.append("VegaMovies: no matching post") + return results, errors - seen, resolved = set(), [] - for lk in links[:16]: - if lk in seen: + # Step 2: fetch post content + pr = await client.get(f"{site}/wp-json/wp/v2/posts/{post_id}") + if pr.status_code != 200: + errors.append(f"VegaMovies: post HTTP {pr.status_code}") + return results, errors + content = (pr.json().get("content") or {}).get("rendered", "") + nexdrive_links = re.findall(r'https?://nexdrive\.[a-z]+/[a-z0-9]+/[a-zA-Z0-9]+/?', content) + hubcloud_links = re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', content) + if not nexdrive_links and not hubcloud_links: + # Broad fallback: any locker link in content + nexdrive_links = re.findall(r'https?://[^\s"\'<>]*(?:vcloud|nexdrive|dgdrive|fastdl)\.[a-z]+/[^\s"\'<>]{4,60}', content) + + resolved = [] + for hl in hubcloud_links[:4]: + resolved.extend(await _sf_resolve_hubcloud(client, hl)) + for nl in nexdrive_links[:5]: + if len(resolved) >= 10: + break + try: + np = (await client.get(nl, headers={ + "User-Agent": _SF_MOBILE_UA, "Referer": f"{site}/"})).text + except Exception: continue - seen.add(lk) - resolved.extend(await _sf_resolve_hubcloud(client, lk)) - - results = _sf_hubcloud_results("VegaMovies", resolved, media_type, season, episode) + # hubcloud links inside nexdrive page + for hl in re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', np)[:2]: + resolved.extend(await _sf_resolve_hubcloud(client, hl)) + # vcloud links inside nexdrive page (2 fastest: usually 1080p/720p first) + vc_refs = list(dict.fromkeys(re.findall(r'https?://vcloud\.[a-z]+/[a-zA-Z0-9]+', np)))[:2] + for vl in vc_refs: + resolved.extend(await _sf_resolve_vcloud(client, vl, str(nl))) + + results.extend(_sf_hubcloud_results("VegaMovies", resolved, media_type, season, episode)) if not results: - errors.append("VegaMovies: no resolvable streams (hubcloud may be CF-blocked)") + errors.append("VegaMovies: no resolvable streams") + except Exception as ex: + errors.append(f"VegaMovies: {str(ex)}") + return results, errors - except Exception as e: - errors.append(f"VegaMovies: {str(e)}") - return results, errors +# ---------- MoviesHunt (Nuvio movieshunt.js port, v10): WP search -> post -> abhilinks -> hubcloud ---------- +# Live-tested: direct MKV via pixeldrain, movie+TV +_MH_SITES = ["https://movieshunt.casa", "https://movieshunt.run"] -# ---------- Movies4u (Nuvio movies4u.js): WP + m4uplay + hubcloud ---------- -async def scrape_movies4u(tmdb_id: int, media_type: str, season: int = None, episode: int = None): +async def scrape_movieshunt(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] - try: info = await get_tmdb_info(tmdb_id, media_type) - title = info.get("title") + title = info.get("title") or "" + imdb_id = info.get("imdb_id") if not title: - return [], ["Movies4u: no TMDB title"] + errors.append("MoviesHunt: no title") + return results, errors + q = title.replace(" ", "+") async with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=_SF_HUB_HEADERS) as client: - doms = (await client.get(PHISHER_DOMAINS)).json() - site = (doms.get("movies4u") or "https://new5.movies4u.clinic").rstrip("/") - search_html = (await client.get(f"{site}/", params={"s": title})).text - posts = re.findall(r'href="(https?://[^"]*movies4u[^"]*/[^"/]+/)"', search_html) - slug_frag = re.sub(r'[^a-z0-9]+', '-', title.lower()).strip('-') - post_url = next((p for p in posts if slug_frag in p.lower()), None) - if not post_url and posts: - post_url = posts[0] - if not post_url: - return [], ["Movies4u: post not found"] - - post_html = (await client.get(post_url)).text - m4uplay_links = re.findall(r'https?://m4uplay\.[a-z]+/file/[A-Za-z0-9]+', post_html) - links = list(m4uplay_links) + _sf_extract_links(post_html) - - seen, resolved = set(), [] - for lk in links[:16]: - if lk in seen: + post_url = None + for site in _MH_SITES: + try: + sr = await client.get(f"{site}/", params={"s": q}) + if sr.status_code != 200: + continue + post_links = re.findall( + rf'href="({re.escape(site)}/[a-z0-9-]{{10,140}}/?)"', + sr.text) + post_links = [p for p in post_links if not re.search(r'(disclaimer|contact|how-to|request|find-movie|dmca|privacy|about|page/)', p)] + if post_links: + post_url = post_links[0] + break + except Exception: continue - seen.add(lk) - if "m4uplay." in lk: - try: - player_html = (await client.get(lk)).text - for nl in re.findall(r'https?://m4ulinks\.[a-z]+/number/\d+', player_html)[:4]: - num_html = (await client.get(nl)).text - for hl in _sf_extract_links(num_html)[:6]: - if hl not in seen: - seen.add(hl) - resolved.extend(await _sf_resolve_hubcloud(client, hl)) - except Exception: - pass - elif any(x in lk for x in ("hubcloud.", "hubdrive.", "vcloud.", "hblinks.", "abhilinks.")): - resolved.extend(await _sf_resolve_hubcloud(client, lk)) - - results = _sf_hubcloud_results("Movies4u", resolved, media_type, season, episode) - if not results: - errors.append("Movies4u: no resolvable streams (hubcloud may be CF-blocked)") - - except Exception as e: - errors.append(f"Movies4u: {str(e)}") - - return results, errors - -# ---------- MoviesHunt (Nuvio movieshunt.js): WP + abhilinks + hubvid proxy ---------- + if not post_url: + errors.append("MoviesHunt: no matching post") + return results, errors -async def scrape_movieshunt(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] + pr = await client.get(post_url) + content = pr.text - try: - info = await get_tmdb_info(tmdb_id, media_type) - title = info.get("title") - if not title: - return [], ["MoviesHunt: no TMDB title"] + # abhilinks archive links (episode/movie pages) + abhi_links = re.findall(r'https?://abhilinks\.site/archives/[a-z0-9]+/?', content) + # direct hubcloud links + hc_links = re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', content) - async with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=_SF_HUB_HEADERS) as client: - search_html = (await client.get("https://movieshunt.run/", params={"s": title})).text - posts = list(dict.fromkeys(re.findall(r'href="(https?://movieshunt\.[a-z]+/[^"/]+/)"', search_html))) - if not posts: - return [], ["MoviesHunt: no posts found"] + resolved = [] + for hl in hc_links[:8]: + resolved.extend(await _sf_resolve_hubcloud(client, hl)) - links = [] - for p in posts[:3]: + for al in list(dict.fromkeys(abhi_links))[:6]: + if len(resolved) >= 8: + break try: - links.extend(_sf_extract_links((await client.get(p)).text)) + ar = await client.get(al, headers={"User-Agent": _SF_MOBILE_UA, "Referer": post_url}) except Exception: continue - if not links: - return [], ["MoviesHunt: no links in posts"] + ahc = re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', ar.text) + for hl in ahc[:3]: + resolved.extend(await _sf_resolve_hubcloud(client, hl)) - seen, resolved = set(), [] - for lk in links[:14]: - if lk in seen: - continue - seen.add(lk) - if any(x in lk for x in ("abhilinks.", "hubdrive.", "hblinks.")): - try: - sub_html = (await client.get(lk)).text - for hl in _sf_extract_links(sub_html)[:8]: - if hl not in seen: - seen.add(hl) - resolved.extend(await _sf_resolve_hubcloud(client, hl)) - except Exception: - pass - else: - resolved.extend(await _sf_resolve_hubcloud(client, lk)) - - results = _sf_hubcloud_results("MoviesHunt", resolved, media_type, season, episode) + results.extend(_sf_hubcloud_results("MoviesHunt", resolved, media_type, season, episode)) if not results: errors.append("MoviesHunt: no resolvable streams") - - except Exception as e: - errors.append(f"MoviesHunt: {str(e)}") - + except Exception as ex: + errors.append(f"MoviesHunt: {str(ex)}") return results, errors # ===== Source Map ===== SOURCE_MAP = { - "vidrock": {"name": "VidRock", "fn": lambda tid, mt, s, e: scrape_vidrock(tid, mt, s, e), - "languages": ["English"], "reliability": "high"}, "castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e), - "languages": ["English", "Hindi", "Multi"], "reliability": "medium", - "note": "hlowb.com API with AES-CBC encryption, channel IndiaA"}, - "moviebox": {"name": "MovieBox", "fn": lambda tid, mt, s, e: scrape_moviebox(tid, mt, s, e), - "languages": ["Hindi", "English", "Multi"], "reliability": "high", - "note": "themoviebox.org API with detailPath support"}, - "allmovieland": {"name": "AllMovieLand", "fn": lambda tid, mt, s, e: scrape_allmovieland(tid, mt, s, e), - "languages": ["Hindi", "Tamil", "Telugu", "English", "Multi"], "reliability": "medium"}, + "languages": ["English", "Tamil", "Telugu"], "reliability": "high", + "note": "hlowb.com API, AES-CBC, multi-language m3u8 (EN/Tamil/Telugu), fixed languageId flow"}, "netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e), - "languages": ["Hindi", "English", "Multi"], "reliability": "high"}, - "videasy": {"name": "Videasy", "fn": lambda tid, mt, s, e: scrape_videasy(tid, mt, s, e), - "languages": ["English", "Multi"], "reliability": "medium"}, - "vidsrc": {"name": "VidSrc", "fn": lambda tid, mt, s, e: scrape_vidsrc(tid, mt, s, e), - "languages": ["English"], "reliability": "medium", - "note": "vsrc.su + cloudnestra via enc-dec.app decryption"}, - "vidlink": {"name": "VidLink", "fn": lambda tid, mt, s, e: scrape_vidlink(tid, mt, s, e), - "languages": ["English"], "reliability": "medium", - "note": "vidlink.pro with encrypted TMDB ID via enc-dec.app"}, - "m4uhd": {"name": "M4UHD", "fn": lambda tid, mt, s, e: scrape_m4uhd(tid, mt, s, e), - "languages": ["English", "Hindi", "Multi"], "reliability": "medium"}, - "vidfast": {"name": "VidFast", "fn": lambda tid, mt, s, e: scrape_vidfast(tid, mt, s, e), - "languages": ["English"], "reliability": "medium", - "note": "vidfast.pro with encrypted TMDB ID via enc-dec.app"}, - "showbox": {"name": "ShowBox", "fn": lambda tid, mt, s, e: scrape_showbox(tid, mt, s, e), - "languages": ["English", "Hindi", "Multi"], "reliability": "low", - "note": "Requires uiToken cookie for full access, limited without it"}, - "goatapi": {"name": "GoatAPI", "fn": lambda tid, mt, s, e: scrape_goatapi(tid, mt, s, e), - "languages": ["English"], "reliability": "medium", - "note": "TMDB ID only, no IMDB support"}, - # ===== v9 additions (ported from All-in-One-Nuvio + MediaVanced, live-tested) ===== - "cineby": {"name": "Cineby", "fn": lambda tid, mt, s, e: scrape_cineby(tid, mt, s, e), - "languages": ["English", "Multi"], "reliability": "high", - "note": "speedracelight API with custom keystream cipher (mvm1), up to 4K m3u8"}, - "purstream": {"name": "PurStream", "fn": lambda tid, mt, s, e: scrape_purstream(tid, mt, s, e), - "languages": ["English", "Multi"], "reliability": "high", - "note": "purstream.club search+sheet API, m3u8, episodes supported"}, + "languages": ["Hindi", "English", "Multi"], "reliability": "high", + "note": "net27.cc embed-tmdb API, direct mp4 360p-1080p, TMDB id based, movie+TV"}, + "vidlove": {"name": "VidLove", "fn": lambda tid, mt, s, e: scrape_vidlove(tid, mt, s, e), + "languages": ["English", "Multi"], "reliability": "high", + "note": "api.shows.st JSON API, m3u8 master multi-quality, replaces dead 111movies"}, + "playbox": {"name": "PlayBox", "fn": lambda tid, mt, s, e: scrape_playbox(tid, mt, s, e), + "languages": ["English", "Multi"], "reliability": "high", + "note": "streamdata.vaplayer.ru API, multi-quality m3u8, TMDB id based"}, "movix": {"name": "Movix", "fn": lambda tid, mt, s, e: scrape_movix(tid, mt, s, e), "languages": ["English", "Multi"], "reliability": "high", "note": "api.movix.cash direct API, m3u8 1080p"}, + "purstream": {"name": "PurStream", "fn": lambda tid, mt, s, e: scrape_purstream(tid, mt, s, e), + "languages": ["English", "Multi"], "reliability": "high", + "note": "purstream.club search+sheet API, m3u8, episodes supported"}, "movieshunt": {"name": "MoviesHunt", "fn": lambda tid, mt, s, e: scrape_movieshunt(tid, mt, s, e), "languages": ["Hindi", "English", "Multi"], "reliability": "medium", - "note": "WP + abhilinks + hubvid proxy, direct MKV via pixeldrain, best for movies"}, - "hdhub4u": {"name": "HDHub4u", "fn": lambda tid, mt, s, e: scrape_hdhub4u(tid, mt, s, e), - "languages": ["Hindi", "English", "Multi"], "reliability": "low", - "note": "Typesense search + hubcloud resolver, direct MKV up to 4K; depends on Cloudflare not challenging server IP"}, + "note": "WP search (movieshunt.casa) + abhilinks + hubcloud, direct MKV via pixeldrain/r2"}, "vegamovies": {"name": "VegaMovies", "fn": lambda tid, mt, s, e: scrape_vegamovies(tid, mt, s, e), - "languages": ["Hindi", "English", "Multi"], "reliability": "low", - "note": "WP search by IMDB + nexdrive/vcloud resolver; depends on Cloudflare not challenging server IP"}, - "movies4u": {"name": "Movies4u", "fn": lambda tid, mt, s, e: scrape_movies4u(tid, mt, s, e), - "languages": ["Hindi", "English", "Multi"], "reliability": "low", - "note": "WP + m4uplay + hubcloud resolver; depends on Cloudflare not challenging server IP"}, + "languages": ["Hindi", "English", "Multi"], "reliability": "medium", + "note": "search.php?q=imdb + nexdrive + vcloud chain, direct MKV up to 4K"}, } -DEFAULT_SOURCES = ["cineby", "movix"] - +DEFAULT_SOURCES = ["castle", "netmirror", "vidlove", "playbox", "movix"] # ===== Helper: Run scrapers ===== @@ -3187,76 +1141,55 @@ async def run_scrape(tmdb_id: int, media_type: str, season: int = None, episode: async def root(): return { "api": "StreamForge", - "version": "9.0.0", - "description": "Multi-language m3u8 stream scraper", + "version": "10.0.0", + "description": "Multi-language m3u8/mp4/MKV stream scraper", "endpoints": { - "movie": { - "all_sources": "/movie/{tmdb_id}", - "single_source": "/movie/{tmdb_id}/{source}", - "example": "/movie/912649", - "example_source": "/movie/912649/castle", - }, - "tv": { - "all_sources": "/tv/{tmdb_id}/{season}/{episode}", - "single_source": "/tv/{tmdb_id}/{season}/{episode}/{source}", - "example": "/tv/1396/1/1", - "example_source": "/tv/1396/1/1/vidlink", - }, - "search": { - "path": "/search/{query}", - "example": "/search/Venom", - }, - "api_endpoints": { - "health": "GET /api/health", - "sources": "GET /api/sources", - "search": "GET /api/search?q={query}", - "scrape": "POST /api/scrape", - "scrape_all": "POST /api/scrape/all", - }, + "movie": {"all_sources": "/movie/{tmdb_id}", "single_source": "/movie/{tmdb_id}/{source}", + "example": "/movie/912649", "example_source": "/movie/912649/castle"}, + "tv": {"all_sources": "/tv/{tmdb_id}/{season}/{episode}", "single_source": "/tv/{tmdb_id}/{season}/{episode}/{source}", + "example": "/tv/1396/1/1", "example_source": "/tv/1396/1/1/netmirror"}, + "search": {"path": "/search/{query}", "example": "/search/Venom"}, + "api_endpoints": {"health": "GET /api/health", "sources": "GET /api/sources", "search": "GET /api/search?q={query}", + "scrape": "POST /api/scrape", "scrape_all": "POST /api/scrape/all"}, }, - "sources": {key: {"name": src["name"], "languages": src["languages"], "reliability": src["reliability"], - **({"note": src["note"]} if "note" in src else {})} - for key, src in SOURCE_MAP.items()}, + "sources": {k: {kk: vv for kk, vv in v.items() if kk != "fn"} for k, v in SOURCE_MAP.items()}, "default_sources": DEFAULT_SOURCES, - "changelog_v8": { - "updated": ["MovieBox (themoviebox.org, detailPath)", "Castle (IndiaA channel, getVideo2)", - "VidLink (enc-dec.app)", "VidSrc (cloudnestra approach)", "NetMirror (TMDB key)"], - "added": ["VidFast", "ShowBox", "GoatAPI"], - "removed": ["CineSu (dead/404)", "PrimeSrc (Cloudflare blocked)", "DooFlix (API key revoked)", - "VixSrc (Cloudflare blocked)"], - }, - "changelog_v9": { - "added": ["Cineby (m3u8 up to 4K, movie+TV, keystream cipher port)", - "PurStream (m3u8, movie+TV episodes; API blocks HF IPs - works elsewhere)", - "Movix (m3u8 1080p, movie+TV)", - "MoviesHunt (direct MKV via pixeldrain, Hindi movies)", - "HDHub4u (direct MKV up to 4K, Hindi, hubcloud resolver)", - "VegaMovies (direct MKV, Hindi, nexdrive/vcloud resolver)", - "Movies4u (direct MKV, Hindi, m4uplay+hubcloud resolver)"], - "note_on_legacy_sources": "As of v9, ALL v8 sources (vidrock, castle, moviebox, netmirror, videasy, vidsrc, vidlink, m4uhd, vidfast, showbox, goatapi) were audited live and returned 0 streams (dead domains, changed APIs, or HF IP blocks). They remain registered for explicit calls but were removed from DEFAULT_SOURCES. Cineby/Movix are the verified working defaults.", - "tested_rejected": ["SpencerDevs (domain dead)", "NHDApi (origin down 522)", - "111Movies (SPA rewrite, no SSR data)", "MegaPlay (geo-shell to server IPs)", - "CinemaOS (API changed)", "VidZee (API changed)", "CineVibe (env-locked token)", - "VidPlus (origin down)", "PlayImdb (API unreliable)", - "Torrentio (magnet links, not m3u8/direct)"], - "source_repos": ["github.com/D3adlyRocket/All-in-One-Nuvio", "github.com/yogesh-hacker/MediaVanced"], + "changelog_v10": { + "updated": [ + "Castle - fixed getVideo2 (appMarket=GuanWang, languageId 1003/1033/1037) -> multi-language m3u8 restored", + "NetMirror - rewritten on net27.cc embed-tmdb (TMDB-id based, mp4 360p-1080p, movie+TV)", + "MoviesHunt - new domains (movieshunt.casa) + abhilinks + hubcloud.cx resolver, verified MKV via pixeldrain", + "VegaMovies - new flow (search.php?q=imdb -> wp-json -> nexdrive -> vcloud token chain), up to 4K MKV", + ], + "added": [ + "VidLove - api.shows.st, m3u8 master multi-quality, movie+TV (replaces dead 111movies)", + "PlayBox - streamdata.vaplayer.ru, multi-quality m3u8, movie+TV", + ], + "kept": ["Movix", "PurStream (verified still working)"], + "removed": { + "Cineby": "shutting down (user request)", + "Videasy": "cineby-owned (user request)", + "VidRock": "dead (vidrock.net 403, vidrock.ru timeout)", + "MovieBox": "API removed (themoviebox.org -> HTML, fmoviesunblocked 404)", + "AllMovieLand": "HTTP 403 (Cloudflare)", + "VidLink": "no playlist in response (dead)", + "VidSrc": "cloudnestra flow broken", + "M4UHD": "m4uhd.vip Cloudflare 403", + "VidFast": "worker route config stale vs site rebuild", + "ShowBox": "febbox.com DNS dead", + "GoatAPI": "empty responses", + "HDHub4u": "DNS dead", + "Movies4u": "m4uplay player fully string-obfuscated, unverifiable", + }, }, + "source_repos": ["github.com/D3adlyRocket/All-in-One-Nuvio", "github.com/yogesh-hacker/MediaVanced"], "tips": [ - "No source = default sources (cineby, movix) - the verified-working set. Pass ?sources= or POST /api/scrape with sources list for more", - "Best for Hindi: /movie/ID/allmovieland or /movie/ID/moviebox or /movie/ID/castle or /movie/ID/cineby", - "Best for English: /movie/ID/vidrock or /movie/ID/vidlink or /movie/ID/vidfast or /movie/ID/cineby", - "Cineby: up to 4K m3u8, custom keystream decrypt (mvm1), movie+TV", - "PurStream/Movix: same CDN backend (finepulfe.xyz), m3u8, episodes supported", - "MoviesHunt/HDHub4u/VegaMovies/Movies4u: direct MKV downloads (Hindi), hubcloud-family resolvers", - "HubCloud-family sources may fail when Cloudflare challenges the server IP (retry later)", - "Castle: hlowb.com API with AES-CBC encryption, channel IndiaA, multi-language + multi-quality", - "NetMirror: Searches Netflix, PrimeVideo, Hotstar via API - great for Hindi/English", - "VidLink/VidFast: Use enc-dec.app for ID encryption, supports M3U8 quality variants", - "VidSrc: vsrc.su + cloudnestra.com decryption via enc-dec.app", - "M4UHD: m4uhd.vip with CryptoJS-compatible AES-CBC (EVP_BytesToKey key derivation)", - "ShowBox: Requires uiToken for full access - limited without it", - "GoatAPI: TMDB ID only, returns streams + downloads arrays", - "m3u8 links work in VLC, mpv, or any HLS player", + "No source = default sources (castle, netmirror, vidlove, playbox, movix) - the verified-working set", + "Castle: multi-language m3u8 (English/Tamil/Telugu), best for new Bollywood/Hollywood", + "NetMirror: instant mp4 links 360p-1080p, movie+TV, TMDB id based", + "VidLove/PlayBox/Movix: m3u8, work for both movie and TV", + "MoviesHunt/VegaMovies: direct MKV downloads (Hindi multi-audio), movies+TV packs", + "Direct MKV links work in VLC/mpv; m3u8 works in any HLS player", ], }