修复虎牙绑定角色识别
This commit is contained in:
@@ -14,6 +14,7 @@ class ActivityUserId(TafStruct):
|
||||
self.sCookie: str = ""
|
||||
self.iTokenType: int = 0
|
||||
self.sDeviceInfo: str = ""
|
||||
self.sQIMEI: str = ""
|
||||
|
||||
def write_to(self, os: TafOutputStream):
|
||||
os.write_int64(0, self.lUid)
|
||||
@@ -23,6 +24,7 @@ class ActivityUserId(TafStruct):
|
||||
os.write_string(4, self.sCookie)
|
||||
os.write_int32(5, self.iTokenType)
|
||||
os.write_string(6, self.sDeviceInfo)
|
||||
os.write_string(7, self.sQIMEI)
|
||||
|
||||
def read_from(self, ins: TafInputStream):
|
||||
self.lUid = ins.read_int64(0, default=self.lUid)
|
||||
@@ -32,6 +34,7 @@ class ActivityUserId(TafStruct):
|
||||
self.sCookie = ins.read_string(4, default=self.sCookie)
|
||||
self.iTokenType = ins.read_int32(5, default=self.iTokenType)
|
||||
self.sDeviceInfo = ins.read_string(6, default=self.sDeviceInfo)
|
||||
self.sQIMEI = ins.read_string(7, default=self.sQIMEI)
|
||||
|
||||
|
||||
class GetUserScoreReq(TafStruct):
|
||||
@@ -778,6 +781,7 @@ class GameRole(TafStruct):
|
||||
self.platName: str = ""
|
||||
self.partitionName: str = ""
|
||||
self.gameSerial: str = ""
|
||||
self.extendInfo: str = ""
|
||||
|
||||
def read_from(self, ins: TafInputStream):
|
||||
self.roleId = ins.read_string(0, default=self.roleId)
|
||||
@@ -786,6 +790,7 @@ class GameRole(TafStruct):
|
||||
self.platName = ins.read_string(3, default=self.platName)
|
||||
self.partitionName = ins.read_string(4, default=self.partitionName)
|
||||
self.gameSerial = ins.read_string(5, default=self.gameSerial)
|
||||
self.extendInfo = ins.read_string(6, default=self.extendInfo)
|
||||
|
||||
def write_to(self, os: TafOutputStream):
|
||||
os.write_string(0, self.roleId)
|
||||
@@ -794,6 +799,7 @@ class GameRole(TafStruct):
|
||||
os.write_string(3, self.platName)
|
||||
os.write_string(4, self.partitionName)
|
||||
os.write_string(5, self.gameSerial)
|
||||
os.write_string(6, self.extendInfo)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
@@ -803,6 +809,7 @@ class GameRole(TafStruct):
|
||||
"plat_name": self.platName,
|
||||
"partition_name": self.partitionName,
|
||||
"game_serial": self.gameSerial,
|
||||
"extend_info": self.extendInfo,
|
||||
}
|
||||
|
||||
|
||||
|
||||
+118
-11
@@ -7,6 +7,7 @@
|
||||
Response: Wup 包 (tRsp)
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import random
|
||||
import struct
|
||||
@@ -121,18 +122,66 @@ class HuyaHttpClient:
|
||||
self.logger = logger or print
|
||||
|
||||
@staticmethod
|
||||
def _normalize_cookie(cookie: str) -> str:
|
||||
def _cookie_first_value(cookie: str, key: str) -> str:
|
||||
"""读取 Cookie 中第一次出现的 key;浏览器 Cookie 里 guid 可能重复。"""
|
||||
for item_key, item_value in cookie_pairs(cookie):
|
||||
if item_key == key and item_value:
|
||||
return item_value
|
||||
return ""
|
||||
|
||||
@classmethod
|
||||
def _resolve_cookie_guid(cls, cookie: str) -> str:
|
||||
"""给 cdnws baseinfo 准备稳定 guid,缺失时用账号 Cookie 派生。"""
|
||||
guid = cls._cookie_first_value(cookie, "guid")
|
||||
if guid:
|
||||
return guid
|
||||
|
||||
udb_guid = cls._cookie_first_value(cookie, "udb_guiddata")
|
||||
if udb_guid:
|
||||
return udb_guid[:32]
|
||||
|
||||
parts = [
|
||||
cls._cookie_first_value(cookie, "yyuid"),
|
||||
cls._cookie_first_value(cookie, "udb_uid"),
|
||||
cls._cookie_first_value(cookie, "udb_passport"),
|
||||
cls._cookie_first_value(cookie, "username"),
|
||||
cls._cookie_first_value(cookie, "udb_biztoken"),
|
||||
]
|
||||
seed = "|".join(part for part in parts if part)
|
||||
return hashlib.sha256(seed.encode("utf-8")).hexdigest()[:32] if seed else ""
|
||||
|
||||
@classmethod
|
||||
def _normalize_cookie(cls, cookie: str) -> str:
|
||||
"""HTTP 业务 UserId.sCookie 需要带 huya_ua 前缀,避免重复写入。"""
|
||||
if not cookie:
|
||||
return ""
|
||||
pairs = [(key, value) for key, value in cookie_pairs(normalize_huya_cookie(cookie)) if key != "huya_ua"]
|
||||
if not any(key == "guid" for key, _ in pairs):
|
||||
guid = cls._resolve_cookie_guid(cookie)
|
||||
if guid:
|
||||
pairs.append(("guid", guid))
|
||||
return normalize_cookie_pairs([("huya_ua", HTTP_HUYA_UA), *pairs])
|
||||
|
||||
@classmethod
|
||||
def _generate_rpc_baseinfo(
|
||||
cls,
|
||||
uid: int,
|
||||
guid: str,
|
||||
cookie: str,
|
||||
trace_id: str = None,
|
||||
) -> str:
|
||||
"""生成与浏览器 cdnws 调用一致的 baseinfo。"""
|
||||
rpc_cookie = cls._normalize_cookie(cookie)
|
||||
rpc_guid = guid or cls._resolve_cookie_guid(cookie)
|
||||
return generate_http_baseinfo(uid, rpc_guid, rpc_cookie, trace_id=trace_id)
|
||||
|
||||
@staticmethod
|
||||
def _build_user(uid: int, guid: str, cookie: str):
|
||||
"""构造 HTTP 业务 UserId。"""
|
||||
from .shop_structs import UserId
|
||||
user = UserId()
|
||||
user.lUid = uid
|
||||
user.sGuid = guid
|
||||
user.sGuid = guid or HuyaHttpClient._resolve_cookie_guid(cookie)
|
||||
user.sToken = ""
|
||||
user.sHuYaUA = HTTP_HUYA_UA
|
||||
user.sCookie = HuyaHttpClient._normalize_cookie(cookie)
|
||||
@@ -169,7 +218,7 @@ class HuyaHttpClient:
|
||||
user = ActivityUserId()
|
||||
user.lUid = uid
|
||||
user.sHuYaUA = HTTP_HUYA_UA
|
||||
user.sCookie = normalize_huya_cookie(cookie)
|
||||
user.sCookie = HuyaHttpClient._normalize_cookie(cookie)
|
||||
return user
|
||||
|
||||
def call_rpc(self, service: str, method: str,
|
||||
@@ -195,7 +244,7 @@ class HuyaHttpClient:
|
||||
wup_data = wup.encode() # [4字节长度][wup body]
|
||||
|
||||
# 2. 构造 baseinfo
|
||||
baseinfo = generate_http_baseinfo(uid, guid, cookie)
|
||||
baseinfo = self._generate_rpc_baseinfo(uid, guid, cookie)
|
||||
url = f"https://{CDNWS_HOST}/?baseinfo={baseinfo}"
|
||||
|
||||
self.logger(f"[HTTP] POST {service}.{method}")
|
||||
@@ -476,7 +525,7 @@ class HuyaHttpClient:
|
||||
req = urllib.request.Request(endpoint, data=payload, method="POST", headers={
|
||||
"User-Agent": PC_UA,
|
||||
"Origin": "https://livelink.qq.com",
|
||||
"Referer": bind_page_url,
|
||||
"Referer": "https://livelink.qq.com/",
|
||||
"Content-Type": "application/json;charset=UTF-8",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
||||
@@ -519,6 +568,56 @@ class HuyaHttpClient:
|
||||
"qrcode_token": jdata.get("qrcodeToken") or "",
|
||||
}
|
||||
|
||||
def get_livelink_qrcode_status(self, qrcode_token: str, timeout: float = 15.0) -> dict | None:
|
||||
"""轮询 livelink 小程序码扫码状态。"""
|
||||
import gzip
|
||||
|
||||
token = (qrcode_token or "").strip()
|
||||
if not token:
|
||||
return None
|
||||
|
||||
payload = json.dumps(
|
||||
{"qrcodeToken": token},
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
endpoint = f"{LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus"
|
||||
req = urllib.request.Request(endpoint, data=payload, method="POST", headers={
|
||||
"User-Agent": PC_UA,
|
||||
"Origin": "https://livelink.qq.com",
|
||||
"Referer": "https://livelink.qq.com/",
|
||||
"Content-Type": "application/json;charset=UTF-8",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
||||
})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
resp_data = resp.read()
|
||||
if resp_data[:2] == b"\x1f\x8b" or resp.headers.get("Content-Encoding") == "gzip":
|
||||
resp_data = gzip.decompress(resp_data)
|
||||
except Exception as e:
|
||||
self.logger(f"[LIVELINK] ❌ 二维码状态请求失败: {type(e).__name__}: {e}")
|
||||
return None
|
||||
|
||||
try:
|
||||
data = json.loads(resp_data.decode("utf-8", "replace"))
|
||||
except Exception as e:
|
||||
self.logger(f"[LIVELINK] ❌ 二维码状态响应解析失败: {type(e).__name__}: {e}")
|
||||
return None
|
||||
|
||||
if data.get("iRet") != 0:
|
||||
self.logger(f"[LIVELINK] ❌ 二维码状态接口失败: iRet={data.get('iRet')} msg={data.get('sMsg') or '-'}")
|
||||
return None
|
||||
|
||||
jdata = data.get("jData") if isinstance(data.get("jData"), dict) else {}
|
||||
return {
|
||||
"is_scan": bool(jdata.get("isScan")),
|
||||
"is_expired": bool(jdata.get("isExpired")),
|
||||
"is_completed": bool(jdata.get("isCompleted")),
|
||||
"is_failure": bool(jdata.get("isFailure")),
|
||||
"raw": jdata,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_bind_urls(
|
||||
livelink_param: dict,
|
||||
@@ -526,6 +625,7 @@ class HuyaHttpClient:
|
||||
game_auth_scene: str = "",
|
||||
nick_name: str = "",
|
||||
face_url: str = "",
|
||||
redirect_url: str = "",
|
||||
) -> dict:
|
||||
"""按活动页 JS 逻辑拼绑定二维码 URL。"""
|
||||
from urllib.parse import quote, urlencode
|
||||
@@ -551,7 +651,7 @@ class HuyaHttpClient:
|
||||
f"&path={mini_path}&username=gh_49af166706ae"
|
||||
)
|
||||
pc_query = dict(bind_query)
|
||||
pc_query["redirectUrl"] = ""
|
||||
pc_query["redirectUrl"] = quote(redirect_url or "", safe="")
|
||||
pc_url = f"https://livelink.qq.com/act/a20200527midgroupage/pc/?{join_query(pc_query)}"
|
||||
|
||||
huya_params = {
|
||||
@@ -712,7 +812,7 @@ class HuyaHttpClient:
|
||||
wup.newdata["tReq"] = os.get_bytes()
|
||||
wup_data = wup.encode()
|
||||
|
||||
baseinfo = generate_http_baseinfo(uid, guid, cookie)
|
||||
baseinfo = self._generate_rpc_baseinfo(uid, guid, cookie)
|
||||
url = f"https://{CDNWS_HOST}/?baseinfo={baseinfo}"
|
||||
self.logger(f"[HTTP] POST shopMiddleUI.payOrderSubmitV5")
|
||||
self.logger(f"[HTTP] 发送 hex前60: {wup_data[:60].hex()}")
|
||||
@@ -747,23 +847,30 @@ class HuyaHttpClient:
|
||||
|
||||
def _self_check():
|
||||
uid = 1199647239697
|
||||
cookie = "yyuid=1199647239697; udb_passport=test"
|
||||
guid = "0a8973013ad3476a53029ddb9edb071f"
|
||||
cookie = f"yyuid=1199647239697; udb_passport=test; guid={guid}"
|
||||
trace_id = "0123456789abcdef:0123456789abcdef:0:0"
|
||||
|
||||
encoded = generate_http_baseinfo(uid, "", cookie, trace_id=trace_id)
|
||||
encoded = HuyaHttpClient._generate_rpc_baseinfo(uid, "", cookie, trace_id=trace_id)
|
||||
raw = base64.b64decode(urllib.parse.unquote(encoded))
|
||||
|
||||
parsed = WSConnectParaInfo()
|
||||
parsed.read_from(TafInputStream(raw))
|
||||
|
||||
assert parsed.lUid == uid
|
||||
assert parsed.sGuid == guid
|
||||
assert parsed.sUA == HTTP_HUYA_UA
|
||||
assert parsed.sCookie == cookie
|
||||
assert parsed.sCookie.startswith(f"huya_ua={HTTP_HUYA_UA}; ")
|
||||
assert f"guid={guid}" in parsed.sCookie
|
||||
assert parsed.sTraceId == trace_id
|
||||
|
||||
user = HuyaHttpClient._build_activity_user(uid, cookie)
|
||||
assert user.sHuYaUA == HTTP_HUYA_UA
|
||||
assert user.sCookie == cookie
|
||||
assert user.sGuid == ""
|
||||
assert user.sCookie == parsed.sCookie
|
||||
|
||||
empty_user = HuyaHttpClient._build_activity_user(0, "")
|
||||
assert empty_user.sCookie == ""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -22,6 +22,10 @@ HUYA_RECHARGE_SOURCE_ID = "yellowcarlist"
|
||||
HUYA_RECHARGE_SCENE = 4
|
||||
HUYA_PAYMENT_POLL_SECONDS = 180
|
||||
HUYA_PAYMENT_POLL_INTERVAL = 3
|
||||
HUYA_BIND_ROLE_POLL_SECONDS = 180
|
||||
HUYA_BIND_ROLE_POLL_INTERVAL = 3
|
||||
HUYA_BIND_ZT_UUID = "b02faae1"
|
||||
HUYA_BIND_ROOM_ID = "30596253"
|
||||
HUYA_RECHARGE_EXTRA_PRODUCTS = [
|
||||
{
|
||||
"spu_id": "hy-5879340",
|
||||
@@ -96,7 +100,11 @@ class HuyaBatchRunner:
|
||||
@staticmethod
|
||||
def _role_name(bind_status) -> str:
|
||||
account_data = bind_status.accountData
|
||||
return account_data.gameRole.roleName or account_data.gameAccount.nick or ""
|
||||
return account_data.gameRole.roleName or ""
|
||||
|
||||
@staticmethod
|
||||
def _has_bind_role(bind_status) -> bool:
|
||||
return bool(bind_status and HuyaBatchRunner._role_name(bind_status))
|
||||
|
||||
@staticmethod
|
||||
def _bind_role_result(bind_status) -> dict:
|
||||
@@ -118,7 +126,7 @@ class HuyaBatchRunner:
|
||||
@staticmethod
|
||||
def _role_channel(bind_status) -> str:
|
||||
game_role = bind_status.accountData.gameRole
|
||||
parts = [bind_status.gameName, game_role.areaName, game_role.platName]
|
||||
parts = [game_role.platName, game_role.areaName]
|
||||
return " / ".join(part for part in parts if part)
|
||||
|
||||
@staticmethod
|
||||
@@ -167,13 +175,163 @@ class HuyaBatchRunner:
|
||||
"change_bind_day": int(bind_status.changeBindDay or 0),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _bind_ready_result(cls, bind_status) -> dict:
|
||||
role_info = cls._bind_role_result(bind_status)
|
||||
return {
|
||||
**role_info,
|
||||
**cls._bind_change_state(bind_status),
|
||||
"bind_status": bind_status.to_dict(),
|
||||
"bind_ready_for_confirm": bool(role_info["role_name"]),
|
||||
"bind_phase": "role_ready" if role_info["role_name"] else "waiting_role",
|
||||
}
|
||||
|
||||
def _resolve_bind_status(
|
||||
self,
|
||||
client: HuyaHttpClient,
|
||||
uid: int,
|
||||
cookie: str,
|
||||
b_act_id_int: int,
|
||||
):
|
||||
"""按活动页逻辑解析绑定状态,优先返回含角色的状态。"""
|
||||
outer_status = client.check_user_bind_game_account(
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id=b_act_id_int,
|
||||
is_use_outer_act_id=1,
|
||||
)
|
||||
if outer_status is None:
|
||||
return None, {}
|
||||
|
||||
query_result = {
|
||||
"bind_status_source": "outer",
|
||||
"outer_bind_status": outer_status.to_dict(),
|
||||
}
|
||||
if outer_status.status != 200:
|
||||
return outer_status, query_result
|
||||
|
||||
chosen_status = outer_status
|
||||
account_data = outer_status.accountData
|
||||
should_check_inner = (
|
||||
not self._has_bind_role(outer_status)
|
||||
and bool(account_data.isNeedActCheck or not account_data.isBindAcount or not account_data.isBindRole)
|
||||
)
|
||||
if should_check_inner:
|
||||
inner_status = client.check_user_bind_game_account(
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id=b_act_id_int,
|
||||
is_use_outer_act_id=0,
|
||||
)
|
||||
if inner_status is not None:
|
||||
query_result["inner_bind_status"] = inner_status.to_dict()
|
||||
if inner_status.status == 200 and self._has_bind_role(inner_status):
|
||||
chosen_status = inner_status
|
||||
query_result["bind_status_source"] = "inner"
|
||||
|
||||
query_result["bind_status"] = chosen_status.to_dict()
|
||||
return chosen_status, query_result
|
||||
|
||||
def _apply_role_to_account(self, account: HuyaAccount, bind_status, status: str):
|
||||
role_name = self._role_name(bind_status)
|
||||
account.status = status
|
||||
account.game_name = role_name or bind_status.gameName or account.game_name
|
||||
account.game_name = role_name or account.game_name
|
||||
account.game_channel = self._role_channel(bind_status) or account.game_channel
|
||||
account.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
@staticmethod
|
||||
def _bind_redirect_url(config_info: dict) -> str:
|
||||
room_pid = str(config_info.get("room_pid") or "").strip()
|
||||
if not room_pid:
|
||||
return ""
|
||||
return (
|
||||
f"https://zt.huya.com/{HUYA_BIND_ZT_UUID}/pc/index.html"
|
||||
f"?sourceId={HUYA_RECHARGE_SOURCE_ID}"
|
||||
f"&pid={room_pid}"
|
||||
f"&anchorUid={room_pid}"
|
||||
f"&roomid={HUYA_BIND_ROOM_ID}"
|
||||
)
|
||||
|
||||
def _wait_bind_role_result(
|
||||
self,
|
||||
client: HuyaHttpClient,
|
||||
worker_db: Session,
|
||||
task: HuyaTask,
|
||||
account: HuyaAccount,
|
||||
uid: int,
|
||||
cookie: str,
|
||||
b_act_id_int: int,
|
||||
result: dict,
|
||||
) -> tuple[str, dict]:
|
||||
deadline = time.monotonic() + HUYA_BIND_ROLE_POLL_SECONDS
|
||||
qrcode_token = str(result.get("qrcode_token") or "")
|
||||
qrcode_finished = not qrcode_token
|
||||
while not self._stop.is_set() and time.monotonic() < deadline:
|
||||
if self._stop.wait(HUYA_BIND_ROLE_POLL_INTERVAL):
|
||||
break
|
||||
|
||||
if qrcode_token and not qrcode_finished:
|
||||
qrcode_status = client.get_livelink_qrcode_status(qrcode_token, timeout=10.0)
|
||||
if qrcode_status is not None:
|
||||
result["qrcode_status"] = qrcode_status
|
||||
if qrcode_status["is_expired"] or qrcode_status["is_failure"]:
|
||||
result.update({
|
||||
"bind_phase": "qrcode_expired",
|
||||
"bind_ready_for_confirm": False,
|
||||
})
|
||||
self._update_task_progress(worker_db, task, "running", "绑定小程序码已失效,请重新获取", result)
|
||||
return "", result
|
||||
if qrcode_status["is_completed"]:
|
||||
qrcode_finished = True
|
||||
result["bind_phase"] = "qrcode_completed"
|
||||
elif qrcode_status["is_scan"]:
|
||||
result["bind_phase"] = "qrcode_scanned"
|
||||
else:
|
||||
result["bind_phase"] = "waiting_scan"
|
||||
|
||||
bind_status, bind_query_result = self._resolve_bind_status(
|
||||
client=client,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id_int=b_act_id_int,
|
||||
)
|
||||
if bind_status is None:
|
||||
continue
|
||||
result.update(bind_query_result)
|
||||
|
||||
if bind_status.status != 200:
|
||||
result.update({
|
||||
"bind_phase": "role_check_failed",
|
||||
"bind_status": bind_status.to_dict(),
|
||||
})
|
||||
self._update_task_progress(worker_db, task, "running", bind_status.msg or "等待绑定角色同步", result)
|
||||
continue
|
||||
|
||||
previous_phase = result.get("bind_phase")
|
||||
ready = self._bind_ready_result(bind_status)
|
||||
if not ready["role_name"] and previous_phase in {"waiting_scan", "qrcode_scanned", "qrcode_completed"}:
|
||||
ready["bind_phase"] = previous_phase
|
||||
result.update(ready)
|
||||
role_name = ready["role_name"]
|
||||
if role_name:
|
||||
self._apply_role_to_account(account, bind_status, "game_queried")
|
||||
self._update_task_progress(worker_db, task, "running", f"已识别角色: {role_name},待确认绑定", result)
|
||||
return role_name, result
|
||||
|
||||
if result.get("bind_phase") == "qrcode_completed":
|
||||
message = "小程序绑定已完成,等待角色同步"
|
||||
elif result.get("bind_phase") == "qrcode_scanned":
|
||||
message = "已扫码,等待小程序绑定完成"
|
||||
else:
|
||||
message = "已生成绑定小程序码,等待扫码绑定"
|
||||
self._update_task_progress(worker_db, task, "running", message, result)
|
||||
|
||||
result.update({
|
||||
"bind_phase": "role_timeout" if not self._stop.is_set() else "stopped",
|
||||
"bind_ready_for_confirm": False,
|
||||
})
|
||||
return "", result
|
||||
|
||||
def _mark_task(
|
||||
self,
|
||||
worker_db: Session,
|
||||
@@ -913,11 +1071,11 @@ class HuyaBatchRunner:
|
||||
return
|
||||
|
||||
client = HuyaHttpClient(logger=lambda msg: self._push_log("info", f"[{uid}] {msg}"))
|
||||
bind_status = client.check_user_bind_game_account(
|
||||
bind_status, bind_query_result = self._resolve_bind_status(
|
||||
client=client,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id=b_act_id_int,
|
||||
is_use_outer_act_id=1,
|
||||
b_act_id_int=b_act_id_int,
|
||||
)
|
||||
if bind_status is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙绑定状态接口无响应")
|
||||
@@ -928,7 +1086,7 @@ class HuyaBatchRunner:
|
||||
task,
|
||||
"failed",
|
||||
bind_status.msg or f"虎牙绑定状态查询失败: {bind_status.status}",
|
||||
bind_status.to_dict(),
|
||||
bind_query_result or bind_status.to_dict(),
|
||||
)
|
||||
return
|
||||
|
||||
@@ -981,12 +1139,14 @@ class HuyaBatchRunner:
|
||||
profile_nick = profile.nick or profile.passport or profile_nick
|
||||
profile_avatar = profile.avatar or ""
|
||||
|
||||
bind_redirect_url = self._bind_redirect_url(config_info)
|
||||
urls = client.build_bind_urls(
|
||||
live_link.livelinkParam,
|
||||
b_act_id_int,
|
||||
game_auth_scene=bind_status.gameAuthScene,
|
||||
nick_name=profile_nick,
|
||||
face_url=profile_avatar,
|
||||
redirect_url=bind_redirect_url,
|
||||
)
|
||||
mini_qrcode = client.get_livelink_mini_qrcode(urls["qr_url"])
|
||||
if not mini_qrcode:
|
||||
@@ -1003,8 +1163,11 @@ class HuyaBatchRunner:
|
||||
result = {
|
||||
"bind_act_id": b_act_id_int,
|
||||
"mini_qrcode_image": mini_qrcode["mini_qrcode_image"],
|
||||
"qrcode_token": mini_qrcode["qrcode_token"],
|
||||
"bind_status": bind_status.to_dict(),
|
||||
"qrcode_token": mini_qrcode.get("qrcode_token") or "",
|
||||
**bind_query_result,
|
||||
"bind_phase": "waiting_scan" if mini_qrcode.get("qrcode_token") else "waiting_role",
|
||||
"bind_ready_for_confirm": False,
|
||||
"bind_redirect_url": bind_redirect_url,
|
||||
**role_info,
|
||||
**change_state,
|
||||
"profile": {
|
||||
@@ -1014,10 +1177,33 @@ class HuyaBatchRunner:
|
||||
}
|
||||
|
||||
account.status = "bind_qr_generated"
|
||||
account.game_name = role_info["role_name"] or bind_status.gameName or account.game_name
|
||||
account.game_name = role_info["role_name"] or account.game_name
|
||||
account.game_channel = self._role_channel(bind_status) or account.game_channel
|
||||
account.nickname = profile_nick or account.nickname
|
||||
account.updated_at = datetime.now(timezone.utc)
|
||||
self._mark_task(worker_db, task, "success", "已生成绑定小程序码", result)
|
||||
self._update_task_progress(worker_db, task, "running", "已生成绑定小程序码,等待绑定角色", result)
|
||||
|
||||
role_name, result = self._wait_bind_role_result(
|
||||
client=client,
|
||||
worker_db=worker_db,
|
||||
task=task,
|
||||
account=account,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id_int=b_act_id_int,
|
||||
result=result,
|
||||
)
|
||||
if role_name:
|
||||
self._mark_task(worker_db, task, "success", f"已识别角色: {role_name},待确认绑定", result)
|
||||
return
|
||||
|
||||
if result.get("bind_phase") == "stopped":
|
||||
self._mark_task(worker_db, task, "failed", "任务已停止", result)
|
||||
return
|
||||
if result.get("bind_phase") == "qrcode_expired":
|
||||
self._mark_task(worker_db, task, "failed", "绑定小程序码已失效,请重新获取", result)
|
||||
return
|
||||
self._mark_task(worker_db, task, "success", "已生成绑定小程序码,未检测到绑定角色", result)
|
||||
|
||||
def _execute_query_game_name(
|
||||
self,
|
||||
@@ -1048,11 +1234,11 @@ class HuyaBatchRunner:
|
||||
return
|
||||
|
||||
client = HuyaHttpClient(logger=lambda msg: self._push_log("info", f"[{uid}] {msg}"))
|
||||
bind_status = client.check_user_bind_game_account(
|
||||
bind_status, bind_query_result = self._resolve_bind_status(
|
||||
client=client,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id=b_act_id_int,
|
||||
is_use_outer_act_id=1,
|
||||
b_act_id_int=b_act_id_int,
|
||||
)
|
||||
if bind_status is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙角色信息接口无响应")
|
||||
@@ -1063,7 +1249,7 @@ class HuyaBatchRunner:
|
||||
task,
|
||||
"failed",
|
||||
bind_status.msg or f"虎牙角色信息查询失败: {bind_status.status}",
|
||||
{"bind_act_id": b_act_id_int, "bind_status": bind_status.to_dict()},
|
||||
{"bind_act_id": b_act_id_int, **bind_query_result},
|
||||
)
|
||||
return
|
||||
|
||||
@@ -1073,7 +1259,7 @@ class HuyaBatchRunner:
|
||||
"bind_act_id": b_act_id_int,
|
||||
**role_info,
|
||||
**change_state,
|
||||
"bind_status": bind_status.to_dict(),
|
||||
**bind_query_result,
|
||||
}
|
||||
role_name = role_info["role_name"]
|
||||
if role_name:
|
||||
@@ -1114,11 +1300,11 @@ class HuyaBatchRunner:
|
||||
return
|
||||
|
||||
client = HuyaHttpClient(logger=lambda msg: self._push_log("info", f"[{uid}] {msg}"))
|
||||
role_status = client.check_user_bind_game_account(
|
||||
role_status, role_query_result = self._resolve_bind_status(
|
||||
client=client,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id=b_act_id_int,
|
||||
is_use_outer_act_id=0,
|
||||
b_act_id_int=b_act_id_int,
|
||||
)
|
||||
if role_status is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙绑定角色查询接口无响应")
|
||||
@@ -1129,17 +1315,19 @@ class HuyaBatchRunner:
|
||||
task,
|
||||
"failed",
|
||||
role_status.msg or f"虎牙绑定角色查询失败: {role_status.status}",
|
||||
{"bind_act_id": b_act_id_int, "bind_status": role_status.to_dict()},
|
||||
{"bind_act_id": b_act_id_int, **role_query_result},
|
||||
)
|
||||
return
|
||||
|
||||
if not role_status.accountData.isBindAcount or not role_status.accountData.isBindRole:
|
||||
role_info = self._bind_role_result(role_status)
|
||||
role_name = role_info["role_name"]
|
||||
if not role_name:
|
||||
result = {
|
||||
"bind_act_id": b_act_id_int,
|
||||
"bind_confirmed": False,
|
||||
"bind_status": role_status.to_dict(),
|
||||
**role_query_result,
|
||||
}
|
||||
self._mark_task(worker_db, task, "failed", "尚未绑定游戏角色,请先扫码完成绑定", result)
|
||||
self._mark_task(worker_db, task, "failed", "尚未识别到待确认角色,请先扫码完成绑定", result)
|
||||
return
|
||||
|
||||
confirm_resp = client.confirm_bind_act_account(
|
||||
@@ -1156,6 +1344,7 @@ class HuyaBatchRunner:
|
||||
"bind_confirmed": False,
|
||||
"confirm_result": confirm_resp.to_dict(),
|
||||
"before_bind_status": role_status.to_dict(),
|
||||
**role_query_result,
|
||||
}
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
@@ -1166,57 +1355,57 @@ class HuyaBatchRunner:
|
||||
)
|
||||
return
|
||||
|
||||
refreshed_status = client.check_user_bind_game_account(
|
||||
refreshed_status, refreshed_query_result = self._resolve_bind_status(
|
||||
client=client,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id=b_act_id_int,
|
||||
is_use_outer_act_id=1,
|
||||
b_act_id_int=b_act_id_int,
|
||||
)
|
||||
if refreshed_status is None:
|
||||
result = {
|
||||
"bind_act_id": b_act_id_int,
|
||||
"bind_confirmed": False,
|
||||
"bind_confirmed": True,
|
||||
"confirm_result": confirm_resp.to_dict(),
|
||||
"before_bind_status": role_status.to_dict(),
|
||||
**role_info,
|
||||
**role_query_result,
|
||||
}
|
||||
self._mark_task(worker_db, task, "error", "虎牙活动绑定状态刷新无响应", result)
|
||||
self._apply_role_to_account(account, role_status, "bind_confirmed")
|
||||
self._mark_task(worker_db, task, "success", f"确认绑定: {role_name}", result)
|
||||
return
|
||||
if refreshed_status.status != 200:
|
||||
result = {
|
||||
"bind_act_id": b_act_id_int,
|
||||
"bind_confirmed": False,
|
||||
"bind_confirmed": True,
|
||||
"confirm_result": confirm_resp.to_dict(),
|
||||
"before_bind_status": role_status.to_dict(),
|
||||
"bind_status": refreshed_status.to_dict(),
|
||||
**role_info,
|
||||
**role_query_result,
|
||||
"refresh_error": refreshed_query_result,
|
||||
}
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
refreshed_status.msg or f"虎牙活动绑定状态刷新失败: {refreshed_status.status}",
|
||||
result,
|
||||
)
|
||||
self._apply_role_to_account(account, role_status, "bind_confirmed")
|
||||
self._mark_task(worker_db, task, "success", f"确认绑定: {role_name}", result)
|
||||
return
|
||||
|
||||
bind_confirmed = bool(
|
||||
refreshed_confirmed = bool(
|
||||
refreshed_status.accountData.isBindAcount
|
||||
and refreshed_status.accountData.isBindRole
|
||||
)
|
||||
role_info = self._bind_role_result(refreshed_status)
|
||||
refreshed_role_info = self._bind_role_result(refreshed_status)
|
||||
final_status = refreshed_status if refreshed_role_info["role_name"] else role_status
|
||||
final_role_info = refreshed_role_info if refreshed_role_info["role_name"] else role_info
|
||||
result = {
|
||||
"bind_act_id": b_act_id_int,
|
||||
"bind_confirmed": bind_confirmed,
|
||||
"bind_confirmed": True,
|
||||
"refreshed_is_bound": refreshed_confirmed,
|
||||
"confirm_result": confirm_resp.to_dict(),
|
||||
"before_bind_status": role_status.to_dict(),
|
||||
"bind_status": refreshed_status.to_dict(),
|
||||
**role_info,
|
||||
**role_query_result,
|
||||
"refresh_result": refreshed_query_result,
|
||||
**final_role_info,
|
||||
}
|
||||
if not bind_confirmed:
|
||||
self._mark_task(worker_db, task, "failed", "确认后仍未检测到活动绑定角色", result)
|
||||
return
|
||||
|
||||
self._apply_role_to_account(account, refreshed_status, "bind_confirmed")
|
||||
role_name = self._role_name(refreshed_status) or "已绑定"
|
||||
self._apply_role_to_account(account, final_status, "bind_confirmed")
|
||||
role_name = final_role_info["role_name"] or role_name or "已绑定"
|
||||
self._mark_task(worker_db, task, "success", f"确认绑定: {role_name}", result)
|
||||
|
||||
def _execute_one(self, task_id: int, account_info: dict, config_info: dict, total: int):
|
||||
|
||||
@@ -214,6 +214,10 @@ function hasMiniQrcode(task: HuyaTaskItem): boolean {
|
||||
return task.task_type === 'get_bind_qr' && Boolean(resultText(task.result, 'mini_qrcode_image'));
|
||||
}
|
||||
|
||||
function bindReadyForConfirm(task: HuyaTaskItem | null | undefined): boolean {
|
||||
return task?.task_type === 'get_bind_qr' && task.result?.bind_ready_for_confirm === true;
|
||||
}
|
||||
|
||||
function hasPaymentQrcode(task: HuyaTaskItem): boolean {
|
||||
return task.task_type === 'create_recharge_order' && Boolean(resultText(task.result, 'pay_url'));
|
||||
}
|
||||
@@ -430,6 +434,12 @@ export default function HuyaTasksPage() {
|
||||
if (latest !== payTask) setPayTask(latest);
|
||||
}, [payTask, tasks]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!qrTask) return;
|
||||
const latest = tasks.find((task) => task.id === qrTask.id);
|
||||
if (latest && latest !== qrTask) setQrTask(latest);
|
||||
}, [qrTask, tasks]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!accountContextMenu) return;
|
||||
const close = () => setAccountContextMenu(null);
|
||||
@@ -757,6 +767,26 @@ export default function HuyaTasksPage() {
|
||||
const failedCount = tasks.filter((task) => ['failed', 'error'].includes(task.status)).length;
|
||||
const qrResult = qrTask?.result || null;
|
||||
const qrImage = resultText(qrResult, 'mini_qrcode_image');
|
||||
const qrBindPhase = resultText(qrResult, 'bind_phase');
|
||||
const qrBindReady = bindReadyForConfirm(qrTask);
|
||||
const qrWaitingRole = qrTask?.status === 'running' && !qrBindReady;
|
||||
const qrGameTitle = resultText(qrResult, 'game_title');
|
||||
const qrRoleName = resultText(qrResult, 'role_name');
|
||||
const qrGameRole = resultObject(qrResult, 'game_role');
|
||||
const qrRoleArea = typeof qrGameRole?.area_name === 'string' ? qrGameRole.area_name : '';
|
||||
const qrRolePlat = typeof qrGameRole?.plat_name === 'string' ? qrGameRole.plat_name : '';
|
||||
const qrRoleLine = qrBindReady ? [qrRolePlat, qrRoleArea, qrRoleName].filter(Boolean).join(' - ') : '';
|
||||
const qrStatusText = qrBindReady
|
||||
? '已识别角色,待确认'
|
||||
: qrBindPhase === 'role_timeout'
|
||||
? '未检测到角色'
|
||||
: qrBindPhase === 'qrcode_completed'
|
||||
? '等待角色同步'
|
||||
: qrBindPhase === 'qrcode_scanned'
|
||||
? '已扫码'
|
||||
: qrBindPhase === 'qrcode_expired'
|
||||
? '二维码已失效'
|
||||
: '等待绑定';
|
||||
const qrAccountName = qrTask
|
||||
? resultProfileNick(qrResult) || qrTask.account_nickname || qrTask.account_uid || `#${qrTask.account_id}`
|
||||
: '';
|
||||
@@ -779,10 +809,34 @@ export default function HuyaTasksPage() {
|
||||
const exchangeRecordsAccountName = exchangeRecordsTask
|
||||
? exchangeRecordsTask.account_nickname || exchangeRecordsTask.account_uid || `#${exchangeRecordsTask.account_id}`
|
||||
: '';
|
||||
const confirmQrBind = () => {
|
||||
if (!qrTask || !qrBindReady) return;
|
||||
const accountId = qrTask.account_id;
|
||||
setQrTask(null);
|
||||
void startTask('confirm_bind', [accountId]);
|
||||
};
|
||||
const queryQrRole = () => {
|
||||
if (!qrTask) return;
|
||||
const accountId = qrTask.account_id;
|
||||
setQrTask(null);
|
||||
void startTask('query_game_name', [accountId]);
|
||||
};
|
||||
|
||||
const renderTaskResult = (value: Record<string, unknown> | null, record: HuyaTaskItem) => {
|
||||
const bindQrImage = resultText(value, 'mini_qrcode_image');
|
||||
if (bindQrImage) {
|
||||
if (bindReadyForConfirm(record)) {
|
||||
const roleName = resultText(value, 'role_name');
|
||||
return (
|
||||
<Space size={6}>
|
||||
<Tag color="gold">待确认</Tag>
|
||||
{roleName ? <Text>{roleName}</Text> : null}
|
||||
<Button size="small" icon={<QrcodeOutlined />} onClick={() => openQrTask(record)}>
|
||||
查看
|
||||
</Button>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Button size="small" icon={<QrcodeOutlined />} onClick={() => openQrTask(record)}>
|
||||
查看二维码
|
||||
@@ -1686,11 +1740,19 @@ export default function HuyaTasksPage() {
|
||||
open={!!qrTask}
|
||||
onCancel={() => setQrTask(null)}
|
||||
footer={null}
|
||||
width={360}
|
||||
width={400}
|
||||
>
|
||||
{qrTask && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: '8px 0 12px' }}>
|
||||
<Text strong style={{ maxWidth: '100%', textAlign: 'center' }}>{qrAccountName}</Text>
|
||||
<Space direction="vertical" size={4} style={{ width: '100%', textAlign: 'center' }}>
|
||||
<Text strong>{qrAccountName}</Text>
|
||||
<Tag
|
||||
color={qrBindReady ? 'gold' : qrBindPhase === 'role_timeout' ? 'orange' : 'processing'}
|
||||
style={{ alignSelf: 'center', marginInlineEnd: 0 }}
|
||||
>
|
||||
{qrStatusText}
|
||||
</Tag>
|
||||
</Space>
|
||||
{qrImage ? (
|
||||
<div
|
||||
style={{
|
||||
@@ -1716,6 +1778,32 @@ export default function HuyaTasksPage() {
|
||||
) : (
|
||||
<Text type="secondary">暂无二维码</Text>
|
||||
)}
|
||||
{qrRoleLine ? (
|
||||
<Space direction="vertical" size={2} style={{ width: '100%', textAlign: 'center' }}>
|
||||
{qrGameTitle ? <Text type="secondary">{qrGameTitle}</Text> : null}
|
||||
<Text strong>{qrRoleLine}</Text>
|
||||
</Space>
|
||||
) : null}
|
||||
<Space size={8}>
|
||||
<Button onClick={() => setQrTask(null)}>关闭</Button>
|
||||
<Button
|
||||
icon={<SearchOutlined />}
|
||||
disabled={!canTask || starting || qrWaitingRole}
|
||||
loading={starting}
|
||||
onClick={queryQrRole}
|
||||
>
|
||||
查询角色
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<CheckCircleOutlined />}
|
||||
disabled={!qrBindReady || !canTask || starting}
|
||||
loading={starting}
|
||||
onClick={confirmQrBind}
|
||||
>
|
||||
确认绑定
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
Reference in New Issue
Block a user