import json import re 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.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" CDN_HEADERS = {"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"} def load_episodes(drama_id: str) -> list[dict]: drama_id = str(drama_id or "").strip() if not drama_id: raise RuntimeError("没有这部剧") cached = _read_cache(drama_id) fresh = _fetch_episodes(drama_id) merged, save = _merge(cached, fresh) if save or (not cached and merged): _write_cache(drama_id, merged) return merged def episode_src(drama_id: str, cid: int) -> dict: for ep in load_episodes(drama_id): if int(ep.get("cid") or 0) == int(cid): return ep return {} 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 _choose_src(played: dict) -> tuple[str, str]: candidates: list[str] = [] for value in (played.get("m3u8"),): text = str(value or "").strip() if text: candidates.append(text) lines = played.get("lines") if isinstance(played.get("lines"), list) else [] for line in lines: if not isinstance(line, dict): continue url = str(line.get("url") or "").strip() if url: candidates.append(url) preview = str(played.get("preview_m3u8") or "").strip() if preview: candidates.append(preview) for url in candidates: if url and not is_direct_media(url): return url, "hls" for url in candidates: 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 _fetch_episodes(drama_id: str) -> list[dict]: detail = api.drama_detail(drama_id) 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 seq = _int(item.get("seq")) if seq <= 0: continue kind = str(item.get("type") or "free").strip() or "free" skeleton.append({ "cid": seq, "idx": seq, "title": str(item.get("name") or f"第{seq}集").strip() or f"第{seq}集", "src": "", "type": kind, "price": _int(item.get("price")), "is_buy": item.get("is_buy") is True or item.get("is_buy") is None, "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": "", }) if not skeleton: raise RuntimeError("没有读到分集") def play_one(row: dict) -> dict: try: played = api.drama_play(drama_id, int(row["cid"])) except RuntimeError as exc: row["locked_reason"] = str(exc) or "这一集暂时不能下载" 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: if kind == "file" or row["is_preview"]: row["is_preview"] = True row["locked_reason"] = "当前账号只能下到试看" else: 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 _lock_reason(row: dict) -> str: kind = str(row.get("type") or "free") if kind in {"vip", "VIP"}: return "需要 VIP" if kind in {"coin", "points", "point", "pay"}: return "需要积分或付费" if not row.get("is_buy"): return "尚未购买" return "没有可下载的地址" def _merge(cached: list[dict], fresh: list[dict]) -> tuple[list[dict], bool]: by_cid: dict[int, dict] = {} for source in (cached, fresh): for ep in source: cid = _int(ep.get("cid")) if cid <= 0: continue current = by_cid.get(cid) if current is None: by_cid[cid] = dict(ep) by_cid[cid]["cid"] = cid by_cid[cid]["idx"] = _int(ep.get("idx") or cid) continue for key, value in ep.items(): if key == "src": if value: current["src"] = value continue if value not in (None, "", [], {}): current[key] = value merged = sorted(by_cid.values(), key=lambda item: (int(item.get("idx") or 0), int(item["cid"]))) filled_fresh = sum(1 for ep in fresh if ep.get("src")) filled_cached = sum(1 for ep in cached if ep.get("src")) return merged, filled_fresh >= filled_cached and filled_fresh > 0 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