fix(douyu): 稳定绑定轮询并留档角色接口响应
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -37,14 +38,46 @@ from .douyu_account_probe import (
|
||||
resolve_elite_role,
|
||||
)
|
||||
from .douyu_activity_query import query_esports_bind_info
|
||||
from .douyu_role_audit import (
|
||||
record_role_api_candidates,
|
||||
record_role_api_response,
|
||||
)
|
||||
|
||||
DOUYU_LEGACY_BIND_ACT_ALIAS = "20250213NQCYX"
|
||||
DOUYU_BIND_ROLE_POLL_SECONDS = 600
|
||||
|
||||
|
||||
def _positive_env_int(name: str, default: int) -> int:
|
||||
try:
|
||||
value = int(os.getenv(name, str(default)))
|
||||
except ValueError:
|
||||
return default
|
||||
return value if value > 0 else default
|
||||
|
||||
|
||||
# 繁忙时段成功案例也可能轮询 60+ 次才出现角色,10 分钟过短。
|
||||
DOUYU_BIND_ROLE_POLL_SECONDS = _positive_env_int(
|
||||
"DOUYU_BIND_ROLE_POLL_SECONDS",
|
||||
20 * 60,
|
||||
)
|
||||
DOUYU_BIND_ROLE_POLL_INTERVAL = 5
|
||||
DOUYU_BIND_ROLE_POLL_FAST_SECONDS = 2 * 60
|
||||
DOUYU_BIND_ROLE_POLL_MEDIUM_SECONDS = 10 * 60
|
||||
DOUYU_BIND_ROLE_POLL_SLOW_INTERVAL = 20
|
||||
DOUYU_BIND_ACTION_ALIAS_EVERY_POLLS = 3
|
||||
DOUYU_CONFIRM_EFFECT_POLL_TIMES = 3
|
||||
DOUYU_CONFIRM_EFFECT_POLL_INTERVAL = 3
|
||||
|
||||
|
||||
def bind_poll_interval_seconds(elapsed_seconds: float) -> int:
|
||||
"""Return the scan-wait polling cadence for a task's elapsed lifetime."""
|
||||
elapsed = max(0.0, float(elapsed_seconds or 0))
|
||||
if elapsed < DOUYU_BIND_ROLE_POLL_FAST_SECONDS:
|
||||
return DOUYU_BIND_ROLE_POLL_INTERVAL
|
||||
if elapsed < DOUYU_BIND_ROLE_POLL_MEDIUM_SECONDS:
|
||||
return 10
|
||||
return DOUYU_BIND_ROLE_POLL_SLOW_INTERVAL
|
||||
|
||||
|
||||
class BindMixin:
|
||||
"""游戏角色绑定域:绑定状态机、扫码/确认绑定、换绑冷却。"""
|
||||
|
||||
@@ -157,6 +190,113 @@ class BindMixin:
|
||||
actionable_aliases=actionable_aliases,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _is_newly_confirmed_binding(
|
||||
cls,
|
||||
snapshot: dict,
|
||||
*,
|
||||
baseline_role_name: str,
|
||||
baseline_is_bound_act: bool,
|
||||
) -> bool:
|
||||
"""扫码完成后官方可能直接返回 bindAct=1,而不是 pending。"""
|
||||
role_name = str(snapshot.get("role_name") or "").strip()
|
||||
if not snapshot.get("is_bound_act") or not role_name:
|
||||
return False
|
||||
baseline_role = baseline_role_name.strip()
|
||||
if not baseline_is_bound_act or not baseline_role:
|
||||
return True
|
||||
return role_name.casefold() != baseline_role.casefold()
|
||||
|
||||
@classmethod
|
||||
def _find_newly_confirmed_binding(
|
||||
cls,
|
||||
candidates: list[dict],
|
||||
*,
|
||||
baseline_role_name: str,
|
||||
baseline_is_bound_act: bool,
|
||||
) -> dict | None:
|
||||
"""Find a scan result that the official API already confirmed."""
|
||||
for candidate in candidates:
|
||||
if cls._is_newly_confirmed_binding(
|
||||
binding_snapshot(candidate),
|
||||
baseline_role_name=baseline_role_name,
|
||||
baseline_is_bound_act=baseline_is_bound_act,
|
||||
):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _bind_poll_snapshot(info: dict | None) -> dict[str, Any] | None:
|
||||
"""Small, JSON-safe snapshot used only to detect polling changes."""
|
||||
if not isinstance(info, dict):
|
||||
return None
|
||||
snapshot = binding_snapshot(info)
|
||||
return {
|
||||
"role_name": snapshot["role_name"],
|
||||
"area_name": snapshot["area_name"],
|
||||
"plat_name": snapshot["plat_name"],
|
||||
"is_bound_act": bool(snapshot["is_bound_act"]),
|
||||
"is_bound_role": bool(snapshot["is_bound_role"]),
|
||||
"need_bind_act": bool(snapshot["need_bind_act"]),
|
||||
"need_bind_role": bool(snapshot["need_bind_role"]),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _bind_poll_snapshot_changed(
|
||||
cls,
|
||||
previous: dict | None,
|
||||
current: dict | None,
|
||||
) -> bool:
|
||||
current_snapshot = cls._bind_poll_snapshot(current)
|
||||
if current_snapshot is None:
|
||||
return False
|
||||
previous_snapshot = cls._bind_poll_snapshot(previous)
|
||||
if previous_snapshot is not None:
|
||||
return previous_snapshot != current_snapshot
|
||||
return bool(
|
||||
current_snapshot["role_name"]
|
||||
or current_snapshot["is_bound_act"]
|
||||
or current_snapshot["is_bound_role"]
|
||||
or current_snapshot["need_bind_act"]
|
||||
or current_snapshot["need_bind_role"]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _split_bind_poll_aliases(
|
||||
query_aliases: list[str],
|
||||
config: dict,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Prefer the cheap legacy probe; activity aliases are verified on change."""
|
||||
legacy_alias = str(config.get("legacy_act_alias") or "").strip()
|
||||
if legacy_alias and legacy_alias in query_aliases:
|
||||
return (
|
||||
[legacy_alias],
|
||||
[alias for alias in query_aliases if alias != legacy_alias],
|
||||
)
|
||||
return query_aliases, []
|
||||
|
||||
@staticmethod
|
||||
def _bind_poll_elapsed_seconds(
|
||||
result: dict,
|
||||
*,
|
||||
now: datetime,
|
||||
deadline: datetime | None,
|
||||
) -> float:
|
||||
raw_generated_at = str(result.get("qr_generated_at") or "").strip()
|
||||
generated_at: datetime | None = None
|
||||
if raw_generated_at:
|
||||
try:
|
||||
generated_at = datetime.fromisoformat(raw_generated_at)
|
||||
except ValueError:
|
||||
generated_at = None
|
||||
if generated_at is not None and generated_at.tzinfo is None:
|
||||
generated_at = generated_at.replace(tzinfo=UTC)
|
||||
if generated_at is None and deadline is not None:
|
||||
generated_at = deadline - timedelta(seconds=DOUYU_BIND_ROLE_POLL_SECONDS)
|
||||
if generated_at is None:
|
||||
return 0.0
|
||||
return max(0.0, (now - generated_at).total_seconds())
|
||||
|
||||
def _bind_snapshot(self, bind_info: dict | None) -> dict:
|
||||
return binding_snapshot(bind_info)
|
||||
|
||||
@@ -732,7 +872,6 @@ class BindMixin:
|
||||
task.queue_lane = "binding_poll"
|
||||
task.next_run_at = now + timedelta(seconds=max(1, interval_seconds))
|
||||
task.last_run_at = now
|
||||
task.attempt_count = int(task.attempt_count or 0) + 1
|
||||
|
||||
def poll_bind_role_once(
|
||||
self,
|
||||
@@ -754,7 +893,19 @@ class BindMixin:
|
||||
if not query_aliases:
|
||||
query_aliases = self._query_bind_act_aliases(config)
|
||||
deadline = task.run_deadline_at
|
||||
if deadline is not None and now >= deadline:
|
||||
poll_number = int(result.get("poll_count") or 0) + 1
|
||||
interval_seconds = bind_poll_interval_seconds(
|
||||
self._bind_poll_elapsed_seconds(result, now=now, deadline=deadline)
|
||||
)
|
||||
last_poll = bool(
|
||||
deadline is not None
|
||||
and (
|
||||
now >= deadline
|
||||
or now + timedelta(seconds=interval_seconds) >= deadline
|
||||
)
|
||||
)
|
||||
|
||||
def finish_timeout() -> None:
|
||||
result.update(
|
||||
{
|
||||
"bind_polling": False,
|
||||
@@ -771,17 +922,78 @@ class BindMixin:
|
||||
"绑定二维码已过期,未识别到新扫码角色",
|
||||
result,
|
||||
)
|
||||
return
|
||||
|
||||
client = self._client(str(account.cookie or ""))
|
||||
candidates = self._fetch_bind_info_candidates(client, query_aliases)
|
||||
primary_aliases, action_aliases_to_verify = self._split_bind_poll_aliases(
|
||||
query_aliases,
|
||||
config,
|
||||
)
|
||||
candidates = self._fetch_bind_info_candidates(client, primary_aliases)
|
||||
primary_info = candidates[0] if candidates else None
|
||||
legacy_changed = self._bind_poll_snapshot_changed(
|
||||
result.get("bind_poll_legacy_snapshot"),
|
||||
primary_info,
|
||||
)
|
||||
verify_action_alias = bool(
|
||||
action_aliases_to_verify
|
||||
and (
|
||||
legacy_changed
|
||||
or last_poll
|
||||
or poll_number % DOUYU_BIND_ACTION_ALIAS_EVERY_POLLS == 0
|
||||
)
|
||||
)
|
||||
action_candidates: list[dict] = []
|
||||
if verify_action_alias:
|
||||
action_candidates = self._fetch_bind_info_candidates(
|
||||
client,
|
||||
action_aliases_to_verify,
|
||||
)
|
||||
candidates.extend(action_candidates)
|
||||
if primary_info is not None and legacy_changed:
|
||||
record_role_api_candidates(
|
||||
db,
|
||||
account_id=account.id,
|
||||
task_id=task.id,
|
||||
candidates=[primary_info],
|
||||
scope=SCOPE_ELITE,
|
||||
stage="binding_poll.legacy_changed",
|
||||
source="douyu_task.get_bind_qr",
|
||||
)
|
||||
action_snapshot = [
|
||||
self._bind_poll_snapshot(item) for item in action_candidates
|
||||
]
|
||||
if action_candidates and action_snapshot != result.get(
|
||||
"bind_poll_action_audit"
|
||||
):
|
||||
record_role_api_candidates(
|
||||
db,
|
||||
account_id=account.id,
|
||||
task_id=task.id,
|
||||
candidates=action_candidates,
|
||||
scope=SCOPE_ELITE,
|
||||
stage="binding_poll.action_alias",
|
||||
source="douyu_task.get_bind_qr",
|
||||
)
|
||||
result["bind_poll_action_audit"] = action_snapshot
|
||||
result["bind_poll_round"] = poll_number
|
||||
result["bind_poll_query_aliases"] = [
|
||||
*primary_aliases,
|
||||
*(action_aliases_to_verify if verify_action_alias else []),
|
||||
]
|
||||
if primary_info is not None:
|
||||
result["bind_poll_legacy_snapshot"] = self._bind_poll_snapshot(primary_info)
|
||||
if not candidates:
|
||||
attempts = max(1, int(task.attempt_count or 1))
|
||||
backoff = min(30, max(DOUYU_BIND_ROLE_POLL_INTERVAL, attempts * 2))
|
||||
if deadline is not None and datetime.now(UTC) >= deadline:
|
||||
finish_timeout()
|
||||
return
|
||||
result["bind_poll_error"] = "所有 actAlias 查询绑定信息失败"
|
||||
result["bind_polling"] = True
|
||||
result["bind_phase"] = "waiting_scan"
|
||||
self._schedule_next_bind_poll(task, now=now, interval_seconds=backoff)
|
||||
self._schedule_next_bind_poll(
|
||||
task,
|
||||
now=now,
|
||||
interval_seconds=interval_seconds,
|
||||
)
|
||||
self._update_task_progress(
|
||||
db,
|
||||
task,
|
||||
@@ -833,7 +1045,7 @@ class BindMixin:
|
||||
)
|
||||
self._push_binding_decision_log(
|
||||
task=task,
|
||||
stage=f"poll:{int(result.get('poll_count') or 0) + 1}",
|
||||
stage=f"poll:{poll_number}",
|
||||
candidates=candidates,
|
||||
decisions=candidate_decisions,
|
||||
selected=bind_info,
|
||||
@@ -841,6 +1053,63 @@ class BindMixin:
|
||||
actionable_aliases=action_aliases,
|
||||
)
|
||||
|
||||
directly_confirmed = self._find_newly_confirmed_binding(
|
||||
candidates,
|
||||
baseline_role_name=baseline_role_name,
|
||||
baseline_is_bound_act=baseline_is_bound_act,
|
||||
)
|
||||
if directly_confirmed is not None:
|
||||
bind_info = directly_confirmed
|
||||
snapshot = self._bind_snapshot(bind_info)
|
||||
query_alias = str(bind_info.get("act_alias") or "")
|
||||
selected_decision = binding_pending_decision(
|
||||
bind_info,
|
||||
baseline_role_name=baseline_role_name,
|
||||
baseline_is_bound_act=baseline_is_bound_act,
|
||||
baseline_info=baseline_info,
|
||||
actionable_aliases=action_aliases,
|
||||
)
|
||||
selected_decision = {
|
||||
**selected_decision,
|
||||
"confirmable": False,
|
||||
"reason": "directly_confirmed",
|
||||
}
|
||||
summary = (
|
||||
f"act={query_alias or '-'} "
|
||||
f"{self._format_bind_summary(bind_info, pending=False)}"
|
||||
)
|
||||
task.queue_lane = ""
|
||||
task.next_run_at = None
|
||||
result.update(
|
||||
{
|
||||
**snapshot,
|
||||
"act_alias": query_alias,
|
||||
"query_act_alias": query_alias,
|
||||
"role_name": snapshot["role_name"],
|
||||
"current_role_name": snapshot["role_name"],
|
||||
"current_area_name": snapshot["area_name"],
|
||||
"current_plat_name": snapshot["plat_name"],
|
||||
"bind_ready_for_confirm": False,
|
||||
"bind_confirmed": True,
|
||||
"bind_phase": "confirmed",
|
||||
"bind_polling": False,
|
||||
"poll_count": poll_number,
|
||||
"bind_summary": summary,
|
||||
"action_act_aliases": action_aliases,
|
||||
"bind_decision": selected_decision,
|
||||
"bind_candidate_decisions": candidate_decisions,
|
||||
}
|
||||
)
|
||||
self._apply_bind_info_to_account(account, bind_info, BIND_BOUND)
|
||||
self._mark_task(
|
||||
db,
|
||||
task,
|
||||
"success",
|
||||
f"绑定成功: {snapshot['role_name']}",
|
||||
result,
|
||||
)
|
||||
return
|
||||
|
||||
if is_pending_role:
|
||||
task.queue_lane = ""
|
||||
task.next_run_at = None
|
||||
@@ -853,8 +1122,8 @@ class BindMixin:
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "role_ready",
|
||||
"bind_polling": False,
|
||||
"pending_role_name": snapshot["role_name"],
|
||||
"poll_count": int(result.get("poll_count") or 0) + 1,
|
||||
"pending_role_name": snapshot["role_name"],
|
||||
"poll_count": poll_number,
|
||||
"bind_summary": summary,
|
||||
"action_act_aliases": action_aliases,
|
||||
"bind_decision": selected_decision,
|
||||
@@ -894,17 +1163,20 @@ class BindMixin:
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "waiting_scan",
|
||||
"bind_polling": True,
|
||||
"poll_count": int(result.get("poll_count") or 0) + 1,
|
||||
"poll_count": poll_number,
|
||||
"bind_summary": summary,
|
||||
"action_act_aliases": action_aliases,
|
||||
"bind_decision": selected_decision,
|
||||
"bind_candidate_decisions": candidate_decisions,
|
||||
}
|
||||
)
|
||||
if deadline is not None and datetime.now(UTC) >= deadline:
|
||||
finish_timeout()
|
||||
return
|
||||
self._schedule_next_bind_poll(
|
||||
task,
|
||||
now=now,
|
||||
interval_seconds=DOUYU_BIND_ROLE_POLL_INTERVAL,
|
||||
interval_seconds=interval_seconds,
|
||||
)
|
||||
self._update_task_progress(
|
||||
db,
|
||||
@@ -934,6 +1206,15 @@ class BindMixin:
|
||||
db, task, "failed", "查询绑定信息失败,请检查 Cookie 或 actAlias"
|
||||
)
|
||||
return
|
||||
record_role_api_candidates(
|
||||
db,
|
||||
account_id=account.id,
|
||||
task_id=task.id,
|
||||
candidates=before_candidates,
|
||||
scope=SCOPE_ELITE,
|
||||
stage="bind_qr.preflight",
|
||||
source="douyu_task.get_bind_qr",
|
||||
)
|
||||
# baseline 用活动 alias 的“当前已绑定”;pending 检测优先 cjm 的换绑最新态
|
||||
before = self._pick_baseline_bind_info(before_candidates, config) or {}
|
||||
# 换绑冷却必须看活动当前绑定(QYOOB),不要用 cjm
|
||||
@@ -1078,6 +1359,17 @@ class BindMixin:
|
||||
"bind_decision": pending_decision,
|
||||
"bind_candidate_decisions": candidate_decisions,
|
||||
"poll_count": 0,
|
||||
"bind_poll_legacy_snapshot": self._bind_poll_snapshot(
|
||||
next(
|
||||
(
|
||||
item
|
||||
for item in before_candidates
|
||||
if str(item.get("act_alias") or "")
|
||||
== str(config.get("legacy_act_alias") or "")
|
||||
),
|
||||
None,
|
||||
)
|
||||
),
|
||||
}
|
||||
if pending_decision["confirmable"]:
|
||||
pending_snapshot = self._bind_snapshot(pending_before)
|
||||
@@ -1153,6 +1445,15 @@ class BindMixin:
|
||||
db, task, "failed", "查询绑定信息失败,请检查 Cookie 或 actAlias"
|
||||
)
|
||||
return
|
||||
record_role_api_candidates(
|
||||
db,
|
||||
account_id=account.id,
|
||||
task_id=task.id,
|
||||
candidates=before_candidates,
|
||||
scope=SCOPE_ELITE,
|
||||
stage="confirm_bind.precheck",
|
||||
source="douyu_task.confirm_bind",
|
||||
)
|
||||
# 确认前“已生效绑定”角色(bound_act=1),确认失败/回查失败时写库用,避免待确认角色污染 game_name
|
||||
before_bound = self._pick_current_bound_info(
|
||||
before_candidates,
|
||||
@@ -1300,6 +1601,16 @@ class BindMixin:
|
||||
)
|
||||
return
|
||||
confirm_raw = confirm_result.get("raw") or {}
|
||||
record_role_api_response(
|
||||
db,
|
||||
account_id=account.id,
|
||||
task_id=task.id,
|
||||
response=confirm_raw if isinstance(confirm_raw, dict) else {},
|
||||
scope=SCOPE_ELITE,
|
||||
stage="confirm_bind.response",
|
||||
source="douyu_task.confirm_bind",
|
||||
act_alias=use_confirm_alias,
|
||||
)
|
||||
self._push_log(
|
||||
"info",
|
||||
f"确认绑定接口返回 act={use_confirm_alias} "
|
||||
@@ -1332,6 +1643,16 @@ class BindMixin:
|
||||
after = _pick_bound_after(after_candidates)
|
||||
if after is not None:
|
||||
break
|
||||
if after_candidates:
|
||||
record_role_api_candidates(
|
||||
db,
|
||||
account_id=account.id,
|
||||
task_id=task.id,
|
||||
candidates=after_candidates,
|
||||
scope=SCOPE_ELITE,
|
||||
stage="confirm_bind.after",
|
||||
source="douyu_task.confirm_bind",
|
||||
)
|
||||
if after is None:
|
||||
# 已生效绑定始终未出现:确认未生效(或同步延迟超时),保留原绑定
|
||||
if before_bound is not None:
|
||||
|
||||
Reference in New Issue
Block a user