Spaces:
Running
Running
Commit ·
f0eee2c
1
Parent(s): 06776a7
fix: completely rewrite Castle scraper with type-safe .get() calls
Browse files483 unmodified lines4844854864874884894904914924934874884894902 unmodified lines493494495502496497498499500507501502503504511512513514515505506507508509510511517518519520521522523512513514515516517525526527528529518519520521522523532533534535536537538539540541542543544545546547524525526527528529530531532533534535536549550551537538539540541554555556557558559560561562563564565566567568569570571572573574575576577578542543544545546547548549550551552553554555556557582558559584560561562587588563564565566591592593594595596597598599600601602603567568569570571572573574575576606577578579609610611612613614580581582583584585586587588589616617618619590591592593594595596597622623624625626627628629630631632633634635636598599600601602603604605638606640607608642609610611612613614615616644645646647648649650651652617618619654655620621622623624658625626627628629630631632633634635636637660661662663664665666667668669670671672673674675676677678679680681682683684685638639640641687642643644645690691692693646647648649695696650651652653699700701702703704705706654655656657658659660661662663708709710711712713714715716717718719720664665666667668669722723724725670671672673727728674675730731732733734735736737738739740741742743744745746747748749750751676677678679680681682683684685686687688689690691692693753754755756757758694695696697698699700701761762702764765766767768769703704705706707708709771772710711774712713714777778779780781782783784785786787788715716717718719720790791792793721722723724795796797798799800801802803804805725726727728729730731732733734735808736737738811812739740741814815742743744818819745746747821822823824748749750751752753827754755756757758832759760761762483 unmodified lines return results, errors
# ===== 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"# ===== Castle Scraper (hlowb.com API with AES-CBC) =====
async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = []2 unmodified lines try: from Crypto.Cipher import AES from Crypto.Util.Padding import unpad import traceback as _tb
info = await get_tmdb_info(tmdb_id, media_type) title = info.get("title", "") imdb_id = info.get("imdb_id", "") if not title: errors.append("Castle: Could not get title from TMDB") errors.append("Castle: No title from TMDB") return results, errors
CASTLE_BASE = "https://api.hlowb.com" CASTLE_HEADERS = { "User-Agent": "okhttp/4.9.3", "Accept": "application/json", "Accept-Language": "en-US", } PKG = "com.gwzq.clz" CH = "1" CLI = "1" LANG = "en-US" SIGN = "ED0955EB04E67A1D9F3305B95454FED485261475" HEADERS = {"User-Agent": "okhttp/4.9.3", "Accept": "application/json", "Accept-Language": "en-US"}
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client: # Step 1: Get security key sec_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}") async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: # Get security key sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/{CH}?clientType={CLI}&lang={LANG}") if sec_r.status_code != 200: errors.append(f"Castle: sec key HTTP {sec_r.status_code}") return results, errors
sec_data = sec_resp.json() raw_key = sec_data.get("data", "") if not raw_key: errors.append("Castle: No security key") 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 format") return results, errors try: 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 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
def castle_decrypt(encrypted_text: str) -> dict: """Decrypt Castle API response""" # Try JSON-wrapped first data_str = encrypted_text sec_key = base64.b64decode(raw_k).decode("utf-8", errors="ignore") except: sec_key = raw_k
# Derive AES key 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): """Decrypt Castle response""" d = text try: j = json.loads(encrypted_text) if isinstance(j.get("data"), str): data_str = j["data"] j = json.loads(text) if isinstance(j, dict) and isinstance(j.get("data"), str): d = 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']}"
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}") raw = base64.b64decode(d) c = AES.new(aes_k, AES.MODE_CBC, aes_iv) dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore") return json.loads(dec)
# Search kw = f"{title} {info.get('year', '')}".strip() sr = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={ "channel": CH, "clientType": CLI, "keyword": kw, "lang": LANG, "mode": "1", "packageName": PKG, "page": "1", "size": "20" }) if sr.status_code != 200: errors.append(f"Castle: search HTTP {sr.status_code}") return results, errors
try: search_parsed = castle_decrypt(search_resp.text) sp = cdec(sr.text) except Exception as e: errors.append(f"Castle: Search decrypt failed - {str(e)}") errors.append(f"Castle: search decrypt fail: {e}") return results, errors
if search_parsed.get("code") != 200: errors.append(f"Castle: Search API error - {search_parsed.get('msg', 'unknown')}") if not isinstance(sp, dict) or sp.get("code") != 200: errors.append(f"Castle: search error {sp.get('msg','?') if isinstance(sp, dict) else type(sp)}") return results, errors
# Find matching movie data_block = search_parsed.get("data", {}) if isinstance(data_block, str): try: data_block = json.loads(data_block) except: data_block = {} if not isinstance(data_block, dict): errors.append(f"Castle: Unexpected data_block type: {type(data_block).__name__}") return results, errors rows = data_block.get("rows", []) if not rows: errors.append(f"Castle: No rows in data_block, keys={list(data_block.keys())[:5]}") db = sp.get("data", {}) if isinstance(db, str): try: db = json.loads(db) except: db = {} if not isinstance(db, dict): errors.append(f"Castle: data not dict: {type(db)}") return results, errors
rows = db.get("rows", []) if not rows: errors.append("Castle: No search results") errors.append("Castle: no results") return results, errors
title_lower = title.lower().strip() 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") # Match by title mid = None tl = title.lower() for r in rows: if not isinstance(r, dict): continue rt = (r.get("title") or "").lower() if tl in rt or rt in tl: mid = r.get("id") break if not matched_id: matched_id = rows[0].get("id") if not matched_id: errors.append("Castle: No matching result") if not mid and rows: if isinstance(rows[0], dict): mid = rows[0].get("id") if not mid: errors.append("Castle: no match") return results, errors mid = str(mid)
movie_id = str(matched_id)
# Step 3: Get details 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": movie_id, "packageName": CASTLE_PKG, } ) if detail_resp.status_code != 200: errors.append(f"Castle: Detail HTTP {detail_resp.status_code}") # Get details dr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={ "channel": CH, "clientType": CLI, "lang": LANG, "movieId": mid, "packageName": PKG }) if dr.status_code != 200: errors.append(f"Castle: detail HTTP {dr.status_code}") return results, errors
try: detail_parsed = castle_decrypt(detail_resp.text) dp = cdec(dr.text) except: detail_parsed = {} dp = {} dd = dp.get("data", dp) if isinstance(dd, str): try: dd = json.loads(dd) except: dd = {} if not isinstance(dd, dict): dd = {}
detail_data = detail_parsed.get("data", detail_parsed) if isinstance(detail_parsed, dict) else {} if isinstance(detail_data, str): try: detail_data = json.loads(detail_data) except: detail_data = {}
# For TV: navigate to season episode_id = None # For TV: find season/episode ep_id = None if media_type == "tv" and season and episode: seasons = detail_data.get("seasons", []) target_season = None 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: target_season = s sid = s.get("id") if sid and str(sid) != mid: s_id = str(sid) sdr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={ "channel": CH, "clientType": CLI, "lang": LANG, "movieId": s_id, "packageName": PKG }) try: sdp = cdec(sdr.text) sdd = sdp.get("data", sdp) if isinstance(sdd, dict): dd = sdd except: pass break 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: eps = dd.get("episodes", []) for ep in eps: if not isinstance(ep, dict): continue if ep.get("number") == episode or ep.get("episodeNum") == episode: episode_id = str(ep.get("id", "")) ep_id = str(ep.get("id", "")) break mid = s_id else: # For movies: use first episode/language episodes = detail_data.get("episodes", []) if episodes: episode_id = str(episodes[0].get("id", "")) eps = dd.get("episodes", []) if eps and isinstance(eps[0], dict): ep_id = str(eps[0].get("id", ""))
if not episode_id: errors.append("Castle: Could not find episode") if not ep_id: errors.append("Castle: no episode found") return results, errors
# Step 4: Get video URL - try language tracks first, then shared languages = 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: continue # Get video - try language tracks langs = dd.get("languages", dd.get("languageList", [])) if not isinstance(langs, list): langs = []
for lt in langs: if not isinstance(lt, dict): continue ln = lt.get("name", lt.get("languageName", "")) lid = lt.get("languageId", lt.get("id", "")) if not lid: continue 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, "languageId": str(lang_id), "isNewUser": "1", "resolution": "2", "packageName": CASTLE_PKG, body = { "mode": "1", "appMarket": "google_play", "clientType": CLI, "woolUser": "0", "apkSignKey": SIGN, "androidVersion": "13", "movieId": mid, "episodeId": ep_id, "languageId": str(lid), "isNewUser": "1", "resolution": "2", "packageName": 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"} vr = await client.post( f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo?clientType={CLI}&packageName={PKG}&channel={CH}&lang={LANG}", json=body, headers={"Content-Type": "application/json"} ) if video_resp.status_code != 200: continue if vr.status_code != 200: continue try: video_parsed = castle_decrypt(video_resp.text) except: continue video_data = video_parsed.get("data", video_parsed) if isinstance(video_data, str): try: video_data = json.loads(video_data) except: video_data = {} if not isinstance(video_data, dict): continue video_url = video_data.get("videoUrl", "") if not video_url: continue
# 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)) vp = cdec(vr.text) except: continue vd = vp.get("data", vp) if isinstance(vd, str): try: vd = json.loads(vd) except: continue if not isinstance(vd, dict): continue vurl = vd.get("videoUrl", "") if not vurl: continue
vids = vd.get("videos", []) if vids and isinstance(vids, list): for v in vids: if not isinstance(v, dict): continue vu = v.get("url", vurl) q = v.get("resolutionDescription", v.get("resolution", "720p")) q = re.sub(r'^(SD|HD|FHD)\s+', '', str(q)) 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", "source": f"Castle [{ln}]", "title": f"Castle {ln} - {q}", "quality": q, "language": detect_language(ln) if ln else "English", "url": vu, "type": "m3u8" if ".m3u8" in vu 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", "source": f"Castle [{ln}]", "title": f"Castle {ln} - 720p", "quality": "720p", "language": detect_language(ln) if ln else "English", "url": vurl, "type": "m3u8" if ".m3u8" in vurl else "direct", }) except: continue except: continue
# Fallback: shared video without language track # Fallback: shared video 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, body = { "mode": "1", "appMarket": "google_play", "clientType": CLI, "woolUser": "0", "apkSignKey": SIGN, "androidVersion": "13", "movieId": mid, "episodeId": ep_id, "isNewUser": "1", "resolution": "3", "packageName": 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"} vr = await client.post( f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo?clientType={CLI}&packageName={PKG}&channel={CH}&lang={LANG}", json=body, headers={"Content-Type": "application/json"} ) if video_resp.status_code == 200: video_parsed = castle_decrypt(video_resp.text) video_data = video_parsed.get("data", video_parsed) if isinstance(video_data, str): try: video_data = json.loads(video_data) except: video_data = {} if isinstance(video_data, dict): video_url = video_data.get("videoUrl", "") if video_url: if vr.status_code == 200: vp = cdec(vr.text) vd = vp.get("data", vp) if isinstance(vd, str): try: vd = json.loads(vd) except: vd = {} if isinstance(vd, dict): vurl = vd.get("videoUrl", "") if vurl: results.append({ "source": "Castle", "title": "Castle Stream - 1080p", "title": "Castle - 1080p", "quality": "1080p", "language": "English", "url": video_url, "type": "m3u8" if ".m3u8" in video_url else "direct", "url": vurl, "type": "m3u8" if ".m3u8" in vurl else "direct", }) except: pass except: pass
# Deduplicate seen_urls = set() unique_results = [] seen = set() uniq = [] for r in results: if r["url"] not in seen_urls: seen_urls.add(r["url"]) unique_results.append(r) results = unique_results if r["url"] not in seen: seen.add(r["url"]) uniq.append(r) results = uniq
if not results: errors.append("Castle: No streams found") errors.append("Castle: no streams found")
except ImportError: errors.append("Castle: pycryptodome not installed") except Exception as e: errors.append(f"Castle: {str(e)}") errors.append(f"Castle ERR: {type(e).__name__}: {str(e)}")
return results, errors
main.py+194-267