Spaces:
Running
Running
Commit ·
5bf3320
1
Parent(s): e6abf12
fix: Castle scraper - use correct hlowb.com API params (channel/clientType/packageName/lang/mode)
Browse files485 unmodified lines4864874884894904919 unmodified lines5015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107115 unmodified lines7177187197207217227232 unmodified lines7267277287297307317321603 unmodified lines2336233723382339234023412342485 unmodified lines# ===== Castle Scraper (hlowb.com API with AES-CBC decryption) =====async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []errors = []9 unmodified linesreturn results, errorsCASTLE_BASE = "https://api.hlowb.com"async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client:# Step 1: Get security keysec_resp = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1?channel=",headers={"Accept": "application/json"})if sec_resp.status_code != 200:errors.append(f"Castle: Security key request failed HTTP {sec_resp.status_code}")return results, errorssec_data = sec_resp.json()raw_key = sec_data.get("data", "")if not raw_key:errors.append("Castle: No security key in response")return results, errors# data can be base64-encoded string or plain stringtry:security_key = base64.b64decode(raw_key).decode("utf-8", errors="ignore")except Exception:security_key = raw_key# Also try nested format: {"data": {"securityKey": "..."}}if isinstance(sec_data.get("data"), dict):security_key = sec_data["data"].get("securityKey", security_key)# Derive AES key and IV: (securityKey + "T!BgJB")[:16]aes_key_str = (security_key + "T!BgJB")[:16]aes_key = aes_key_str.encode("utf-8")aes_iv = aes_key # IV = same as key# Step 2: Search for the moviesearch_resp = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword",params={"keyword": title, "channel": ""},headers={"Accept": "application/json"})if search_resp.status_code != 200:errors.append(f"Castle: Search failed HTTP {search_resp.status_code}")return results, errorssearch_data = search_resp.json()encrypted_data = search_data.get("data", "")# Handle case where data might not be encrypted (direct JSON)search_results = Noneif isinstance(encrypted_data, (dict, list)):search_results = encrypted_dataelif isinstance(encrypted_data, str) and encrypted_data:try:raw = base64.b64decode(encrypted_data)cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv)decrypted = unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")search_results = json.loads(decrypted)except Exception as dec_err:# Try parsing as plain JSONtry:search_results = json.loads(encrypted_data)except:errors.append(f"Castle: Search decryption failed - {str(dec_err)}")return results, errorsif search_results is None:errors.append("Castle: No search data in response")return results, errors# Find matching movie by titlemovie_list = search_results if isinstance(search_results, list) else search_results.get("list", search_results.get("data", []))if not isinstance(movie_list, list):movie_list = []title_lower = title.lower().strip()matched_movie = Nonefor item in movie_list:item_title = (item.get("title") or item.get("name") or "").lower().strip()item_id = item.get("id")if not item_id:continueif item_title == title_lower or title_lower in item_title or item_title in title_lower:matched_movie = itembreakif not matched_movie and movie_list:matched_movie = movie_list[0]if not matched_movie:errors.append("Castle: No matching movie found in search results")return results, errorsmovie_id = matched_movie.get("id")# Step 3: Get movie detailsdetail_resp = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie",params={"channel": "", "id": movie_id},headers={"Accept": "application/json"})if detail_resp.status_code != 200:errors.append(f"Castle: Detail request failed HTTP {detail_resp.status_code}")return results, errorsdetail_data = detail_resp.json()encrypted_detail = detail_data.get("data", "")if isinstance(encrypted_detail, (dict, list)):detail_parsed = encrypted_detailelif isinstance(encrypted_detail, str) and encrypted_detail:try:raw = base64.b64decode(encrypted_detail)cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv)decrypted_detail = unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")detail_parsed = json.loads(decrypted_detail)except:detail_parsed = {}else:detail_parsed = detail_data# Step 4: Get video URLvideo_resp = await client.get(f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2",params={"clientType": "1", "channel": "", "id": movie_id},headers={"Accept": "application/json"})if video_resp.status_code != 200:errors.append(f"Castle: Video request failed HTTP {video_resp.status_code}")return results, errorsvideo_data = video_resp.json()encrypted_video = video_data.get("data", "")video_parsed = Noneif isinstance(encrypted_video, (dict, list)):video_parsed = encrypted_videoelif isinstance(encrypted_video, str) and encrypted_video:try:raw = base64.b64decode(encrypted_video)cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv)decrypted_video = unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")video_parsed = json.loads(decrypted_video)except Exception as dec_err:# Try parsing as plain JSONtry:video_parsed = json.loads(encrypted_video)except:errors.append(f"Castle: Video decryption failed - {str(dec_err)}")return results, errorsif video_parsed is None:errors.append("Castle: No video data in response")return results, errors# Extract stream URLs from video responsedef extract_castle_streams(obj, depth=0):streams = []if depth > 10:return streamsif isinstance(obj, dict):for key in ["url", "playUrl", "videoUrl", "streamUrl", "downloadUrl"]:val = obj.get(key, "")if val and isinstance(val, str) and (val.startswith("http") or ".m3u8" in val):quality = obj.get("quality") or obj.get("resolution") or obj.get("name") or "Auto"lang = obj.get("language") or obj.get("lang") or ""name = obj.get("name") or obj.get("title") or obj.get("serverName") or ""streams.append({"url": val,"quality": str(quality),"language": lang,"name": name,})for key in ["list", "sources", "episodes", "items", "videoInfo", "playList"]:child = obj.get(key)if child:streams.extend(extract_castle_streams(child, depth + 1))if not streams:for v in obj.values():if isinstance(v, (dict, list)):streams.extend(extract_castle_streams(v, depth + 1))elif isinstance(obj, list):for item in obj:streams.extend(extract_castle_streams(item, depth + 1))return streamscastle_streams = extract_castle_streams(video_parsed)for cs in castle_streams:s_url = cs["url"]quality = cs.get("quality", "Auto")q_match = re.search(r'(\d{3,4})p', str(quality))if q_match:quality = q_match.group(1) + "p"elif "4k" in str(quality).lower() or "2160" in str(quality):quality = "4K"lang = cs.get("language", "")lang = detect_language(lang) if lang else "English"name = cs.get("name", "")s_type = "m3u8" if ".m3u8" in s_url else ("direct" if ".mp4" in s_url else "m3u8")results.append({"source": "Castle","title": name or "Castle Stream","quality": quality,"language": lang,"url": s_url,"type": s_type,})# Deduplicateseen_urls = set()5 unmodified linesresults = unique_resultsif not results:errors.append("Castle: No streams found after decryption")except ImportError:errors.append("Castle: pycryptodome not installed")2 unmodified linesreturn results, errors# ===== MovieBox Scraper (h5-api.aoneroom.com) =====async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, episode: int = None):1603 unmodified lines"No source = default sources (cinesu, dooflix, castle, moviebox, netmirror, vidrock, vidlink, primesrc)","Best for Hindi: /movie/ID/allmovieland or /movie/ID/dooflix or /movie/ID/moviebox or /movie/ID/castle","Best for English: /movie/ID/cinesu or /movie/ID/vidrock or /movie/ID/vidlink or /movie/ID/videasy","Castle: hlowb.com API with AES-CBC encryption, returns multiple quality streams","NetMirror: Searches Netflix, PrimeVideo, Hotstar via API - great for Hindi/English","VidLink: vidlink.pro with encrypted TMDB ID, supports M3U8 quality variants","PrimeSrc: primesrc.me with AES-CBC decryption",485 unmodified lines4864874884894904914924934944954964979 unmodified lines5075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907915 unmodified lines7977987998008018028032 unmodified lines8068078088098108111603 unmodified lines2415241624172418241924202421485 unmodified lines# ===== Castle Scraper (hlowb.com API with AES-CBC decryption) =====CASTLE_PKG = "com.gwzq.clz"CASTLE_CHANNEL = "1"CASTLE_CLIENT = "1"CASTLE_LANG = "en-US"CASTLE_SIGN_KEY = "ED0955EB04E67A1D9F3305B95454FED485261475"async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []errors = []9 unmodified linesreturn results, errorsCASTLE_BASE = "https://api.hlowb.com"CASTLE_HEADERS = {"User-Agent": "okhttp/4.9.3","Accept": "application/json","Accept-Language": "en-US",}async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client:# Step 1: Get security keysec_resp = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/{CASTLE_CHANNEL}?clientType={CASTLE_CLIENT}&lang={CASTLE_LANG}")if sec_resp.status_code != 200:errors.append(f"Castle: Security key HTTP {sec_resp.status_code}")return results, errorssec_data = sec_resp.json()raw_key = sec_data.get("data", "")if not raw_key:errors.append("Castle: No security key")return results, errorstry:security_key = base64.b64decode(raw_key).decode("utf-8", errors="ignore")except Exception:security_key = raw_key# Derive AES key: (securityKey + "T!BgJB"), pad/trim to 16 bytescombined = security_key + "T!BgJB"if len(combined) < 16:combined = combined + "\x00" * (16 - len(combined))aes_key_str = combined[:16]aes_key = aes_key_str.encode("utf-8")aes_iv = aes_keydef castle_decrypt(encrypted_text: str) -> dict:"""Decrypt Castle API response"""# Try JSON-wrapped firstdata_str = encrypted_texttry:j = json.loads(encrypted_text)if isinstance(j.get("data"), str):data_str = j["data"]except:passraw = base64.b64decode(data_str)cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv)decrypted = unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")return json.loads(decrypted)# Step 2: Search with full paramssearch_keyword = titleif info.get("year"):search_keyword = f"{title} {info['year']}"search_resp = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword",params={"channel": CASTLE_CHANNEL,"clientType": CASTLE_CLIENT,"keyword": search_keyword,"lang": CASTLE_LANG,"mode": "1","packageName": CASTLE_PKG,"page": "1","size": "20",})if search_resp.status_code != 200:errors.append(f"Castle: Search HTTP {search_resp.status_code}")return results, errorstry:search_parsed = castle_decrypt(search_resp.text)except Exception as e:errors.append(f"Castle: Search decrypt failed - {str(e)}")return results, errorsif search_parsed.get("code") != 200:errors.append(f"Castle: Search API error - {search_parsed.get('msg', 'unknown')}")return results, errors# Find matching moviedata_block = search_parsed.get("data", {})rows = data_block.get("rows", []) if isinstance(data_block, dict) else []if not rows:errors.append("Castle: No search results")return results, errorstitle_lower = title.lower().strip()matched_id = Nonefor row in rows:row_title = (row.get("title") or "").lower().strip()if row_title == title_lower or title_lower in row_title or row_title in title_lower:matched_id = row.get("id")breakif not matched_id:matched_id = rows[0].get("id")if not matched_id:errors.append("Castle: No matching result")return results, errorsmovie_id = str(matched_id)# Step 3: Get detailsdetail_resp = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie",params={"channel": CASTLE_CHANNEL,"clientType": CASTLE_CLIENT,"lang": CASTLE_LANG,"movieId": movie_id,"packageName": CASTLE_PKG,})if detail_resp.status_code != 200:errors.append(f"Castle: Detail HTTP {detail_resp.status_code}")return results, errorstry:detail_parsed = castle_decrypt(detail_resp.text)except:detail_parsed = {}detail_data = detail_parsed.get("data", detail_parsed) if isinstance(detail_parsed, dict) else {}# For TV: navigate to seasonepisode_id = Noneif media_type == "tv" and season and episode:seasons = detail_data.get("seasons", [])target_season = Nonefor s in seasons:if s.get("number") == season or s.get("seasonNum") == season:target_season = sbreakif target_season and target_season.get("id"):season_id = str(target_season["id"])if season_id != movie_id:# Fetch season detailss_detail_resp = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie",params={"channel": CASTLE_CHANNEL,"clientType": CASTLE_CLIENT,"lang": CASTLE_LANG,"movieId": season_id,"packageName": CASTLE_PKG,})try:s_detail_parsed = castle_decrypt(s_detail_resp.text)s_detail_data = s_detail_parsed.get("data", s_detail_parsed)if isinstance(s_detail_data, dict):detail_data = s_detail_datamovie_id = season_idexcept:pass# Find episodeepisodes = detail_data.get("episodes", [])for ep in episodes:if ep.get("number") == episode or ep.get("episodeNum") == episode:episode_id = str(ep.get("id", ""))breakelse:# For movies: use first episode/languageepisodes = detail_data.get("episodes", [])if episodes:episode_id = str(episodes[0].get("id", ""))if not episode_id:errors.append("Castle: Could not find episode")return results, errors# Step 4: Get video URL - try language tracks first, then sharedlanguages = detail_data.get("languages", detail_data.get("languageList", []))for lang_track in languages:lang_name = lang_track.get("name", lang_track.get("languageName", ""))lang_id = lang_track.get("languageId", lang_track.get("id", ""))if not lang_id:continuetry:video_body = {"mode": "1","appMarket": "google_play","clientType": CASTLE_CLIENT,"woolUser": "0","apkSignKey": CASTLE_SIGN_KEY,"androidVersion": "13","movieId": movie_id,"episodeId": episode_id,"languageId": str(lang_id),"isNewUser": "1","resolution": "2","packageName": CASTLE_PKG,}video_resp = await client.post(f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo?clientType={CASTLE_CLIENT}&packageName={CASTLE_PKG}&channel={CASTLE_CHANNEL}&lang={CASTLE_LANG}",json=video_body,headers={"Content-Type": "application/json"})if video_resp.status_code != 200:continuetry:video_parsed = castle_decrypt(video_resp.text)except:continuevideo_data = video_parsed.get("data", video_parsed)if not isinstance(video_data, dict):continuevideo_url = video_data.get("videoUrl", "")if not video_url:continue# Extract quality variantsvideos = video_data.get("videos", [])if videos:for v in videos:v_url = v.get("url", video_url)quality = v.get("resolutionDescription", v.get("resolution", "Auto"))quality = re.sub(r'^(SD|HD|FHD)\s+', '', str(quality))results.append({"source": f"Castle [{lang_name}]","title": f"Castle {lang_name} - {quality}","quality": quality,"language": detect_language(lang_name) if lang_name else "English","url": v_url,"type": "m3u8" if ".m3u8" in v_url else "direct",})else:quality_map = {1: "480p", 2: "720p", 3: "1080p"}quality = quality_map.get(2, "720p")results.append({"source": f"Castle [{lang_name}]","title": f"Castle {lang_name} - {quality}","quality": quality,"language": detect_language(lang_name) if lang_name else "English","url": video_url,"type": "m3u8" if ".m3u8" in video_url else "direct",})except:continue# Fallback: shared video without language trackif not results:try:video_body = {"mode": "1","appMarket": "google_play","clientType": CASTLE_CLIENT,"woolUser": "0","apkSignKey": CASTLE_SIGN_KEY,"androidVersion": "13","movieId": movie_id,"episodeId": episode_id,"isNewUser": "1","resolution": "3","packageName": CASTLE_PKG,}video_resp = await client.post(f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo?clientType={CASTLE_CLIENT}&packageName={CASTLE_PKG}&channel={CASTLE_CHANNEL}&lang={CASTLE_LANG}",json=video_body,headers={"Content-Type": "application/json"})if video_resp.status_code == 200:video_parsed = castle_decrypt(video_resp.text)video_data = video_parsed.get("data", video_parsed)if isinstance(video_data, dict):video_url = video_data.get("videoUrl", "")if video_url:results.append({"source": "Castle","title": "Castle Stream - 1080p","quality": "1080p","language": "English","url": video_url,"type": "m3u8" if ".m3u8" in video_url else "direct",})except:pass# Deduplicateseen_urls = set()5 unmodified linesresults = unique_resultsif not results:errors.append("Castle: No streams found")except ImportError:errors.append("Castle: pycryptodome not installed")2 unmodified linesreturn results, errors# ===== MovieBox Scraper (h5-api.aoneroom.com) =====async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, episode: int = None):1603 unmodified lines"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","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",
main.py+238-159