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 lines4864874884894904914924934944954964979 unmodified lines5075085095105115125135145155055165175185085095195205215125225235245255265275185285295205305315325335255265275345295305355365375385395405325415425435445455465475485495505515525535545555565575585595605615625345635645375385655665675685695705715725735745755765415775785795445455465475485495505515525535545555565575585595605615625805815825835635645655665845855695705715725865875885895905915925935945955965975755765775785795805815825985996006016026035845855865875885896046056066076086095926106115946126136145975986156166176186196206216226236016246256266046056066076086096106116126136146156276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726176736746756766776196206216226236246256266786796806816296306826836846326336346356856866876886896906376386396406416426916926936946956966976986997007017027037047057067077087097107117126447137146466476486496506517157167177187197207217226536546556566576586596606616626636646656666676686697237247257267277287297307317327337347357367376716726736746756766776786796806816826836846856866876886896906916926936946956966976986997387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787017027037047057067077087797807817827837847857867877887897907915 unmodified lines7977987997208008018028032 unmodified lines8068078087298098108111603 unmodified lines24152416241723392418241924202421485 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 lines return results, errors
CASTLE_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=HEADERS) as client: async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client: # Step 1: Get security key sec_resp = await client.get( f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1?channel=", headers={"Accept": "application/json"} 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 request failed HTTP {sec_resp.status_code}") errors.append(f"Castle: Security key HTTP {sec_resp.status_code}") return results, errors
sec_data = sec_resp.json() raw_key = sec_data.get("data", "") if not raw_key: errors.append("Castle: No security key in response") errors.append("Castle: No security key") return results, errors # data can be base64-encoded string or plain string try: 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] # Derive AES key: (securityKey + "T!BgJB"), pad/trim to 16 bytes combined = 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_key # IV = same as key aes_iv = aes_key
def castle_decrypt(encrypted_text: str) -> dict: """Decrypt Castle API response""" # Try JSON-wrapped first data_str = encrypted_text try: j = json.loads(encrypted_text) if isinstance(j.get("data"), str): data_str = j["data"] except: pass raw = 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 params search_keyword = title if info.get("year"): search_keyword = f"{title} {info['year']}"
# Step 2: Search for the movie search_resp = await client.get( f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={"keyword": title, "channel": ""}, headers={"Accept": "application/json"} 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 failed HTTP {search_resp.status_code}") errors.append(f"Castle: Search HTTP {search_resp.status_code}") return results, errors
search_data = search_resp.json() encrypted_data = search_data.get("data", "") # Handle case where data might not be encrypted (direct JSON) search_results = None if isinstance(encrypted_data, (dict, list)): search_results = encrypted_data elif 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 JSON try: search_results = json.loads(encrypted_data) except: errors.append(f"Castle: Search decryption failed - {str(dec_err)}") try: search_parsed = castle_decrypt(search_resp.text) except Exception as e: errors.append(f"Castle: Search decrypt failed - {str(e)}") return results, errors if search_results is None: errors.append("Castle: No search data in response") return results, errors
# Find matching movie by title movie_list = search_results if isinstance(search_results, list) else search_results.get("list", search_results.get("data", [])) if not isinstance(movie_list, list): movie_list = [] if search_parsed.get("code") != 200: errors.append(f"Castle: Search API error - {search_parsed.get('msg', 'unknown')}") return results, errors
# Find matching movie data_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, errors
title_lower = title.lower().strip() matched_movie = None for item in movie_list: item_title = (item.get("title") or item.get("name") or "").lower().strip() item_id = item.get("id") if not item_id: continue if item_title == title_lower or title_lower in item_title or item_title in title_lower: matched_movie = item matched_id = None for 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") break
if not matched_movie and movie_list: matched_movie = movie_list[0]
if not matched_movie: errors.append("Castle: No matching movie found in search results") if not matched_id: matched_id = rows[0].get("id") if not matched_id: errors.append("Castle: No matching result") return results, errors
movie_id = matched_movie.get("id") movie_id = str(matched_id)
# Step 3: Get movie details # Step 3: Get details detail_resp = await client.get( f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={"channel": "", "id": movie_id}, headers={"Accept": "application/json"} 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 request failed HTTP {detail_resp.status_code}") errors.append(f"Castle: Detail HTTP {detail_resp.status_code}") return results, errors
detail_data = detail_resp.json() encrypted_detail = detail_data.get("data", "") if isinstance(encrypted_detail, (dict, list)): detail_parsed = encrypted_detail elif 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 = {} try: 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 season episode_id = None if media_type == "tv" and season and episode: seasons = detail_data.get("seasons", []) target_season = None for s in seasons: if s.get("number") == season or s.get("seasonNum") == season: target_season = s break if target_season and target_season.get("id"): season_id = str(target_season["id"]) if season_id != movie_id: # Fetch season details s_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_data movie_id = season_id except: pass # Find episode episodes = detail_data.get("episodes", []) for ep in episodes: if ep.get("number") == episode or ep.get("episodeNum") == episode: episode_id = str(ep.get("id", "")) break else: detail_parsed = detail_data # For movies: use first episode/language episodes = detail_data.get("episodes", []) if episodes: episode_id = str(episodes[0].get("id", ""))
# Step 4: Get video URL video_resp = await client.get( f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2", params={"clientType": "1", "channel": "", "id": movie_id}, headers={"Accept": "application/json"} ) if video_resp.status_code != 200: errors.append(f"Castle: Video request failed HTTP {video_resp.status_code}") if not episode_id: errors.append("Castle: Could not find episode") return results, errors
video_data = video_resp.json() encrypted_video = video_data.get("data", "") # Step 4: Get video URL - try language tracks first, then shared languages = detail_data.get("languages", detail_data.get("languageList", [])) video_parsed = None if isinstance(encrypted_video, (dict, list)): video_parsed = encrypted_video elif isinstance(encrypted_video, str) and encrypted_video: 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: continue 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 JSON 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: continue try: video_parsed = json.loads(encrypted_video) video_parsed = castle_decrypt(video_resp.text) except: errors.append(f"Castle: Video decryption failed - {str(dec_err)}") return results, errors if video_parsed is None: errors.append("Castle: No video data in response") return results, errors continue video_data = video_parsed.get("data", video_parsed) if not isinstance(video_data, dict): continue video_url = video_data.get("videoUrl", "") if not video_url: continue
# Extract stream URLs from video response def extract_castle_streams(obj, depth=0): streams = [] if depth > 10: return streams if isinstance(obj, dict): for key in ["url", "playUrl", "videoUrl", "streamUrl", "downloadUrl"]: val = obj.get(key, "") if val and isinstance(val, str) and (val.startswith("http") or ".m3u8" in val): quality = obj.get("quality") or obj.get("resolution") or obj.get("name") or "Auto" lang = obj.get("language") or obj.get("lang") or "" name = obj.get("name") or obj.get("title") or obj.get("serverName") or "" streams.append({ "url": val, "quality": str(quality), "language": lang, "name": name, # Extract quality variants videos = 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", }) for key in ["list", "sources", "episodes", "items", "videoInfo", "playList"]: child = obj.get(key) if child: streams.extend(extract_castle_streams(child, depth + 1)) if not streams: for v in obj.values(): if isinstance(v, (dict, list)): streams.extend(extract_castle_streams(v, depth + 1)) elif isinstance(obj, list): for item in obj: streams.extend(extract_castle_streams(item, depth + 1)) return streams
castle_streams = extract_castle_streams(video_parsed)
for cs in castle_streams: s_url = cs["url"] quality = cs.get("quality", "Auto") q_match = re.search(r'(\d{3,4})p', str(quality)) if q_match: quality = q_match.group(1) + "p" elif "4k" in 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") 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 track if 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": name or "Castle Stream", "quality": quality, "language": lang, "url": s_url, "type": s_type, }) 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
# Deduplicate seen_urls = set()5 unmodified lines results = unique_results
if not results: errors.append("Castle: No streams found after decryption") errors.append("Castle: No streams found")
except ImportError: errors.append("Castle: pycryptodome not installed")2 unmodified lines
return results, errors
# ===== MovieBox Scraper (h5-api.aoneroom.com) =====
async def scrape_moviebox(tmdb_id: int, media_type: str, season: int = None, episode: int = None):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", "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