fix(douyu): 对齐绑定小程序码并修复残留任务停止
This commit is contained in:
+126
-17
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import Any, cast
|
||||
@@ -23,6 +24,11 @@ PC_UA = (
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/133.0.0.0 Safari/537.36"
|
||||
)
|
||||
DOUYU_BIND_DEFAULT_ROOM_ID = "9263298"
|
||||
DOUYU_LEGACY_BIND_GAME_ID = "cjm"
|
||||
LIVELINK_MINI_QR_API = (
|
||||
"https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode"
|
||||
)
|
||||
|
||||
|
||||
class DouyuActivityError(RuntimeError):
|
||||
@@ -417,13 +423,17 @@ class DouyuActivityClient:
|
||||
ctn = cookie_value(self.cookie, "acf_ccn") or ctn
|
||||
return ctn
|
||||
|
||||
def get_bind_qr(self, act_alias: str) -> dict[str, Any]:
|
||||
def get_bind_qr(
|
||||
self,
|
||||
act_alias: str,
|
||||
*,
|
||||
room_id: str = DOUYU_BIND_DEFAULT_ROOM_ID,
|
||||
) -> dict[str, Any]:
|
||||
"""生成腾讯游戏角色绑定二维码。
|
||||
|
||||
2026-11-22 新 HAR:活动页“切换”按钮会引导用户去斗鱼个人中心,个人中心
|
||||
普通入口携带完整游戏列表,二维码无法自动选中和平精英。``gameRoleBindUrl``
|
||||
仍是旧版直接角色绑定页,带 ``gameIdList=cjm``,优先使用;只有旧入口缺失
|
||||
时才回退到普通 ``url``。
|
||||
2026-11-22 HAR:``bindRoleParam.url`` 是来联绑定页参数入口,页面内部再
|
||||
调用 ``getMiniAppQrcode`` 生成真正的微信小程序码。``gameRoleBindUrl``
|
||||
是直接角色绑定页,把它编码成普通二维码会进入错误的网页流程。
|
||||
"""
|
||||
ctn = self.acf_ccn(refresh_subscribe=False)
|
||||
payload = self._request_json(
|
||||
@@ -432,15 +442,19 @@ class DouyuActivityClient:
|
||||
"获取绑定二维码",
|
||||
params={"actAlias": act_alias},
|
||||
headers={
|
||||
"Referer": "https://www.douyu.com/",
|
||||
"Referer": self._peace_page_referer(room_id),
|
||||
},
|
||||
)
|
||||
data = payload.get("data") or {}
|
||||
url = data.get("gameRoleBindUrl") or data.get("url") or ""
|
||||
url = data.get("url") or data.get("gameRoleBindUrl") or ""
|
||||
if not url:
|
||||
raise DouyuActivityError(payload.get("msg") or "获取绑定二维码失败")
|
||||
mini_qrcode = self.get_livelink_mini_qrcode(url)
|
||||
return {
|
||||
"url": url,
|
||||
"mini_qrcode_image": mini_qrcode["mini_qrcode_image"],
|
||||
"qrcode_token": mini_qrcode["qrcode_token"],
|
||||
"has_mini_qrcode": True,
|
||||
"role_param_url": data.get("url") or "",
|
||||
"game_role_bind_url": data.get("gameRoleBindUrl") or "",
|
||||
"query_params": data.get("queryParams") or {},
|
||||
@@ -449,6 +463,80 @@ class DouyuActivityClient:
|
||||
"raw": payload,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _livelink_qrcode_image_src(qrcode: str) -> str:
|
||||
"""把来联接口返回的二维码内容转换为可直接展示的图片地址。"""
|
||||
text = str(qrcode or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
lower = text.lower()
|
||||
if lower.startswith(("https://", "http://", "data:image/")):
|
||||
return text
|
||||
mime = "image/png" if text.startswith("iVBOR") else "image/jpeg"
|
||||
return f"data:{mime};base64,{text}"
|
||||
|
||||
def get_livelink_mini_qrcode(self, bind_page_url: str) -> dict[str, str]:
|
||||
"""按来联绑定页参数生成真正可扫的微信小程序码。"""
|
||||
query = urlsplit(bind_page_url or "").query
|
||||
if not query:
|
||||
raise DouyuActivityError("绑定小程序码参数缺失")
|
||||
params = parse_qs(query, keep_blank_values=True)
|
||||
platform_id = (params.get("livePlatId") or [""])[0]
|
||||
act_id = (params.get("actId") or [""])[0]
|
||||
from_id = (params.get("fromId") or [""])[0]
|
||||
if len(from_id) > 32:
|
||||
from_id = ""
|
||||
suffix = "".join(
|
||||
secrets.choice("abcdefghijklmnopqrstuvwxyz0123456789") for _ in range(8)
|
||||
)
|
||||
session_id = f"{int(time.time())}_{suffix}"
|
||||
request_payload = {"queryString": f"{query}&sessionId={session_id}"}
|
||||
request_headers = {
|
||||
"User-Agent": PC_UA,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
||||
"Content-Type": "application/json;charset=UTF-8",
|
||||
"Origin": "https://livelink.qq.com",
|
||||
"Referer": "https://livelink.qq.com/",
|
||||
"Gap-Plat-Id": platform_id,
|
||||
"Gap-Act-Id": act_id,
|
||||
"Gap-User-From": "pc",
|
||||
"Gap-From-Id": from_id,
|
||||
"Vulcan-AccType": "auth_in_h5",
|
||||
"Vulcan-PlatUser-Session": "",
|
||||
}
|
||||
try:
|
||||
with requests.Session() as session:
|
||||
session.trust_env = False
|
||||
response = session.post(
|
||||
LIVELINK_MINI_QR_API,
|
||||
json=request_payload,
|
||||
headers=request_headers,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
except requests.RequestException as exc:
|
||||
raise DouyuActivityError(f"获取绑定小程序码失败: {exc}") from exc
|
||||
except ValueError as exc:
|
||||
raise DouyuActivityError("绑定小程序码接口返回不是 JSON") from exc
|
||||
if payload.get("iRet") not in (0, "0"):
|
||||
raise DouyuActivityError(
|
||||
str(payload.get("sMsg") or "获取绑定小程序码失败")
|
||||
)
|
||||
data = payload.get("jData") if isinstance(payload.get("jData"), dict) else {}
|
||||
image = self._livelink_qrcode_image_src(str(data.get("qrcode") or ""))
|
||||
if not image:
|
||||
raise DouyuActivityError("绑定小程序码接口未返回二维码图片")
|
||||
self.logger(
|
||||
f"获取绑定小程序码: plat={platform_id or '-'} "
|
||||
f"act={act_id or '-'} token={'有' if data.get('qrcodeToken') else '无'}"
|
||||
)
|
||||
return {
|
||||
"mini_qrcode_image": image,
|
||||
"qrcode_token": str(data.get("qrcodeToken") or ""),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _first_present(data: dict[str, Any], *keys: str):
|
||||
"""按候选 key 取第一个非 None 值。"""
|
||||
@@ -457,20 +545,39 @@ class DouyuActivityClient:
|
||||
return data.get(key)
|
||||
return None
|
||||
|
||||
def bind_info(self, act_alias: str, *, v2: bool = False) -> dict[str, Any]:
|
||||
"""查询绑定游戏账号信息。"""
|
||||
def bind_info(
|
||||
self,
|
||||
act_alias: str,
|
||||
*,
|
||||
v2: bool = False,
|
||||
room_id: str = DOUYU_BIND_DEFAULT_ROOM_ID,
|
||||
) -> dict[str, Any]:
|
||||
"""查询绑定游戏账号信息。
|
||||
|
||||
2026-11-22 HAR:活动 alias 使用 ``actAlias``,legacy 最新态 ``cjm``
|
||||
使用 ``gameId``。两者不能统一拼成 ``actAlias=cjm``。
|
||||
"""
|
||||
url = self.BIND_INFO_V2_API if v2 else self.BIND_INFO_API
|
||||
alias = str(act_alias or "").strip()
|
||||
params = (
|
||||
{"gameId": alias}
|
||||
if alias == DOUYU_LEGACY_BIND_GAME_ID
|
||||
else {"actAlias": alias}
|
||||
)
|
||||
payload = self._request_json(
|
||||
"get",
|
||||
url,
|
||||
"查询绑定信息",
|
||||
params={"actAlias": act_alias},
|
||||
headers={"Origin": "", "Referer": "https://www.douyu.com/"},
|
||||
params=params,
|
||||
headers={
|
||||
"Origin": "",
|
||||
"Referer": self._peace_page_referer(room_id),
|
||||
},
|
||||
)
|
||||
if payload.get("error") not in (0, "0", None):
|
||||
raise DouyuActivityError(payload.get("msg") or "查询绑定信息失败")
|
||||
parsed = self._parse_bind_info(
|
||||
payload, act_alias=act_alias, api_version="v2" if v2 else "v1"
|
||||
payload, act_alias=alias, api_version="v2" if v2 else "v1"
|
||||
)
|
||||
self._log_bind_info(parsed)
|
||||
return parsed
|
||||
@@ -672,7 +779,12 @@ class DouyuActivityClient:
|
||||
raise DouyuActivityError(bind.get("msg") or "完成电竞手册绑定失败")
|
||||
return {"agreement": agreement, "act_bind": bind}
|
||||
|
||||
def confirm_bind(self, act_alias: str) -> dict[str, Any]:
|
||||
def confirm_bind(
|
||||
self,
|
||||
act_alias: str,
|
||||
*,
|
||||
room_id: str = DOUYU_BIND_DEFAULT_ROOM_ID,
|
||||
) -> dict[str, Any]:
|
||||
"""按最新 actBind 链路确认当前扫码选择的游戏角色。"""
|
||||
ctn = self.acf_ccn(refresh_subscribe=False)
|
||||
payload = self._request_json(
|
||||
@@ -681,10 +793,7 @@ class DouyuActivityClient:
|
||||
"确认绑定",
|
||||
files=self._multipart_fields({"actAlias": act_alias, "ctn": ctn}),
|
||||
headers={
|
||||
"Referer": (
|
||||
"https://www.douyu.com/pages/live-peace-handbook/web"
|
||||
"?ditchname=pass0"
|
||||
),
|
||||
"Referer": self._peace_page_referer(room_id),
|
||||
},
|
||||
)
|
||||
if payload.get("error") not in (0, "0"):
|
||||
|
||||
Reference in New Issue
Block a user