Files

490 lines
16 KiB
Python

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 {}
stale = not row.get("lines_ready")
if (row.get("playable") and stale) or row.get("locked_reason") == "登录已失效":
played = _play_rows(drama_id, [dict(row)], allow_buy=False)
updated = played[0] if played else row
_store_row(drama_id, updated)
return updated
return row
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 _preview_url(url: str) -> bool:
path = (url or "").split("?", 1)[0].lower()
return path.endswith("preview.mp4") or "/preview." in path
def _line_urls(played: dict, *, allow_preview: bool) -> list[str]:
urls: list[str] = []
def add(value) -> None:
url = str(value or "").strip()
if not url or url in urls:
return
if not allow_preview and _preview_url(url):
return
urls.append(url)
lines = played.get("lines") if isinstance(played.get("lines"), list) else []
for line in lines:
if isinstance(line, dict):
add(line.get("url"))
add(played.get("m3u8"))
if allow_preview:
add(played.get("preview_m3u8"))
return urls
def _open_src(url: str) -> tuple[str, str] | None:
if is_direct_media(url):
return None if _preview_url(url) else (url, "file")
try:
text = http.read_text(url, headers=_cdn_headers())
except Exception:
return None
if "#EXTM3U" not in text.upper():
return None
return url, "hls"
def _choose_src(played: dict) -> tuple[str, str]:
urls = _line_urls(played, allow_preview=False) or _line_urls(played, allow_preview=True)
for url in urls:
if not is_direct_media(url):
return url, "hls"
for url in urls:
if is_direct_media(url) and not _preview_url(url):
return url, "file"
return "", ""
def _ordered_line_urls(played: dict, src: str) -> list[str]:
urls = _line_urls(played, allow_preview=False)
chosen = (src or "").strip()
if chosen and not _preview_url(chosen):
urls = [chosen, *[url for url in urls if url != chosen]]
return urls
def pick_line(row: dict, line: int) -> str:
urls: list[str] = []
for item in row.get("line_urls") or []:
text = str(item or "").strip()
if text and text not in urls and not _preview_url(text):
urls.append(text)
src = str(row.get("src") or "").strip()
if src and not _preview_url(src) and src not in urls:
urls.insert(0, src)
if line < 0:
line = 0
if not urls:
return src if line == 0 else ""
if line >= len(urls):
return ""
return urls[line]
def _resolve_src(played: dict, *, allow_preview: bool) -> tuple[str, str]:
for url in _line_urls(played, allow_preview=False):
opened = _open_src(url)
if opened:
return opened
if not allow_preview:
return "", ""
for url in _line_urls(played, allow_preview=True):
if _preview_url(url) and is_direct_media(url):
return url, "file"
opened = _open_src(url)
if opened:
return opened
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,
"line_urls": [],
"lines_ready": 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["lines_ready"] = True
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["lines_ready"] = True
row["locked_reason"] = public_lock_reason(row, str(exc))
return row
row["is_buy"] = True
row["needs_coin"] = False
row["points"] = 0
vip_episode = episode_kind(row) in VIP_TYPES
identity = "account" if _uses_account(row) else "guest"
try:
played = api.drama_play(drama_id, int(row["cid"]), identity=identity)
except TokenExpired:
row["src"] = ""
row["playable"] = False
row["is_preview"] = False
row["lines_ready"] = False
row["locked_reason"] = "登录已失效"
return row
except RuntimeError as exc:
row["src"] = ""
row["playable"] = False
row["lines_ready"] = True
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["preview_seconds"] = _int(played.get("preview_seconds"))
row["preview_m3u8"] = preview
src, kind = _resolve_src(played, allow_preview=not vip_episode)
row["src"] = src
row["src_kind"] = kind
row["line_urls"] = _ordered_line_urls(played, src)
row["lines_ready"] = True
if src:
row["playable"] = True
row["is_preview"] = (not vip_episode) and (kind == "file" and _preview_url(src) or played.get("is_preview") is True and _preview_url(src))
row["locked_reason"] = ""
row["points"] = 0
else:
row["playable"] = False
row["is_preview"] = False
row["locked_reason"] = _vip_lock_reason(row) if vip_episode else _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 _vip_lock_reason(row: dict) -> str:
if not client.account_token:
return "需要 VIP"
try:
api.user_info(identity="account")
except TokenExpired:
client.account_token = ""
client.save()
return "登录已失效"
except RuntimeError:
return "这一集暂时不能播放"
return "这一集暂时不能播放"
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") and episode_kind(row) not in VIP_TYPES:
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["line_urls"] = old.get("line_urls") or []
row["lines_ready"] = bool(old.get("lines_ready"))
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