import json import re from pathlib import Path from urllib.parse import quote, urljoin from server.services.dramabox import api from server.services.dramabox.client import client from server.services.http import http from server.services.playlist import is_direct_media, looks_like_segment CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "dramabox" / "playlists" def load_episodes(drama_id: str, language: str = "") -> list[dict]: drama_id = str(drama_id or "").strip() language = (language or client.language).strip() if not drama_id: raise RuntimeError("没有这部剧") cached = _read_cache(drama_id, language) fresh = _fetch_episodes(drama_id, language) merged, save = _merge(cached, fresh) if save or (not cached and merged): _write_cache(drama_id, language, 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, drama_id: str = "") -> str: if is_direct_media(src): raise RuntimeError("这一集是整段视频") headers = api.cdn_headers(book_id=drama_id) text = http.read_text(src, headers=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=headers), variant_url) def _fetch_episodes(drama_id: str, language: str = "") -> list[dict]: data = api.film(drama_id, language or None) rows = data.get("chapterList") if isinstance(data, dict) else None if not isinstance(rows, list) or not rows: raise RuntimeError("没有读到分集") episodes = [] for item in rows: if not isinstance(item, dict): continue cid = _int(item.get("id")) idx = _int(item.get("index")) + 1 if cid <= 0: continue if idx <= 0: idx = len(episodes) + 1 src, kind = _choose_src(item) unlocked = item.get("unlock") is True row = { "cid": cid, "idx": idx, "title": str(item.get("name") or f"第{idx}集").strip() or f"第{idx}集", "src": src, "src_kind": kind, "type": "free" if unlocked else "lock", "price": _int(item.get("chapterPrice")), "cover": str(item.get("cover") or ""), "duration": _int(item.get("duration")), "is_preview": False, "preview_seconds": 0, "hls_key": "", "locked_reason": "" if src else ("需要解锁" if not unlocked else "没有可下载的地址"), } episodes.append(row) if not episodes: raise RuntimeError("没有读到分集") return episodes def _choose_src(item: dict) -> tuple[str, str]: m3u8 = str(item.get("m3u8Url") or "").strip() mp4 = str(item.get("mp4") or "").strip() if m3u8 and not is_direct_media(m3u8): return m3u8, "hls" if mp4: return mp4, "file" if m3u8: return m3u8, "file" if is_direct_media(m3u8) else "hls" 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 _cache_file(drama_id: str, language: str = "") -> Path: return CACHE_DIR / (language or client.language) / f"{drama_id}.json" def _read_cache(drama_id: str, language: str = "") -> list[dict]: path = _cache_file(drama_id, language) 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, language: str, episodes: list[dict]) -> None: path = _cache_file(drama_id, language) path.parent.mkdir(parents=True, exist_ok=True) 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/dramabox/play/segment?url=" + quote(url, safe="") def _int(value) -> int: try: return int(float(str(value))) except (TypeError, ValueError): return 0