feat: 接入黄豆短剧独立清单与下载
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""黄豆短剧平台。会话、清单和下载与 RaptDrama 隔离。"""
|
||||
@@ -0,0 +1,150 @@
|
||||
from server.services.huangdou.client import ApiError, TokenExpired, client
|
||||
from server.services.huangdou.crypto import USER_AGENT
|
||||
|
||||
|
||||
def device_info() -> dict:
|
||||
return {
|
||||
"browserName": "Chrome",
|
||||
"language": "zh-CN",
|
||||
"userAgent": USER_AGENT,
|
||||
"platform": "Win32",
|
||||
}
|
||||
|
||||
|
||||
def login_device(*, force_new: bool = False) -> dict:
|
||||
data = client.request(
|
||||
"/login/device",
|
||||
{
|
||||
"line_code": "china_1",
|
||||
"channel_code": "",
|
||||
"share_code": "",
|
||||
"clipboard_text": "",
|
||||
"force_new": "1" if force_new else "",
|
||||
"device_info": device_info(),
|
||||
},
|
||||
auth=False,
|
||||
)
|
||||
if not isinstance(data, dict):
|
||||
raise RuntimeError("设备登录没有返回数据")
|
||||
token = str(data.get("token") or "").strip()
|
||||
if not token:
|
||||
raise RuntimeError("设备登录没有返回 token")
|
||||
client.token = token
|
||||
return data
|
||||
|
||||
|
||||
def user_info() -> dict:
|
||||
data = client.request("/user/info", {}, auth=True)
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def system_info() -> dict:
|
||||
data = client.request(
|
||||
"/system/info",
|
||||
{
|
||||
"line_code": "china_1",
|
||||
"channel_code": "",
|
||||
"share_code": "",
|
||||
"clipboard_text": "",
|
||||
"device_info": device_info(),
|
||||
"package_name": "",
|
||||
},
|
||||
auth=True,
|
||||
)
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def nav_list() -> list[dict]:
|
||||
data = client.request("/drama/navList", {"with_filters": "1"}, auth=True)
|
||||
rows = _list_of(data)
|
||||
return [item for item in rows if isinstance(item, dict)]
|
||||
|
||||
|
||||
def nav_block(code: str, tab: str = "", page: int = 1) -> list[dict]:
|
||||
data = client.request(
|
||||
"/drama/navBlock",
|
||||
{"code": str(code or ""), "tab": str(tab or ""), "page": str(page)},
|
||||
auth=True,
|
||||
)
|
||||
rows = _list_of(data)
|
||||
return [item for item in rows if isinstance(item, dict)]
|
||||
|
||||
|
||||
def drama_list(
|
||||
*,
|
||||
page: int = 1,
|
||||
page_size: int = 18,
|
||||
keywords: str = "",
|
||||
order: str = "",
|
||||
cat_id: str = "",
|
||||
tag_id: str = "",
|
||||
source: str = "",
|
||||
canvas: str = "",
|
||||
pay_type: str = "",
|
||||
update_status: str = "",
|
||||
) -> list[dict]:
|
||||
body = {"page": str(page), "page_size": str(page_size)}
|
||||
if order:
|
||||
body["order"] = order
|
||||
if cat_id:
|
||||
body["cat_id"] = cat_id
|
||||
if tag_id:
|
||||
body["tag_id"] = tag_id
|
||||
if source:
|
||||
body["source"] = source
|
||||
if canvas:
|
||||
body["canvas"] = canvas
|
||||
if keywords:
|
||||
body["keywords"] = keywords
|
||||
if update_status:
|
||||
body["update_status"] = update_status
|
||||
if pay_type:
|
||||
body["pay_type"] = pay_type
|
||||
data = client.request("/drama/list", body, auth=True)
|
||||
rows = _list_of(data)
|
||||
return [item for item in rows if isinstance(item, dict)]
|
||||
|
||||
|
||||
def limited_free(page: int = 1) -> list[dict]:
|
||||
data = client.request("/drama/limitedFree", {"page": str(page), "size": "18"}, auth=True)
|
||||
rows = _list_of(data)
|
||||
return [item for item in rows if isinstance(item, dict)]
|
||||
|
||||
|
||||
def drama_detail(drama_id: str) -> dict:
|
||||
data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True)
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def drama_play(drama_id: str, seq: int) -> dict:
|
||||
data = client.request("/drama/play", {"id": str(drama_id), "seq": str(seq)}, auth=True)
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _list_of(data) -> list:
|
||||
if isinstance(data, list):
|
||||
return data
|
||||
if isinstance(data, dict):
|
||||
rows = data.get("list")
|
||||
if isinstance(rows, list):
|
||||
return rows
|
||||
items = data.get("items")
|
||||
if isinstance(items, list):
|
||||
return items
|
||||
return []
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ApiError",
|
||||
"TokenExpired",
|
||||
"client",
|
||||
"drama_detail",
|
||||
"drama_list",
|
||||
"drama_play",
|
||||
"limited_free",
|
||||
"login_device",
|
||||
"nav_block",
|
||||
"nav_list",
|
||||
"system_info",
|
||||
"user_info",
|
||||
]
|
||||
@@ -0,0 +1,261 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from server.services.huangdou import api
|
||||
from server.services.huangdou.covers import covers
|
||||
|
||||
CACHE_PATH = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "catalog.json"
|
||||
AD_STYLE = {"ad", "banner", "splash", "advert"}
|
||||
|
||||
|
||||
def enabled_cache() -> bool:
|
||||
flag = os.environ.get("RAPTD_CATALOG_CACHE", "1").strip().lower()
|
||||
return flag not in ("0", "false", "no")
|
||||
|
||||
|
||||
async def stream(refresh: bool = False):
|
||||
if enabled_cache():
|
||||
if refresh:
|
||||
CACHE_PATH.unlink(missing_ok=True)
|
||||
else:
|
||||
cached = _read_cache()
|
||||
if cached:
|
||||
for event in cached:
|
||||
yield event
|
||||
return
|
||||
collected: list[dict] = []
|
||||
failed = False
|
||||
async for event in _fetch():
|
||||
if event.get("failed"):
|
||||
failed = True
|
||||
collected.append(event)
|
||||
yield event
|
||||
if enabled_cache() and not failed and collected and collected[-1].get("type") == "done":
|
||||
_write_cache(collected)
|
||||
|
||||
|
||||
async def _fetch():
|
||||
navs = await asyncio.to_thread(api.nav_list)
|
||||
sections = []
|
||||
jobs = []
|
||||
for index, nav in enumerate(navs):
|
||||
code = str(nav.get("code") or "").strip()
|
||||
name = str(nav.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
key = f"nav-{code or index}"
|
||||
sections.append({"key": key, "name": name, "note": "", "loading": True})
|
||||
jobs.append((key, name, nav))
|
||||
sections.append({"key": "limited-free", "name": "限时免费", "note": "", "loading": True})
|
||||
if not sections:
|
||||
raise RuntimeError("没有获取到分类")
|
||||
yield {"type": "outline", "sections": sections}
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
|
||||
async def run(job):
|
||||
key, name, nav = job
|
||||
|
||||
def work():
|
||||
try:
|
||||
items = _nav_items(nav)
|
||||
loop.call_soon_threadsafe(queue.put_nowait, _page(key, name, items, done=True))
|
||||
except Exception as exc:
|
||||
loop.call_soon_threadsafe(
|
||||
queue.put_nowait,
|
||||
_page(key, name, [], str(exc) or "获取清单失败", done=True, failed=True),
|
||||
)
|
||||
finally:
|
||||
loop.call_soon_threadsafe(queue.put_nowait, None)
|
||||
|
||||
await asyncio.to_thread(work)
|
||||
|
||||
async def run_limited():
|
||||
def work():
|
||||
try:
|
||||
items = [_drama(item) for item in api.limited_free(1)]
|
||||
items = [item for item in items if item]
|
||||
loop.call_soon_threadsafe(queue.put_nowait, _page("limited-free", "限时免费", items, done=True))
|
||||
except Exception as exc:
|
||||
loop.call_soon_threadsafe(
|
||||
queue.put_nowait,
|
||||
_page("limited-free", "限时免费", [], str(exc) or "获取清单失败", done=True, failed=True),
|
||||
)
|
||||
finally:
|
||||
loop.call_soon_threadsafe(queue.put_nowait, None)
|
||||
|
||||
await asyncio.to_thread(work)
|
||||
|
||||
tasks = [asyncio.create_task(run(job)) for job in jobs]
|
||||
tasks.append(asyncio.create_task(run_limited()))
|
||||
finished = 0
|
||||
try:
|
||||
while finished < len(tasks):
|
||||
event = await queue.get()
|
||||
if event is None:
|
||||
finished += 1
|
||||
continue
|
||||
yield event
|
||||
yield {"type": "done"}
|
||||
finally:
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
|
||||
def search(keyword: str) -> list[dict]:
|
||||
text = (keyword or "").strip()
|
||||
if not text:
|
||||
return []
|
||||
items = []
|
||||
seen = set()
|
||||
for page in range(1, 6):
|
||||
rows = api.drama_list(page=page, page_size=18, keywords=text)
|
||||
if not rows:
|
||||
break
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
if len(rows) < 18:
|
||||
break
|
||||
return items
|
||||
|
||||
|
||||
def _nav_items(nav: dict) -> list[dict]:
|
||||
code = str(nav.get("code") or "").strip()
|
||||
items = _block_items(code) if code else []
|
||||
if items:
|
||||
return items
|
||||
return _filter_items(nav)
|
||||
|
||||
|
||||
def _filter_items(nav: dict) -> list[dict]:
|
||||
filters = nav.get("filters")
|
||||
if not isinstance(filters, list) or not filters:
|
||||
return []
|
||||
items = []
|
||||
seen: set[str] = set()
|
||||
primary = filters[0] if isinstance(filters[0], dict) else {}
|
||||
params = primary.get("filter") if isinstance(primary.get("filter"), dict) else {}
|
||||
for page in range(1, 4):
|
||||
rows = api.drama_list(
|
||||
page=page,
|
||||
page_size=18,
|
||||
order=str(params.get("order") or ""),
|
||||
cat_id=str(params.get("cat_id") or ""),
|
||||
tag_id=str(params.get("tag_id") or ""),
|
||||
source=str(params.get("source") or ""),
|
||||
canvas=str(params.get("canvas") or ""),
|
||||
pay_type=str(params.get("pay_type") or ""),
|
||||
update_status=str(params.get("update_status") or ""),
|
||||
)
|
||||
if not rows:
|
||||
break
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
if len(rows) < 18:
|
||||
break
|
||||
for extra in filters[1:]:
|
||||
if not isinstance(extra, dict):
|
||||
continue
|
||||
params = extra.get("filter") if isinstance(extra.get("filter"), dict) else {}
|
||||
rows = api.drama_list(
|
||||
page=1,
|
||||
page_size=18,
|
||||
order=str(params.get("order") or ""),
|
||||
cat_id=str(params.get("cat_id") or ""),
|
||||
tag_id=str(params.get("tag_id") or ""),
|
||||
source=str(params.get("source") or ""),
|
||||
canvas=str(params.get("canvas") or ""),
|
||||
pay_type=str(params.get("pay_type") or ""),
|
||||
update_status=str(params.get("update_status") or ""),
|
||||
)
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
return items
|
||||
|
||||
|
||||
def _block_items(code: str) -> list[dict]:
|
||||
blocks = api.nav_block(code, page=1)
|
||||
items = []
|
||||
seen = set()
|
||||
for block in blocks:
|
||||
style = str(block.get("style") or "").strip().lower()
|
||||
route = str(block.get("route") or "").strip().lower()
|
||||
if style in AD_STYLE or "ad" in route:
|
||||
continue
|
||||
rows = block.get("items")
|
||||
if not isinstance(rows, list):
|
||||
continue
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
return items
|
||||
|
||||
|
||||
def _drama(item: dict) -> dict | None:
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
drama_id = str(item.get("id") or item.get("drama_id") or "").strip()
|
||||
title = str(item.get("name") or item.get("title") or "").strip()
|
||||
if not drama_id or not title:
|
||||
return None
|
||||
image = str(item.get("img_y") or item.get("img") or item.get("img_x") or "").strip()
|
||||
pay_type = str(item.get("pay_type") or "").strip()
|
||||
episode_type = str(item.get("type") or "").strip()
|
||||
return {
|
||||
"id": drama_id,
|
||||
"title": title,
|
||||
"image": covers.local_url(image) if image else "",
|
||||
"payType": pay_type,
|
||||
"episodeCount": str(item.get("episode_count") or ""),
|
||||
"corner": str(item.get("corner") or ""),
|
||||
"limitedFree": item.get("limited_free") is True,
|
||||
"locked": bool(pay_type) and pay_type not in {"free", "0", "none"},
|
||||
"kind": episode_type,
|
||||
}
|
||||
|
||||
|
||||
def _page(key: str, name: str, items: list[dict], note: str = "", done: bool = False, failed: bool = False) -> dict:
|
||||
event = {"type": "page", "key": key, "name": name, "note": note, "items": items, "done": done}
|
||||
if failed:
|
||||
event["failed"] = True
|
||||
return event
|
||||
|
||||
|
||||
def _read_cache() -> list[dict] | None:
|
||||
if not CACHE_PATH.is_file():
|
||||
return None
|
||||
try:
|
||||
data = json.loads(CACHE_PATH.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return None
|
||||
events = data.get("events") if isinstance(data, dict) else None
|
||||
if not isinstance(events, list) or not events:
|
||||
return None
|
||||
return events
|
||||
|
||||
|
||||
def _write_cache(events: list[dict]) -> None:
|
||||
CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = CACHE_PATH.with_suffix(".json.tmp")
|
||||
temporary.write_text(json.dumps({"events": events}, ensure_ascii=False), encoding="utf-8")
|
||||
temporary.replace(CACHE_PATH)
|
||||
@@ -0,0 +1,152 @@
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from server.services.http import http
|
||||
from server.services.huangdou.crypto import (
|
||||
APP_VERSION,
|
||||
DEVICE_TYPE,
|
||||
LANG,
|
||||
USER_AGENT,
|
||||
decrypt_body,
|
||||
encrypt_body,
|
||||
new_uuid,
|
||||
session_id_of,
|
||||
sign_header,
|
||||
)
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
STATE_DIR = ROOT / "cache" / "huangdou"
|
||||
SESSION_PATH = STATE_DIR / "session.json"
|
||||
|
||||
HOSTS = (
|
||||
"https://pmihlvee.cc",
|
||||
"https://sxqirtho.top",
|
||||
"https://qicuknlj.top",
|
||||
"https://ferncider.cc",
|
||||
"https://hvthtcpa.top",
|
||||
"https://onyxripple.cc",
|
||||
"https://vivifable.top",
|
||||
"https://kucvcxrv.cc",
|
||||
"https://larkgarden.top",
|
||||
"https://niniharbor.top",
|
||||
"https://larksummit.icu",
|
||||
)
|
||||
|
||||
LINE_CODE = "china_1"
|
||||
|
||||
|
||||
class TokenExpired(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class ApiError(RuntimeError):
|
||||
def __init__(self, message: str, code=None) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
class HuangdouClient:
|
||||
def __init__(self) -> None:
|
||||
self.device_id = new_uuid()
|
||||
self.session_id = session_id_of("")
|
||||
self.token = ""
|
||||
self.host = HOSTS[0]
|
||||
self.profile: dict = {}
|
||||
self._load()
|
||||
|
||||
def _load(self) -> None:
|
||||
if not SESSION_PATH.is_file():
|
||||
return
|
||||
try:
|
||||
data = json.loads(SESSION_PATH.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return
|
||||
if not isinstance(data, dict):
|
||||
return
|
||||
self.device_id = str(data.get("device_id") or self.device_id)
|
||||
self.session_id = session_id_of(str(data.get("session_id") or self.session_id))
|
||||
self.token = str(data.get("token") or "")
|
||||
host = str(data.get("host") or "")
|
||||
if host.startswith("https://"):
|
||||
self.host = host.rstrip("/")
|
||||
profile = data.get("profile")
|
||||
if isinstance(profile, dict):
|
||||
self.profile = profile
|
||||
|
||||
def save(self) -> None:
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
"device_id": self.device_id,
|
||||
"session_id": self.session_id,
|
||||
"token": self.token,
|
||||
"host": self.host,
|
||||
"profile": self.profile,
|
||||
}
|
||||
temporary = SESSION_PATH.with_suffix(".json.tmp")
|
||||
temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
temporary.replace(SESSION_PATH)
|
||||
|
||||
def clear_token(self) -> None:
|
||||
self.token = ""
|
||||
self.profile = {}
|
||||
self.save()
|
||||
|
||||
def request(self, path: str, data: dict | None = None, *, auth: bool = True) -> dict | list | None:
|
||||
last_error: Exception | None = None
|
||||
hosts = [self.host, *[item for item in HOSTS if item != self.host]]
|
||||
for host in hosts:
|
||||
try:
|
||||
payload = self._call(host, path, data or {}, auth=auth)
|
||||
self.host = host
|
||||
return payload
|
||||
except (TokenExpired, ApiError):
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
last_error = exc
|
||||
raise last_error or RuntimeError("网络请求异常")
|
||||
|
||||
def _call(self, host: str, path: str, data: dict, *, auth: bool) -> dict | list | None:
|
||||
url = host.rstrip("/") + "/api" + path
|
||||
request_id = new_uuid()
|
||||
now = str(int(time.time()))
|
||||
body = {
|
||||
"token": self.token if auth else "",
|
||||
"deviceId": self.device_id,
|
||||
"data": data,
|
||||
}
|
||||
headers = {
|
||||
"Accept": "*/*",
|
||||
"Accept-Language": LANG,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Origin": host,
|
||||
"Referer": host + "/",
|
||||
"User-Agent": USER_AGENT,
|
||||
"version": APP_VERSION,
|
||||
"deviceType": DEVICE_TYPE,
|
||||
"time": now,
|
||||
"sign": sign_header(self.session_id, request_id, now, url),
|
||||
"requestId": request_id,
|
||||
"sessionId": self.session_id,
|
||||
"deviceBrand": "",
|
||||
"deviceModel": "",
|
||||
"systemName": "",
|
||||
"systemVersion": "",
|
||||
"X-Lang": LANG,
|
||||
}
|
||||
try:
|
||||
response = http.send("POST", url, headers=headers, content=encrypt_body(body, request_id), timeout=30.0)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"请求失败: {exc}") from exc
|
||||
if response.status_code != 200:
|
||||
raise RuntimeError(f"网络请求异常 ({response.status_code})")
|
||||
parsed = decrypt_body(response.content, request_id)
|
||||
if parsed.get("status") == "n":
|
||||
code = parsed.get("errorCode")
|
||||
if str(code) == "2002":
|
||||
raise TokenExpired("登录已失效")
|
||||
raise ApiError(str(parsed.get("error") or "网络请求异常"), code)
|
||||
return parsed.get("data")
|
||||
|
||||
|
||||
client = HuangdouClient()
|
||||
@@ -0,0 +1,71 @@
|
||||
import hashlib
|
||||
import re
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from server.services.http import http
|
||||
from server.services.huangdou.crypto import USER_AGENT, decrypt_resource
|
||||
|
||||
CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "covers"
|
||||
_lock = threading.Lock()
|
||||
_IMAGE_TYPES = {
|
||||
b"\xff\xd8\xff": "image/jpeg",
|
||||
b"\x89PNG": "image/png",
|
||||
b"GIF8": "image/gif",
|
||||
b"RIFF": "image/webp",
|
||||
}
|
||||
|
||||
|
||||
class CoverCache:
|
||||
def local_url(self, remote: str) -> str:
|
||||
remote = (remote or "").strip()
|
||||
if not remote:
|
||||
return ""
|
||||
if remote.startswith("/api/huangdou/covers/"):
|
||||
return remote
|
||||
if not remote.startswith(("http://", "https://")):
|
||||
return remote
|
||||
digest = hashlib.sha256(remote.encode("utf-8")).hexdigest()
|
||||
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
meta = CACHE_DIR / f"{digest}.url"
|
||||
if not meta.is_file():
|
||||
meta.write_text(remote, encoding="utf-8")
|
||||
return f"/api/huangdou/covers/{digest}"
|
||||
|
||||
def read(self, digest: str) -> tuple[bytes, str]:
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", digest):
|
||||
raise RuntimeError("封面不存在")
|
||||
meta = CACHE_DIR / f"{digest}.url"
|
||||
body = CACHE_DIR / digest
|
||||
if not meta.is_file():
|
||||
raise RuntimeError("封面不存在")
|
||||
if body.is_file() and body.stat().st_size > 0:
|
||||
return body.read_bytes(), _media_type(body)
|
||||
remote = meta.read_text(encoding="utf-8").strip()
|
||||
data, media = http.get_bytes(remote, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"})
|
||||
data = decrypt_resource(data)
|
||||
media = _sniff_media(data) or media
|
||||
with _lock:
|
||||
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
body.write_bytes(data)
|
||||
(CACHE_DIR / f"{digest}.type").write_text(media, encoding="utf-8")
|
||||
return data, media
|
||||
|
||||
|
||||
def _sniff_media(data: bytes) -> str:
|
||||
for magic, media in _IMAGE_TYPES.items():
|
||||
if data.startswith(magic):
|
||||
return media
|
||||
return ""
|
||||
|
||||
|
||||
def _media_type(path: Path) -> str:
|
||||
sidecar = Path(f"{path}.type")
|
||||
if sidecar.is_file():
|
||||
media = sidecar.read_text(encoding="utf-8").strip()
|
||||
if media.startswith("image/"):
|
||||
return media
|
||||
return "image/jpeg"
|
||||
|
||||
|
||||
covers = CoverCache()
|
||||
@@ -0,0 +1,115 @@
|
||||
import gzip
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.primitives.padding import PKCS7
|
||||
|
||||
WEB_AES_KEY = "7961beb44246e3012ce228d6b5ced05a"
|
||||
IMAGE_AES_KEY = "525202f9149e061d"
|
||||
SIGN_PREFIX = "Dart"
|
||||
APP_VERSION = "2.0.0"
|
||||
DEVICE_TYPE = "web"
|
||||
LANG = "zh-CN"
|
||||
USER_AGENT = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
_SCHEME = re.compile(r"^https?://", re.I)
|
||||
_IMAGE_MAGIC = (
|
||||
b"\xff\xd8\xff",
|
||||
b"\x89PNG",
|
||||
b"GIF8",
|
||||
b"RIFF",
|
||||
b"\x00\x00\x00 ftyp",
|
||||
)
|
||||
|
||||
|
||||
def new_uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def session_id_of(value: str) -> str:
|
||||
text = (value or "").strip()
|
||||
if not text:
|
||||
text = new_uuid()
|
||||
return text.replace("-", "")
|
||||
|
||||
|
||||
def derive_aes_key(request_id: str, secret: str = WEB_AES_KEY) -> bytes:
|
||||
raw = bytes.fromhex(request_id.replace("-", ""))
|
||||
return hmac.new(secret.encode("utf-8"), raw, hashlib.sha256).digest()
|
||||
|
||||
|
||||
def sign_header(session_id: str, request_id: str, time_text: str, url: str) -> str:
|
||||
path = _SCHEME.sub("", url)
|
||||
payload = f"{SIGN_PREFIX}|{session_id}|{request_id}|{time_text}|{path}"
|
||||
digest = hashlib.md5(payload.encode("utf-8")).hexdigest()
|
||||
return f"{digest}-{time_text}"
|
||||
|
||||
|
||||
def _aes_cbc(key: bytes, iv: bytes, data: bytes, encrypt: bool) -> bytes:
|
||||
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
|
||||
if encrypt:
|
||||
padder = PKCS7(128).padder()
|
||||
blob = padder.update(data) + padder.finalize()
|
||||
engine = cipher.encryptor()
|
||||
return engine.update(blob) + engine.finalize()
|
||||
engine = cipher.decryptor()
|
||||
blob = engine.update(data) + engine.finalize()
|
||||
unpadder = PKCS7(128).unpadder()
|
||||
return unpadder.update(blob) + unpadder.finalize()
|
||||
|
||||
|
||||
def encrypt_body(payload: dict, request_id: str, secret: str = WEB_AES_KEY) -> bytes:
|
||||
plain = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
packed = gzip.compress(plain)
|
||||
iv = os.urandom(16)
|
||||
key = derive_aes_key(request_id, secret)
|
||||
return iv + _aes_cbc(key, iv, packed, True)
|
||||
|
||||
|
||||
def decrypt_body(blob: bytes, request_id: str, secret: str = WEB_AES_KEY) -> dict:
|
||||
if len(blob) < 32:
|
||||
raise RuntimeError("响应数据格式错误")
|
||||
iv, data = blob[:16], blob[16:]
|
||||
key = derive_aes_key(request_id, secret)
|
||||
try:
|
||||
raw = _aes_cbc(key, iv, data, False)
|
||||
except ValueError as exc:
|
||||
raise RuntimeError("响应数据格式错误") from exc
|
||||
try:
|
||||
text = gzip.decompress(raw).decode("utf-8")
|
||||
except OSError:
|
||||
text = raw.decode("utf-8")
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError("响应数据格式错误") from exc
|
||||
if not isinstance(parsed, dict):
|
||||
raise RuntimeError("响应数据格式错误")
|
||||
return parsed
|
||||
|
||||
|
||||
def decrypt_resource(data: bytes, key: str = IMAGE_AES_KEY) -> bytes:
|
||||
if _looks_like_image(data) or len(data) < 16 or len(data) % 16 != 0:
|
||||
return data
|
||||
secret = key.encode("utf-8")
|
||||
cipher = Cipher(algorithms.AES(secret), modes.ECB())
|
||||
engine = cipher.decryptor()
|
||||
blob = engine.update(data) + engine.finalize()
|
||||
try:
|
||||
unpadder = PKCS7(128).unpadder()
|
||||
plain = unpadder.update(blob) + unpadder.finalize()
|
||||
except ValueError:
|
||||
return data
|
||||
return plain if _looks_like_image(plain) else data
|
||||
|
||||
|
||||
def _looks_like_image(data: bytes) -> bool:
|
||||
return any(data.startswith(magic) for magic in _IMAGE_MAGIC)
|
||||
@@ -0,0 +1,76 @@
|
||||
from pathlib import Path
|
||||
|
||||
from server.services.downloads import DownloadManager, _plain_text
|
||||
from server.services.huangdou import api
|
||||
from server.services.huangdou.client import client
|
||||
from server.services.huangdou.covers import covers
|
||||
from server.services.huangdou.crypto import USER_AGENT
|
||||
from server.services.huangdou import playlist as hd_playlist
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
|
||||
|
||||
def _load_episodes(_token, _device, drama_id: str) -> list[dict]:
|
||||
return hd_playlist.load_episodes(str(drama_id))
|
||||
|
||||
|
||||
def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) -> None:
|
||||
name = title.strip()
|
||||
desc = ""
|
||||
pay_type = ""
|
||||
free_episodes = ""
|
||||
vip_episodes = ""
|
||||
points_price = ""
|
||||
money = ""
|
||||
try:
|
||||
detail = api.drama_detail(str(drama_id))
|
||||
fetched = str(detail.get("name") or "").strip()
|
||||
if fetched:
|
||||
name = fetched
|
||||
desc = _plain_text(detail.get("description") or "")
|
||||
pay_type = _field(detail.get("pay_type"))
|
||||
free_episodes = _field(detail.get("free_episodes"))
|
||||
vip_episodes = _field(detail.get("vip_episodes"))
|
||||
points_price = _field(detail.get("points_price"))
|
||||
money = _field(detail.get("money"))
|
||||
except Exception:
|
||||
pass
|
||||
lines = [
|
||||
f"ID: {drama_id}",
|
||||
f"名称: {name}",
|
||||
f"简介: {desc}",
|
||||
f"付费类型: {pay_type or '—'}",
|
||||
f"免费集数: {free_episodes or '—'}",
|
||||
f"VIP 集: {vip_episodes or '—'}",
|
||||
f"积分价格: {points_price or '—'}",
|
||||
f"金额: {money or '—'}",
|
||||
"",
|
||||
]
|
||||
(folder / "简介.txt").write_text("\n".join(lines), encoding="utf-8")
|
||||
|
||||
|
||||
def _read_cover(image: str):
|
||||
digest = (image or "").rstrip("/").rsplit("/", 1)[-1].strip()
|
||||
return covers.read(digest)
|
||||
|
||||
|
||||
def _field(value) -> str:
|
||||
if isinstance(value, list):
|
||||
return "、".join(str(item) for item in value if item not in (None, ""))
|
||||
text = str(value or "").strip()
|
||||
return text
|
||||
|
||||
|
||||
def _auth():
|
||||
return client.token, None
|
||||
|
||||
|
||||
downloads = DownloadManager(
|
||||
state_dir=ROOT / "cache" / "huangdou" / "downloads",
|
||||
default_directory=str((Path.cwd() / "download" / "huangdou").resolve()),
|
||||
load_episodes=_load_episodes,
|
||||
write_intro=_write_intro,
|
||||
read_cover=_read_cover,
|
||||
current_auth=_auth,
|
||||
headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"},
|
||||
)
|
||||
@@ -0,0 +1,89 @@
|
||||
from server.services.huangdou import api
|
||||
from server.services.huangdou.client import TokenExpired, client
|
||||
from server.services.huangdou.covers import covers as huangdou_covers
|
||||
|
||||
|
||||
def enter() -> dict:
|
||||
try:
|
||||
if client.token:
|
||||
profile = _profile(api.user_info())
|
||||
client.profile = profile
|
||||
client.save()
|
||||
return {"token": client.token, "profile": profile}
|
||||
except TokenExpired:
|
||||
client.clear_token()
|
||||
except RuntimeError:
|
||||
pass
|
||||
raw = api.login_device(force_new=False)
|
||||
try:
|
||||
info = api.user_info()
|
||||
except RuntimeError:
|
||||
info = raw
|
||||
profile = _profile(info if isinstance(info, dict) else raw)
|
||||
client.profile = profile
|
||||
client.save()
|
||||
return {"token": client.token, "profile": profile}
|
||||
|
||||
|
||||
def current(token: str) -> dict:
|
||||
token = (token or "").strip()
|
||||
if not token:
|
||||
raise RuntimeError("请先登录")
|
||||
if token != client.token:
|
||||
client.token = token
|
||||
try:
|
||||
profile = _profile(api.user_info())
|
||||
except TokenExpired as exc:
|
||||
client.clear_token()
|
||||
raise RuntimeError("登录已失效") from exc
|
||||
client.profile = profile
|
||||
client.save()
|
||||
return {"token": client.token, "profile": profile}
|
||||
|
||||
|
||||
def logout(token: str) -> None:
|
||||
if token and token == client.token:
|
||||
client.clear_token()
|
||||
return
|
||||
if not token:
|
||||
client.clear_token()
|
||||
|
||||
|
||||
def _profile(raw: dict) -> dict:
|
||||
data = raw if isinstance(raw, dict) else {}
|
||||
vip = _truthy(data.get("is_vip"))
|
||||
head = str(data.get("headico") or "").strip()
|
||||
return {
|
||||
"id": data.get("id") or data.get("user_id") or "",
|
||||
"username": data.get("username") or "",
|
||||
"nickname": data.get("nickname") or data.get("username") or "黄豆用户",
|
||||
"email": data.get("email") or "",
|
||||
"phone": data.get("phone") or "",
|
||||
"badge": "VIP" if vip else "",
|
||||
"vipday": 1 if vip else 0,
|
||||
"score": _number(data.get("balance")),
|
||||
"watched": _number(data.get("play_num")),
|
||||
"rewards": 0,
|
||||
"login_day": 0,
|
||||
"is_vip": data.get("is_vip") or "",
|
||||
"balance": data.get("balance") or "0",
|
||||
"group_name": data.get("group_name") or "",
|
||||
"group_end_time": data.get("group_end_time") or "",
|
||||
"account_type": data.get("account_type") or "",
|
||||
"has_login": data.get("has_login") or "",
|
||||
"sign": data.get("sign") or "",
|
||||
"avatarNumUrl": huangdou_covers.local_url(head) if head else "",
|
||||
"headico": head,
|
||||
}
|
||||
|
||||
|
||||
def _truthy(value) -> bool:
|
||||
text = str(value or "").strip().lower()
|
||||
return text in {"1", "true", "y", "yes", "vip"}
|
||||
|
||||
|
||||
def _number(value) -> int:
|
||||
try:
|
||||
return int(float(str(value or "0")))
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
@@ -0,0 +1,279 @@
|
||||
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
|
||||
Reference in New Issue
Block a user