import json import re import threading from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from urllib.parse import quote, urljoin from server.services.huangdou import api from server.services.huangdou.client import TokenExpired, client from server.services.huangdou.coins import ( PAID_TYPES, VIP_TYPES, already_bought, buy_method, episode_kind, episode_note, keep_episode, price_of, public_lock_reason, ) from server.services.http import http from server.services.huangdou.crypto import USER_AGENT from server.services.playlist import is_direct_media, looks_like_segment CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "playlists" _cache_lock = threading.Lock() def _cdn_headers() -> dict: return {"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"} def load_episodes(drama_id: str) -> list[dict]: drama_id = str(drama_id or "").strip() if not drama_id: raise RuntimeError("没有这部剧") detail = api.drama_detail(drama_id, identity=_viewer_identity()) rows = detail.get("episodes") if isinstance(detail, dict) else None if not isinstance(rows, list) or not rows: raise RuntimeError("没有读到分集") fresh = _menu_rows(rows) if not fresh: raise RuntimeError("没有读到分集") merged = _keep_sources(_read_cache(drama_id), fresh) _write_cache(drama_id, merged) return merged def episode_src(drama_id: str, cid: int) -> dict: drama_id = str(drama_id or "").strip() row = _cached_row(drama_id, cid) if row is None: row = _cached_row(drama_id, cid, refresh=True) if not row: return {} if not row.get("playable") or row.get("src"): return row played = _play_rows(drama_id, [dict(row)], allow_buy=False) updated = played[0] if played else row _store_row(drama_id, updated) return updated def playback_playlist(src: str) -> str: if is_direct_media(src): raise RuntimeError("这一集是整段视频") text = http.read_text(src, headers=_cdn_headers()) variant_rel = next( (line.strip() for line in text.splitlines() if line.strip() and not line.startswith("#")), "", ) if not variant_rel: raise RuntimeError("播放列表没有视频地址") if looks_like_segment(variant_rel): return _rewrite_playlist(text, src) variant_url = urljoin(src, variant_rel) return _rewrite_playlist(http.read_text(variant_url, headers=_cdn_headers()), variant_url) def decode_key(value: str) -> bytes: text = (value or "").strip() if not text: return b"" try: raw = bytes.fromhex(text) if raw: return raw except ValueError: pass import base64 try: return base64.b64decode(text) except Exception: return text.encode("utf-8") def store_fallback_key(source_dir: Path, key: str) -> None: raw = decode_key(key) if not raw: return source_dir.mkdir(parents=True, exist_ok=True) (source_dir / "hls.key").write_bytes(raw) def line_options(played: dict) -> list[dict]: found = [] seen: set[str] = set() lines = played.get("lines") if isinstance(played.get("lines"), list) else [] for line in lines: if not isinstance(line, dict): continue name = str(line.get("name") or "").strip() url = str(line.get("url") or "").strip() if not name or not url or name in seen: continue seen.add(name) found.append({"name": name, "label": name}) return found def available_lines(host: str = "") -> list[dict]: if host: client.set_host(host) rows = _guest_rows(lambda: api.drama_list(page=1, page_size=3)) last_error = "没有读到线路" for item in rows: if not isinstance(item, dict): continue drama_id = str(item.get("id") or "").strip() if not drama_id: continue try: played = _guest_rows(lambda current=drama_id: api.drama_play(current, 1)) except RuntimeError as exc: last_error = str(exc) or last_error continue if not isinstance(played, dict): continue lines = line_options(played) if lines: return lines raise RuntimeError(last_error) def _guest_rows(load): try: if not client.token: api.login_device() return load() except TokenExpired: api.login_device() return load() def _choose_src(played: dict) -> tuple[str, str]: selected = (client.play_line or "").strip() lines = played.get("lines") if isinstance(played.get("lines"), list) else [] named: list[tuple[str, str]] = [] for line in lines: if not isinstance(line, dict): continue name = str(line.get("name") or "").strip() url = str(line.get("url") or "").strip() if url: named.append((name, url)) ordered = [] if selected: ordered.extend(url for name, url in named if name == selected) ordered.extend(url for _name, url in named) m3u8 = str(played.get("m3u8") or "").strip() if m3u8: ordered.append(m3u8) preview = str(played.get("preview_m3u8") or "").strip() if preview: ordered.append(preview) for url in ordered: if url and not is_direct_media(url): return url, "hls" for url in ordered: if is_direct_media(url): return url, "file" return "", "" def apply_hls_key(text: str, source_dir: Path, key: str) -> str: secret = (key or "").strip() if not secret: return text if "EXT-X-KEY" in text.upper(): return text raw = decode_key(secret) if not raw: return text source_dir.mkdir(parents=True, exist_ok=True) (source_dir / "hls.key").write_bytes(raw) lines = text.splitlines() inserted = False result = [] for line in lines: result.append(line) if not inserted and line.startswith("#EXTM3U"): result.append('#EXT-X-KEY:METHOD=AES-128,URI="hls.key"') inserted = True if not inserted: result.insert(0, '#EXT-X-KEY:METHOD=AES-128,URI="hls.key"') return "\n".join(result) + "\n" def load_for_download(drama_id: str, *, allow_paid: bool, account_vip: bool) -> list[dict]: drama_id = str(drama_id or "").strip() if not drama_id: raise RuntimeError("没有这部剧") detail = api.drama_detail(drama_id, identity=_viewer_identity()) rows = detail.get("episodes") if isinstance(detail, dict) else None if not isinstance(rows, list) or not rows: raise RuntimeError("没有读到分集") skeleton = [] for item in rows: if not isinstance(item, dict): continue if not keep_episode(item, allow_paid=allow_paid, account_vip=account_vip): continue row = _skeleton_row(item, account_vip=account_vip) if row: skeleton.append(row) return _play_rows(drama_id, skeleton, allow_buy=allow_paid) def _viewer_identity() -> str: return "account" if client.account_token else "guest" def _menu_rows(rows: list) -> list[dict]: from server.services.huangdou.login import account_is_vip vip = account_is_vip() skeleton = [] for item in rows: if not isinstance(item, dict): continue row = _skeleton_row(item, account_vip=vip) if row: skeleton.append(row) return skeleton def _skeleton_row(item: dict, *, account_vip: bool) -> dict | None: seq = _int(item.get("seq")) if seq <= 0: return None kind = str(item.get("type") or "free").strip() or "free" playable, reason, points = episode_note(item, account_vip=account_vip) return { "cid": seq, "idx": seq, "title": str(item.get("name") or f"第{seq}集").strip() or f"第{seq}集", "src": "", "type": kind, "price": price_of(item), "points": points, "playable": playable, "needs_coin": points > 0, "is_buy": item.get("is_buy"), "cover": str(item.get("cover") or ""), "duration": _int(item.get("duration")), "methods": item.get("methods") if isinstance(item.get("methods"), list) else [], "is_preview": False, "preview_seconds": 0, "preview_m3u8": "", "hls_key": "", "src_kind": "", "locked_reason": reason, } def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[dict]: if not skeleton: return [] def play_one(row: dict) -> dict: if row.get("needs_coin") and not already_bought(row): if not allow_buy or not client.account_token: row["src"] = "" row["playable"] = False row["locked_reason"] = public_lock_reason(row, row.get("locked_reason") or "") return row try: api.drama_buy(drama_id, int(row["cid"]), buy_method(row)) except RuntimeError as exc: row["src"] = "" row["playable"] = False row["locked_reason"] = public_lock_reason(row, str(exc)) return row row["is_buy"] = True row["needs_coin"] = False row["points"] = 0 identity = "account" if _uses_account(row) else "guest" try: played = api.drama_play(drama_id, int(row["cid"]), identity=identity) except RuntimeError as exc: row["src"] = "" row["playable"] = False row["locked_reason"] = public_lock_reason(row, str(exc)) return row preview = str(played.get("preview_m3u8") or "").strip() row["hls_key"] = str(played.get("hls_key") or "").strip() row["is_preview"] = played.get("is_preview") is True row["preview_seconds"] = _int(played.get("preview_seconds")) row["preview_m3u8"] = preview src, kind = _choose_src(played) row["src"] = src row["src_kind"] = kind if src: row["playable"] = True if kind == "file" or row["is_preview"]: row["is_preview"] = True row["locked_reason"] = "" row["points"] = 0 else: row["playable"] = False row["locked_reason"] = _lock_reason(row) return row updated = [] with ThreadPoolExecutor(max_workers=6) as pool: futures = [pool.submit(play_one, dict(row)) for row in skeleton] by_cid = {} for future in as_completed(futures): row = future.result() by_cid[int(row["cid"])] = row for row in skeleton: updated.append(by_cid.get(int(row["cid"]), row)) return updated def _uses_account(row: dict) -> bool: if not client.account_token: return False kind = episode_kind(row) if kind in VIP_TYPES: return True if kind in PAID_TYPES or _int(row.get("price")) > 0: return bool(already_bought(row) or row.get("needs_coin")) return False def _lock_reason(row: dict) -> str: if _int(row.get("points") or row.get("price")) > 0 and not already_bought(row): return public_lock_reason(row, "") kind = episode_kind(row) if kind in VIP_TYPES: return "需要 VIP" return "没有可播放的地址" def _cached_row(drama_id: str, cid: int, *, refresh: bool = False) -> dict | None: rows = load_episodes(drama_id) if refresh else _read_cache(drama_id) for ep in rows: if int(ep.get("cid") or 0) == int(cid): return ep return None def _keep_sources(cached: list[dict], fresh: list[dict]) -> list[dict]: previous = {int(ep.get("cid") or 0): ep for ep in cached if int(ep.get("cid") or 0) > 0} merged = [] for row in fresh: old = previous.get(int(row["cid"])) if old and old.get("is_preview"): row["is_preview"] = True if row.get("playable") and old and old.get("src") and not old.get("is_preview"): row["src"] = old.get("src") or "" row["src_kind"] = old.get("src_kind") or "" row["hls_key"] = old.get("hls_key") or "" row["preview_seconds"] = old.get("preview_seconds") or 0 row["preview_m3u8"] = old.get("preview_m3u8") or "" merged.append(row) return merged def _store_row(drama_id: str, row: dict) -> None: with _cache_lock: rows = _read_cache(drama_id) cid = int(row.get("cid") or 0) replaced = False updated = [] for item in rows: if int(item.get("cid") or 0) == cid: updated.append(row) replaced = True else: updated.append(item) if not replaced: updated.append(row) _write_cache(drama_id, updated) def _read_cache(drama_id: str) -> list[dict]: path = CACHE_DIR / f"{drama_id}.json" if not path.is_file(): return [] try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return [] rows = data.get("episodes") if isinstance(data, dict) else None return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else [] def _write_cache(drama_id: str, episodes: list[dict]) -> None: CACHE_DIR.mkdir(parents=True, exist_ok=True) path = CACHE_DIR / f"{drama_id}.json" temporary = path.with_suffix(".json.tmp") temporary.write_text(json.dumps({"episodes": episodes}, ensure_ascii=False), encoding="utf-8") temporary.replace(path) def _rewrite_playlist(text: str, base: str) -> str: lines = [] for line in text.splitlines(): stripped = line.strip() if not stripped: lines.append(line) continue if stripped.startswith("#"): lines.append(_rewrite_tag(line, base)) continue lines.append(_proxy_url(urljoin(base, stripped))) return "\n".join(lines) + "\n" def _rewrite_tag(line: str, base: str) -> str: def replace(match): return 'URI="' + _proxy_url(urljoin(base, match.group(1))) + '"' return re.sub(r'URI="([^"]*)"', replace, line) def _proxy_url(url: str) -> str: return "/api/huangdou/play/segment?url=" + quote(url, safe="") def _int(value) -> int: try: return int(float(str(value))) except (TypeError, ValueError): return 0