feat: 将工具更名为 VideosDownTools,并完善黄豆登录与清单

This commit is contained in:
Nixevol
2026-10-25 01:58:29 +08:00
parent 7253217e18
commit 3c2105c786
27 changed files with 1349 additions and 237 deletions
+1 -1
View File
@@ -23,7 +23,7 @@ from server.services.dramabox.downloads import downloads as dramabox_downloads
def create_app() -> FastAPI:
app = FastAPI(title="RaptDrama")
app = FastAPI(title="VideosDownTools")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
+89 -6
View File
@@ -11,10 +11,12 @@ from server.services.http import http
from server.services.huangdou import catalog as hd_catalog
from server.services.huangdou import login as hd_login
from server.services.huangdou import playlist as hd_playlist
from server.services.huangdou import accounts as hd_accounts
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.downloads import downloads as hd_downloads
from server.services.huangdou.downloads import enqueue_download
from server.services.playlist import is_direct_media
router = APIRouter(prefix="/api/huangdou")
@@ -24,6 +26,37 @@ class TokenBody(BaseModel):
token: str = ""
refresh: bool = False
keyword: str = ""
host: str = ""
class FingerprintBody(BaseModel):
browserName: str = ""
language: str = ""
userAgent: str = ""
platform: str = ""
class SavedAccountBody(BaseModel):
username: str = ""
password: str = ""
nickname: str = ""
class SavedAccountsBody(BaseModel):
accounts: list[SavedAccountBody] = []
class LoginBody(BaseModel):
host: str = ""
username: str = ""
password: str = ""
class AccountBody(BaseModel):
token: str = ""
username: str = ""
password: str = ""
rotate_fingerprint: bool = False
class DownloadItem(BaseModel):
@@ -34,6 +67,7 @@ class DownloadItem(BaseModel):
class DownloadStartBody(BaseModel):
token: str = ""
download_points: bool = False
items: list[DownloadItem] = []
@@ -59,9 +93,52 @@ def _require_token(token: str) -> None:
client.token = token
@router.post("/fingerprint")
def adopt_fingerprint(body: FingerprintBody):
client.adopt_browser_fingerprint(body.model_dump())
return {"ok": True}
@router.post("/fingerprint/roll")
def roll_fingerprint():
client.roll_account_fingerprint()
return {"ok": True}
@router.get("/accounts")
def list_accounts():
return {"accounts": hd_accounts.load()}
@router.put("/accounts")
def save_accounts(body: SavedAccountsBody):
return {"accounts": hd_accounts.replace([item.model_dump() for item in body.accounts])}
@router.post("/login")
def login(body: LoginBody):
def action():
entered = hd_login.enter(body.host)
if body.username.strip() and body.password:
return hd_login.login_account(body.username, body.password)
return entered
return call(action)
@router.post("/login/device")
def login_device():
return call(hd_login.enter)
def login_device(body: TokenBody | None = None):
host = body.host if body else ""
return call(lambda: hd_login.enter(host))
@router.post("/login/account")
def login_account(body: AccountBody):
def action():
_require_token(body.token)
return hd_login.login_account(body.username, body.password, body.rotate_fingerprint)
return call(action)
@router.post("/resume")
@@ -131,7 +208,8 @@ def list_episodes(body: PlayBody):
"cid": ep["cid"],
"idx": ep["idx"],
"title": ep["title"],
"playable": bool(ep.get("src")),
"playable": bool(ep.get("playable")),
"points": int(ep.get("points") or 0),
"type": ep.get("type") or "",
"media": "file" if (ep.get("src_kind") == "file" or is_direct_media(ep.get("src") or "")) else "hls",
"is_preview": bool(ep.get("is_preview")),
@@ -156,7 +234,7 @@ def _public_url(url: str) -> str:
def play_segment(url: str):
target = _public_url(url)
try:
upstream = http.open_stream(target, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"})
upstream = http.open_stream(target, headers={"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"})
except (httpx.HTTPError, TimeoutError, OSError, RuntimeError) as exc:
raise HTTPException(status_code=502, detail="分片读取失败") from exc
media = upstream.headers.get("content-type", "video/mp2t").split(";", 1)[0].strip() or "video/mp2t"
@@ -179,7 +257,7 @@ def play_file(vid: str, cid: int):
if not src:
raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址")
try:
upstream = http.open_stream(src, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"})
upstream = http.open_stream(src, headers={"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"})
except (httpx.HTTPError, TimeoutError, OSError, RuntimeError) as exc:
raise HTTPException(status_code=502, detail="分片读取失败") from exc
media = upstream.headers.get("content-type", "video/mp4").split(";", 1)[0].strip() or "video/mp4"
@@ -236,7 +314,12 @@ def list_downloads():
def start_downloads(body: DownloadStartBody):
def action():
_require_token(body.token)
return hd_downloads.enqueue(body.token, None, [item.model_dump() for item in body.items])
hd_downloads._headers["Referer"] = client.host.rstrip("/") + "/"
return enqueue_download(
body.token,
[item.model_dump() for item in body.items],
body.download_points,
)
return call(action)
+71
View File
@@ -0,0 +1,71 @@
import json
import threading
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
PATH = ROOT / "cache" / "huangdou" / "accounts.json"
_lock = threading.Lock()
def load() -> list[dict]:
with _lock:
return _parse()
def replace(rows: list) -> list[dict]:
cleaned = []
seen: set[str] = set()
if isinstance(rows, list):
for item in rows:
if not isinstance(item, dict):
continue
username = str(item.get("username") or "").strip()
password = str(item.get("password") or "")
if not username or not password or username in seen:
continue
seen.add(username)
cleaned.append(
{
"username": username,
"password": password,
"nickname": str(item.get("nickname") or "").strip(),
}
)
if len(cleaned) >= 30:
break
with _lock:
PATH.parent.mkdir(parents=True, exist_ok=True)
temporary = PATH.with_suffix(".json.tmp")
temporary.write_text(json.dumps({"accounts": cleaned}, ensure_ascii=False), encoding="utf-8")
temporary.replace(PATH)
return cleaned
def _parse() -> list[dict]:
if not PATH.is_file():
return []
try:
data = json.loads(PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return []
rows = data.get("accounts") if isinstance(data, dict) else None
if not isinstance(rows, list):
return []
cleaned = []
seen: set[str] = set()
for item in rows:
if not isinstance(item, dict):
continue
username = str(item.get("username") or "").strip()
password = str(item.get("password") or "")
if not username or not password or username in seen:
continue
seen.add(username)
cleaned.append(
{
"username": username,
"password": password,
"nickname": str(item.get("nickname") or "").strip(),
}
)
return cleaned
+52 -7
View File
@@ -2,7 +2,16 @@ from server.services.huangdou.client import ApiError, TokenExpired, client
from server.services.huangdou.crypto import USER_AGENT
def device_info() -> dict:
def device_info(identity: str = "guest") -> dict:
if identity == "account":
client._ensure_fingerprint()
info = client.device_info
else:
if not client.guest_device_id:
client.roll_guest_fingerprint()
info = client.guest_device_info
if isinstance(info, dict) and info:
return dict(info)
return {
"browserName": "Chrome",
"language": "zh-CN",
@@ -33,8 +42,34 @@ def login_device(*, force_new: bool = False) -> dict:
return data
def user_info() -> dict:
data = client.request("/user/info", {}, auth=True)
def login_username(username: str, password: str, channel_code: str = "") -> dict:
data = client.request(
"/login/username",
{
"line_code": "china_1",
"share_code": "",
"channel_code": channel_code,
"username": username.strip(),
"password": password,
"clipboard_text": "",
"device_info": device_info("account"),
},
auth=False,
identity="account",
)
if not isinstance(data, dict):
raise RuntimeError("账号登录没有返回数据")
token = str(data.get("token") or "").strip()
if not token:
raise RuntimeError("账号登录没有返回 token")
client.account_token = token
client.account_username = username.strip()
client.save()
return data
def user_info(*, identity: str = "guest") -> dict:
data = client.request("/user/info", {}, auth=True, identity=identity)
return data if isinstance(data, dict) else {}
@@ -110,13 +145,21 @@ def limited_free(page: int = 1, size: int = 50) -> dict:
return data if isinstance(data, dict) else {}
def drama_detail(drama_id: str) -> dict:
data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True)
def drama_detail(drama_id: str, *, identity: str = "guest") -> dict:
data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True, identity=identity)
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)
def drama_play(drama_id: str, seq: int, *, identity: str = "guest") -> dict:
data = client.request("/drama/play", {"id": str(drama_id), "seq": str(seq)}, auth=True, identity=identity)
return data if isinstance(data, dict) else {}
def drama_buy(drama_id: str, seq: int, method: str = "") -> dict:
body = {"id": str(drama_id), "seq": str(seq)}
if method:
body["method"] = method
data = client.request("/drama/doBuy", body, auth=True, identity="account")
return data if isinstance(data, dict) else {}
@@ -141,7 +184,9 @@ __all__ = [
"drama_list",
"drama_play",
"limited_free",
"drama_buy",
"login_device",
"login_username",
"nav_block",
"nav_list",
"system_info",
+151 -31
View File
@@ -19,21 +19,15 @@ 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",
)
DEFAULT_HOST = "https://pmihlvee.cc"
LINE_CODE = "china_1"
DEFAULT_DEVICE_INFO = {
"browserName": "Chrome",
"language": LANG,
"userAgent": USER_AGENT,
"platform": "Win32",
}
class TokenExpired(RuntimeError):
@@ -48,12 +42,20 @@ class ApiError(RuntimeError):
class HuangdouClient:
def __init__(self) -> None:
self.device_id = new_uuid()
self.session_id = session_id_of("")
self.device_id = ""
self.session_id = ""
self.device_info: dict = {}
self.device_info_source = ""
self.guest_device_id = ""
self.guest_session_id = ""
self.guest_device_info: dict = {}
self.token = ""
self.host = HOSTS[0]
self.account_token = ""
self.account_username = ""
self.host = DEFAULT_HOST
self.profile: dict = {}
self._load()
self._ensure_fingerprint()
def _load(self) -> None:
if not SESSION_PATH.is_file():
@@ -65,10 +67,21 @@ class HuangdouClient:
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.session_id = str(data.get("session_id") or self.session_id)
info = data.get("device_info")
if isinstance(info, dict) and info:
self.device_info = dict(info)
self.device_info_source = str(data.get("device_info_source") or "")
self.guest_device_id = str(data.get("guest_device_id") or "")
self.guest_session_id = str(data.get("guest_session_id") or "")
guest_info = data.get("guest_device_info")
if isinstance(guest_info, dict) and guest_info:
self.guest_device_info = dict(guest_info)
self.token = str(data.get("token") or "")
self.account_token = str(data.get("account_token") or "")
self.account_username = str(data.get("account_username") or "")
host = str(data.get("host") or "")
if host.startswith("https://"):
if host.startswith("http://") or host.startswith("https://"):
self.host = host.rstrip("/")
profile = data.get("profile")
if isinstance(profile, dict):
@@ -79,7 +92,14 @@ class HuangdouClient:
payload = {
"device_id": self.device_id,
"session_id": self.session_id,
"device_info": self.device_info,
"device_info_source": self.device_info_source,
"guest_device_id": self.guest_device_id,
"guest_session_id": self.guest_session_id,
"guest_device_info": self.guest_device_info,
"token": self.token,
"account_token": self.account_token,
"account_username": self.account_username,
"host": self.host,
"profile": self.profile,
}
@@ -87,32 +107,123 @@ class HuangdouClient:
temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
temporary.replace(SESSION_PATH)
def _ensure_fingerprint(self) -> None:
changed = False
if not self.device_id:
self.device_id = new_uuid()
changed = True
if not self.session_id:
self.session_id = session_id_of("")
changed = True
if not self.device_info:
self.device_info = dict(DEFAULT_DEVICE_INFO)
self.device_info_source = "default"
changed = True
if changed:
self.save()
def _new_device_info(self) -> dict:
return dict(self.device_info) if self.device_info else dict(DEFAULT_DEVICE_INFO)
def adopt_browser_fingerprint(self, info: dict) -> bool:
self._ensure_fingerprint()
if self.device_info_source in {"browser", "fixed"}:
return False
cleaned = {
"browserName": str((info or {}).get("browserName") or "").strip() or "Chrome",
"language": str((info or {}).get("language") or "").strip() or LANG,
"userAgent": str((info or {}).get("userAgent") or "").strip(),
"platform": str((info or {}).get("platform") or "").strip() or "Win32",
}
if not cleaned["userAgent"]:
return False
self.device_info = cleaned
self.device_info_source = "browser"
self.save()
return True
def roll_guest_fingerprint(self) -> None:
self.guest_device_id = new_uuid()
self.guest_session_id = session_id_of("")
self.guest_device_info = self._new_device_info()
self.token = ""
self.save()
def roll_account_fingerprint(self) -> None:
self._ensure_fingerprint()
info = dict(self.device_info) if self.device_info else dict(DEFAULT_DEVICE_INFO)
self.device_id = new_uuid()
self.session_id = session_id_of("")
self.device_info = info
self.device_info_source = "fixed"
self.account_token = ""
self.save()
def clear_token(self) -> None:
self.token = ""
self.guest_device_id = ""
self.guest_session_id = ""
self.guest_device_info = {}
self.account_token = ""
self.account_username = ""
self.profile = {}
self.save()
def request(self, path: str, data: dict | None = None, *, auth: bool = True) -> dict | list | None:
def set_host(self, host: str) -> str:
text = normalize_host(host)
if text:
self.host = text
self.save()
return self.host
def request(self, path: str, data: dict | None = None, *, auth: bool = True, identity: str = "guest") -> dict | list | None:
token, device_id, session_id, info = self._identity(identity, auth)
user_agent = str((info or {}).get("userAgent") or USER_AGENT)
last_error: Exception | None = None
hosts = [self.host, *[item for item in HOSTS if item != self.host]]
for host in hosts:
for _ in range(2):
try:
payload = self._call(host, path, data or {}, auth=auth)
self.host = host
return payload
return self._call(
self.host,
path,
data or {},
token=token,
device_id=device_id,
session_id=session_id,
user_agent=user_agent,
)
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:
def _identity(self, identity: str, auth: bool) -> tuple[str, str, str, dict]:
if identity == "account":
self._ensure_fingerprint()
token = self.account_token if auth else ""
return token, self.device_id, self.session_id, self.device_info
if not self.guest_device_id or not self.guest_session_id:
self.roll_guest_fingerprint()
token = self.token if auth else ""
return token, self.guest_device_id, self.guest_session_id, self.guest_device_info
def _call(
self,
host: str,
path: str,
data: dict,
*,
token: str,
device_id: str,
session_id: str,
user_agent: str,
) -> 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,
"token": token,
"deviceId": device_id,
"data": data,
}
headers = {
@@ -121,13 +232,13 @@ class HuangdouClient:
"Content-Type": "application/x-www-form-urlencoded",
"Origin": host,
"Referer": host + "/",
"User-Agent": USER_AGENT,
"User-Agent": user_agent,
"version": APP_VERSION,
"deviceType": DEVICE_TYPE,
"time": now,
"sign": sign_header(self.session_id, request_id, now, url),
"sign": sign_header(session_id, request_id, now, url),
"requestId": request_id,
"sessionId": self.session_id,
"sessionId": session_id,
"deviceBrand": "",
"deviceModel": "",
"systemName": "",
@@ -144,9 +255,18 @@ class HuangdouClient:
if parsed.get("status") == "n":
code = parsed.get("errorCode")
if str(code) == "2002":
raise TokenExpired("登录已失效")
raise TokenExpired(str(parsed.get("error") or "登录已失效"))
raise ApiError(str(parsed.get("error") or "网络请求异常"), code)
return parsed.get("data")
def normalize_host(host: str) -> str:
text = (host or "").strip().rstrip("/")
if text and "://" not in text:
text = "https://" + text
if text and not (text.startswith("https://") or text.startswith("http://")):
raise RuntimeError("域名需要以 http 或 https 开头")
return text
client = HuangdouClient()
+109
View File
@@ -0,0 +1,109 @@
PAID_TYPES = {"coin", "coins", "point", "points", "pay", "money"}
VIP_TYPES = {"vip"}
FREE_TYPES = {"", "free", "0", "none"}
def episode_kind(item: dict) -> str:
return str(item.get("type") or "free").strip().lower()
def already_bought(item: dict) -> bool:
value = item.get("is_buy")
if value is None or value is True:
return True
return str(value).strip().lower() in {"1", "y", "yes", "true"}
def price_of(item: dict) -> int:
for key in ("price", "points", "point", "integral"):
number = _int(item.get(key))
if number:
return number
return 0
def paid_cost(item: dict) -> int:
if episode_kind(item) in FREE_TYPES or already_bought(item):
return 0
return price_of(item)
def episode_note(item: dict, *, account_vip: bool) -> tuple[bool, str, int]:
cost = paid_cost(item)
if cost > 0:
return False, f"{cost} 积分", cost
if episode_kind(item) in VIP_TYPES and not already_bought(item) and not account_vip:
return False, "需要 VIP", 0
return True, "", 0
def public_lock_reason(item: dict, message: str) -> str:
price = price_of(item) or _int(item.get("points"))
text = (message or "").strip()
if not already_bought(item) and price > 0:
return f"{price} 积分"
if any(word in text for word in ("不含", "权益", "解锁")):
return "这一集暂时不能播放"
return text or "这一集暂时不能播放"
def summarize(rows) -> dict:
coins = 0
coin_count = 0
free_count = 0
vip_count = 0
if isinstance(rows, list):
for item in rows:
if not isinstance(item, dict):
continue
cost = paid_cost(item)
if cost > 0:
coins += cost
coin_count += 1
continue
kind = episode_kind(item)
if kind in VIP_TYPES:
vip_count += 1
else:
free_count += 1
return {
"coins": coins,
"coin_count": coin_count,
"free_count": free_count,
"vip_count": vip_count,
}
def allow_payment(pay: bool, has_account: bool, balance: int, coins: int) -> bool:
return bool(pay and has_account and coins > 0 and balance >= coins)
def keep_episode(item: dict, *, allow_paid: bool, account_vip: bool) -> bool:
if paid_cost(item) > 0:
return allow_paid
if episode_kind(item) in VIP_TYPES and not already_bought(item):
return account_vip
return True
def buy_method(item: dict) -> str:
methods = item.get("methods")
if not isinstance(methods, list):
return ""
for method in methods:
if isinstance(method, str) and method.strip():
return method.strip()
if isinstance(method, dict):
for key in ("code", "method", "type", "id", "name"):
text = str(method.get(key) or "").strip()
if text:
return text
return ""
def _int(value) -> int:
try:
number = int(float(str(value)))
except (TypeError, ValueError):
return 0
return number if number > 0 else 0
+20 -7
View File
@@ -1,3 +1,4 @@
import threading
from pathlib import Path
from server.services.downloads import DownloadManager, _plain_text
@@ -5,13 +6,31 @@ 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 login as hd_login
from server.services.huangdou import playlist as hd_playlist
_pay_lock = threading.Lock()
ROOT = Path(__file__).resolve().parents[3]
def _load_episodes(_token, _device, drama_id: str, _locale: str = "") -> list[dict]:
return hd_playlist.load_episodes(str(drama_id))
return hd_playlist.load_for_download(
str(drama_id),
allow_paid=bool(getattr(downloads, "allow_paid", False)),
account_vip=bool(getattr(downloads, "account_vip", False)),
)
def enqueue_download(token: str, items: list[dict], download_points: bool) -> dict:
with _pay_lock:
downloads.allow_paid = bool(download_points and client.account_token)
downloads.account_vip = hd_login.account_is_vip()
try:
return downloads.enqueue(token, None, items)
finally:
downloads.allow_paid = False
downloads.account_vip = False
def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) -> None:
@@ -20,8 +39,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device)
pay_type = ""
free_episodes = ""
vip_episodes = ""
points_price = ""
money = ""
try:
detail = api.drama_detail(str(drama_id))
fetched = str(detail.get("name") or "").strip()
@@ -31,8 +48,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device)
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 = [
@@ -42,8 +57,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device)
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")
+102 -21
View File
@@ -3,23 +3,45 @@ 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
def enter(host: str = "") -> dict:
if host:
client.set_host(host)
client.account_token = ""
client.account_username = ""
client.roll_guest_fingerprint()
raw = api.login_device(force_new=False)
guest = _user_from_login(raw)
if guest:
profile = _profile(guest)
profile["has_login"] = ""
profile["host"] = client.host
else:
profile = public_profile(None)
client.profile = profile
client.save()
return {"token": client.token, "profile": profile}
def login_account(username: str, password: str, rotate_fingerprint: bool = False) -> dict:
username = (username or "").strip()
password = password or ""
if not username or not password:
raise RuntimeError("请填写账号和密码")
if not client.token:
raise RuntimeError("请先进入")
previous = None
if rotate_fingerprint:
previous = (client.device_id, client.session_id, dict(client.device_info), client.account_token)
client.roll_account_fingerprint()
try:
info = api.user_info()
except RuntimeError:
info = raw
profile = _profile(info if isinstance(info, dict) else raw)
raw = api.login_username(username, password)
info = _user_from_login(raw) or api.user_info(identity="account")
except Exception:
if previous is not None:
client.device_id, client.session_id, client.device_info, client.account_token = previous
client.save()
raise
profile = public_profile(info if isinstance(info, dict) else {})
client.profile = profile
client.save()
return {"token": client.token, "profile": profile}
@@ -36,17 +58,76 @@ def current(token: str) -> dict:
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
raise RuntimeError("登录已失效")
account = _account_info()
profile = public_profile(account)
client.profile = profile
client.save()
return {"token": client.token, "profile": profile}
def account_balance() -> int:
if not client.account_token:
return 0
try:
info = api.user_info(identity="account")
except (TokenExpired, RuntimeError):
return _number(client.profile.get("balance") if isinstance(client.profile, dict) else 0)
return _number(info.get("balance") if isinstance(info, dict) else 0)
def account_is_vip() -> bool:
if not client.account_token:
return False
profile = client.profile if isinstance(client.profile, dict) else {}
return _truthy(profile.get("is_vip")) or bool(profile.get("badge"))
def _user_from_login(data: dict) -> dict:
if not isinstance(data, dict):
return {}
for key in ("user", "userInfo", "user_info", "info"):
nested = data.get(key)
if isinstance(nested, dict) and (nested.get("id") or nested.get("username") or nested.get("nickname")):
return nested
if data.get("id") or data.get("username") or data.get("nickname"):
return data
return {}
def _account_info() -> dict:
if not client.account_token:
return {}
try:
info = api.user_info(identity="account")
except TokenExpired:
client.account_token = ""
client.save()
return {}
except RuntimeError:
return {}
return info if isinstance(info, dict) else {}
def public_profile(account: dict | None = None) -> dict:
if account and client.account_token:
profile = _profile(account)
profile["has_login"] = "1"
profile["username"] = client.account_username or profile.get("username") or ""
else:
guest = {}
if client.token:
try:
fetched = api.user_info()
except (TokenExpired, RuntimeError):
fetched = {}
guest = fetched if isinstance(fetched, dict) else {}
profile = _profile(guest)
profile["has_login"] = ""
profile["host"] = client.host
return profile
def logout(token: str) -> None:
if token and token == client.token:
client.clear_token()
+183 -70
View File
@@ -1,41 +1,70 @@
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 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"
CDN_HEADERS = {"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"}
_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("没有这部剧")
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)
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:
for ep in load_episodes(drama_id):
if int(ep.get("cid") or 0) == int(cid):
return ep
return {}
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 {}
if not row.get("playable") or row.get("src"):
return row
played = _play_rows(drama_id, [dict(row)], allow_buy=False)
updated = played[0] if played else row
_store_row(drama_id, updated)
return updated
def playback_playlist(src: str) -> str:
if is_direct_media(src):
raise RuntimeError("这一集是整段视频")
text = http.read_text(src, headers=CDN_HEADERS)
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("#")),
"",
@@ -45,7 +74,7 @@ def playback_playlist(src: str) -> str:
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)
return _rewrite_playlist(http.read_text(variant_url, headers=_cdn_headers()), variant_url)
def decode_key(value: str) -> bytes:
@@ -122,8 +151,11 @@ def apply_hls_key(text: str, source_dir: Path, key: str) -> str:
return "\n".join(result) + "\n"
def _fetch_episodes(drama_id: str) -> list[dict]:
detail = api.drama_detail(drama_id)
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("没有读到分集")
@@ -131,36 +163,89 @@ def _fetch_episodes(drama_id: str) -> list[dict]:
for item in rows:
if not isinstance(item, dict):
continue
seq = _int(item.get("seq"))
if seq <= 0:
if not keep_episode(item, allow_paid=allow_paid, account_vip=account_vip):
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": "",
})
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,
"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:
raise RuntimeError("没有读到分集")
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["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["locked_reason"] = public_lock_reason(row, str(exc))
return row
row["is_buy"] = True
row["needs_coin"] = False
row["points"] = 0
identity = "account" if _uses_account(row) else "guest"
try:
played = api.drama_play(drama_id, int(row["cid"]))
played = api.drama_play(drama_id, int(row["cid"]), identity=identity)
except RuntimeError as exc:
row["locked_reason"] = str(exc) or "这一集暂时不能下载"
row["src"] = ""
row["playable"] = False
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()
@@ -171,10 +256,13 @@ def _fetch_episodes(drama_id: str) -> list[dict]:
row["src"] = src
row["src_kind"] = kind
if src:
row["playable"] = True
if kind == "file" or row["is_preview"]:
row["is_preview"] = True
row["locked_reason"] = "当前账号只能下到试看"
row["locked_reason"] = ""
row["points"] = 0
else:
row["playable"] = False
row["locked_reason"] = _lock_reason(row)
return row
@@ -190,41 +278,66 @@ def _fetch_episodes(drama_id: str) -> list[dict]:
return updated
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:
kind = str(row.get("type") or "free")
if kind in {"vip", "VIP"}:
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"
if kind in {"coin", "points", "point", "pay"}:
return "需要积分或付费"
if not row.get("is_buy"):
return "尚未购买"
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 _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"):
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["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]: