import re 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 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("没有这部剧") # 分集只走 App 接口。登录页选的地区决定请求语言。 if not client.can_browse(): raise RuntimeError("请先进入 DramaBox") from server.services.dramabox.app_api import load_app_episodes return load_app_episodes(drama_id) 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 _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="")