diff --git "a/main.py" "b/main.py" --- "a/main.py" +++ "b/main.py" @@ -1,6 +1,9 @@ """ -StreamForge API v7 - Multi-Language Stream Scraper +StreamForge API v8 - Multi-Language Stream Scraper Scrapes direct m3u8 URLs from multiple sources +Updated: MovieBox, Castle, VidLink, VidSrc, NetMirror +Added: VidFast, ShowBox, GoatAPI +Removed: CineSu (dead), PrimeSrc (Cloudflare), DooFlix (API key revoked) """ from fastapi import FastAPI, HTTPException, Query @@ -18,7 +21,7 @@ import hashlib app = FastAPI( title="StreamForge API", description="Multi-language m3u8 stream scraper", - version="7.0.0", + version="8.0.0", ) app.add_middleware( @@ -66,6 +69,21 @@ async def get_tmdb_info(tmdb_id: int, media_type: str) -> dict: } +async def get_tmdb_info_with_key(tmdb_id: int, media_type: str, api_key: str) -> dict: + async with httpx.AsyncClient(timeout=10) as client: + type_path = "tv" if media_type == "tv" else "movie" + resp = await client.get( + f"{TMDB_BASE}/{type_path}/{tmdb_id}", + params={"api_key": api_key, "append_to_response": "external_ids"} + ) + data = resp.json() + return { + "imdb_id": data.get("external_ids", {}).get("imdb_id"), + "title": data.get("title") or data.get("name"), + "year": (data.get("release_date") or data.get("first_air_date") or "")[:4], + } + + def detect_language(label: str) -> str: lower = label.lower() if "hindi" in lower or "hin" in lower: return "Hindi" @@ -110,226 +128,59 @@ def cryptojs_aes_decrypt(ciphertext_b64: str, passphrase: str) -> str: return unpad(cipher.decrypt(ct), AES.block_size).decode("utf-8", errors="ignore") -def castle_aes_decrypt(ciphertext_b64: str, key_str: str) -> str: - """AES-CBC decrypt for Castle (hlowb.com) API responses.""" - from Crypto.Cipher import AES - from Crypto.Util.Padding import unpad - - aes_key = (key_str + "T!BgJB")[:16].encode("utf-8") - aes_iv = aes_key # IV = same as key - raw = base64.b64decode(ciphertext_b64) - cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) - return unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") - - -# ===== CineSu Scraper ===== - -async def scrape_cinesu(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client: - if media_type == "movie": - url = f"https://cine.su/v1/stream/master/movie/{tmdb_id}.m3u8" - else: - s = season or 1 - e = episode or 1 - url = f"https://cine.su/v1/stream/master/tv/{tmdb_id}/{s}/{e}.m3u8" - - resp = await client.get(url, headers={ - "Referer": "https://cine.su/en/watch", - "Origin": "https://cine.su", - }) - - if resp.status_code == 404: - errors.append("CineSu: Content not available") - return results, errors - - if resp.status_code != 200: - errors.append(f"CineSu: HTTP {resp.status_code}") - return results, errors - - content = resp.text - if "#EXT-X-STREAM-INF" in content: - lines = content.split("\n") - for i, line in enumerate(lines): - if line.startswith("#EXT-X-STREAM-INF:"): - resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) - name = re.search(r'NAME="([^"]+)"', line) - quality = resolution.group(1) if resolution else "Auto" - label = name.group(1) if name else quality - if i + 1 < len(lines) and lines[i + 1].startswith("http"): - results.append({ - "source": "CineSu", - "title": label, - "quality": quality, - "language": "English", - "url": lines[i + 1].strip(), - "type": "m3u8", - }) - elif ".m3u8" in content: - m3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', content) - if m3u8_match: - results.append({ - "source": "CineSu", - "title": "English Stream", - "quality": "Auto", - "language": "English", - "url": m3u8_match.group(0), - "type": "m3u8", - }) - - if not results: - errors.append("CineSu: No streams found") - - except Exception as e: - errors.append(f"CineSu: {str(e)}") - - return results, errors - - -# ===== VixSrc Scraper ===== - -async def scrape_vixsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: - if media_type == "movie": - api_url = f"https://vixsrc.to/api/movie/{tmdb_id}" - else: - s = season or 1 - e = episode or 1 - api_url = f"https://vixsrc.to/api/tv/{tmdb_id}/{s}/{e}" - - api_resp = await client.get(api_url) - - try: - api_data = api_resp.json() - except: - errors.append("VixSrc: API returned non-JSON (possible Cloudflare block)") - return results, errors - - src_path = api_data.get("src", "") - if not src_path: - errors.append("VixSrc: No embed path returned") - return results, errors - - embed_resp = await client.get(f"https://vixsrc.to{src_path}") - - if embed_resp.status_code == 410: - api_resp2 = await client.get(api_url) - try: - api_data2 = api_resp2.json() - except: - errors.append("VixSrc: API retry failed") - return results, errors - src_path2 = api_data2.get("src", "") - if not src_path2: - errors.append("VixSrc: No embed path on retry") - return results, errors - embed_resp = await client.get(f"https://vixsrc.to{src_path2}") - src_path = src_path2 - - html = embed_resp.text - - token = None - expires = None - playlist_url = None - - mp_match = re.search(r'window\.masterPlaylist\s*=\s*(\{[\s\S]*?\})\s*\n', html) - if mp_match: - mp_text = mp_match.group(1) - token_m = re.search(r"'token'\s*:\s*'([^']+)'", mp_text) - expires_m = re.search(r"'expires'\s*:\s*'([^']+)'", mp_text) - url_m = re.search(r"url\s*:\s*'([^']+)'", mp_text) - - if token_m: token = token_m.group(1) - if expires_m: expires = expires_m.group(1) - if url_m: playlist_url = url_m.group(1) - - if not token: - token_match = re.search(r'token["\']\s*:\s*["\']([^"\']+)', html) - if token_match: token = token_match.group(1) - if not playlist_url: - url_match = re.search(r'url\s*:\s*["\']([^"\']+playlist[^"\']*)', html) - if url_match: playlist_url = url_match.group(1) - - if not (token and playlist_url): - errors.append("VixSrc: Could not extract stream parameters from embed") - return results, errors - - if not expires: - expires = str(int(time.time()) + 86400) - sep = "&" if "?" in playlist_url else "?" - master_url = f"{playlist_url}{sep}token={token}&expires={expires}&h=1" - - pl_resp = await client.get(master_url, headers={"Referer": f"https://vixsrc.to{src_path}"}) - pl_content = pl_resp.text - - if "#EXTM3U" in pl_content: - audio_tracks = [] - lines = pl_content.split("\n") - for line in lines: - if line.startswith("#EXT-X-MEDIA:TYPE=AUDIO"): - name_match = re.search(r'NAME="([^"]+)"', line) - lang_match = re.search(r'LANGUAGE="([^"]+)"', line) - uri_match = re.search(r'URI="([^"]+)"', line) - if name_match and uri_match: - audio_tracks.append({ - "language": name_match.group(1), - "lang_code": lang_match.group(1) if lang_match else name_match.group(1), - "uri": uri_match.group(1), - }) - - for i, line in enumerate(lines): - if line.startswith("#EXT-X-STREAM-INF:"): - resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) - quality = resolution.group(1) if resolution else "Auto" - if i + 1 < len(lines) and lines[i + 1].startswith("http"): - video_url = lines[i + 1].strip() - if audio_tracks: - for track in audio_tracks: - results.append({ - "source": "VixSrc", - "title": f"{track['language']} Audio", - "quality": quality, - "language": detect_language(track["language"]), - "url": video_url, - "audio_url": track["uri"], - "type": "m3u8", - }) - else: - results.append({ - "source": "VixSrc", - "title": "English Stream", - "quality": quality, - "language": "English", - "url": video_url, - "type": "m3u8", - }) - else: - results.append({ - "source": "VixSrc", - "title": "Stream", - "quality": "Auto", - "language": "Multi", - "url": master_url, - "type": "m3u8", - }) - - if not results: - errors.append("VixSrc: No streams found in playlist") - - except Exception as e: - errors.append(f"VixSrc: {str(e)}") - - return results, errors +def normalize_title(title: str) -> str: + """Normalize title by removing brackets, (Dub), (HD), etc.""" + cleaned = re.sub(r'\[[^\]]*\]', '', title) + cleaned = re.sub(r'\((?:Dub|HD|Cam|TS|HDRip|BRRip|DVDRip|WEBRip|WEB-DL)\)', '', cleaned, flags=re.IGNORECASE) + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + return cleaned + + +def extract_language_from_title(title: str) -> str: + """Extract language from title brackets like [Hindi], [Tamil] etc.""" + bracket_match = re.search(r'\[([^\]]+)\]', title) + if bracket_match: + lang_text = bracket_match.group(1) + detected = detect_language(lang_text) + if detected != "English" or lang_text.lower() == "english": + return detected + 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" -# ===== VidRock Scraper (AES-encrypted API) ===== +# ===== VidRock Scraper (AES-encrypted API) - KEEP AS-IS ===== async def scrape_vidrock(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] @@ -390,101 +241,7 @@ async def scrape_vidrock(tmdb_id: int, media_type: str, season: int = None, epis return results, errors -# ===== DooFlix Scraper (Hindi/Indian content - API based) ===== - -async def scrape_dooflix(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - async with httpx.AsyncClient(timeout=15, follow_redirects=False) as client: - BASE_API = "https://panel.watchkaroabhi.com" - API_KEY = "qNhKLJiZVyoKdi9NCQGz8CIGrpUijujE" - - dooflix_headers = { - "X-Package-Name": "com.king.moja", - "User-Agent": "dooflix", - "X-App-Version": "305", - } - STREAM_REFERER = "https://molop.art/" - - if media_type == "movie": - url = f"{BASE_API}/api/3/movie/{tmdb_id}/links?api_key={API_KEY}" - else: - s = season or 1 - e = episode or 1 - url = f"{BASE_API}/api/3/tv/{tmdb_id}/season/{s}/episode/{e}/links?api_key={API_KEY}" - - resp = await client.get(url, headers=dooflix_headers) - if resp.status_code != 200: - errors.append(f"DooFlix: API error HTTP {resp.status_code}") - return results, errors - - data = resp.json() - links = data.get("links", []) - - if not links: - errors.append("DooFlix: No links found") - return results, errors - - for link_obj in links: - try: - link_url = link_obj.get("url", "") - host = link_obj.get("host", "Server") - if not link_url: - continue - - redir_resp = await client.get( - link_url, - headers={ - "Referer": STREAM_REFERER, - "User-Agent": "dooflix", - }, - ) - - stream_url = None - if redir_resp.status_code in (301, 302, 303, 307, 308): - stream_url = redir_resp.headers.get("location", "") - elif redir_resp.status_code == 200: - stream_url = link_url - else: - stream_url = redir_resp.headers.get("location", link_url) - - if not stream_url: - continue - - s_type = "m3u8" if ".m3u8" in stream_url else "direct" - quality = "Auto" - q_match = re.search(r'(\d{3,4})p', stream_url) - if q_match: - quality = q_match.group(1) + "p" - - results.append({ - "source": f"DooFlix/{host}", - "title": f"DooFlix - {host}", - "quality": quality, - "language": "Hindi", - "url": stream_url, - "type": s_type, - "headers": { - "Referer": STREAM_REFERER, - "User-Agent": "dooflix", - }, - }) - - except Exception as e: - errors.append(f"DooFlix/{host}: {str(e)}") - - if not results: - errors.append("DooFlix: No streams resolved") - - except Exception as e: - errors.append(f"DooFlix: {str(e)}") - - return results, errors - - -# ===== Castle Scraper (hlowb.com API with AES-CBC) ===== +# ===== Castle Scraper (hlowb.com API with AES-CBC) - COMPLETE REWRITE ===== async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] @@ -501,92 +258,157 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo return results, errors CASTLE_BASE = "https://api.hlowb.com" - PKG = "com.gwzq.clz" - CH = "1" + PKG = "com.external.castle" + CH = "IndiaA" CLI = "1" LANG = "en-US" SIGN = "ED0955EB04E67A1D9F3305B95454FED485261475" - HEADERS = {"User-Agent": "okhttp/4.9.3", "Accept": "application/json", "Accept-Language": "en-US"} - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: - # Get security key - sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/{CH}?clientType={CLI}&lang={LANG}") + CASTLE_HEADERS = { + "User-Agent": "okhttp/4.9.3", + "Accept": "application/json", + "Accept-Language": "en-US,en;q=0.9", + "Connection": "Keep-Alive", + "Referer": "https://api.hlowb.com", + } + + async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client: + # Step 1: Get security key + sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1", params={ + "channel": CH, "clientType": CLI, "lang": LANG + }) if sec_r.status_code != 200: errors.append(f"Castle: sec key HTTP {sec_r.status_code}") return results, errors + sec_j = sec_r.json() raw_k = sec_j.get("data", "") if not raw_k or not isinstance(raw_k, str): - errors.append("Castle: bad sec key") + errors.append("Castle: bad sec key response") return results, errors + + # The security key may be base64-encoded or plain text try: sec_key = base64.b64decode(raw_k).decode("utf-8", errors="ignore") - except: + except Exception: sec_key = raw_k + # AES decryption: key = first 16 chars of (sec_key + "T!BgJB"), IV = same combined = (sec_key + "T!BgJB") aes_k = (combined + "\x00" * max(0, 16 - len(combined)))[:16].encode("utf-8") aes_iv = aes_k - def cdec(text): + def castle_decrypt(text): + """Decrypt Castle API response.""" d = text try: j = json.loads(text) if isinstance(j, dict) and isinstance(j.get("data"), str): d = j["data"] - except: + except Exception: + pass + + # Try base64 decode first + try: + raw = base64.b64decode(d) + c = AES.new(aes_k, AES.MODE_CBC, aes_iv) + dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") + return json.loads(dec) + except Exception: + pass + + # Try hex decode + try: + raw = bytes.fromhex(d) + c = AES.new(aes_k, AES.MODE_CBC, aes_iv) + dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") + return json.loads(dec) + except Exception: pass - raw = base64.b64decode(d) - c = AES.new(aes_k, AES.MODE_CBC, aes_iv) - dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") - return json.loads(dec) - # Search + # Try plain JSON (some endpoints may return unencrypted) + try: + return json.loads(text) + except Exception: + raise ValueError(f"Castle decrypt failed for data length={len(d)}") + + # Step 2: Search kw = f"{title} {info.get('year', '')}".strip() sr = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={ "channel": CH, "clientType": CLI, "keyword": kw, "lang": LANG, - "mode": "1", "packageName": PKG, "page": "1", "size": "20" + "mode": "1", "packageName": PKG, "page": "1", "size": "30" }) if sr.status_code != 200: errors.append(f"Castle: search HTTP {sr.status_code}") return results, errors try: - sp = cdec(sr.text) + sp = castle_decrypt(sr.text) except Exception as e: errors.append(f"Castle: search decrypt fail: {e}") return results, errors if not isinstance(sp, dict) or sp.get("code") != 200: - errors.append(f"Castle: search API error") + errors.append(f"Castle: search API error (code={sp.get('code') if isinstance(sp, dict) else 'N/A'})") return results, errors db = sp.get("data", {}) if isinstance(db, str): - try: db = json.loads(db) - except: db = {} + try: + db = json.loads(db) + except Exception: + db = {} rows = db.get("rows", []) if isinstance(db, dict) else [] if not rows: errors.append("Castle: no search results") return results, errors - # Match by title + # Match by title - also check subjectType for movie/tv filtering mid = None - tl = title.lower() + tl = normalize_title(title).lower() + target_subject_type = 1 if media_type == "movie" else 2 + + # First try: exact normalized title match + correct subjectType for r in rows: - if not isinstance(r, dict): continue - rt = (r.get("title") or "").lower() - if tl in rt or rt in tl: + if not isinstance(r, dict): + continue + rt = normalize_title(r.get("title", "") or r.get("name", "")).lower() + r_type = r.get("subjectType", r.get("type", 0)) + if tl == rt and r_type == target_subject_type: mid = r.get("id") break + + # Second try: substring match + correct subjectType + if not mid: + for r in rows: + if not isinstance(r, dict): + continue + rt = normalize_title(r.get("title", "") or r.get("name", "")).lower() + r_type = r.get("subjectType", r.get("type", 0)) + if (tl in rt or rt in tl) and r_type == target_subject_type: + mid = r.get("id") + break + + # Third try: exact/substring match without type filter + if not mid: + for r in rows: + if not isinstance(r, dict): + continue + rt = normalize_title(r.get("title", "") or r.get("name", "")).lower() + if tl in rt or rt in tl: + mid = r.get("id") + break + + # Fallback: first result if not mid and isinstance(rows[0], dict): mid = rows[0].get("id") + if not mid: errors.append("Castle: no match") return results, errors mid = str(mid) - # Get details + # Step 3: Get details dr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={ "channel": CH, "clientType": CLI, "lang": LANG, "movieId": mid, "packageName": PKG @@ -594,25 +416,31 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo if dr.status_code != 200: errors.append(f"Castle: detail HTTP {dr.status_code}") return results, errors + try: - dp = cdec(dr.text) - except: + dp = castle_decrypt(dr.text) + except Exception: dp = {} + dd = dp.get("data", dp) if isinstance(dd, str): - try: dd = json.loads(dd) - except: dd = {} - if not isinstance(dd, dict): dd = {} + try: + dd = json.loads(dd) + except Exception: + dd = {} + if not isinstance(dd, dict): + dd = {} # For TV: navigate seasons/episodes ep_id = mid # Default: same as movieId for movies if media_type == "tv" and season and episode: seasons = dd.get("seasons", []) s_id = mid - for s in seasons: - if not isinstance(s, dict): continue - if s.get("number") == season or s.get("seasonNum") == season: - sid = s.get("id") + for s_item in seasons: + if not isinstance(s_item, dict): + continue + if s_item.get("number") == season or s_item.get("seasonNum") == season: + sid = s_item.get("id") if sid and str(sid) != mid: s_id = str(sid) sdr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={ @@ -620,52 +448,69 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo "movieId": s_id, "packageName": PKG }) try: - sdp = cdec(sdr.text) + sdp = castle_decrypt(sdr.text) sdd = sdp.get("data", sdp) - if isinstance(sdd, dict): dd = sdd - except: pass + if isinstance(sdd, dict): + dd = sdd + except Exception: + pass break eps = dd.get("episodes", []) for ep in eps: - if not isinstance(ep, dict): continue + if not isinstance(ep, dict): + continue if ep.get("number") == episode or ep.get("episodeNum") == episode: ep_id = str(ep.get("id", "")) break mid = s_id else: - # Movies: check for episodes list + # Movies: check for episodes list (some movies have a single "episode") eps = dd.get("episodes", []) if eps and isinstance(eps[0], dict): ep_id = str(eps[0].get("id", "")) - # Get video via getVideo2 (shared/no language track) + # 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 + "mode": "1", + "appMarket": "google_play", + "clientType": CLI, + "woolUser": "0", + "apkSignKey": SIGN, + "androidVersion": "13", + "movieId": mid, + "episodeId": str(ep_id), + "isNewUser": "1", + "resolution": str(resolution), + "packageName": PKG, } vr = await client.post( - f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo?clientType={CLI}&packageName={PKG}&channel={CH}&lang={LANG}", - json=body, headers={"Content-Type": "application/json"} + 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 = cdec(vr.text) + 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: continue + try: + vd = json.loads(vd) + except Exception: + continue if not isinstance(vd, dict): - errors.append(f"Castle: video not dict res={resolution}: {type(vd)}") + 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')}") @@ -678,18 +523,25 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo vids = vd.get("videos", []) if vids and isinstance(vids, list): for v in vids: - if not isinstance(v, dict): continue + if not isinstance(v, dict): + continue vu = v.get("url", vurl) q = v.get("resolutionDescription", v.get("resolution", quality)) q = re.sub(r'^(SD|HD|FHD)\s+', '', str(q)) - results.append({ + # 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", @@ -700,7 +552,8 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo "type": "m3u8" if ".m3u8" in vurl else "direct", }) break # Got a stream, stop trying lower resolutions - except: continue + except Exception: + continue # Also try per-language tracks langs = dd.get("languages", dd.get("languageList", [])) @@ -713,33 +566,39 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo ln = lt.get("name", lt.get("languageName", "")) elif isinstance(lt, str): ln = lt - # Try to find languageId from languageList ll = dd.get("languageList", []) for lli in ll: if isinstance(lli, dict) and lli.get("name", "").lower() == lt.lower(): lid = lli.get("languageId", lli.get("id")) break - if not lid: continue + if not lid: + continue try: body = { "mode": "1", "appMarket": "google_play", "clientType": CLI, "woolUser": "0", "apkSignKey": SIGN, "androidVersion": "13", "movieId": mid, "episodeId": str(ep_id), "languageId": str(lid), - "isNewUser": "1", "resolution": "3", "packageName": PKG + "isNewUser": "1", "resolution": "3", "packageName": PKG, } vr = await client.post( - f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo?clientType={CLI}&packageName={PKG}&channel={CH}&lang={LANG}", + 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: continue - vp = cdec(vr.text) + if vr.status_code != 200: + continue + vp = castle_decrypt(vr.text) vd = vp.get("data", vp) if isinstance(vd, str): - try: vd = json.loads(vd) - except: continue - if not isinstance(vd, dict): continue + try: + vd = json.loads(vd) + except Exception: + continue + if not isinstance(vd, dict): + continue vurl = vd.get("videoUrl", "") - if not vurl: continue + if not vurl: + continue results.append({ "source": f"Castle [{ln}]", "title": f"Castle {ln} - 1080p", @@ -748,7 +607,8 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo "url": vurl, "type": "m3u8" if ".m3u8" in vurl else "direct", }) - except: continue + except Exception: + continue # Deduplicate seen = set() @@ -769,16 +629,17 @@ async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episo return results, errors -# ===== MovieBox Scraper (h5-api.aoneroom.com) ===== + +# ===== MovieBox Scraper (themoviebox.org) - UPDATED ===== async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] try: - import urllib.parse - + 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())) @@ -791,11 +652,14 @@ async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, epi mb_headers = { "Accept": "application/json", "token": token, - "Origin": "https://moviebox.app", - "Referer": "https://moviebox.app/", + "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 + # 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", "") @@ -805,7 +669,12 @@ async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, epi search_resp = await client.post( f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/search", - json={"keyword": title, "page": 1, "size": 20}, + json={ + "keyword": title, + "page": 1, + "perPage": 28, + "subjectType": 0, # 0 = all, 1 = movie, 2 = tv + }, headers=mb_headers, ) if search_resp.status_code != 200: @@ -818,15 +687,19 @@ async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, epi errors.append("MovieBox: No search results") return results, errors - # Step 2: Match by normalized title + year - title_norm = re.sub(r'[^a-zA-Z0-9]', '', title.lower()) + # 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_norm = re.sub(r'[^a-zA-Z0-9]', '', item_title.lower()) + 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: + if item_norm == title_norm and item_type == target_subject_type: if year and item_year and year == item_year: matched_item = item break @@ -834,10 +707,31 @@ async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, epi 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]', '', item_title.lower()) + 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 @@ -850,18 +744,65 @@ async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, epi 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 download URLs + # 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": subject_id}, - headers=mb_headers, + 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}") @@ -873,44 +814,6 @@ async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, epi errors.append("MovieBox: No download items found") return results, errors - # For TV: find season/episode - if media_type == "tv": - s = season or 1 - e = episode or 1 - token = generate_moviebox_token() - mb_headers["token"] = token - - detail_resp = await client.get( - f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/detail", - params={"subjectId": subject_id}, - headers=mb_headers, - ) - if detail_resp.status_code == 200: - detail_data = detail_resp.json() - episodes = detail_data.get("data", {}).get("episodes", []) - target_ep = None - for ep_item in episodes: - ep_season = ep_item.get("seasonNumber", ep_item.get("season", 0)) - ep_num = ep_item.get("episodeNumber", ep_item.get("episode", 0)) - if int(ep_season) == s and int(ep_num) == e: - target_ep = ep_item - break - - if target_ep and target_ep.get("id"): - token = generate_moviebox_token() - mb_headers["token"] = token - - ep_dl_resp = await client.get( - f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/download", - params={"subjectId": target_ep["id"]}, - headers=mb_headers, - ) - if ep_dl_resp.status_code == 200: - ep_dl_data = ep_dl_resp.json() - ep_dl_items = ep_dl_data.get("data", {}).get("items", []) - if ep_dl_items: - dl_items = ep_dl_items - for dl_item in dl_items: stream_url = dl_item.get("url") or dl_item.get("downloadUrl") or dl_item.get("playUrl", "") if not stream_url: @@ -921,10 +824,20 @@ async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, epi 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", "") - lang = detect_language(lang) if lang else "Hindi" + 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_item.get("name") or dl_item.get("title") or dl_item.get("serverName", "MovieBox Stream") + 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") @@ -946,7 +859,7 @@ async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, epi return results, errors -# ===== Videasy Scraper (Multi-server encrypted API) ===== +# ===== 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 = [] @@ -1015,11 +928,11 @@ async def scrape_videasy(tmdb_id: int, media_type: str, season: int = None, epis if not res_data or not res_data.get("sources"): return server_results, f"{name}: No sources" - for s in res_data["sources"]: - stream_url = s.get("url", "") + for s_item in res_data["sources"]: + stream_url = s_item.get("url", "") if not stream_url: continue - quality = s.get("quality", "Auto") + quality = s_item.get("quality", "Auto") server_results.append({ "source": f"Videasy/{name}", @@ -1066,7 +979,7 @@ async def scrape_videasy(tmdb_id: int, media_type: str, season: int = None, epis return results, errors -# ===== NetMirror Scraper (Netflix/PrimeVideo/Hotstar via API) ===== +# ===== NetMirror Scraper (Netflix/PrimeVideo/Hotstar via API) - UPDATED TMDB KEY ===== async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] @@ -1092,7 +1005,7 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep cfg_resp = await cfg_client.get(CONFIG_URL) cfg_data = cfg_resp.json() api_base = cfg_data.get("nfmirror", FALLBACK_API) - except: + except Exception: pass info = await get_tmdb_info(tmdb_id, media_type) @@ -1118,7 +1031,7 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep try: search_data = search_resp.json() - except: + except Exception: return service_results, [f"{svc_name}: Search returned non-JSON"] search_results = search_data.get("searchResult", []) @@ -1134,9 +1047,9 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep starts_matches.append(item) elif title_lower in item_title or item_title in title_lower: contains_matches.append(item) - + all_matches = exact_matches + starts_matches + contains_matches - + if not all_matches: return service_results, [f"{svc_name}: No match found"] @@ -1153,25 +1066,25 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep if post_resp.status_code != 200: continue post_data = post_resp.json() - except: + except Exception: continue - + score = 0 nm_type = post_data.get("type", "") nm_year = post_data.get("year", "") nm_rating = 0 - + for detail in post_data.get("moredetails", []): if detail.get("k") == "IMDB Rating": try: nm_rating = float(detail.get("v", "0").replace("/10", "")) - except: + except Exception: nm_rating = 0 break - + if nm_type == expected_type: score += 50 - + try: if tmdb_year and nm_year: year_diff = abs(int(tmdb_year) - int(nm_year)) @@ -1183,41 +1096,41 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep score += 10 elif year_diff <= 5: score += 5 - except: + except Exception: pass - + score += nm_rating - + scored_matches.append({ "match": match_item, "post_data": post_data, "score": score, }) - + scored_matches.sort(key=lambda x: x["score"], reverse=True) final_id = None if media_type == "tv": s = season or 1 e = episode or 1 - + for scored in scored_matches: post_data = scored["post_data"] - + seasons = post_data.get("season", []) if not seasons: continue - + target_term = f"Season {s}" season_entry = None for se in seasons: if target_term in se.get("s", "").__str__(): season_entry = se break - + if not season_entry or not season_entry.get("id"): continue - + season_id = season_entry["id"] episode_id = None page = 1 @@ -1225,7 +1138,7 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep ep_resp = await client.get(f"{api_base}/episodes.php?id={season_id}&page={page}", headers=headers) try: ep_data = ep_resp.json() - except: + except Exception: break episodes = ep_data.get("episodes", []) for ep_item in episodes: @@ -1235,14 +1148,14 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep if int(ep_data.get("nextPageShow", 0)) != 1: break page += 1 - + if episode_id: final_id = episode_id break - + if not final_id: return service_results, [f"{svc_name}: No match with Season {s} Episode {e}"] - + else: if scored_matches: final_id = scored_matches[0]["match"].get("id") @@ -1255,7 +1168,7 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep try: player_data = player_resp.json() - except: + except Exception: return service_results, [f"{svc_name}: Player returned non-JSON"] video_link = player_data.get("video_link", "") @@ -1267,7 +1180,7 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep verify_resp = await client.get(video_link, headers=headers) if "#EXTM3U" not in verify_resp.text: return service_results, [f"{svc_name}: Master playlist unreachable"] - except: + except Exception: pass s_type = "m3u8" if ".m3u8" in video_link else ("direct" if ".mp4" in video_link or ".mkv" in video_link else "m3u8") @@ -1316,7 +1229,7 @@ async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, ep return results, errors -# ===== AllMovieLand Scraper (Hindi/Tamil/Multi via allmovieland.one) ===== +# ===== AllMovieLand Scraper (Hindi/Tamil/Multi via allmovieland.one) - KEEP AS-IS ===== async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] @@ -1324,7 +1237,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, try: UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36" - + info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") if not title: @@ -1332,7 +1245,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, return results, errors async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers={"User-Agent": UA}, http2=False) as client: - + search_resp = await client.get( "https://allmovieland.one/index.php", params={"story": title, "do": "search", "subaction": "search"} @@ -1343,7 +1256,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, search_html = search_resp.text articles = re.findall(r']*>(.*?)', search_html, re.DOTALL) - + if not articles: errors.append("AllMovieLand: No search results") return results, errors @@ -1358,7 +1271,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, 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) @@ -1375,7 +1288,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, 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 @@ -1392,7 +1305,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, 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 @@ -1427,7 +1340,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, if text != "7" and text.startswith("["): file_list = json.loads(text.replace(",]", "]")) break - except: + except Exception: pass if not file_list: @@ -1464,7 +1377,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, continue playlist_url = f"{player_domain}/playlist/{file_path}.txt" - + m3u8_url = None for attempt in range(7): try: @@ -1474,7 +1387,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, if text != "7" and text.startswith("http"): m3u8_url = text break - except: + except Exception: pass if m3u8_url: @@ -1507,212 +1420,7 @@ async def scrape_allmovieland(tmdb_id: int, media_type: str, season: int = None, return results, errors -# ===== VidSrc Scraper (dual approach: Nuvio + MediaVanced) ===== - -async def scrape_vidsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): - results = [] - errors = [] - - try: - info = await get_tmdb_info(tmdb_id, media_type) - imdb_id = info.get("imdb_id") - if not imdb_id: - errors.append("VidSrc: Could not get IMDB ID from TMDB") - return results, errors - - DECRYPT_API = "https://enc-dec.app/api/dec-cloudnestra" - - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: - - # ===== Approach 1: Nuvio - vsrc.su → vsembed.su → cloudorchestranova ===== - try: - if media_type == "tv": - s = season or 1 - e = episode or 1 - nuvio_embed = f"https://vsrc.su/embed/tv/{imdb_id}/{s}/{e}" - else: - nuvio_embed = f"https://vsrc.su/embed/movie/{imdb_id}" - - nuvio_resp = await client.get(nuvio_embed) - nuvio_html = nuvio_resp.text - - # Look for vsembed.su iframe - vsembed_m = re.search(r']+src="(?:https?:)?//vsembed\.su/embed/([^"]+)"', nuvio_html) - if not vsembed_m: - vsembed_m = re.search(r'src="((?:https?:)?//vsembed\.su/[^"]+)"', nuvio_html) - - if vsembed_m: - vsembed_path = vsembed_m.group(1) - if not vsembed_path.startswith("http"): - vsembed_path = f"https://vsembed.su{vsembed_path}" if vsembed_path.startswith("/") else f"https://{vsembed_path}" - - vsembed_resp = await client.get(vsembed_path, headers={"Referer": "https://vsrc.su/"}) - vsembed_html = vsembed_resp.text - - # Look for cloudorchestranova iframe - cloud_m = re.search(r']+src="(?:https?:)?//cloudorchestranova\.com/([^"]+)"', vsembed_html) - if not cloud_m: - cloud_m = re.search(r'src="((?:https?:)?//cloudorchestranova\.com/[^"]+)"', vsembed_html) - - if cloud_m: - cloud_path = cloud_m.group(1) - if not cloud_path.startswith("http"): - cloud_url = f"https://cloudorchestranova.com/{cloud_path}" if not cloud_path.startswith("http") else cloud_path - else: - cloud_url = cloud_path - - cloud_resp = await client.get(cloud_url, headers={ - "Referer": "https://vsembed.su/", - "Origin": "https://vsembed.su", - }) - - if cloud_resp.status_code != 403 and "Cloudflare" not in cloud_resp.text: - cloud_html = cloud_resp.text - - # Find hidden div for decryption - hidden_pattern = r"""]*style=["\x27]display\s*:\s*none;?["\x27][^>]*>([a-zA-Z0-9:/.,{}_=+ -]+)""" - hidden_m = re.search(hidden_pattern, cloud_html) - if hidden_m: - div_id = hidden_m.group(1) - div_text = hidden_m.group(2) - - dec_resp = await client.post( - DECRYPT_API, - json={"text": div_text, "div_id": div_id}, - headers={"Content-Type": "application/json"}, - ) - - if dec_resp.status_code == 200: - dec_data = dec_resp.json() - stream_urls = dec_data.get("result", []) - if isinstance(stream_urls, list): - for idx, stream_url in enumerate(stream_urls): - if not stream_url: - continue - quality = "Auto" - url_lower = stream_url.lower() - if "2160" in url_lower or "4k" in url_lower: - quality = "2160p" - elif "1440" in url_lower: - quality = "1440p" - elif "1080" in url_lower: - quality = "1080p" - elif "720" in url_lower: - quality = "720p" - - results.append({ - "source": f"VidSrc/nuvio{idx + 1}", - "title": f"VidSrc Nuvio Server {idx + 1}", - "quality": quality, - "language": "English", - "url": stream_url, - "type": "m3u8", - "headers": { - "Referer": "https://cloudorchestranova.com/", - "Origin": "https://cloudorchestranova.com", - }, - }) - except Exception as nuvio_err: - errors.append(f"VidSrc Nuvio: {str(nuvoio_err)}") - - # ===== Approach 2: MediaVanced - vidsrc.to → #player_iframe → prorcp_iframe ===== - if not results: - try: - if media_type == "tv": - s = season or 1 - e = episode or 1 - mv_embed = f"https://vidsrc.to/embed/tv/{imdb_id}/{s}/{e}" - else: - mv_embed = f"https://vidsrc.to/embed/movie/{imdb_id}" - - mv_resp = await client.get(mv_embed) - if mv_resp.status_code != 403 and "Cloudflare" not in mv_resp.text: - mv_html = mv_resp.text - - # Look for #player_iframe or data-id - player_iframe_m = re.search(r'id="player_iframe"[^>]*src="([^"]+)"', mv_html) - if not player_iframe_m: - player_iframe_m = re.search(r'data-id="([^"]+)"', mv_html) - - if player_iframe_m: - iframe_src = player_iframe_m.group(1) - if not iframe_src.startswith("http"): - iframe_src = f"https://vidsrc.to{iframe_src}" - - iframe_resp = await client.get(iframe_src, headers={"Referer": "https://vidsrc.to/"}) - iframe_html = iframe_resp.text - - # Look for prorcp_iframe - prorcp_m = re.search(r'id="prorcp_iframe"[^>]*src="([^"]+)"', iframe_html) - if not prorcp_m: - prorcp_m = re.search(r'src="([^"]+prorcp[^"]*)"', iframe_html) - - if prorcp_m: - prorcp_url = prorcp_m.group(1) - if not prorcp_url.startswith("http"): - prorcp_url = f"https:{prorcp_url}" if prorcp_url.startswith("//") else prorcp_url - - prorcp_resp = await client.get(prorcp_url, headers={"Referer": "https://vidsrc.to/"}) - prorcp_html = prorcp_resp.text - - # Extract file: URL from the source - file_match = re.search(r'file\s*:\s*"(https?://[^"]+\.m3u8[^"]*)"', prorcp_html) - if not file_match: - file_match = re.search(r'"(https?://[^"]+\.m3u8[^"]*)"', prorcp_html) - - if file_match: - stream_url = file_match.group(1) - quality = "Auto" - url_lower = stream_url.lower() - if "2160" in url_lower or "4k" in url_lower: - quality = "2160p" - elif "1440" in url_lower: - quality = "1440p" - elif "1080" in url_lower: - quality = "1080p" - elif "720" in url_lower: - quality = "720p" - - results.append({ - "source": "VidSrc/mediavanced", - "title": "VidSrc MediaVanced", - "quality": quality, - "language": "English", - "url": stream_url, - "type": "m3u8", - "headers": { - "Referer": "https://vidsrc.to/", - }, - }) - - # Alternative: extract source directly from iframe page - if not results: - src_match = re.search(r'file\s*:\s*"(https?://[^"]+\.m3u8[^"]*)"', iframe_html) - if src_match: - results.append({ - "source": "VidSrc/mediavanced", - "title": "VidSrc MediaVanced", - "quality": "Auto", - "language": "English", - "url": src_match.group(1), - "type": "m3u8", - "headers": { - "Referer": "https://vidsrc.to/", - }, - }) - except Exception as mv_err: - errors.append(f"VidSrc MediaVanced: {str(mv_err)}") - - if not results: - errors.append("VidSrc: No streams found from either approach") - - except Exception as e: - errors.append(f"VidSrc: {str(e)}") - - return results, errors - - -# ===== VidLink Scraper (vidlink.pro with encrypted ID) ===== +# ===== 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 = [] @@ -1721,6 +1429,15 @@ async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, epis 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 @@ -1741,17 +1458,13 @@ async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, epis # Step 2: Get stream URL if media_type == "movie": - stream_url = f"{VIDLINK_BASE}/api/b/movie/{encrypted_id}" + stream_api = f"{VIDLINK_BASE}/api/b/movie/{encrypted_id}" else: s = season or 1 e = episode or 1 - stream_url = f"{VIDLINK_BASE}/api/b/tv/{encrypted_id}/{s}/{e}" + stream_api = f"{VIDLINK_BASE}/api/b/tv/{encrypted_id}/{s}/{e}" - stream_resp = await client.get(stream_url, headers={ - "Accept": "application/json", - "Referer": f"{VIDLINK_BASE}/", - "Origin": VIDLINK_BASE, - }) + 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}") @@ -1760,7 +1473,7 @@ async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, epis stream_data = stream_resp.json() playlist_url = None - # Extract playlist URL from response + # 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", "") @@ -1778,36 +1491,43 @@ async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, epis if playlist_url.endswith(".m3u8") or "m3u8" in playlist_url: try: m3u8_resp = await client.get(playlist_url, headers={ - "Referer": f"{VIDLINK_BASE}/", - "Origin": VIDLINK_BASE, + "Referer": "https://vidlink.pro/", + "Origin": "https://vidlink.pro", }) if "#EXT-X-STREAM-INF" in m3u8_resp.text: - lines = m3u8_resp.text.split("\n") - for i, line in enumerate(lines): - if line.startswith("#EXT-X-STREAM-INF:"): - resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) - name = re.search(r'NAME="([^"]+)"', line) - quality = resolution.group(1) if resolution else "Auto" - label = name.group(1) if name else quality - if i + 1 < len(lines) and lines[i + 1].strip(): - variant_url = lines[i + 1].strip() - if not variant_url.startswith("http"): - base_url = playlist_url.rsplit("/", 1)[0] - variant_url = f"{base_url}/{variant_url}" - - results.append({ - "source": "VidLink", - "title": label, - "quality": quality, - "language": "English", - "url": variant_url, - "type": "m3u8", - "headers": { - "Referer": f"{VIDLINK_BASE}/", - "Origin": VIDLINK_BASE, - }, - }) + 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", @@ -1817,8 +1537,8 @@ async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, epis "url": playlist_url, "type": "m3u8", "headers": { - "Referer": f"{VIDLINK_BASE}/", - "Origin": VIDLINK_BASE, + "Referer": "https://vidlink.pro/", + "Origin": "https://vidlink.pro", }, }) except Exception: @@ -1830,8 +1550,8 @@ async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, epis "url": playlist_url, "type": "m3u8", "headers": { - "Referer": f"{VIDLINK_BASE}/", - "Origin": VIDLINK_BASE, + "Referer": "https://vidlink.pro/", + "Origin": "https://vidlink.pro", }, }) else: @@ -1844,8 +1564,8 @@ async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, epis "url": playlist_url, "type": s_type, "headers": { - "Referer": f"{VIDLINK_BASE}/", - "Origin": VIDLINK_BASE, + "Referer": "https://vidlink.pro/", + "Origin": "https://vidlink.pro", }, }) @@ -1858,145 +1578,224 @@ async def scrape_vidlink(tmdb_id: int, media_type: str, season: int = None, epis return results, errors -# ===== PrimeSrc Scraper (primesrc.me with AES-CBC decryption) ===== +# ===== VidSrc Scraper (cloudnestra approach) - REWRITTEN ===== -async def scrape_primesrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): +async def scrape_vidsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = [] try: - from Crypto.Cipher import AES - from Crypto.Util.Padding import unpad - - PRIMESRC_BASE = "https://primesrc.me" - PRIMESRC_KEY = b"kiemtienmua911ca" - PRIMESRC_IV = b"1234567890oiuytr" + VIDSRC_TMDB_KEY = "439c478a771f35c05022f9feabcca01c" + DECRYPT_API = "https://enc-dec.app/api/dec-cloudnestra" - info = await get_tmdb_info(tmdb_id, media_type) + # 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: - errors.append("PrimeSrc: Could not get IMDB ID from TMDB") + 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 - content_type = "tv" if media_type == "tv" else "movie" - async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: - # Step 1: Get servers - servers_resp = await client.get( - f"{PRIMESRC_BASE}/api/v1/s", - params={"imdb": imdb_id, "type": content_type}, - headers={"Accept": "application/json"} - ) - if servers_resp.status_code != 200: - errors.append(f"PrimeSrc: Servers API failed HTTP {servers_resp.status_code}") - return results, errors - servers_data = servers_resp.json() - servers_list = servers_data if isinstance(servers_data, list) else servers_data.get("servers", servers_data.get("data", [])) + # 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 - if not servers_list: - errors.append("PrimeSrc: No servers found") + # 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 - for server in servers_list: - try: - server_key = server.get("key") or server.get("id") or server.get("serverKey", "") - server_name = server.get("name") or server.get("serverName", "Server") - if not server_key: - continue + # Step 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 - # Step 2: Get server link - link_resp = await client.get( - f"{PRIMESRC_BASE}/api/v1/l", - params={"key": server_key}, - headers={"Accept": "application/json"} - ) - if link_resp.status_code != 200: - continue + # 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) - link_data = link_resp.json() - server_id = link_data.get("id") or link_data.get("serverId") or link_data.get("key", server_key) - if not server_id: - continue + 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" - # Step 3: Get encrypted video - video_resp = await client.get( - f"{PRIMESRC_BASE}/api/v1/video", - params={"id": server_id}, - headers={"Accept": "application/json"} - ) - if video_resp.status_code != 200: - continue + results.append({ + "source": "VidSrc", + "title": "VidSrc Stream", + "quality": quality, + "language": "English", + "url": js_src, + "type": "m3u8", + "headers": { + "Referer": "https://cloudnestra.com/", + }, + }) + return results, errors - video_data = video_resp.json() - encrypted_text = video_data.get("data") or video_data.get("encrypted") or video_data.get("url", "") + # 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 - if not encrypted_text: - continue + cloud_resp = await client.get(cloudnestra_url, headers={ + "Referer": "https://vsrc.su/", + "Origin": "https://vsrc.su", + }) - # Step 4: AES-CBC decrypt (hex-encoded ciphertext) - try: - if isinstance(encrypted_text, str): - try: - ct_bytes = bytes.fromhex(encrypted_text) - except ValueError: - ct_bytes = base64.b64decode(encrypted_text) - else: - continue + if cloud_resp.status_code == 403 or "Cloudflare" in cloud_resp.text: + errors.append("VidSrc: Cloudflare blocked on cloudnestra") + return results, errors - cipher = AES.new(PRIMESRC_KEY, AES.MODE_CBC, PRIMESRC_IV) - decrypted = unpad(cipher.decrypt(ct_bytes), AES.block_size) - decrypted_str = decrypted.decode("utf-8", errors="ignore") + 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 - try: - dec_json = json.loads(decrypted_str) - source_url = dec_json.get("source") or dec_json.get("url") or dec_json.get("file", "") - except json.JSONDecodeError: - url_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', decrypted_str) - source_url = url_match.group(0) if url_match else decrypted_str.strip() + # 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 not source_url or not source_url.startswith("http"): - continue + if dec_resp.status_code != 200: + errors.append(f"VidSrc: Decrypt API failed HTTP {dec_resp.status_code}") + return results, errors - s_type = "m3u8" if ".m3u8" in source_url else "direct" - quality = "Auto" - q_match = re.search(r'(\d{3,4})p', source_url) - if q_match: - quality = q_match.group(1) + "p" + dec_data = dec_resp.json() + stream_urls = dec_data.get("result", []) - results.append({ - "source": f"PrimeSrc/{server_name}", - "title": f"PrimeSrc - {server_name}", - "quality": quality, - "language": "English", - "url": source_url, - "type": s_type, - "headers": { - "Referer": f"{PRIMESRC_BASE}/", - "Origin": PRIMESRC_BASE, - }, - }) + if isinstance(stream_urls, str): + stream_urls = [stream_urls] - except Exception as dec_err: - errors.append(f"PrimeSrc/{server_name}: Decryption failed - {str(dec_err)}") - continue + if not stream_urls: + errors.append("VidSrc: No streams from decryption") + return results, errors - except Exception as srv_err: - errors.append(f"PrimeSrc/{server_name}: {str(srv_err)}") + # 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("PrimeSrc: No streams found") + errors.append("VidSrc: No streams found") - except ImportError: - errors.append("PrimeSrc: pycryptodome not installed") except Exception as e: - errors.append(f"PrimeSrc: {str(e)}") + errors.append(f"VidSrc: {str(e)}") return results, errors -# ===== M4UHD Scraper (m4uhd.vip with CryptoJS-compatible AES-CBC) ===== +# ===== 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 = [] @@ -2029,7 +1828,6 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod search_html = search_resp.text - # Extract movie links and titles using regex movie_blocks = re.findall( r']*class="[^"]*item[^"]*"[^>]*>.*?]*href="([^"]+)"[^>]*>.*?(?:]*alt="([^"]*)")?', search_html, re.DOTALL @@ -2044,7 +1842,6 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod errors.append("M4UHD: No search results found") return results, errors - # Find best match movie_page_url = None title_lower = title.lower() for link, mtitle in movie_blocks: @@ -2060,7 +1857,6 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod errors.append("M4UHD: Could not find movie page") return results, errors - # Step 2: Get movie page - extract server list and CSRF token movie_resp = await client.get(movie_page_url) if movie_resp.status_code != 200: errors.append(f"M4UHD: Movie page HTTP {movie_resp.status_code}") @@ -2068,7 +1864,6 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod movie_html = movie_resp.text - # Extract CSRF token csrf_match = re.search(r'name="csrf[_-]token"\s+(?:value|content)="([^"]+)"', movie_html, re.I) if not csrf_match: csrf_match = re.search(r'(?:value|content)="([^"]+)"[^>]*name="csrf[_-]token"', movie_html, re.I) @@ -2076,7 +1871,6 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod csrf_match = re.search(r'csrf[_-]?token["\s:=]+["\']?([a-fA-F0-9]+)', movie_html, re.I) csrf_token = csrf_match.group(1) if csrf_match else "" - # Extract server list servers = re.findall(r'data-id="(\d+)"[^>]*>([^<]+)', movie_html) if not servers: servers = re.findall(r'class="[^"]*server[^"]*"[^>]*data-id="(\d+)"[^>]*>([^<]*)', movie_html) @@ -2087,10 +1881,8 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod errors.append("M4UHD: No servers found on movie page") return results, errors - # Process each server for server_id, server_name in servers[:3]: try: - # Step 3: POST /ajax to get embed URL ajax_data = { "id": server_id, "csrf_token": csrf_token, @@ -2123,14 +1915,12 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod if not embed_url: continue - # Step 4: GET embed page if not embed_url.startswith("http"): embed_url = f"{M4UHD_BASE}{embed_url}" embed_resp = await client.get(embed_url, headers={"Referer": movie_page_url}) embed_html = embed_resp.text - # Extract encrypted idfile_enc and idUser_enc idfile_match = re.search(r'idfile_enc["\s:=]+["\']?([a-zA-Z0-9+/=]+)', embed_html) iduser_match = re.search(r'idUser_enc["\s:=]+["\']?([a-zA-Z0-9+/=]+)', embed_html) @@ -2141,7 +1931,6 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod errors.append(f"M4UHD/{server_name}: No encrypted file ID found") continue - # Step 5: Decrypt with EVP_BytesToKey def m4uhd_decrypt(ciphertext_b64: str, secret: str) -> str: raw = base64.b64decode(ciphertext_b64) if raw[:8] == b"Salted__": @@ -2162,11 +1951,9 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod ct = cipher.encrypt(crypto_pad(plaintext.encode(), AES.block_size)) return base64.b64encode(b"Salted__" + salt + ct).decode() - # Decrypt file ID and user ID idfile = m4uhd_decrypt(idfile_enc, FILE_ID_SECRET) iduser = m4uhd_decrypt(iduser_enc, USER_ID_SECRET) if iduser_enc else "" - # Step 6: Build encrypted payload and POST to playiframe API payload_data = { "idfile": idfile, "idUser": iduser, @@ -2174,7 +1961,6 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod payload_json = json.dumps(payload_data) encrypted_payload = m4uhd_encrypt(payload_json, ENCRYPT_PAYLOAD_SECRET) - # Compute HMAC hmac_val = hashlib.md5((encrypted_payload + HMAC_KEY).encode()).hexdigest() play_resp = await client.post( @@ -2196,11 +1982,9 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod if not encrypted_response: continue - # Step 7: Decrypt response try: decrypted_response = m4uhd_decrypt(encrypted_response, DECRYPT_RESPONSE_SECRET) - # Extract video URL from decrypted response try: dec_json = json.loads(decrypted_response) video_url = dec_json.get("url") or dec_json.get("source") or dec_json.get("file") or dec_json.get("link", "") @@ -2249,23 +2033,449 @@ async def scrape_m4uhd(tmdb_id: int, media_type: str, season: int = None, episod 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 + + # ===== Source Map ===== SOURCE_MAP = { - "cinesu": {"name": "CineSu", "fn": lambda tid, mt, s, e: scrape_cinesu(tid, mt, s, e), - "languages": ["English"], "reliability": "high"}, - "vixsrc": {"name": "VixSrc", "fn": lambda tid, mt, s, e: scrape_vixsrc(tid, mt, s, e), - "languages": ["English", "Italian", "Multi"], "reliability": "low", - "note": "Cloudflare-blocked from datacenter IPs, works from residential only"}, "vidrock": {"name": "VidRock", "fn": lambda tid, mt, s, e: scrape_vidrock(tid, mt, s, e), "languages": ["English"], "reliability": "high"}, - "dooflix": {"name": "DooFlix", "fn": lambda tid, mt, s, e: scrape_dooflix(tid, mt, s, e), - "languages": ["Hindi", "English", "Multi"], "reliability": "high"}, "castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e), - "languages": ["English", "Hindi", "Multi"], "reliability": "broken", - "note": "hlowb.com API requires undocumented auth params - returns 400"}, + "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"], "reliability": "high"}, + "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"}, "netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e), @@ -2273,17 +2483,25 @@ SOURCE_MAP = { "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": "low", - "note": "Cloudflare-blocked from datacenter IPs (vsrc.su/cloudorchestranova)"}, + "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"}, - "primesrc": {"name": "PrimeSrc", "fn": lambda tid, mt, s, e: scrape_primesrc(tid, mt, s, e), - "languages": ["English"], "reliability": "medium"}, + "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"}, } -DEFAULT_SOURCES = ["cinesu", "dooflix", "moviebox", "netmirror", "vidrock", "vidlink", "primesrc"] +DEFAULT_SOURCES = ["vidrock", "moviebox", "netmirror", "vidlink", "vidfast", "castle", "videasy"] # ===== Helper: Run scrapers ===== @@ -2344,7 +2562,7 @@ async def run_scrape(tmdb_id: int, media_type: str, season: int = None, episode: async def root(): return { "api": "StreamForge", - "version": "7.0.0", + "version": "8.0.0", "description": "Multi-language m3u8 stream scraper", "endpoints": { "movie": { @@ -2357,7 +2575,7 @@ async def root(): "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/cinesu", + "example_source": "/tv/1396/1/1/vidlink", }, "search": { "path": "/search/{query}", @@ -2375,16 +2593,24 @@ async def root(): **({"note": src["note"]} if "note" in src else {})} for key, src 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)"], + }, "tips": [ - "No source = default sources (cinesu, dooflix, castle, moviebox, netmirror, vidrock, vidlink, primesrc)", - "Best for Hindi: /movie/ID/allmovieland or /movie/ID/dooflix or /movie/ID/moviebox or /movie/ID/castle", - "Best for English: /movie/ID/cinesu or /movie/ID/vidrock or /movie/ID/vidlink or /movie/ID/videasy", - "Castle: hlowb.com API with AES decryption, returns multi-language + multi-quality streams", + "No source = default sources (vidrock, moviebox, netmirror, vidlink, vidfast, castle, videasy)", + "Best for Hindi: /movie/ID/allmovieland or /movie/ID/moviebox or /movie/ID/castle", + "Best for English: /movie/ID/vidrock or /movie/ID/vidlink or /movie/ID/vidfast or /movie/ID/videasy", + "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: vidlink.pro with encrypted TMDB ID, supports M3U8 quality variants", - "PrimeSrc: primesrc.me with AES-CBC decryption", + "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)", - "VixSrc/VidSrc: Blocked from cloud IPs, works residential only", + "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", ], }